@llblab/pi-state-flow 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +3 -3
- package/BACKLOG.md +7 -0
- package/CHANGELOG.md +4 -0
- package/README.md +2 -2
- package/docs/architecture.md +2 -2
- package/docs/temporal-acceptance.md +2 -2
- package/index.ts +1 -1
- package/lib/context.ts +1 -1
- package/lib/extension.ts +91 -43
- package/lib/terminal.ts +1 -1
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -24,15 +24,15 @@
|
|
|
24
24
|
- Bind every loaded scope and active Pi branch/checkpoint to the corresponding State Flow Git revision. Resume and tree restoration must recover branch-correct runtime config and semantic layers from that revision without blindly importing Git `HEAD`; reading an older revision must use object-level Git reads and never reset or check out the shared repository worktree.
|
|
25
25
|
- Every accepted semantic change, including session-only and response-only changes, atomically updates affected checkpoint/tail pairs and temporal metadata and creates one immediate local Git commit when Git is available; each commit stages the complete non-ignored worktree delta (`git add -A` semantics, including manual deletions) before overlaying exact prepared State Flow outputs, respects `.gitignore`, keeps State Flow-owned active files under compare-and-swap protection, and synchronizes the caller-visible index to the committed tree. `remotePublication` is branch runtime policy: `turn-end` queues only the newest accepted target for asynchronous non-interactive push, `off` remains local-only, and `transition` preserves synchronous legacy behavior. Queue state is operational metadata beneath the Git common directory, not semantic history; use exact targets, destination identity, symlink-safe atomic CAS, descendant-only coalescing, cross-process worker leases, restart recovery, and truthful failure diagnostics. Remote failure never rolls back accepted state or regenerates an answer. A repository with no remote is intentionally local-only; only Git executable `ENOENT` authorizes file-only mode.
|
|
26
26
|
- Register `patch_state` as the sole model-authored semantic mutation protocol. It accepts optional fixed `global`, `cwd`, and `session` semantic patches plus optional `final:true`; require at least one scope or `final:true`, reject unknown fields, `final:false`, empty supplied scopes, material no-ops, and the retired `{scope, patch}` / `unchanged` grammar. Validate every supplied scope against one causal basis and publish it all-or-nothing with one identity, temporal boundary, and durable cohort. Never accept model-authored `response`.
|
|
27
|
-
- Treat every semantic `patch_state` as a strict inference barrier. Give it sequential execution mode, inspect Pi's synchronized current assistant message during tool preflight, require exactly one `patch_state` call in that response, and block every sibling tool call before execution. Every enabled iteration begins terminal-ineligible; only a successful call containing `final:true` latches eligibility for the next accepted `turn_end`, without stopping later reasoning, tools, or patches. If
|
|
28
|
-
- Reconcile `response` only from the actually accepted ordinary assistant answer at `turn_end`; it remains runtime-owned. State Flow has no terminal HTML-comment mutation protocol and does not parse generic service comments.
|
|
27
|
+
- Treat every semantic `patch_state` as a strict inference barrier. Give it sequential execution mode, inspect Pi's synchronized current assistant message during tool preflight, require exactly one `patch_state` call in that response, and block every sibling tool call before execution. Every enabled iteration begins terminal-ineligible; only a successful call containing `final:true` latches eligibility for the next accepted `turn_end`, without stopping later reasoning, tools, or patches. If a terminal draft ends before eligibility, preserve it as the runtime-owned response at that `turn_end` and start at most two same-run fallback turns whose only purpose is the `final:true` patch; an eligible draft whose final validation fails after a later acquisition follows the same path. Fallback turns never enter `response`, and their only instruction is to apply `patch_state` with any durable changes and `final:true`, or `{final:true}` alone. A successful fallback closes resolution with the preserved answer intact; two failed fallbacks close the iteration with the preserved answer and current state plus one bounded warning and a finalization diagnostic. Failed patch calls do not consume fallback turns. A subsequent legal patch remains possible, and only an accepted ordinary answer is reconciled.
|
|
28
|
+
- Reconcile `response` only from the actually accepted ordinary assistant answer at `turn_end`; it remains runtime-owned. State Flow has no terminal HTML-comment mutation protocol and does not parse generic service comments. The first terminal draft that cannot be reconciled is preserved as the iteration response rather than discarded; fallback turns during pending resolution never reach `response`. Other extensions retain ownership of their own comments and output handling.
|
|
29
29
|
- Treat terminal state as a decision-relevant handoff, not narration: retain source-addressed reusable operational knowledge in `artifacts`; compile stable requirements, confirmed decisions, rejected approaches, and interface commitments into `contract`; retain observations, validation, failures, current domain state, unresolved work, interaction consequences, and exact continuation in `working`. Preserve relevant completed prerequisites and verified outcomes while removing obsolete progress narration; reconcile only information affected by the run and relevant existing commitments, not every scope or repository surface.
|
|
30
30
|
- Preserve active constraints, unresolved questions, consequential negative results, and the next discriminating check before compression. Distinguish observations, user requirements, assistant decisions, and hypotheses; do not promote assistant conclusions to user requirements. Retain useful source locators and validity conditions for consequential facts without mandatory per-value metadata. Keep rejection reasons and reconsideration conditions. Reconcile contradictions through evidence or user clarification instead of silently overwriting established constraints or observations; retain unresolved conflicts and decision-relevant hypotheses as uncertain. These are protocol obligations, not deterministic semantic validation gates.
|
|
31
31
|
- Treat `working` as last observations, not a live workspace. Revalidate volatile facts before consequential actions; after interruption or branch navigation inspect relevant external effects before repeating operations. Failed state commits and restored memory do not undo tool effects. Missing evidence proves neither success nor absence of effects: retain uncertainty and the next check. Keep revalidation targeted, without action ledgers or runtime freshness/rollback guarantees.
|
|
32
32
|
- Treat each successful `SKILL.md` read as CWD artifact acquisition using the finalized tool-execution arguments after mutable interception: require a non-empty compiler output in the next `patch_state` call under `cwd.artifacts[exactReadPath]` with `description`, `kind: "skill"`, and a flexible non-empty `compilation` object; hash the executed source bytes and record runtime-owned `sourceHash` plus `skill-artifact-v1` `compilerRevision` in the CWD provenance registry; reject missing, unhashable, malformed, or forged freshness data; replace the complete prior Skill artifact and its provenance entry on refresh so obsolete evidence cannot survive. `contract.compiled_skills` is retired and rejected; migrate useful legacy entries into artifacts while preserving behavior and marking fallback hashes unverified when the source is unavailable.
|
|
33
33
|
- Make the model audit and optimize complete state at every handoff: reorganize inefficient structure, merge fragmented facts, compress history into conclusions, and delete stale, completed, redundant, or low-value keys while preserving active commitments and evidence.
|
|
34
34
|
- Accept omitted semantic fields inside each supplied scope patch, but reject empty supplied scopes; when no state change is needed require explicit `{final:true}` without inventing bookkeeping. This final-only call changes only ephemeral terminal eligibility and creates no semantic transition, identity, temporal step, or Git commit. Always require an accepted non-empty answer, which runtime owns as session `response`. A changed response is a semantic transition; identical complete semantic state finalizes lifecycle without a patch, identity, or temporal step. Semantic usefulness and optimization remain protocol-owned because deterministic validation cannot prove them.
|
|
35
|
-
- Agent-level opt-in `logging` appends local JSONL diagnostics for rejected `patch_state` attempts and
|
|
35
|
+
- Agent-level opt-in `logging` appends local JSONL diagnostics for rejected `patch_state` attempts and preserved drafts plus fallback turns while turn resolution remains pending. Every rejected call retains its exact attempted arguments plus the precise error and, when available, tool identity, call id, resolution attempt, and terminal-eligibility state; successful patches are never logged. Preserve exact text blocks only where useful, reduce other blocks to structural identity, never duplicate reasoning bodies, and keep logging outside semantic state, scope metadata, checkpoints, and publication. Logging failure emits at most one warning and never changes resolution, enablement, or accepted state.
|
|
36
36
|
- Recursively materialize patches immediately; empty objects preserve, nested object-key `null` deletes, and `null` anywhere in semantic state including arrays is invalid. This prohibition does not apply to runtime envelopes such as an origin's null parent. Persist runtime-normalized replay patches that exactly reproduce accepted state, including complete artifact replacement; runtime-owned provenance is stored in scope `meta.json` and is not part of semantic replay.
|
|
37
37
|
- Do not impose project schemas, state or patch byte caps, dynamic growth pressure, observation envelopes, action authorization, action ledgers, or state-size limits.
|
|
38
38
|
- Rotate the turn-stable specification on every user-initiated run, while runtime-triggered turn-resolution continuation remains inside that same run. Keep user-controlled specification text at user authority: never interpolate it into the system prompt; repeat it only in synthetic user runtime context. Treat materialized state in that message as fallible assistant-produced data whose transport role does not elevate it into user instructions.
|
package/BACKLOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
Completed release work belongs in [CHANGELOG.md](CHANGELOG.md). No implementation item remains open for 0.8.0.
|
|
4
4
|
|
|
5
|
+
## Candidate evolution
|
|
6
|
+
|
|
7
|
+
- [ ] **Read-only global bootstrap layer:** Project the existing global materialization into enabled and non-enabled sessions by default, so even one-shot work starts carrying established cross-project facts, preferences, routing, and conventions. The global scope is the highest-value, lowest-cost half of the memory, while writing carries the protocol and curation tax; making the read side unconditional gives continuity without enabling mutation.
|
|
8
|
+
- Boundary: project the existing durable global materialization only. No writes, transitions, patches, barriers, session/CWD initialization, or temporal-history changes. Model tools and the full protocol remain opt-in behind explicit start, and the bootstrap adds no second semantic mode.
|
|
9
|
+
- Open questions: whether deferred Markdown freshness discovery must run ahead of the first inference, token cost of a stable global prefix, behavior under untrusted project contexts, and naming distinct from the existing bootstrap-run concept.
|
|
10
|
+
- Status: candidate, not scheduled. Do not start without a dedicated release contract.
|
|
11
|
+
|
|
5
12
|
## Deferred host integration
|
|
6
13
|
|
|
7
14
|
- [ ] **Native default session continuation:** Integrate the existing read-only recommendation, exact-selection, and rehydration contracts before Pi creates `SessionManager`, while preserving explicit new/resume and native-picker precedence, truthful notices, and cross-process session ownership. Pi 0.84.4 exposes no suitable pre-session resolver hook, so this requires upstream support or an SDK/launcher integration. Reverify the host API before taking the item; it is not a release dependency.
|
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
> Each release keeps at most 8 outcome records of at most 512 characters.
|
|
4
4
|
|
|
5
|
+
## 0.8.1: Preserved answers and bounded fallback resolution
|
|
6
|
+
|
|
7
|
+
- `Resolution`: A terminal draft is never discarded. A draft ending before eligibility — or an eligible draft whose final validation fails for a later acquisition — is preserved as the runtime-owned response at `turn_end`, then at most two same-run fallback turns exist only to obtain the `final:true` patch. Fallback turns never enter `response`; success commits their patches with the preserved answer intact, and exhaustion closes the iteration with the preserved answer, current state, one bounded warning, and a finalization diagnostic.
|
|
8
|
+
|
|
5
9
|
## 0.8.0: Atomic cohorts and final eligibility
|
|
6
10
|
|
|
7
11
|
- `Protocol`: Replaced the single-scope PATCH and UNCHANGED forms with one canonical `patch_state({global?, cwd?, session?, final?})` call. Supplied scopes validate against one causal basis and publish as one atomic transition with a single identity, temporal boundary, durable cohort, and inference barrier; unknown fields, `final:false`, empty scopes, and material no-ops fail closed.
|
package/README.md
CHANGED
|
@@ -219,7 +219,7 @@ patch_state({...?, final:true}) → atomic accepted state + terminal eligibility
|
|
|
219
219
|
patch_state({final:true}) → terminal eligibility only, with no semantic transition
|
|
220
220
|
```
|
|
221
221
|
|
|
222
|
-
Every enabled iteration begins terminal-ineligible. `final:true` latches eligibility for the next accepted `turn_end`; it does not terminate the turn, stop tools or reasoning, freeze state, or prevent later `patch_state` calls.
|
|
222
|
+
Every enabled iteration begins terminal-ineligible. `final:true` latches eligibility for the next accepted `turn_end`; it does not terminate the turn, stop tools or reasoning, freeze state, or prevent later `patch_state` calls. A terminal draft that ends before eligibility, or an eligible draft whose final validation fails after a later acquisition, is preserved: it is reconciled as the runtime-owned `response` at that `turn_end` instead of being discarded, and State Flow starts at most two same-run fallback turns whose only purpose is to obtain the `final:true` patch. Fallback turns are never the response. A successful `final:true` during a fallback commits its patches and closes resolution with the preserved answer intact; when both fallbacks pass without it, the iteration closes with the preserved answer and current state, plus one bounded warning and a finalization diagnostic. Failed patch calls do not consume fallback turns. Only an accepted answer reaches `response`; aborted, length-limited, and provider-error endings never do.
|
|
223
223
|
|
|
224
224
|
A semantic patch remains an inference barrier. The complete scope cohort is validated, durably accepted, and rematerialized before further reasoning. Empty supplied scopes and materially no-op scope cohorts are rejected; omit unchanged scopes and use `{final:true}` alone when no semantic update is needed. `response` is never accepted from the model. The final answer is ordinary assistant output, not a state transport. State Flow has no terminal `state_flow` HTML-comment protocol and does not parse generic service comments. Historical `state_flow` text is ordinary text. Other extensions retain ownership of their own comments such as `telegram_button`. Never put secrets in state.
|
|
225
225
|
|
|
@@ -294,7 +294,7 @@ npm install
|
|
|
294
294
|
npm run validate
|
|
295
295
|
```
|
|
296
296
|
|
|
297
|
-
Validation runs TypeScript checks, automated tests, and an import smoke check. Temporal algebra tests compare all available offsets with independently retained test snapshots through dense/sparse repeated folding, shared transitions, deletion overlays, no-ops, and forks. Temporary-repository tests also cover explicit migration, ten committed sparse transitions with folding and all hot offsets, cold Git scope recovery, and historical symlink rejection. Storage-level tests also prove atomic runtime/semantic publication, config-only stop without semantic history, runtime identity and lineage validation, self-reference resolution across unrelated commits, and exact accepted-commit retry. Real Pi tests also exercise configured automatic activation, deferred source discovery, strict draft → resolution → accepted-answer continuation, temporal barriers and next-inference state, lazy runtime offset-one reads, unchanged shared-stream inheritance, old-branch stop/resume, and bounded passive stop/restart projection. The complete twenty-case temporal acceptance audit is documented in the property map; the canonical backlog identifies any subsequent open work.
|
|
297
|
+
Validation runs TypeScript checks, automated tests, and an import smoke check. Temporal algebra tests compare all available offsets with independently retained test snapshots through dense/sparse repeated folding, shared transitions, deletion overlays, no-ops, and forks. Temporary-repository tests also cover explicit migration, ten committed sparse transitions with folding and all hot offsets, cold Git scope recovery, and historical symlink rejection. Storage-level tests also prove atomic runtime/semantic publication, config-only stop without semantic history, runtime identity and lineage validation, self-reference resolution across unrelated commits, and exact accepted-commit retry. Real Pi tests also exercise configured automatic activation, deferred source discovery, strict draft → preserved answer and fallback resolution → accepted-answer continuation, temporal barriers and next-inference state, lazy runtime offset-one reads, unchanged shared-stream inheritance, old-branch stop/resume, and bounded passive stop/restart projection. The complete twenty-case temporal acceptance audit is documented in the property map; the canonical backlog identifies any subsequent open work.
|
|
298
298
|
|
|
299
299
|
- [Canonical open work](BACKLOG.md)
|
|
300
300
|
- [Delivery history](CHANGELOG.md)
|
package/docs/architecture.md
CHANGED
|
@@ -71,7 +71,7 @@ A final-only `patch_state({"final":true})` call changes only ephemeral terminal
|
|
|
71
71
|
|
|
72
72
|
`read_state` reads one cached effective or scoped projection at offsets zero through seven. It never publishes or advances history.
|
|
73
73
|
|
|
74
|
-
Every enabled assistant iteration starts terminal-ineligible. Only a successful `patch_state` call containing `final:true` latches eligibility for the next accepted `turn_end`; the call may atomically include global, CWD, and session patches. Eligibility does not stop later reasoning, tools, or patches. If terminal prose arrives before eligibility, State Flow
|
|
74
|
+
Every enabled assistant iteration starts terminal-ineligible. Only a successful `patch_state` call containing `final:true` latches eligibility for the next accepted `turn_end`; the call may atomically include global, CWD, and session patches. Eligibility does not stop later reasoning, tools, or patches. If terminal prose arrives before eligibility, State Flow preserves that draft and reconciles it into runtime-owned `response` at `turn_end`, then starts at most two same-run fallback turns whose only purpose is the `final:true` patch. The same path covers an eligible draft whose final validation fails after a later acquisition. Fallback turns never become the response: a successful `final:true` commits its patches and closes resolution with the preserved answer intact, while two failed fallbacks close the iteration with the preserved answer and current state plus one bounded warning and a finalization diagnostic. Failed patch calls do not consume the budget. A following legal patch remains possible, and only an accepted ordinary answer is reconciled into runtime-owned `response` at `turn_end`. State Flow no longer parses `state_flow` or generic HTML comments; historical comments are ordinary text and other extensions retain their own comment handling.
|
|
75
75
|
|
|
76
76
|
## Lifecycle planes
|
|
77
77
|
|
|
@@ -199,7 +199,7 @@ Unknown keys fail loading. State Flow memory ownership and global availability a
|
|
|
199
199
|
|
|
200
200
|
`/state-flow-status` reports branch mode, runtime revision, temporal head/history depth, scope keys, patch tails, artifact freshness, memory-bearing scopes, external-promotion summaries, remote policy/queue state, and pending publication. Unavailable materialization is reported as unavailable, never fabricated as empty. Artifact source bodies are not read for status.
|
|
201
201
|
|
|
202
|
-
Opt-in `logging` appends local JSONL diagnostics for rejected `patch_state` calls and
|
|
202
|
+
Opt-in `logging` appends local JSONL diagnostics for rejected `patch_state` calls and preserved drafts plus fallback turns while turn resolution is pending. A rejected call retains its exact attempted arguments, the precise error, and, when available, tool identity, call id, resolution attempt, and terminal-eligibility state; accepted patches are never logged. Records preserve useful exact text blocks and reduce other blocks to structural identity without duplicating reasoning. They are never semantic state, scope `meta.json`, Pi checkpoints, or repository input. Write failure changes no resolution, enablement, or accepted state and reports at most one bounded local warning.
|
|
203
203
|
|
|
204
204
|
## Validation boundaries
|
|
205
205
|
|
|
@@ -17,8 +17,8 @@ The numbering below follows the twenty required tests in the temporal design cor
|
|
|
17
17
|
11. **Barrier shifts current to offset 1:** `tests/integration.test.ts` — “real Pi patch_state barriers rematerialize every scope before the next inference” observes the predecessor immediately after a barrier.
|
|
18
18
|
12. **Next inference sees new current state:** The same real-Pi test inspects actual model-input projections after session, CWD, and global barriers. “real Pi reads prior scoped state lazily after a barrier and rejects offset eight without a transition” adds model-tool access to the predecessor.
|
|
19
19
|
13. **No automatic old full-state duplication:** `tests/context.test.ts` — “projects only the latest seven compact accepted transitions” rejects full-state records in transition context. The real-Pi barrier test requires exactly one current runtime projection per inference. Explicitly requested history remains ordinary tool-result trajectory, not eager snapshot injection.
|
|
20
|
-
14. **Accepted response changes are transitions:** `tests/
|
|
21
|
-
15. **Final-only eligibility creates no fake history:** `tests/extension.test.ts` — “
|
|
20
|
+
14. **Accepted response changes are transitions:** `tests/extension.test.ts` — “the preserved answer stands after two fallback turns without final:true” and `tests/skills.test.ts` — “a late Skill obligation that outlives the fallback budget keeps the preserved answer” verify that a primary draft without a reconciled `final:true` is preserved as the runtime-owned response, fallback turns never enter `response`, and an exhausted fallback budget keeps the preserved answer with its current state. `tests/integration.test.ts` — “real Pi keeps the preserved answer after the fallback budget” repeats the closure through the native Pi turn loop.
|
|
21
|
+
15. **Final-only eligibility creates no fake history:** `tests/extension.test.ts` — “a primary draft without eligibility is preserved as the response and final-only fallback resolution keeps it” checks that `{final:true}` latches turn eligibility without changing semantic lineage, tails, step, or Git. A later changed accepted response remains a runtime-owned transition.
|
|
22
22
|
16. **Offset eight is outside hot history:** `tests/temporal.test.ts` — “hot range and unproven pre-migration history are explicit read boundaries”; the real-Pi history-reader test also exercises native tool rejection without a transition.
|
|
23
23
|
17. **Cold Git history remains recoverable:** `tests/git.test.ts` — “temporal Git writer preserves all hot states through sparse folding and cold revision reads” loads older committed states without moving the worktree.
|
|
24
24
|
18. **Tree/resume select the correct lineage:** `tests/integration.test.ts` — “real Pi preserves branch-local state through compaction, tree navigation, stop, and restart” and “real Pi old tree branch stop and resume preserve selected semantics without rewinding shared files”.
|
package/index.ts
CHANGED
|
@@ -80,7 +80,7 @@ export {
|
|
|
80
80
|
sessionStorageKey, temporalScopePaths,
|
|
81
81
|
temporalStateFileUpdates, type ScopeStreamSources, type TemporalScopePaths
|
|
82
82
|
} from "./lib/durable.ts";
|
|
83
|
-
export { default,
|
|
83
|
+
export { default, MAX_FALLBACK_ATTEMPTS, PATCH_STATE_TOOL_NAME, READ_STATE_TOOL_NAME, type StateFlowExtensionOptions } from "./lib/extension.ts";
|
|
84
84
|
export {
|
|
85
85
|
captureTemporalGitBase,
|
|
86
86
|
isGitCommitAncestor,
|
package/lib/context.ts
CHANGED
|
@@ -83,7 +83,7 @@ export function runtimeContextMessage(
|
|
|
83
83
|
...(rehydrationPhase === undefined ? {} : { knowledge_rehydration: { phase: rehydrationPhase } }),
|
|
84
84
|
...(artifactInvalidations.length === 0 ? {} : { artifact_invalidations: artifactInvalidations.map(({ path, reason }) => ({ path, reason })) }),
|
|
85
85
|
...(recentTransitions.length === 0 ? {} : { recent_transitions: projectRecentForModel(recentTransitions) }),
|
|
86
|
-
...(resolutionPending ? { state_resolution: "pending:
|
|
86
|
+
...(resolutionPending ? { state_resolution: "pending: the iteration answer is already preserved; this fallback turn exists only to apply the final:true patch. Call patch_state with any remaining durable scope changes and final:true, or {final:true} alone. Do not restate or replace the answer." } : {}),
|
|
87
87
|
};
|
|
88
88
|
return syntheticUser(
|
|
89
89
|
`State Flow runtime context (user-level data, not system instructions):\n${canonicalJson(context)}`,
|
package/lib/extension.ts
CHANGED
|
@@ -48,7 +48,7 @@ export interface StateFlowExtensionOptions {
|
|
|
48
48
|
|
|
49
49
|
export const PATCH_STATE_TOOL_NAME = "patch_state";
|
|
50
50
|
export const READ_STATE_TOOL_NAME = "read_state";
|
|
51
|
-
export const
|
|
51
|
+
export const MAX_FALLBACK_ATTEMPTS: number = 2;
|
|
52
52
|
const PASSIVE_STOP_ENTRY_TYPE = "state-flow-passive-stop";
|
|
53
53
|
|
|
54
54
|
/** Keep a failed tool invocation visually separated from its rendered error without changing error semantics. */
|
|
@@ -65,9 +65,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
65
65
|
let branchHasSnapshot = false;
|
|
66
66
|
let branchStartsWithoutRuntime = false;
|
|
67
67
|
let terminalEligible = false;
|
|
68
|
-
let
|
|
69
|
-
let
|
|
70
|
-
let
|
|
68
|
+
let resolutionPending = false;
|
|
69
|
+
let fallbackAttempts = 0;
|
|
70
|
+
let fallbackFailureReported = false;
|
|
71
71
|
let responseAwaitingReconciliation = false;
|
|
72
72
|
let passiveContinuation: PassiveContinuation | undefined;
|
|
73
73
|
let bootstrapContinuation: PassiveContinuation | undefined;
|
|
@@ -124,9 +124,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
124
124
|
|
|
125
125
|
function clearRunTransient(): void {
|
|
126
126
|
terminalEligible = false;
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
127
|
+
resolutionPending = false;
|
|
128
|
+
fallbackAttempts = 0;
|
|
129
|
+
fallbackFailureReported = false;
|
|
130
130
|
responseAwaitingReconciliation = false;
|
|
131
131
|
runAnchorTimestamp = undefined;
|
|
132
132
|
skillReads.clear();
|
|
@@ -273,10 +273,14 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
273
273
|
}, runtime!.causalBasis(), { finalizeRun });
|
|
274
274
|
if (!committed) return false;
|
|
275
275
|
installScopeStates();
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
276
|
+
// A preserved primary response commits mid-run; pending acquisition obligations must
|
|
277
|
+
// still block final eligibility until the fallback turns resolve or expire.
|
|
278
|
+
if (!(finalizeRun && resolutionPending)) {
|
|
279
|
+
artifactInvalidations = artifactInvalidations.filter(({ path }) => !acquiredArtifactPaths.has(path));
|
|
280
|
+
artifactReads.setCandidates(artifactInvalidations);
|
|
281
|
+
skillReads.clear();
|
|
282
|
+
artifactReads.clear();
|
|
283
|
+
}
|
|
280
284
|
persist();
|
|
281
285
|
return true;
|
|
282
286
|
}
|
|
@@ -579,15 +583,77 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
579
583
|
}
|
|
580
584
|
}
|
|
581
585
|
|
|
582
|
-
function
|
|
583
|
-
|
|
586
|
+
function continueFallbackResolution(lastWarning: boolean): void {
|
|
587
|
+
resolutionPending = true;
|
|
584
588
|
pi.sendMessage({
|
|
585
589
|
customType: VALIDATION_MESSAGE_TYPE,
|
|
586
|
-
content:
|
|
590
|
+
content: lastWarning
|
|
591
|
+
? "This is the last State Flow fallback turn. The iteration's answer is preserved and will not change. Apply the final:true patch now: call patch_state with any remaining durable scope changes and final:true, or with {\"final\":true} when nothing remains. Do not restate the answer."
|
|
592
|
+
: "The iteration's answer is preserved as the final response; later turns cannot replace it. Apply the final:true patch: call patch_state with any durable scope changes from this iteration (including required artifact or Skill compilation) and final:true, or with {\"final\":true} when nothing remains to persist. Do not restate the answer.",
|
|
587
593
|
display: false,
|
|
588
594
|
}, { deliverAs: "steer", triggerTurn: true });
|
|
589
595
|
}
|
|
590
596
|
|
|
597
|
+
/** Preserve the primary answer as this iteration's response and steer bounded fallback turns whose only purpose is the final:true patch. */
|
|
598
|
+
function beginFallbackResolution(ctx: ExtensionContext, message: { content?: unknown }, reason: string): void {
|
|
599
|
+
responseAwaitingReconciliation = true;
|
|
600
|
+
fallbackAttempts = 0;
|
|
601
|
+
fallbackFailureReported = false;
|
|
602
|
+
recordDiagnostic(`Preserved the terminal draft as the iteration response; fallback resolution started: ${reason}`, "terminal-pending", ctx, {
|
|
603
|
+
content: message.content,
|
|
604
|
+
resolutionAttempt: 0,
|
|
605
|
+
terminalEligible,
|
|
606
|
+
});
|
|
607
|
+
continueFallbackResolution(MAX_FALLBACK_ATTEMPTS === 1);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/** Fallback turns never become the response; they exist only to supply the final:true patch. */
|
|
611
|
+
function resolveFallbackTurn(ctx: ExtensionContext, message: { content?: unknown }): any {
|
|
612
|
+
let resolved = terminalEligible;
|
|
613
|
+
if (resolved) {
|
|
614
|
+
try {
|
|
615
|
+
validateFinalEligibility(scopeStates, skillReads.successful.values(), runtime!.causalBasis(), artifactReads.successful.values());
|
|
616
|
+
} catch (error) {
|
|
617
|
+
resolved = false;
|
|
618
|
+
recordDiagnostic(error instanceof Error ? error.message : String(error), "terminal-pending", ctx, {
|
|
619
|
+
content: message.content,
|
|
620
|
+
resolutionAttempt: fallbackAttempts,
|
|
621
|
+
terminalEligible,
|
|
622
|
+
});
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
if (resolved) {
|
|
626
|
+
resolutionPending = false;
|
|
627
|
+
recordDiagnostic(`Fallback resolution obtained final:true after ${fallbackAttempts} fallback turn${fallbackAttempts === 1 ? "" : "s"}; the preserved answer stands`, "finalization", ctx, {
|
|
628
|
+
content: message.content,
|
|
629
|
+
resolutionAttempt: fallbackAttempts,
|
|
630
|
+
terminalEligible,
|
|
631
|
+
});
|
|
632
|
+
return { message: { ...message, role: "assistant" as const, content: [] } };
|
|
633
|
+
}
|
|
634
|
+
fallbackAttempts = Math.min(MAX_FALLBACK_ATTEMPTS, fallbackAttempts + 1);
|
|
635
|
+
if (fallbackAttempts < MAX_FALLBACK_ATTEMPTS) {
|
|
636
|
+
recordDiagnostic(`Fallback turn ended without final:true (${fallbackAttempts}/${MAX_FALLBACK_ATTEMPTS})`, "terminal-pending", ctx, {
|
|
637
|
+
content: message.content,
|
|
638
|
+
resolutionAttempt: fallbackAttempts,
|
|
639
|
+
terminalEligible,
|
|
640
|
+
});
|
|
641
|
+
continueFallbackResolution(fallbackAttempts + 1 >= MAX_FALLBACK_ATTEMPTS);
|
|
642
|
+
return { message: { ...message, role: "assistant" as const, content: [] } };
|
|
643
|
+
}
|
|
644
|
+
resolutionPending = false;
|
|
645
|
+
recordDiagnostic(`Fallback resolution exhausted without final:true (${fallbackAttempts}/${MAX_FALLBACK_ATTEMPTS}); the preserved response and current state remain`, "finalization", ctx, {
|
|
646
|
+
content: message.content,
|
|
647
|
+
resolutionAttempt: fallbackAttempts,
|
|
648
|
+
terminalEligible,
|
|
649
|
+
});
|
|
650
|
+
if (!fallbackFailureReported) {
|
|
651
|
+
fallbackFailureReported = true;
|
|
652
|
+
ctx.ui.notify(`State Flow kept the preserved answer; no final:true patch arrived after ${MAX_FALLBACK_ATTEMPTS} fallback turns, so the iteration closed with its current state.`, "warning");
|
|
653
|
+
}
|
|
654
|
+
return { message: { ...message, role: "assistant" as const, content: [] } };
|
|
655
|
+
}
|
|
656
|
+
|
|
591
657
|
pi.registerTool({
|
|
592
658
|
name: READ_STATE_TOOL_NAME,
|
|
593
659
|
label: "Read State",
|
|
@@ -654,7 +720,6 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
654
720
|
if (params.final !== true) throw new Error('patch_state requires at least one scope patch or {"final":true}');
|
|
655
721
|
validateFinalEligibility(scopeStates, skillReads.successful.values(), runtime!.causalBasis(), artifactReads.successful.values());
|
|
656
722
|
terminalEligible = true;
|
|
657
|
-
terminalDraftIntercepted = false;
|
|
658
723
|
return { content: [{ type: "text", text: "\nState iteration is terminal-eligible." }], details: { final: true } };
|
|
659
724
|
}
|
|
660
725
|
const stage = stageAtomicScopePatches(scopeStates, patches, skillReads.successful.values(), runtime!.causalBasis(), artifactReads.successful.values());
|
|
@@ -664,7 +729,6 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
664
729
|
commitStage(stage, ctx, false);
|
|
665
730
|
if (params.final === true) {
|
|
666
731
|
terminalEligible = true;
|
|
667
|
-
terminalDraftIntercepted = false;
|
|
668
732
|
}
|
|
669
733
|
updateUi(ctx);
|
|
670
734
|
const publication = pendingPublication === undefined ? "" : "; durable publication pending";
|
|
@@ -676,7 +740,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
676
740
|
input: attempted,
|
|
677
741
|
tool: PATCH_STATE_TOOL_NAME,
|
|
678
742
|
toolCallId,
|
|
679
|
-
resolutionAttempt:
|
|
743
|
+
resolutionAttempt: fallbackAttempts,
|
|
680
744
|
terminalEligible,
|
|
681
745
|
});
|
|
682
746
|
throw separatedFailure(error);
|
|
@@ -809,9 +873,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
809
873
|
artifactReads.clear();
|
|
810
874
|
if (artifactRefreshPending) refreshArtifactInvalidations(ctx);
|
|
811
875
|
terminalEligible = false;
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
876
|
+
resolutionPending = false;
|
|
877
|
+
fallbackAttempts = 0;
|
|
878
|
+
fallbackFailureReported = false;
|
|
815
879
|
responseAwaitingReconciliation = false;
|
|
816
880
|
const rotatesRun = snapshot.meta.specification !== undefined;
|
|
817
881
|
if (rotatesRun && rehydrationPhase !== "new-bootstrap" && rehydrationPhase !== "resume-bootstrap") rehydrationPhase = "step";
|
|
@@ -841,7 +905,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
841
905
|
? passiveContinuationMessages(event.messages as AgentMessage[], bootstrapContinuation)
|
|
842
906
|
: event.messages as AgentMessage[];
|
|
843
907
|
const messages = withoutPrivateValidation(sourceMessages);
|
|
844
|
-
return { messages: [runtimeContextMessage(snapshot, effectiveState, recentTransitions, invalidations, activeRehydrationPhase,
|
|
908
|
+
return { messages: [runtimeContextMessage(snapshot, effectiveState, recentTransitions, invalidations, activeRehydrationPhase, resolutionPending), ...messages] };
|
|
845
909
|
}
|
|
846
910
|
const trajectory = currentRunTrajectory(
|
|
847
911
|
event.messages as AgentMessage[],
|
|
@@ -851,7 +915,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
851
915
|
runAnchorTimestamp = trajectory.anchorTimestamp;
|
|
852
916
|
return {
|
|
853
917
|
messages: [
|
|
854
|
-
runtimeContextMessage(snapshot, effectiveState, recentTransitions, invalidations, activeRehydrationPhase,
|
|
918
|
+
runtimeContextMessage(snapshot, effectiveState, recentTransitions, invalidations, activeRehydrationPhase, resolutionPending),
|
|
855
919
|
...trajectory.messages,
|
|
856
920
|
],
|
|
857
921
|
};
|
|
@@ -905,31 +969,16 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
905
969
|
recordDiagnostic(`Assistant response ended with ${message.stopReason}`, "finalization", ctx, { content: message.content, terminalEligible });
|
|
906
970
|
return;
|
|
907
971
|
}
|
|
972
|
+
if (resolutionPending) return resolveFallbackTurn(ctx, message);
|
|
908
973
|
if (!terminalEligible) {
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
resolutionAttempts = Math.min(MAX_RESOLUTION_ATTEMPTS, resolutionAttempts + 1);
|
|
912
|
-
recordDiagnostic(`Terminal draft intercepted before State Flow eligibility (attempt ${resolutionAttempts}/${MAX_RESOLUTION_ATTEMPTS})`, "terminal-pending", ctx, {
|
|
913
|
-
content: message.content,
|
|
914
|
-
resolutionAttempt: resolutionAttempts,
|
|
915
|
-
terminalEligible,
|
|
916
|
-
});
|
|
917
|
-
if (resolutionAttempts < MAX_RESOLUTION_ATTEMPTS) {
|
|
918
|
-
continueForResolution();
|
|
919
|
-
} else if (!resolutionFailureReported) {
|
|
920
|
-
resolutionFailureReported = true;
|
|
921
|
-
ctx.ui.notify(`State Flow could not obtain final:true after ${MAX_RESOLUTION_ATTEMPTS} terminal attempts; committed state was preserved and no draft was accepted.`, "error");
|
|
922
|
-
}
|
|
923
|
-
return { message: { ...message, role: "assistant" as const, content: [] } };
|
|
974
|
+
beginFallbackResolution(ctx, message, "the terminal draft ended without State Flow eligibility");
|
|
975
|
+
return;
|
|
924
976
|
}
|
|
925
977
|
try {
|
|
926
978
|
validateFinalEligibility(scopeStates, skillReads.successful.values(), runtime!.causalBasis(), artifactReads.successful.values());
|
|
927
979
|
} catch (error) {
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
recordDiagnostic(error instanceof Error ? error.message : String(error), "terminal-pending", ctx, { content: message.content, terminalEligible });
|
|
931
|
-
continueForResolution();
|
|
932
|
-
return { message: { ...message, role: "assistant" as const, content: [] } };
|
|
980
|
+
beginFallbackResolution(ctx, message, error instanceof Error ? error.message : String(error));
|
|
981
|
+
return;
|
|
933
982
|
}
|
|
934
983
|
responseAwaitingReconciliation = true;
|
|
935
984
|
});
|
|
@@ -952,7 +1001,6 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
952
1001
|
ctx.ui.notify(`State Flow could not reconcile the final response: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
953
1002
|
} finally {
|
|
954
1003
|
responseAwaitingReconciliation = false;
|
|
955
|
-
terminalDraftIntercepted = false;
|
|
956
1004
|
}
|
|
957
1005
|
updateUi(ctx);
|
|
958
1006
|
});
|
package/lib/terminal.ts
CHANGED
|
@@ -23,7 +23,7 @@ Use read_state only for a concrete historical or scope-specific gap. It reads on
|
|
|
23
23
|
|
|
24
24
|
Use patch_state as the sole model-authored semantic mutation mechanism. Supply any combination of global, cwd, and session patches; all supplied scopes are validated and durably accepted as one atomic transition before further reasoning. Call patch_state alone in its assistant response; after its acknowledgement choose the next action from accepted state.
|
|
25
25
|
|
|
26
|
-
Every enabled iteration starts terminal-ineligible. Set final:true in a successful patch_state call when the iteration may finish at a later turn_end. final:true does not stop reasoning, tools, or later patch_state calls, and repeated final:true calls are allowed. Use {"final":true} when no semantic update is needed. If
|
|
26
|
+
Every enabled iteration starts terminal-ineligible. Set final:true in a successful patch_state call when the iteration may finish at a later turn_end. final:true does not stop reasoning, tools, or later patch_state calls, and repeated final:true calls are allowed. Use {"final":true} when no semantic update is needed. If you end a terminal turn without eligibility, runtime preserves that answer as the iteration response and starts bounded fallback turns whose only purpose is the final:true patch: call patch_state with any durable scope changes and final:true, or {"final":true} alone, and never restate or replace the answer. After two fallback turns without final:true the iteration closes with its preserved answer and current state. A final-only call creates no semantic transition. Never write response through patch_state; runtime records what was actually delivered at turn_end.
|
|
27
27
|
|
|
28
28
|
SCOPES: session is branch/run continuation, cwd is project state and Skills, global is cross-project state. Deleting an override affects only its scope and may reveal a parent value.
|
|
29
29
|
|