Skip to content

Commit 13a7b30

Browse files
authored
E3: orchestrate revision-bound planning suggestions through Store (#35)
* docs: audit lane E planning contracts and remaining gaps * feat: prepare bounded read-only planning requests * docs: qualify v1 dispatch coverage and name Store correctly * docs: use exported Store name in planning handoff * feat: coordinate identity-bound planning suggestions * fix: narrow planning issue data and initial revision * test: verify shutdown refuses a distinct new plan * fix: isolate stable provider identity fields * docs: clarify provider identity boundary wording * fix: classify suggestion publication races from durable state * fix: preserve external terminal state after provider rejection * Integrate suggestion lifecycle persistence * Reconcile lost suggestion settlements * Bind suggestion admission to caller snapshot
1 parent ff2daca commit 13a7b30

3 files changed

Lines changed: 453 additions & 0 deletions

File tree

‎core/planning-suggestions.ts‎

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
import { identityKey, type PlanIdentity } from './identity.ts';
2+
import { prepareSuggestions, type AuthorInput, type AuthorProvider } from './planning-author.ts';
3+
import type { Diagnostic, EditReply, Plan } from './plan.ts';
4+
5+
/** Implemented by the existing Store. No SQL or second persistence writer in core. */
6+
export interface SuggestionStore {
7+
getPlan(identity: PlanIdentity): Plan;
8+
getSnapshot(identity: PlanIdentity): { id: string; base: string; head: string };
9+
beginSuggestions(identity: PlanIdentity, expected: { revision: number; snapshotId: string }): string;
10+
completeSuggestions(identity: PlanIdentity, id: string, reply: unknown): void;
11+
settleSuggestion(identity: PlanIdentity, id: string, expected: { revision: number; snapshotId: string }, outcome: { state: 'failed' | 'cancelled' | 'invalidated'; reason: string }): boolean;
12+
getSuggestions(identity: PlanIdentity, id: string): { state: string; revision: number; snapshotId: string | null; reply: EditReply | null; reason: string | null };
13+
}
14+
export type SuggestionInput = Omit<AuthorInput, 'requestId' | 'previousPlan'> & { snapshotId: string };
15+
export type SuggestionOutcome =
16+
| { state: 'completed'; id: string; warnings: Diagnostic[] }
17+
| { state: 'failed' | 'cancelled' | 'stale'; id: string; reason: string };
18+
export interface SuggestionHandle {
19+
readonly id: string;
20+
readonly result: Promise<SuggestionOutcome>;
21+
cancel(reason?: string): void;
22+
}
23+
interface Active {
24+
handle: SuggestionHandle;
25+
stop: (state: 'failed' | 'cancelled', reason: string) => void;
26+
}
27+
type TerminalOutcome = Extract<SuggestionOutcome, { reason: string }>;
28+
function persistentReason(reason: string): string {
29+
return (reason.trim() || 'Suggestion invocation ended without a reason.').slice(0, 4000);
30+
}
31+
function retainDiagnostic(reason: string | null, diagnostic: string): string {
32+
return reason && reason !== diagnostic ? `${reason} ${diagnostic}` : diagnostic;
33+
}
34+
35+
/** One instance per runner. Close it before closing Store. Not a cross-process scheduler. */
36+
export class SuggestionCoordinator {
37+
#store: SuggestionStore;
38+
#provider: AuthorProvider;
39+
#active = new Map<string, Active>();
40+
#closing = false;
41+
#closePromise?: Promise<void>;
42+
#timeoutMs: number;
43+
constructor(store: SuggestionStore, provider: AuthorProvider, timeoutMs = 120_000) {
44+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2_147_483_647)
45+
throw new Error('Suggestion timeout must fit a positive timer interval.');
46+
this.#store = store; this.#provider = provider; this.#timeoutMs = timeoutMs;
47+
}
48+
start(input: SuggestionInput): SuggestionHandle {
49+
if (this.#closing) throw new Error('Suggestion coordinator is closing.');
50+
const identity = { ...input.context.identity }, key = identityKey(identity);
51+
if (this.#active.has(key)) throw new Error('A suggestion invocation is still active for this plan.');
52+
const snapshotId = input.snapshotId;
53+
const previousPlan = this.#store.getPlan(identity), snapshot = this.#store.getSnapshot(identity);
54+
if (previousPlan.revision !== input.revision) throw new Error('Stale plan revision.');
55+
if (snapshot.id !== snapshotId || snapshot.base !== input.repo.baseSha) throw new Error('Stale repository snapshot.');
56+
// Validate before allocating a durable request; no await permits local state changes.
57+
const prepared = prepareSuggestions({ ...input, requestId: 'pending', previousPlan });
58+
const expected = Object.freeze({ revision: input.revision, snapshotId });
59+
const id = this.#store.beginSuggestions(identity, expected);
60+
const request = Object.freeze({ ...prepared.request, requestId: id });
61+
const controller = new AbortController();
62+
let stopped: Omit<TerminalOutcome, 'id'> | undefined;
63+
const cancellation = () => stopped;
64+
let settled = false;
65+
const reconcile = (outcome: TerminalOutcome): TerminalOutcome => {
66+
const current = this.#store.getSuggestions(identity, id);
67+
if (current.state === 'cancelled') return { id, state: 'cancelled', reason: retainDiagnostic(current.reason, outcome.reason) };
68+
if (current.state === 'invalidated') return { id, state: 'stale', reason: retainDiagnostic(current.reason, outcome.reason) };
69+
if (current.state === 'failed') return { id, state: 'failed', reason: retainDiagnostic(current.reason, outcome.reason) };
70+
if (this.#store.getPlan(identity).revision !== expected.revision || this.#store.getSnapshot(identity).id !== expected.snapshotId)
71+
return { id, state: 'stale', reason: retainDiagnostic(current.reason, outcome.reason) };
72+
return outcome;
73+
};
74+
const stop = (state: 'failed' | 'cancelled', reason: string) => {
75+
if (stopped || settled) return;
76+
stopped = { state, reason };
77+
// Even if storage fails, deliver cancellation to the invocation and retain its slot.
78+
try {
79+
if (!this.#store.settleSuggestion(identity, id, expected, { state, reason: persistentReason(reason) })) {
80+
const reconciled = reconcile({ id, state, reason });
81+
stopped = { state: reconciled.state, reason: reconciled.reason };
82+
}
83+
}
84+
catch (error) { stopped.reason += ` Request cleanup failed: ${String(error)}`; }
85+
finally { controller.abort(new Error(reason)); }
86+
};
87+
const timer = setTimeout(() => stop('failed', 'Suggestion invocation timed out.'), this.#timeoutMs);
88+
let finish!: (result: SuggestionOutcome) => void;
89+
const result = new Promise<SuggestionOutcome>(resolve => { finish = resolve; });
90+
const handle: SuggestionHandle = Object.freeze({ id, result,
91+
cancel: (reason = 'Suggestion cancelled by user.') => stop('cancelled', reason) });
92+
this.#active.set(key, { handle, stop });
93+
// Defer invocation until the handle owns its slot, including synchronous provider errors.
94+
void Promise.resolve().then(async () => {
95+
let outcome: SuggestionOutcome;
96+
try {
97+
if (stopped) outcome = { id, ...stopped };
98+
else {
99+
const source = await this.#provider.invoke(request, controller.signal);
100+
const afterInvocation = cancellation();
101+
if (afterInvocation) outcome = { id, ...afterInvocation };
102+
else {
103+
const current = this.#store.getSuggestions(identity, id);
104+
if (this.#store.getPlan(identity).revision !== request.revision ||
105+
this.#store.getSnapshot(identity).id !== snapshot.id || current.state === 'invalidated') {
106+
outcome = { id, state: 'stale', reason: 'Plan revision or snapshot changed during authoring.' };
107+
} else if (current.state !== 'pending') {
108+
outcome = { id, state: current.state === 'cancelled' ? 'cancelled' : 'stale', reason: `Suggestion request is ${current.state}.` };
109+
} else {
110+
const validated = prepared.validate(source);
111+
this.#store.completeSuggestions(identity, id, validated.value);
112+
outcome = { id, state: 'completed', warnings: validated.warnings };
113+
}
114+
}
115+
}
116+
} catch (error) {
117+
outcome = { id, ...(stopped ?? { state: 'failed' as const, reason: error instanceof Error ? error.message : String(error) }) };
118+
// A different Store connection may cancel or advance the revision while
119+
// the provider runs or before publication CAS. Keep the original error too.
120+
if (!stopped) {
121+
try {
122+
const current = this.#store.getSuggestions(identity, id);
123+
if (current.state === 'invalidated' || this.#store.getPlan(identity).revision !== request.revision ||
124+
this.#store.getSnapshot(identity).id !== snapshot.id)
125+
outcome = { id, state: 'stale', reason: `Plan revision or snapshot changed before publication. ${outcome.reason}` };
126+
else if (current.state === 'cancelled')
127+
outcome = { id, state: 'cancelled', reason: `Suggestion request was cancelled before publication. ${outcome.reason}` };
128+
} catch { /* Preserve the original error if durable state cannot be read. */ }
129+
}
130+
}
131+
if (outcome.state !== 'completed') {
132+
const terminal = outcome.state === 'stale' ? 'invalidated' : outcome.state;
133+
try {
134+
if (!this.#store.settleSuggestion(identity, id, expected, { state: terminal, reason: persistentReason(outcome.reason) }))
135+
outcome = reconcile(outcome);
136+
}
137+
catch (error) {
138+
// Keep the original provider/timeout reason, but surface cleanup failure too.
139+
outcome = { ...outcome, reason: `${outcome.reason} Request cleanup failed: ${String(error)}` };
140+
}
141+
}
142+
clearTimeout(timer);
143+
settled = true;
144+
this.#active.delete(key);
145+
finish(outcome);
146+
});
147+
return handle;
148+
}
149+
close(): Promise<void> {
150+
if (this.#closePromise) return this.#closePromise;
151+
this.#closing = true;
152+
const active = [...this.#active.values()];
153+
this.#closePromise = Promise.all(active.map(job => job.handle.result)).then(() => undefined);
154+
for (const job of active) job.stop('cancelled', 'Suggestion coordinator is closing.');
155+
return this.#closePromise;
156+
}
157+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# E3 suggestion lifecycle
2+
3+
The coordinator is a single in-process owner per runner/store. Construct one instance,
4+
not one per HTTP request. The existing `Store` remains the only durable writer and
5+
the only Apply authority. The coordinator does not allocate plan revisions or trust
6+
provider-supplied identity. It captures the identity, revision, immutable base snapshot
7+
and store-generated request ID before invocation. The caller supplies the snapshot ID
8+
that owns its repository data; admission compares that complete identity before the
9+
Store atomically allocates the request. Input containers are copied.
10+
11+
| Holder | States and legal transitions | Owner |
12+
| --- | --- | --- |
13+
| Coordinator | open → closing; closing rejects new starts synchronously | Runner-owned coordinator |
14+
| Invocation | pending → running → completed/failed/cancelled/stale; pending may cancel before launch | Coordinator until provider settles |
15+
| Cancellation | first reason retained; durable request settles and abort is requested immediately; invocation remains tracked and its result stays pending until provider termination | Coordinator and D adapter |
16+
| Durable request | pending → ready → consumed, or pending → failed/cancelled/invalidated; plan or snapshot changes invalidate pending/ready while retaining completed history | Existing Store transactions |
17+
| Durable plan | revision advances only through Store import/Apply; advancing invalidates sibling/pending requests | Store |
18+
| Subprocess/container | abort requested → terminating → terminated; promise settles after final termination | D adapter |
19+
| HTTP and UI | not created by E; F rejects admission/drains admitted requests before coordinator close, then closes Store; G preserves drafts and ignores stale responses | F/G |
20+
21+
The Store persists each request's plan revision, snapshot ID, and terminal reason.
22+
Failed, cancelled, and stale E outcomes use `settleSuggestion`, which can transition
23+
only the exact pending attempt at its captured revision and snapshot. If another
24+
process completed the request first, cleanup loses without changing the ready result.
25+
If another process cancelled or invalidated it first, E rereads the durable state and
26+
reconciles its returned classification while retaining the original diagnostic.
27+
Revision and snapshot changes invalidate durable requests with their cause while
28+
retaining completed replies as stale history. Durable reasons use the Store's bounded
29+
format even when a provider returns an oversized diagnostic. Restart therefore
30+
preserves both the terminal classification and its actionable reason.
31+
32+
There is one active invocation per plan identity. A new start (including a retry)
33+
cannot replace it, regardless of elapsed time, cancellation, or persisted state.
34+
No lease or wall-clock heuristic releases ownership. Timeouts request abort but
35+
do not settle early. First timeout/cancellation/shutdown reason wins over a later
36+
generic provider abort. Different plan identities remain distinct; the production
37+
runner must additionally enforce its global task limit.
38+
39+
Before publication, compare the current plan revision and snapshot with the captured
40+
ones, validate every card via E2, then call Store.completeSuggestions, whose CAS
41+
also checks the request is still pending and bound to the current revision/snapshot.
42+
JavaScript has no await between these checks and publication; Store provides the
43+
transactional request CAS across independent processes.
44+
If the provider rejects or publication CAS refuses after external cancellation or
45+
revision advance, read durable state and return cancelled/stale instead of a provider
46+
failure. Retain the original provider/Store diagnostic alongside that classification.
47+
Automatic cleanup uses the same captured binding and pending-state guard. Explicit
48+
user dismissal remains a separate Store operation. E is not a multi-process scheduler.
49+
50+
`close()` flips admission to closing before aborting invocations and waits for all
51+
providers to settle. It does not close storage. There is no HTTP server, polling,
52+
browser input, retry endpoint or subprocess implementation in this lane.
53+
54+
Checks use controllable promises and timers with real SQLite to assert both returned
55+
outcomes and durable state. Required cases include import before late completion,
56+
snapshot change, completion racing failure cleanup, external cancellation, bounded
57+
provider errors, timeout followed by an unsettled provider,
58+
retry while cancellation is pending, shutdown admission, and post-submit mutation
59+
of caller-owned input. Apply/replay/independent-process serialization remain Store's
60+
existing acceptance boundary; E4 adds integrated fixtures.

0 commit comments

Comments
 (0)