@llblab/pi-state-flow 0.15.0 → 0.16.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # Agent Instructions
2
2
 
3
- - Keep independent domain modules under `lib/`, mirror every domain with a same-named file under `tests/`, place cross-domain architecture checks in `tests/invariants.test.ts`, and keep `index.ts` as a minimal composition/public-export boundary.
3
+ - Keep independent domain modules under `lib/`, mirror every domain with a same-named file under `tests/`, place cross-domain architecture checks in `tests/invariants.test.ts`, and keep `index.ts` as a minimal public-export boundary. Keep `lib/extension.ts` as the Pi lifecycle composition root: it may wire configuration, domain capabilities, handlers, and event subscriptions, but low-level parsing, traversal, formatting, persistence, queue/worker mechanics, and diagnostic I/O belong to their existing owning domains.
4
4
  - Keep the extension opt-in and preserve clear attribution to SKILL.state wherever the inherited explicit-state approach is described.
5
5
  - Preserve Pi's native tool loop and complete inspectable session trace; project completed-run history only at user-run boundaries. The runtime-context builder owns model projection of the raw scope overlay; callers must not pre-project it. Retain persistent and current-run context-bearing custom messages from other extensions, plus the complete current-run trajectory, except State Flow's own validation feedback when it is represented separately.
6
6
  - Expose one canonical materialized state shape across global, CWD, and session scopes with exactly `artifacts`, `contract`, `working`, `intents`, and `response`, plus optional `lazy`; the first four are flexible semantic objects and `response` is the latest complete user-facing answer string where applicable. `intents` contains only active commitments to future action, remains hot by default, and must not become a planner, scheduler, task manager, or execution loop.
@@ -29,7 +29,7 @@
29
29
  - Treat every semantic `patch_state` as a strict inference barrier. Give it sequential execution mode; find the matching synchronized assistant through public parent traversal from the selected leaf without constructing a full branch 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.
30
30
  - 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.
31
31
  - 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.
32
- - 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.
32
+ - 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. Treat resource, document, memory, Skill, and agent locators as semantic references wherever context expresses them. Inside ordinary strings and prose, encode a semantic-state path as `$` immediately followed by one valid `read_state` path, for example `$effective.lazy.memory[7]`; the prefix distinguishes a reference from incidental path-like text and leaves room for future parsing. `{"$ref":"cwd.lazy.plan"}` remains the optional structured state-reference form; neither form is a runtime link type. External resource locators retain their native path, URI, Skill, or agent syntax. Resolve references explicitly through the appropriate read/tool when needed and infer no authority, existence, dependency, hydration, execution, or completion merely from their presence. Never scan, audit, or proactively resolve references merely to find broken ones. Only after one requested `read_state` value path is missing may the query domain perform one bounded reverse lookup over current model-patchable semantic planes for exact structured `$ref` and `$path` matches. When durable sources match, return a successful top-level `{value:null, hint:[...]}` diagnostic sentinel: every hint has `type:"dangling-reference"`, an action message, and at most three runtime-verified current owning paths. The null sentinel is never presented without `hint` for this case; keys, patch, and multi-path reads retain ordinary all-or-error semantics. Never scan runtime-owned `response`, and retain the ordinary missing-path error when no durable source matches. A match proves durable semantic provenance, not staleness; no match does not prove invention. The agent may then inspect ownership and patch a proven stale source while preserving surrounding meaning. Effective-state absence does not identify ownership, and unavailable history, inaccessible external resources, or transient read failure do not prove a dangling reference. 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.
33
33
  - 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.
34
34
  - 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.
35
35
  - Make state stewardship an ordinary model responsibility without a background loop or gratuitous full-state rewrite. Every handoff curates touched and obviously stale or mis-scoped visible branches: place new knowledge at the narrowest valid scope, merge fragmented facts, compress history into conclusions, and delete stale, completed, redundant, or low-value keys while preserving active commitments and evidence. At a completed feature/release/campaign, project switch, or active-version change, require one bounded scoped reconciliation before terminal completion; use targeted `read_state` when ownership is not visible, then write and verify the destination before deleting and verifying the source. Global is only established cross-project/user/environment knowledge, CWD is reusable project truth, and session is branch/run continuation.
package/BACKLOG.md CHANGED
@@ -1,3 +1,5 @@
1
1
  # BACKLOG
2
2
 
3
3
  Completed implementation belongs in [CHANGELOG.md](CHANGELOG.md); durable semantic contracts belong in [AGENTS.md](AGENTS.md) and [docs/architecture.md](docs/architecture.md).
4
+
5
+ No open work.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,18 @@
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.16.1: Resumed activation hotfix
8
+
9
+ - `Resumed activation`: Reasserts the selected session stream as a complete semantic cohort when `/state-flow-start` enables a resumed branch, so extension upgrades cannot misclassify retained session state as an omitted write while shared scopes still reconcile against their live owners.
10
+
11
+ ## 0.16.0: Proportional State Flow guidance
12
+
13
+ - `Operational Skill`: Adds the packaged `state-flow-guide` as an on-demand reference for concrete read, patch, inheritance, acquisition, finalization, and recovery problems without triggering memory audits or unsolicited cleanup.
14
+ - `Memory Skill`: Compresses `state-flow-memory` into one bounded curation procedure while preserving authority separation, intent cleanup, evidence boundaries, ownership checks, two-phase scope transfer, external acceptance verification, and active/passive finalization behavior.
15
+ - `Contract alignment`: Updates executable Skill discovery and release-package inventory checks for both Skills, removes obsolete documentation for retired read syntax, and defines state references as structured `$ref` values or `$`-prefixed `read_state` paths in prose without proactive link scanning.
16
+ - `Reference diagnostics`: When one requested value path is missing and exact durable sources exist, returns `{value:null, hint:[...]}` with a typed reconciliation message and at most three runtime-verified current owning paths. Keys, patch, batch, and unmatched reads remain all-or-error; no match never implies that the agent invented the path.
17
+ - `Composition root`: Reduces `lib/extension.ts` to higher-level Pi lifecycle wiring by moving patch presentation into `protocol`, branch traversal into `session`, diagnostic persistence into `logging`, and durable queue/worker lifecycle into `publication`, without adding domains or changing public behavior.
18
+
7
19
  ## 0.15.0: Intentional agency
8
20
 
9
21
  - `Intent semantic plane`: Adds hot, object-valued `intents` to global, CWD, session, and effective state. An intent is a selected commitment to future action, distinct from requirements in `contract`, observations or possibilities in `working`, and inactive supporting memory in `lazy`.
package/README.md CHANGED
@@ -64,12 +64,14 @@ The same semantic planes exist at every scope:
64
64
  - `response`: The latest complete answer, captured by the runtime.
65
65
  - `lazy`: Durable, versioned memory omitted from ordinary context until explicitly read.
66
66
 
67
- Memory overlays **global → project CWD → session**. Put reusable cross-project knowledge in global, project knowledge in CWD, and private task continuation in session. Hot planes carry what must matter now; `lazy` retains what may matter later without hydrating its body into every prompt. An intent stays hot only while its course remains chosen and disappears when fulfilled, abandoned, superseded, or impossible. It may carry a plain `{"$ref":"cwd.lazy.plan"}` pointer to supporting detail; State Flow never hydrates, executes, or completes that reference automatically.
67
+ Memory overlays **global → project CWD → session**. Put reusable cross-project knowledge in global, project knowledge in CWD, and private task continuation in session. Hot planes carry what must matter now; `lazy` retains what may matter later without hydrating its body into every prompt. An intent stays hot only while its course remains chosen and disappears when fulfilled, abandoned, superseded, or impossible. It may refer to supporting detail through a structured `{"$ref":"cwd.lazy.plan"}` value or a `$`-prefixed state path inside ordinary prose, such as `$effective.lazy.memory[7]`. Both remain semantic content interpreted by the agent: State Flow never parses, validates, hydrates, executes, or completes them automatically. The agent never scans references for breakage. Only when current work already follows one and a single value path is missing does State Flow perform a bounded exact reverse lookup. Matching durable sources produce a top-level `{value:null, hint:[...]}` sentinel whose typed hint names runtime-verified current owning paths and asks the agent to reconcile them. Keys, patch, batch, and unmatched reads retain ordinary all-or-error behavior; no match does not prove that the agent invented the path. The agent may then repair or remove a proven stale locator in its owning value.
68
68
 
69
69
  **Resuming an existing Pi session restores its selected State Flow state and enablement.** A genuinely new session starts with an empty session layer and inherits only shared global/CWD memory; it does not resume another session's private work. Tree navigation follows the selected branch, not whichever state happens to be at Git `HEAD`.
70
70
 
71
71
  The agent uses `read_state` for exact current or historical paths. Unscoped paths read the effective overlay; `global`, `cwd`, and `session` address ownership directly; `[n]` selects one of up to seven prior accepted transition boundaries. Bounded array ranges and `value`, `keys`, or `patch` projections support progressive reads without hydrating whole lazy collections. Git-backed stores retain older committed history separately.
72
72
 
73
+ Two packaged Skills keep guidance proportional: `state-flow-guide` resolves concrete operational questions about reading, patching, inheritance, acquisition, finalization, and recovery; `state-flow-memory` performs one bounded explicit or phase-boundary curation. Neither runs background maintenance.
74
+
73
75
  ## Boundaries worth knowing
74
76
 
75
77
  - `Not a second agent loop`: State Flow adds memory to Pi; it does not run background reasoning or replace session controls.
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { formatPatchStateArguments, normalizePatchStateArguments } from "./protocol.ts";
2
3
  import { type StateFlowTelegramLoader } from "./telegram.ts";
3
4
  import { type MaterializedState, type StateScope } from "./state.ts";
4
5
  export interface StateFlowExtensionOptions {
@@ -17,11 +18,8 @@ export interface StateFlowExtensionOptions {
17
18
  tools?: boolean;
18
19
  };
19
20
  }
21
+ export { formatPatchStateArguments, normalizePatchStateArguments };
20
22
  export declare const PATCH_STATE_TOOL_NAME = "patch_state";
21
23
  export declare const READ_STATE_TOOL_NAME = "read_state";
22
24
  export declare const MAX_FALLBACK_ATTEMPTS: number;
23
- /** Keep successful patch JSON valid while separating adjacent scopes and memory sections visually. */
24
- export declare function formatPatchStateArguments(args: unknown): string;
25
- /** Normalize a bounded compatibility superset without advertising aliases in the model-facing contract. */
26
- export declare function normalizePatchStateArguments(args: unknown): any;
27
25
  export default function stateFlowExtension(pi: ExtensionAPI, options?: StateFlowExtensionOptions): void;
@@ -2,97 +2,38 @@ import { randomUUID } from "node:crypto";
2
2
  import { StringEnum, Type } from "@earendil-works/pi-ai";
3
3
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
4
  import { Text } from "@earendil-works/pi-tui";
5
- import { assistantToolCallCount, finalizedAssistantResponse, stateFlowProtocol } from "./protocol.js";
5
+ import { assistantToolCallCount, finalizedAssistantResponse, formatPatchStateArguments, normalizePatchStateArguments, separatedFailure, separatedOutput, stateFlowProtocol } from "./protocol.js";
6
6
  import { createPassiveContinuation, currentRunTrajectory, lazyNavigationHint, passiveContinuationMessages, runtimeContextMessage, syntheticUser, VALIDATION_MESSAGE_TYPE, withoutPrivateValidation } from "./context.js";
7
7
  import { ArtifactReadTracker } from "./acquisition.js";
8
8
  import { loadStateFlowConfig } from "./config.js";
9
9
  import { createStateFlowTelegramAdapter } from "./telegram.js";
10
- import { isAbsolute, relative, resolve, sep } from "node:path";
10
+ import { isAbsolute, resolve } from "node:path";
11
11
  import { SkillReadTracker } from "./skills.js";
12
12
  import { emptySnapshot, migrationFailure, persistableSnapshot, RevisionUnavailableError } from "./snapshot.js";
13
13
  import { readNativeSessionHeader } from "./continuation.js";
14
14
  import { MissingSessionRuntimeError, SharedScopeRemovalConflictError, TemporalRuntime } from "./runtime.js";
15
15
  import { emptyState, overlayStates, projectStateForModel } from "./state.js";
16
16
  import { commitScopedTransition, stageAtomicScopePatches, stageScopedTransition, validateFinalEligibility } from "./transition.js";
17
- import { discoverSnapshotData, hasPriorConversation, isNewSession, SNAPSHOT_ENTRY_TYPE } from "./session.js";
17
+ import { discoverSnapshotData, findAssistantToolBatch, findPassiveStopBoundary, hasPriorConversation, isNewSession, retainsPhysicalSessionProjection, SNAPSHOT_ENTRY_TYPE } from "./session.js";
18
18
  import { compactStatus, detailedStatus, STATUS_KEY } from "./status.js";
19
19
  import { completeRun, prepareRun, resumeEpisode, startEpisode, stopEpisode } from "./episode.js";
20
20
  import { recoverSnapshot } from "./recovery.js";
21
- import { resolveRemotePublicationPolicy, serializeRemotePublicationPolicyDocument } from "./publication.js";
22
- import { coalescePublicationTarget, createPublicationQueue } from "./publication.js";
23
- import { acquirePublicationWorkerLease, loadPublicationQueue, publicationQueuePath, removePublicationQueue, savePublicationQueue } from "./publication.js";
24
- import { runPublicationWorker } from "./publication.js";
21
+ import { loadPublicationQueue, publicationQueuePath, PublicationWorkerController, resolveRemotePublicationPolicy, serializeRemotePublicationPolicyDocument } from "./publication.js";
25
22
  import { getKnowledgeRoot, GlobalMarkdownDiscovery } from "./discovery.js";
26
23
  import { canonicalJson, isObject, sameJson } from "./json.js";
27
24
  import { readProjectedState, readStatePath } from "./query.js";
28
25
  import { cwdScopeKey, resolveSessionAddress, sessionScopeKey, } from "./durable.js";
29
26
  import { projectRecentTransitionsWithLimit, RECENT_TRANSITION_LIMIT } from "./history.js";
30
- import { appendStateFlowDiagnostic, projectDiagnosticContent, stateFlowLogPath } from "./logging.js";
27
+ import { StateFlowDiagnosticWriter, stateFlowLogPath } from "./logging.js";
31
28
  import { isGitCommitAncestor, pushGitCommit, pushGitTarget, resolveGitPushDestination } from "./git.js";
32
29
  import { ORDINARY_ARTIFACT_COMPILER, planArtifactInvalidation, } from "./artifact.js";
33
30
  import { hasCompactionSizedTranscript, planStateFlowCompaction, shouldRequestStateFlowCompaction, stateFlowCompactionResult } from "./compaction.js";
31
+ export { formatPatchStateArguments, normalizePatchStateArguments };
34
32
  export const PATCH_STATE_TOOL_NAME = "patch_state";
35
33
  export const READ_STATE_TOOL_NAME = "read_state";
36
34
  export const MAX_FALLBACK_ATTEMPTS = 2;
37
35
  const PASSIVE_STOP_ENTRY_TYPE = "state-flow-passive-stop";
38
36
  const PUBLICATION_SHUTDOWN_WAIT_MS = 2_000;
39
- const PATCH_DISPLAY_SECTION_KEYS = new Set([
40
- "global",
41
- "cwd",
42
- "session",
43
- "artifacts",
44
- "contract",
45
- "working",
46
- "response",
47
- "final",
48
- ]);
49
- /** Keep successful patch JSON valid while separating adjacent scopes and memory sections visually. */
50
- export function formatPatchStateArguments(args) {
51
- const seenAtIndent = new Set();
52
- return JSON.stringify(args, null, 2).split("\n").flatMap((line) => {
53
- const indent = line.length - line.trimStart().length;
54
- const match = /^(\s+)"([^"]+)":/.exec(line);
55
- if (match === null || !PATCH_DISPLAY_SECTION_KEYS.has(match[2])) {
56
- for (const seenIndent of seenAtIndent) {
57
- if (seenIndent > indent)
58
- seenAtIndent.delete(seenIndent);
59
- }
60
- return [line];
61
- }
62
- const separator = seenAtIndent.has(indent) ? [""] : [];
63
- seenAtIndent.add(indent);
64
- return [...separator, line];
65
- }).join("\n");
66
- }
67
- /** Normalize a bounded compatibility superset without advertising aliases in the model-facing contract. */
68
- export function normalizePatchStateArguments(args) {
69
- if (!isObject(args) || !Object.hasOwn(args, "final"))
70
- return args;
71
- const value = args.final;
72
- let final;
73
- if (typeof value === "boolean")
74
- final = value;
75
- else if (value === 1)
76
- final = true;
77
- else if (value === 0)
78
- final = false;
79
- else if (typeof value === "string" && value.trim().toLowerCase() === "true")
80
- final = true;
81
- else if (typeof value === "string" && value.trim().toLowerCase() === "false")
82
- final = false;
83
- else
84
- return args;
85
- return { ...args, final };
86
- }
87
- /** Keep tool output visually separated from its heading with exactly one leading newline. */
88
- function separatedOutput(text) {
89
- return `\n${text.replace(/^\n+/, "")}`;
90
- }
91
- /** Keep a failed tool invocation visually separated from its rendered error without changing error semantics. */
92
- function separatedFailure(error) {
93
- const message = error instanceof Error ? error.message : String(error);
94
- return new Error(separatedOutput(message), error instanceof Error ? { cause: error } : undefined);
95
- }
96
37
  export default function stateFlowExtension(pi, options = {}) {
97
38
  const agentDir = options.agentDir ?? getAgentDir();
98
39
  const loadedConfig = loadStateFlowConfig(agentDir, options.repositoryRoot);
@@ -125,15 +66,19 @@ export default function stateFlowExtension(pi, options = {}) {
125
66
  let pendingPublication;
126
67
  let rehydrationPhase;
127
68
  let turnPublicationTarget;
128
- const activePublicationWorkers = new Map();
129
- let publicationStopped = false;
130
69
  let publicationShutdown;
131
70
  const repositoryRoot = resolve(options.repositoryRoot ?? config.directory);
71
+ const diagnosticWriter = new StateFlowDiagnosticWriter(config.logging, stateFlowLogPath(agentDir), repositoryRoot, (message) => activeContext?.ui.notify(message, "warning"));
72
+ const publicationWorker = new PublicationWorkerController({
73
+ resolveDestination: () => resolveGitPushDestination(repositoryRoot),
74
+ isAncestor: (ancestor, descendant) => isGitCommitAncestor(repositoryRoot, ancestor, descendant),
75
+ push: (destination, target, signal) => pushGitTarget(repositoryRoot, destination, target, signal),
76
+ onDiverged: (dropped, target) => activeContext && recordDiagnostic(`Retired publication queue target ${dropped.target} after a journal lineage rewrite; retargeting to ${target}`, "publication-conflict", activeContext),
77
+ });
132
78
  const skillReads = new SkillReadTracker();
133
79
  const artifactReads = new ArtifactReadTracker();
134
80
  const globalMarkdown = new GlobalMarkdownDiscovery(options.knowledgeRoot ?? getKnowledgeRoot(agentDir));
135
81
  let artifactInvalidations = [];
136
- let loggingWarningReported = false;
137
82
  let telegramStartPending = false;
138
83
  function sessionAddress(ctx) {
139
84
  return resolveSessionAddress(ctx.sessionManager.getSessionFile(), ctx.sessionManager.getSessionId(), ctx.sessionManager.getHeader()?.timestamp);
@@ -184,29 +129,6 @@ export default function stateFlowExtension(pi, options = {}) {
184
129
  skillReads.clear();
185
130
  artifactReads.clear();
186
131
  }
187
- function passiveStopBoundary(ctx) {
188
- for (const entry of [...ctx.sessionManager.getBranch()].reverse()) {
189
- try {
190
- if (entry?.type !== "custom" || entry.customType !== PASSIVE_STOP_ENTRY_TYPE)
191
- continue;
192
- const { at, from, reset, owner } = entry.data ?? {};
193
- if (reset === true && owner === ctx.sessionManager.getSessionId())
194
- return undefined;
195
- if (typeof at === "number" && Number.isSafeInteger(at) && at >= 0)
196
- return {
197
- at,
198
- ...(typeof from === "number" && Number.isSafeInteger(from) && from >= 0 ? { from } : {}),
199
- };
200
- }
201
- catch {
202
- // A hostile unrelated branch entry cannot manufacture or suppress a valid marker.
203
- }
204
- }
205
- return undefined;
206
- }
207
- function retainsPhysicalSessionProjection(reason) {
208
- return reason === undefined || reason === "startup" || reason === "reload" || reason === "resume";
209
- }
210
132
  function deferArtifactRefresh() {
211
133
  artifactInvalidations = [];
212
134
  artifactReads.setCandidates([]);
@@ -252,22 +174,6 @@ export default function stateFlowExtension(pi, options = {}) {
252
174
  ? [...new Set([...active, ...owned])]
253
175
  : active.filter((name) => !owned.includes(name)));
254
176
  }
255
- function assistantToolBatch(ctx, toolCallId) {
256
- for (let cursor = ctx.sessionManager.getLeafEntry(); cursor; cursor = cursor.parentId ? ctx.sessionManager.getEntry(cursor.parentId) : undefined) {
257
- const entry = cursor;
258
- if (entry.type !== "message" || entry.message?.role !== "assistant" || !Array.isArray(entry.message.content))
259
- continue;
260
- const calls = entry.message.content.filter((block) => {
261
- return typeof block === "object" && block !== null
262
- && block.type === "toolCall"
263
- && typeof block.id === "string"
264
- && typeof block.name === "string";
265
- });
266
- if (calls.some(({ id }) => id === toolCallId))
267
- return calls.map(({ name }) => name);
268
- }
269
- return undefined;
270
- }
271
177
  function recordPublication(publication, ctx) {
272
178
  const revision = publication.revision ?? publication.commit;
273
179
  if (revision !== undefined)
@@ -294,8 +200,8 @@ export default function stateFlowExtension(pi, options = {}) {
294
200
  return;
295
201
  turnPublicationTarget = target;
296
202
  try {
297
- enqueueTurnPublication(ctx);
298
- launchPublicationWorker();
203
+ enqueueTurnPublication();
204
+ publicationWorker.launch();
299
205
  }
300
206
  catch (error) {
301
207
  ctx.ui.notify(`State Flow accepted the local commit; remote publication is deferred: ${error instanceof Error ? error.message : String(error)}`, "warning");
@@ -338,104 +244,17 @@ export default function stateFlowExtension(pi, options = {}) {
338
244
  persist();
339
245
  return true;
340
246
  }
341
- function enqueueTurnPublication(ctx) {
247
+ function enqueueTurnPublication() {
342
248
  const target = turnPublicationTarget;
343
249
  turnPublicationTarget = undefined;
344
- if (!target)
345
- return;
346
- const destination = resolveGitPushDestination(repositoryRoot);
347
- if (!destination)
348
- return;
349
- const path = publicationQueuePath(destination);
350
- const previous = loadPublicationQueue(path);
351
- const next = previous
352
- ? coalescePublicationTarget(previous, destination, target, (ancestor, descendant) => isGitCommitAncestor(repositoryRoot, ancestor, descendant), {
353
- onDivergedLineage: (dropped) => recordDiagnostic(`Retired publication queue target ${dropped.target} after a journal lineage rewrite; retargeting to ${target}`, "publication-conflict", ctx),
354
- })
355
- : createPublicationQueue(destination, target);
356
- savePublicationQueue(path, next, previous);
357
- }
358
- function launchPublicationWorker() {
359
- if (publicationStopped)
360
- return;
361
- let destination;
362
- try {
363
- destination = resolveGitPushDestination(repositoryRoot);
364
- }
365
- catch (error) {
366
- if (error instanceof Error && /ENOENT/.test(error.message))
367
- return;
368
- throw error;
369
- }
370
- if (!destination)
371
- return;
372
- const path = publicationQueuePath(destination);
373
- if (activePublicationWorkers.has(path))
374
- return;
375
- let queued;
376
- let lease;
377
- try {
378
- queued = loadPublicationQueue(path);
379
- if (!queued)
380
- return;
381
- lease = acquirePublicationWorkerLease(path);
382
- }
383
- catch {
384
- return;
385
- }
386
- if (!lease)
387
- return;
388
- const controller = new AbortController();
389
- const done = runPublicationWorker(queued, ({ target }) => pushGitTarget(repositoryRoot, destination, target, controller.signal), () => loadPublicationQueue(path) ?? queued, (ancestor, descendant) => isGitCommitAncestor(repositoryRoot, ancestor, descendant)).then((result) => {
390
- if (publicationStopped)
391
- return; // Late outcomes belong to an unconfirmed queue, not the replacement generation.
392
- const current = loadPublicationQueue(path);
393
- if (!current)
394
- return;
395
- if (result.next === undefined) {
396
- if (current.target === result.attempted.target)
397
- removePublicationQueue(path, current);
398
- return;
399
- }
400
- if (current.target === result.attempted.target || result.next.target === current.target) {
401
- savePublicationQueue(path, result.next, current);
402
- }
403
- }).catch(() => {
404
- // Queue/CAS truth remains durable; status and a later activation expose retry.
405
- }).finally(() => {
406
- activePublicationWorkers.delete(path);
407
- try {
408
- lease.release();
409
- if (!publicationStopped && loadPublicationQueue(path)?.status === "pending")
410
- launchPublicationWorker();
411
- }
412
- catch {
413
- // Failed lease cleanup or malformed persistence stays inert until retry or repair.
414
- }
415
- });
416
- activePublicationWorkers.set(path, { controller, done });
250
+ if (target)
251
+ publicationWorker.enqueue(target);
417
252
  }
418
253
  function shutdownPublicationWorkers(ctx) {
419
- publicationStopped = true;
420
- return publicationShutdown ??= (async () => {
421
- const workers = [...activePublicationWorkers.values()];
422
- for (const { controller } of workers)
423
- controller.abort();
424
- if (workers.length === 0)
425
- return;
426
- let timeout;
427
- try {
428
- const completed = await Promise.race([
429
- Promise.all(workers.map(({ done }) => done)).then(() => true),
430
- new Promise((resolve) => { timeout = setTimeout(() => resolve(false), PUBLICATION_SHUTDOWN_WAIT_MS); }),
431
- ]);
432
- if (!completed)
433
- ctx.ui.notify(`State Flow push cleanup is unconfirmed after ${PUBLICATION_SHUTDOWN_WAIT_MS}ms; worker leases remain held until child exit.`, "warning");
434
- }
435
- finally {
436
- clearTimeout(timeout);
437
- }
438
- })();
254
+ return publicationShutdown ??= publicationWorker.shutdown(PUBLICATION_SHUTDOWN_WAIT_MS).then((completed) => {
255
+ if (!completed)
256
+ ctx.ui.notify(`State Flow push cleanup is unconfirmed after ${PUBLICATION_SHUTDOWN_WAIT_MS}ms; worker leases remain held until child exit.`, "warning");
257
+ });
439
258
  }
440
259
  function retryPendingPush(ctx) {
441
260
  if (pendingPublication === undefined || !runtime?.view)
@@ -447,8 +266,8 @@ export default function stateFlowExtension(pi, options = {}) {
447
266
  if (mode === "turn-end") {
448
267
  turnPublicationTarget = target;
449
268
  try {
450
- enqueueTurnPublication(ctx);
451
- launchPublicationWorker();
269
+ enqueueTurnPublication();
270
+ publicationWorker.launch();
452
271
  }
453
272
  catch (error) {
454
273
  ctx.ui.notify(`State Flow retained local state; asynchronous publication recovery is deferred: ${error instanceof Error ? error.message : String(error)}`, "warning");
@@ -655,7 +474,7 @@ export default function stateFlowExtension(pi, options = {}) {
655
474
  ctx.ui.notify(`State Flow restored disabled: ${snapshot.meta.validation.error}`, "error");
656
475
  }
657
476
  if (retainsPhysicalSessionProjection(sessionStartReason) && runtime?.view) {
658
- const boundary = passiveStopBoundary(ctx);
477
+ const boundary = findPassiveStopBoundary(ctx.sessionManager.getBranch(), ctx.sessionManager.getSessionId(), PASSIVE_STOP_ENTRY_TYPE);
659
478
  if (boundary !== undefined) {
660
479
  const continuation = createPassiveContinuation(projectStateForModel(overlayStates(scopeStates.global, scopeStates.cwd, scopeStates.session)), boundary.at, boundary.from);
661
480
  if (!snapshot.config.enabled)
@@ -679,34 +498,7 @@ export default function stateFlowExtension(pi, options = {}) {
679
498
  updateUi(ctx);
680
499
  }
681
500
  function recordDiagnostic(error, category, ctx, extras = {}) {
682
- if (!config.logging)
683
- return;
684
- try {
685
- const path = stateFlowLogPath(agentDir);
686
- const fromRepository = relative(repositoryRoot, path);
687
- if (fromRepository === "" || (!isAbsolute(fromRepository) && fromRepository !== ".." && !fromRepository.startsWith(`..${sep}`))) {
688
- throw new Error("diagnostic path overlaps the State Flow repository");
689
- }
690
- appendStateFlowDiagnostic(path, {
691
- at: new Date().toISOString(),
692
- sessionId: sessionAddress(ctx).id,
693
- cwd: resolve(ctx.cwd),
694
- category,
695
- error,
696
- ...(extras.content === undefined ? {} : { content: projectDiagnosticContent(extras.content) }),
697
- ...(extras.input === undefined ? {} : { input: extras.input }),
698
- ...(extras.tool === undefined ? {} : { tool: extras.tool }),
699
- ...(extras.toolCallId === undefined ? {} : { toolCallId: extras.toolCallId }),
700
- ...(extras.resolutionAttempt === undefined ? {} : { resolutionAttempt: extras.resolutionAttempt }),
701
- ...(extras.terminalEligible === undefined ? {} : { terminalEligible: extras.terminalEligible }),
702
- });
703
- }
704
- catch (failure) {
705
- if (loggingWarningReported)
706
- return;
707
- loggingWarningReported = true;
708
- ctx.ui.notify(`State Flow could not write diagnostics: ${failure instanceof Error ? failure.message : String(failure)}`, "warning");
709
- }
501
+ diagnosticWriter.record(sessionAddress(ctx).id, ctx.cwd, error, category, extras);
710
502
  }
711
503
  function continueFallbackResolution(lastWarning) {
712
504
  resolutionPending = true;
@@ -965,8 +757,11 @@ export default function stateFlowExtension(pi, options = {}) {
965
757
  snapshot.meta.remotePublication = serializeRemotePublicationPolicyDocument(resolveRemotePublicationPolicy(existingBranch ? undefined : config.remotePublication, { legacyRuntime: existingBranch }));
966
758
  }
967
759
  branchHasSnapshot = true;
760
+ // Activation reasserts the selected session stream as a complete cohort. A resumed
761
+ // branch may have no reusable temporal revision after an extension upgrade; a
762
+ // runtime-only write would then reject its selected session as an omitted change.
968
763
  const publication = runtime.view
969
- ? runtime.promote(snapshot) ?? runtime.publish(snapshot)
764
+ ? runtime.promote(snapshot) ?? runtime.publish(snapshot, true)
970
765
  : runtime.initialize(snapshot, true, undefined, branchStartsWithoutRuntime);
971
766
  recordPolicyPublication(publication, ctx);
972
767
  installScopeStates();
@@ -1171,7 +966,7 @@ export default function stateFlowExtension(pi, options = {}) {
1171
966
  pi.on("tool_call", (event, ctx) => {
1172
967
  if (!snapshot.config.enabled)
1173
968
  return;
1174
- const batch = assistantToolBatch(ctx, event.toolCallId);
969
+ const batch = findAssistantToolBatch(ctx.sessionManager, event.toolCallId);
1175
970
  const patchCalls = batch?.filter((name) => name === PATCH_STATE_TOOL_NAME).length ?? 0;
1176
971
  if (patchCalls > 0) {
1177
972
  if (patchCalls !== 1) {
@@ -1245,9 +1040,9 @@ export default function stateFlowExtension(pi, options = {}) {
1245
1040
  responseCommitted = true;
1246
1041
  bootstrapContinuation = undefined;
1247
1042
  rehydrationPhase = "step";
1248
- enqueueTurnPublication(ctx);
1043
+ enqueueTurnPublication();
1249
1044
  if (snapshot.meta.remotePublication?.mode === "turn-end")
1250
- launchPublicationWorker();
1045
+ publicationWorker.launch();
1251
1046
  completedRunAccepted = !wasBootstrap;
1252
1047
  }
1253
1048
  catch (error) {
@@ -1279,7 +1074,7 @@ export default function stateFlowExtension(pi, options = {}) {
1279
1074
  startStateFlow(ctx);
1280
1075
  }
1281
1076
  if (snapshot.meta.remotePublication?.mode === "turn-end")
1282
- launchPublicationWorker();
1077
+ publicationWorker.launch();
1283
1078
  if (!completedRunAccepted || compactionStopped || !snapshot.config.enabled || snapshot.meta.bootstrap || resolutionPending
1284
1079
  || compactionInFlight || !ctx.isIdle() || ctx.hasPendingMessages() || !snapshot.meta.durableBase
1285
1080
  || !shouldRequestStateFlowCompaction(ctx.getContextUsage()))
@@ -1304,7 +1099,7 @@ export default function stateFlowExtension(pi, options = {}) {
1304
1099
  restoreActiveBranch(ctx, event.reason);
1305
1100
  retryPendingPush(ctx);
1306
1101
  if (snapshot.meta.remotePublication?.mode === "turn-end")
1307
- launchPublicationWorker();
1102
+ publicationWorker.launch();
1308
1103
  updateUi(ctx);
1309
1104
  void telegram.ensure();
1310
1105
  });
@@ -23,3 +23,21 @@ export declare function projectDiagnosticContent(content: unknown): StateFlowDia
23
23
  /** Diagnostic JSONL lives beneath the active Pi agent directory, never inside the state repository. */
24
24
  export declare function stateFlowLogPath(agentDir: string): string;
25
25
  export declare function appendStateFlowDiagnostic(path: string, record: StateFlowDiagnosticRecord): void;
26
+ export interface DiagnosticExtras {
27
+ content?: unknown;
28
+ input?: unknown;
29
+ tool?: string;
30
+ toolCallId?: string;
31
+ resolutionAttempt?: number;
32
+ terminalEligible?: boolean;
33
+ }
34
+ /** Own diagnostic path safety, projection, persistence, and one-shot failure reporting. */
35
+ export declare class StateFlowDiagnosticWriter {
36
+ private warningReported;
37
+ private readonly enabled;
38
+ private readonly path;
39
+ private readonly repositoryRoot;
40
+ private readonly notify;
41
+ constructor(enabled: boolean, path: string, repositoryRoot: string, notify: (message: string) => void);
42
+ record(sessionId: string, cwd: string, error: string, category: StateFlowDiagnosticCategory, extras?: DiagnosticExtras): void;
43
+ }
@@ -1,6 +1,6 @@
1
1
  // Domain: opt-in diagnostic capture for rejected State Flow resolutions.
2
2
  import { appendFileSync, mkdirSync } from "node:fs";
3
- import { dirname, join } from "node:path";
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
4
  import { isObject } from "./json.js";
5
5
  /** Preserve exact text blocks and block boundaries; reasoning bodies are never duplicated. */
6
6
  export function projectDiagnosticContent(content) {
@@ -22,3 +22,46 @@ export function appendStateFlowDiagnostic(path, record) {
22
22
  mkdirSync(dirname(path), { recursive: true });
23
23
  appendFileSync(path, `${JSON.stringify(record)}\n`, { encoding: "utf8", mode: 0o600 });
24
24
  }
25
+ /** Own diagnostic path safety, projection, persistence, and one-shot failure reporting. */
26
+ export class StateFlowDiagnosticWriter {
27
+ warningReported = false;
28
+ enabled;
29
+ path;
30
+ repositoryRoot;
31
+ notify;
32
+ constructor(enabled, path, repositoryRoot, notify) {
33
+ this.enabled = enabled;
34
+ this.path = path;
35
+ this.repositoryRoot = repositoryRoot;
36
+ this.notify = notify;
37
+ }
38
+ record(sessionId, cwd, error, category, extras = {}) {
39
+ if (!this.enabled)
40
+ return;
41
+ try {
42
+ const fromRepository = relative(this.repositoryRoot, this.path);
43
+ if (fromRepository === "" || (!isAbsolute(fromRepository) && fromRepository !== ".." && !fromRepository.startsWith(`..${sep}`))) {
44
+ throw new Error("diagnostic path overlaps the State Flow repository");
45
+ }
46
+ appendStateFlowDiagnostic(this.path, {
47
+ at: new Date().toISOString(),
48
+ sessionId,
49
+ cwd: resolve(cwd),
50
+ category,
51
+ error,
52
+ ...(extras.content === undefined ? {} : { content: projectDiagnosticContent(extras.content) }),
53
+ ...(extras.input === undefined ? {} : { input: extras.input }),
54
+ ...(extras.tool === undefined ? {} : { tool: extras.tool }),
55
+ ...(extras.toolCallId === undefined ? {} : { toolCallId: extras.toolCallId }),
56
+ ...(extras.resolutionAttempt === undefined ? {} : { resolutionAttempt: extras.resolutionAttempt }),
57
+ ...(extras.terminalEligible === undefined ? {} : { terminalEligible: extras.terminalEligible }),
58
+ });
59
+ }
60
+ catch (failure) {
61
+ if (this.warningReported)
62
+ return;
63
+ this.warningReported = true;
64
+ this.notify(`State Flow could not write diagnostics: ${failure instanceof Error ? failure.message : String(failure)}`);
65
+ }
66
+ }
67
+ }
@@ -1,5 +1,12 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  export type { StateDocument } from "./state.ts";
3
+ /** Keep successful patch JSON valid while separating adjacent scopes and memory sections visually. */
4
+ export declare function formatPatchStateArguments(args: unknown): string;
5
+ /** Normalize a bounded compatibility superset without advertising aliases in the model-facing contract. */
6
+ export declare function normalizePatchStateArguments(args: unknown): any;
7
+ /** Keep visible tool output separated from its heading without changing semantics. */
8
+ export declare function separatedOutput(text: string): string;
9
+ export declare function separatedFailure(error: unknown): Error;
3
10
  /** The compact model-facing contract. Semantic writes never travel through terminal prose. */
4
11
  export declare function stateFlowProtocol(bootstrap: boolean): string;
5
12
  export declare function assistantToolCallCount(content: unknown): number;