@llblab/pi-kit 0.25.0 → 0.27.0

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.
Files changed (169) hide show
  1. package/BACKLOG.md +5 -1
  2. package/CHANGELOG.md +11 -0
  3. package/README.md +10 -8
  4. package/node_modules/@llblab/pi-actors/AGENTS.md +2 -0
  5. package/node_modules/@llblab/pi-actors/CHANGELOG.md +4 -1
  6. package/node_modules/@llblab/pi-actors/LICENSE +21 -0
  7. package/node_modules/@llblab/pi-actors/README.md +1 -1
  8. package/node_modules/@llblab/pi-actors/docs/coordinator-delivery.md +1 -1
  9. package/node_modules/@llblab/pi-actors/package.json +4 -3
  10. package/node_modules/@llblab/pi-claude-usage/AGENTS.md +6 -3
  11. package/node_modules/@llblab/pi-claude-usage/BACKLOG.md +2 -1
  12. package/node_modules/@llblab/pi-claude-usage/CHANGELOG.md +8 -0
  13. package/node_modules/@llblab/pi-claude-usage/README.md +48 -3
  14. package/node_modules/@llblab/pi-claude-usage/index.ts +8 -1159
  15. package/node_modules/@llblab/pi-claude-usage/lib/extension.ts +30 -0
  16. package/node_modules/@llblab/pi-claude-usage/lib/fast.ts +24 -0
  17. package/node_modules/@llblab/pi-claude-usage/lib/query.ts +146 -0
  18. package/node_modules/@llblab/pi-claude-usage/lib/status-format.ts +297 -0
  19. package/node_modules/@llblab/pi-claude-usage/lib/status.ts +366 -0
  20. package/node_modules/@llblab/pi-claude-usage/lib/telegram.ts +44 -0
  21. package/node_modules/@llblab/pi-claude-usage/lib/usage-store.ts +221 -0
  22. package/node_modules/@llblab/pi-claude-usage/lib/usage.ts +128 -0
  23. package/node_modules/@llblab/pi-claude-usage/package.json +9 -5
  24. package/node_modules/@llblab/pi-clean-room/AGENTS.md +1 -0
  25. package/node_modules/@llblab/pi-clean-room/CHANGELOG.md +5 -0
  26. package/node_modules/@llblab/pi-clean-room/LICENSE +21 -0
  27. package/node_modules/@llblab/pi-clean-room/README.md +1 -1
  28. package/node_modules/@llblab/pi-clean-room/package.json +3 -2
  29. package/node_modules/@llblab/pi-codex-usage/AGENTS.md +9 -6
  30. package/node_modules/@llblab/pi-codex-usage/BACKLOG.md +2 -1
  31. package/node_modules/@llblab/pi-codex-usage/CHANGELOG.md +17 -0
  32. package/node_modules/@llblab/pi-codex-usage/README.md +75 -17
  33. package/node_modules/@llblab/pi-codex-usage/index.ts +8 -1602
  34. package/node_modules/@llblab/pi-codex-usage/lib/extension.ts +25 -0
  35. package/node_modules/@llblab/pi-codex-usage/lib/fast.ts +23 -0
  36. package/node_modules/@llblab/pi-codex-usage/lib/query.ts +368 -0
  37. package/node_modules/@llblab/pi-codex-usage/lib/status-format.ts +347 -0
  38. package/node_modules/@llblab/pi-codex-usage/lib/status.ts +435 -0
  39. package/node_modules/@llblab/pi-codex-usage/lib/telegram.ts +45 -0
  40. package/node_modules/@llblab/pi-codex-usage/lib/usage-store.ts +229 -0
  41. package/node_modules/@llblab/pi-codex-usage/lib/usage.ts +425 -0
  42. package/node_modules/@llblab/pi-codex-usage/package.json +11 -6
  43. package/node_modules/@llblab/pi-command-fast/AGENTS.md +7 -0
  44. package/node_modules/@llblab/pi-command-fast/BACKLOG.md +9 -0
  45. package/node_modules/@llblab/pi-command-fast/CHANGELOG.md +7 -0
  46. package/node_modules/@llblab/pi-command-fast/LICENSE +21 -0
  47. package/node_modules/@llblab/pi-command-fast/README.md +42 -0
  48. package/node_modules/@llblab/pi-command-fast/dist/command.d.ts +8 -0
  49. package/node_modules/@llblab/pi-command-fast/dist/command.js +52 -0
  50. package/node_modules/@llblab/pi-command-fast/dist/index.d.ts +3 -0
  51. package/node_modules/@llblab/pi-command-fast/dist/index.js +3 -0
  52. package/node_modules/@llblab/pi-command-fast/dist/models-json.d.ts +10 -0
  53. package/node_modules/@llblab/pi-command-fast/dist/models-json.js +81 -0
  54. package/node_modules/@llblab/pi-command-fast/package.json +49 -0
  55. package/node_modules/@llblab/pi-grow-loop/AGENTS.md +1 -0
  56. package/node_modules/@llblab/pi-grow-loop/CHANGELOG.md +4 -1
  57. package/node_modules/@llblab/pi-grow-loop/LICENSE +21 -0
  58. package/node_modules/@llblab/pi-grow-loop/README.md +1 -1
  59. package/node_modules/@llblab/pi-grow-loop/package.json +3 -2
  60. package/node_modules/@llblab/pi-state-flow/AGENTS.md +7 -6
  61. package/node_modules/@llblab/pi-state-flow/BACKLOG.md +13 -5
  62. package/node_modules/@llblab/pi-state-flow/CHANGELOG.md +16 -1
  63. package/node_modules/@llblab/pi-state-flow/LICENSE +21 -0
  64. package/node_modules/@llblab/pi-state-flow/README.md +117 -35
  65. package/node_modules/@llblab/pi-state-flow/dist/lib/acquisition.d.ts +24 -1
  66. package/node_modules/@llblab/pi-state-flow/dist/lib/acquisition.js +80 -1
  67. package/node_modules/@llblab/pi-state-flow/dist/lib/compaction.d.ts +18 -1
  68. package/node_modules/@llblab/pi-state-flow/dist/lib/compaction.js +41 -1
  69. package/node_modules/@llblab/pi-state-flow/dist/lib/extension.js +346 -303
  70. package/node_modules/@llblab/pi-state-flow/dist/lib/git.d.ts +31 -2
  71. package/node_modules/@llblab/pi-state-flow/dist/lib/git.js +74 -5
  72. package/node_modules/@llblab/pi-state-flow/dist/lib/operation.d.ts +37 -0
  73. package/node_modules/@llblab/pi-state-flow/dist/lib/operation.js +59 -0
  74. package/node_modules/@llblab/pi-state-flow/dist/lib/ownership.d.ts +31 -0
  75. package/node_modules/@llblab/pi-state-flow/dist/lib/ownership.js +117 -0
  76. package/node_modules/@llblab/pi-state-flow/dist/lib/protocol.js +7 -7
  77. package/node_modules/@llblab/pi-state-flow/dist/lib/query.js +1 -1
  78. package/node_modules/@llblab/pi-state-flow/dist/lib/session.d.ts +10 -1
  79. package/node_modules/@llblab/pi-state-flow/dist/lib/session.js +60 -1
  80. package/node_modules/@llblab/pi-state-flow/dist/lib/snapshot.d.ts +6 -0
  81. package/node_modules/@llblab/pi-state-flow/dist/lib/snapshot.js +8 -5
  82. package/node_modules/@llblab/pi-state-flow/dist/lib/status.d.ts +2 -0
  83. package/node_modules/@llblab/pi-state-flow/dist/lib/status.js +28 -0
  84. package/node_modules/@llblab/pi-state-flow/dist/lib/transition.js +6 -1
  85. package/node_modules/@llblab/pi-state-flow/dist/package.json +10 -9
  86. package/node_modules/@llblab/pi-state-flow/dist/skills/state-flow-guide/SKILL.md +14 -6
  87. package/node_modules/@llblab/pi-state-flow/dist/skills/state-flow-memory/SKILL.md +2 -2
  88. package/node_modules/@llblab/pi-state-flow/docs/README.md +19 -9
  89. package/node_modules/@llblab/pi-state-flow/docs/agent-contract-relocation.md +4 -4
  90. package/node_modules/@llblab/pi-state-flow/docs/architecture.md +646 -89
  91. package/node_modules/@llblab/pi-state-flow/docs/compatibility.md +116 -37
  92. package/node_modules/@llblab/pi-state-flow/docs/filesystem-recovery.md +118 -21
  93. package/node_modules/@llblab/pi-state-flow/docs/fork-contract.md +70 -8
  94. package/node_modules/@llblab/pi-state-flow/docs/lazy-state.md +88 -14
  95. package/node_modules/@llblab/pi-state-flow/docs/performance.md +83 -66
  96. package/node_modules/@llblab/pi-state-flow/docs/temporal-acceptance.md +391 -62
  97. package/node_modules/@llblab/pi-state-flow/docs/usage.md +317 -61
  98. package/node_modules/@llblab/pi-state-flow/lib/acquisition.ts +85 -1
  99. package/node_modules/@llblab/pi-state-flow/lib/compaction.ts +49 -2
  100. package/node_modules/@llblab/pi-state-flow/lib/extension.ts +342 -301
  101. package/node_modules/@llblab/pi-state-flow/lib/git.ts +77 -5
  102. package/node_modules/@llblab/pi-state-flow/lib/operation.ts +75 -0
  103. package/node_modules/@llblab/pi-state-flow/lib/ownership.ts +120 -0
  104. package/node_modules/@llblab/pi-state-flow/lib/protocol.ts +7 -8
  105. package/node_modules/@llblab/pi-state-flow/lib/query.ts +1 -1
  106. package/node_modules/@llblab/pi-state-flow/lib/runtime.ts +1 -1
  107. package/node_modules/@llblab/pi-state-flow/lib/session.ts +52 -1
  108. package/node_modules/@llblab/pi-state-flow/lib/snapshot.ts +8 -7
  109. package/node_modules/@llblab/pi-state-flow/lib/status.ts +29 -0
  110. package/node_modules/@llblab/pi-state-flow/lib/transition.ts +5 -1
  111. package/node_modules/@llblab/pi-state-flow/package.json +10 -9
  112. package/node_modules/@llblab/pi-state-flow/skills/state-flow-guide/SKILL.md +14 -6
  113. package/node_modules/@llblab/pi-state-flow/skills/state-flow-memory/SKILL.md +2 -2
  114. package/node_modules/@llblab/pi-telegram/BACKLOG.md +1 -0
  115. package/node_modules/@llblab/pi-telegram/CHANGELOG.md +10 -0
  116. package/node_modules/@llblab/pi-telegram/README.md +1 -1
  117. package/node_modules/@llblab/pi-telegram/dist/lib/bindings.d.ts +4 -1
  118. package/node_modules/@llblab/pi-telegram/dist/lib/bindings.js +16 -12
  119. package/node_modules/@llblab/pi-telegram/dist/lib/bus-follower.d.ts +1 -1
  120. package/node_modules/@llblab/pi-telegram/dist/lib/bus-follower.js +7 -1
  121. package/node_modules/@llblab/pi-telegram/dist/lib/commands.d.ts +12 -3
  122. package/node_modules/@llblab/pi-telegram/dist/lib/commands.js +137 -83
  123. package/node_modules/@llblab/pi-telegram/dist/lib/extension.js +26 -0
  124. package/node_modules/@llblab/pi-telegram/dist/lib/lifecycle.d.ts +57 -2
  125. package/node_modules/@llblab/pi-telegram/dist/lib/lifecycle.js +109 -4
  126. package/node_modules/@llblab/pi-telegram/dist/lib/model.js +2 -4
  127. package/node_modules/@llblab/pi-telegram/dist/lib/status.d.ts +3 -1
  128. package/node_modules/@llblab/pi-telegram/dist/lib/status.js +31 -1
  129. package/node_modules/@llblab/pi-telegram/dist/lib/sync.js +4 -4
  130. package/node_modules/@llblab/pi-telegram/dist/lib/threads.d.ts +1 -0
  131. package/node_modules/@llblab/pi-telegram/dist/lib/threads.js +17 -4
  132. package/node_modules/@llblab/pi-telegram/dist/lib/workspace-retirement.d.ts +2 -2
  133. package/node_modules/@llblab/pi-telegram/dist/lib/workspace-retirement.js +48 -12
  134. package/node_modules/@llblab/pi-telegram/dist/package.json +1 -1
  135. package/node_modules/@llblab/pi-telegram/docs/architecture.md +6 -5
  136. package/node_modules/@llblab/pi-telegram/docs/multi-instance-bus.md +2 -0
  137. package/node_modules/@llblab/pi-telegram/docs/public-api.md +2 -2
  138. package/node_modules/@llblab/pi-telegram/docs/ui-style.md +4 -0
  139. package/node_modules/@llblab/pi-telegram/lib/bindings.ts +17 -10
  140. package/node_modules/@llblab/pi-telegram/lib/bus-follower.ts +8 -2
  141. package/node_modules/@llblab/pi-telegram/lib/commands.ts +135 -97
  142. package/node_modules/@llblab/pi-telegram/lib/extension.ts +25 -0
  143. package/node_modules/@llblab/pi-telegram/lib/lifecycle.ts +140 -4
  144. package/node_modules/@llblab/pi-telegram/lib/model.ts +2 -4
  145. package/node_modules/@llblab/pi-telegram/lib/status.ts +30 -1
  146. package/node_modules/@llblab/pi-telegram/lib/sync.ts +4 -4
  147. package/node_modules/@llblab/pi-telegram/lib/threads.ts +21 -3
  148. package/node_modules/@llblab/pi-telegram/lib/workspace-retirement.ts +46 -13
  149. package/node_modules/@llblab/pi-telegram/package.json +1 -1
  150. package/node_modules/jsonc-parser/CHANGELOG.md +76 -0
  151. package/node_modules/jsonc-parser/LICENSE.md +21 -0
  152. package/node_modules/jsonc-parser/README.md +364 -0
  153. package/node_modules/jsonc-parser/SECURITY.md +41 -0
  154. package/node_modules/jsonc-parser/lib/esm/impl/edit.js +185 -0
  155. package/node_modules/jsonc-parser/lib/esm/impl/format.js +261 -0
  156. package/node_modules/jsonc-parser/lib/esm/impl/parser.js +659 -0
  157. package/node_modules/jsonc-parser/lib/esm/impl/scanner.js +443 -0
  158. package/node_modules/jsonc-parser/lib/esm/impl/string-intern.js +29 -0
  159. package/node_modules/jsonc-parser/lib/esm/main.d.ts +351 -0
  160. package/node_modules/jsonc-parser/lib/esm/main.js +178 -0
  161. package/node_modules/jsonc-parser/lib/umd/impl/edit.js +201 -0
  162. package/node_modules/jsonc-parser/lib/umd/impl/format.js +275 -0
  163. package/node_modules/jsonc-parser/lib/umd/impl/parser.js +682 -0
  164. package/node_modules/jsonc-parser/lib/umd/impl/scanner.js +456 -0
  165. package/node_modules/jsonc-parser/lib/umd/impl/string-intern.js +42 -0
  166. package/node_modules/jsonc-parser/lib/umd/main.d.ts +351 -0
  167. package/node_modules/jsonc-parser/lib/umd/main.js +194 -0
  168. package/node_modules/jsonc-parser/package.json +37 -0
  169. package/package.json +8 -8
@@ -1,12 +1,41 @@
1
1
  /** Await a coherent capture; hosts without cancellation may refuse contention instead of hanging Abort. */
2
2
  export declare function backupCurrentStateFlowFiles(repositoryRoot: string, signal?: AbortSignal, waitForLock?: boolean): Promise<string | undefined>;
3
3
  /** Skip overlapping pushes; the next accepted turn can push the latest HEAD. */
4
- export declare function startStateFlowBackupPush(repositoryRoot: string, onFailure: (error: unknown) => void, onSuccess?: () => void): boolean;
4
+ export declare function startStateFlowBackupPush(repositoryRoot: string, onFailure: (error: unknown) => void, onSuccess?: () => void, signal?: AbortSignal): boolean;
5
5
  /** Resolve only after the push process has closed (including timeout termination). */
6
6
  export declare function awaitInFlightBackupPushes(repositoryRoot: string): Promise<void>;
7
7
  /** Push the current backup commit to its explicitly configured branch remote without blocking settlement. */
8
- export declare function pushCurrentStateFlowBackup(repositoryRoot: string): Promise<{
8
+ export declare function pushCurrentStateFlowBackup(repositoryRoot: string, signal?: AbortSignal): Promise<{
9
9
  commit: string;
10
10
  remote: string;
11
11
  ref: string;
12
12
  } | undefined>;
13
+ /**
14
+ * Settled-turn backup obligation owned by one extension instance: an accepted
15
+ * publication makes a backup due, an accepted turn permits it at settlement,
16
+ * and one lifetime cancels owned captures/pushes without touching accepted state.
17
+ */
18
+ export declare class SettledTurnBackup {
19
+ #private;
20
+ /** An accepted canonical publication makes the next settled-turn backup due. */
21
+ markPublished(): void;
22
+ /** An accepted turn permits the due backup at its settlement. */
23
+ markTurnAccepted(): void;
24
+ /** Forget the current turn's permission without dropping a due backup. */
25
+ clearTurn(): void;
26
+ /** Consume the accepted-turn permission; true only when a backup is also due. */
27
+ takeSettledTurn(): boolean;
28
+ /** Lifetime signal for owned captures and pushes. */
29
+ get lifetime(): AbortSignal;
30
+ /** Cancel owned work and the due backup, then open a fresh lifetime. */
31
+ cancel(): void;
32
+ /** Cancel owned work for shutdown without opening a new lifetime. */
33
+ abort(): void;
34
+ /** Track one owned capture until it settles. */
35
+ track<T>(operation: Promise<T>): Promise<T>;
36
+ /** Owned captures still in flight. */
37
+ get operations(): Promise<unknown>[];
38
+ /** True once per failure streak; a successful push resets it. */
39
+ claimPushFailureNotice(): boolean;
40
+ resetPushFailureNotice(): void;
41
+ }
@@ -204,18 +204,20 @@ export function backupCurrentStateFlowFiles(repositoryRoot, signal, waitForLock
204
204
  return withBackupLock(repositoryRoot, (root) => commitCurrentOwnedFiles(root, currentHead(root), signal, waitForLock), signal, waitForLock);
205
205
  }
206
206
  /** Skip overlapping pushes; the next accepted turn can push the latest HEAD. */
207
- export function startStateFlowBackupPush(repositoryRoot, onFailure, onSuccess) {
207
+ export function startStateFlowBackupPush(repositoryRoot, onFailure, onSuccess, signal) {
208
208
  const root = resolve(repositoryRoot);
209
- if (activePushes.has(root))
209
+ if (signal?.aborted || activePushes.has(root))
210
210
  return false;
211
- const push = pushCurrentStateFlowBackup(root).then((result) => {
212
- if (result) {
211
+ const push = pushCurrentStateFlowBackup(root, signal).then((result) => {
212
+ if (result && !signal?.aborted) {
213
213
  try {
214
214
  onSuccess?.();
215
215
  }
216
216
  catch { /* Reporting cannot change push acceptance. */ }
217
217
  }
218
218
  }, (error) => {
219
+ if (signal?.aborted)
220
+ return;
219
221
  try {
220
222
  onFailure(error);
221
223
  }
@@ -231,15 +233,17 @@ export async function awaitInFlightBackupPushes(repositoryRoot) {
231
233
  await push;
232
234
  }
233
235
  /** Push the current backup commit to its explicitly configured branch remote without blocking settlement. */
234
- export function pushCurrentStateFlowBackup(repositoryRoot) {
236
+ export function pushCurrentStateFlowBackup(repositoryRoot, signal) {
235
237
  return new Promise((resolvePush, rejectPush) => {
236
238
  let root;
237
239
  let commit;
238
240
  let destination;
239
241
  try {
242
+ signal?.throwIfAborted();
240
243
  root = assertRepositoryRoot(repositoryRoot);
241
244
  commit = currentHead(root);
242
245
  destination = configuredPushDestination(root);
246
+ signal?.throwIfAborted();
243
247
  }
244
248
  catch (error) {
245
249
  rejectPush(new Error(redactGitDiagnostic(error instanceof Error ? error.message : String(error))));
@@ -282,6 +286,7 @@ export function pushCurrentStateFlowBackup(repositoryRoot) {
282
286
  return;
283
287
  settled = true;
284
288
  clearTimeout(timeout);
289
+ signal?.removeEventListener("abort", cancelled);
285
290
  if (error)
286
291
  rejectPush(error);
287
292
  else
@@ -297,5 +302,69 @@ export function pushCurrentStateFlowBackup(repositoryRoot) {
297
302
  child.stderr?.destroy(); });
298
303
  child.once("close", (code, endedBy) => finish(failure ?? (code === 0 ? undefined
299
304
  : new Error(`Git backup push failed (${endedBy ?? code}): ${redactGitDiagnostic(stderr.trim()) || "no diagnostic output"}`))));
305
+ function cancelled() {
306
+ terminate(signal?.reason instanceof Error ? signal.reason : new Error("Git backup push cancelled"));
307
+ }
308
+ signal?.addEventListener("abort", cancelled, { once: true });
309
+ if (signal?.aborted)
310
+ cancelled();
300
311
  });
301
312
  }
313
+ /**
314
+ * Settled-turn backup obligation owned by one extension instance: an accepted
315
+ * publication makes a backup due, an accepted turn permits it at settlement,
316
+ * and one lifetime cancels owned captures/pushes without touching accepted state.
317
+ */
318
+ export class SettledTurnBackup {
319
+ #turnAccepted = false;
320
+ #pending = false;
321
+ #lifetime = new AbortController();
322
+ #pushFailureNotified = false;
323
+ #operations = new Set();
324
+ /** An accepted canonical publication makes the next settled-turn backup due. */
325
+ markPublished() { this.#pending = true; }
326
+ /** An accepted turn permits the due backup at its settlement. */
327
+ markTurnAccepted() { this.#turnAccepted = true; }
328
+ /** Forget the current turn's permission without dropping a due backup. */
329
+ clearTurn() { this.#turnAccepted = false; }
330
+ /** Consume the accepted-turn permission; true only when a backup is also due. */
331
+ takeSettledTurn() {
332
+ if (!this.#turnAccepted)
333
+ return false;
334
+ this.#turnAccepted = false;
335
+ if (!this.#pending)
336
+ return false;
337
+ this.#pending = false;
338
+ return true;
339
+ }
340
+ /** Lifetime signal for owned captures and pushes. */
341
+ get lifetime() { return this.#lifetime.signal; }
342
+ /** Cancel owned work and the due backup, then open a fresh lifetime. */
343
+ cancel() {
344
+ this.#lifetime.abort();
345
+ this.#lifetime = new AbortController();
346
+ this.#pending = false;
347
+ }
348
+ /** Cancel owned work for shutdown without opening a new lifetime. */
349
+ abort() { this.#lifetime.abort(); }
350
+ /** Track one owned capture until it settles. */
351
+ async track(operation) {
352
+ this.#operations.add(operation);
353
+ try {
354
+ return await operation;
355
+ }
356
+ finally {
357
+ this.#operations.delete(operation);
358
+ }
359
+ }
360
+ /** Owned captures still in flight. */
361
+ get operations() { return [...this.#operations]; }
362
+ /** True once per failure streak; a successful push resets it. */
363
+ claimPushFailureNotice() {
364
+ if (this.#pushFailureNotified)
365
+ return false;
366
+ this.#pushFailureNotified = true;
367
+ return true;
368
+ }
369
+ resetPushFailureNotice() { this.#pushFailureNotified = false; }
370
+ }
@@ -0,0 +1,37 @@
1
+ /** Minimal shape of a cancellable owned lifecycle operation. */
2
+ export interface OwnedOperation {
3
+ readonly controller: AbortController;
4
+ operation?: Promise<unknown>;
5
+ }
6
+ /**
7
+ * At most one current owner per lifecycle concern. A newer claim supersedes by
8
+ * explicit cancellation, and identity-guarded release prevents a late
9
+ * completion from clearing newer work.
10
+ */
11
+ export declare class OwnedOperationSlot<E extends OwnedOperation> {
12
+ #private;
13
+ /** The current owner, if any. */
14
+ get current(): E | undefined;
15
+ /** True while `entry` still owns the slot. */
16
+ owns(entry: E): boolean;
17
+ /** Install a new owner; callers cancel a previous owner explicitly when supersession requires it. */
18
+ claim(entry: E): E;
19
+ /** Abort and forget the current owner; returns its operation for optional awaiting. */
20
+ cancel(): E["operation"] | undefined;
21
+ /** Forget `entry` only if it still owns the slot. */
22
+ release(entry: E): void;
23
+ /** Attach `operation` to `entry` and remember it until it settles, optionally releasing ownership then. */
24
+ track<P extends NonNullable<E["operation"]>>(entry: E, operation: P, releaseOnSettle?: boolean): P;
25
+ /** Tracked operations not yet settled, including superseded ones. */
26
+ get inflight(): Promise<unknown>[];
27
+ }
28
+ /** A renewable cancellation lifetime: ending it aborts every holder of the current signal. */
29
+ export declare class RenewableLifetime {
30
+ #private;
31
+ /** Signal of the current lifetime. */
32
+ get signal(): AbortSignal;
33
+ /** Abort current holders and open a fresh lifetime. */
34
+ renew(reason?: unknown): void;
35
+ /** Abort current holders without opening a new lifetime (shutdown). */
36
+ end(reason?: unknown): void;
37
+ }
@@ -0,0 +1,59 @@
1
+ // Domain: one cancellable lifecycle owner slot shared by Start, inactive-mode persistence,
2
+ // branch restoration, inference preparation and response reconciliation.
3
+ /**
4
+ * At most one current owner per lifecycle concern. A newer claim supersedes by
5
+ * explicit cancellation, and identity-guarded release prevents a late
6
+ * completion from clearing newer work.
7
+ */
8
+ export class OwnedOperationSlot {
9
+ #current;
10
+ #inflight = new Set();
11
+ /** The current owner, if any. */
12
+ get current() { return this.#current; }
13
+ /** True while `entry` still owns the slot. */
14
+ owns(entry) { return this.#current === entry; }
15
+ /** Install a new owner; callers cancel a previous owner explicitly when supersession requires it. */
16
+ claim(entry) {
17
+ this.#current = entry;
18
+ return entry;
19
+ }
20
+ /** Abort and forget the current owner; returns its operation for optional awaiting. */
21
+ cancel() {
22
+ const entry = this.#current;
23
+ entry?.controller.abort();
24
+ this.#current = undefined;
25
+ return entry?.operation;
26
+ }
27
+ /** Forget `entry` only if it still owns the slot. */
28
+ release(entry) {
29
+ if (this.#current === entry)
30
+ this.#current = undefined;
31
+ }
32
+ /** Attach `operation` to `entry` and remember it until it settles, optionally releasing ownership then. */
33
+ track(entry, operation, releaseOnSettle = true) {
34
+ entry.operation = operation;
35
+ this.#inflight.add(operation);
36
+ const settle = () => {
37
+ this.#inflight.delete(operation);
38
+ if (releaseOnSettle)
39
+ this.release(entry);
40
+ };
41
+ void operation.then(settle, settle);
42
+ return operation;
43
+ }
44
+ /** Tracked operations not yet settled, including superseded ones. */
45
+ get inflight() { return [...this.#inflight]; }
46
+ }
47
+ /** A renewable cancellation lifetime: ending it aborts every holder of the current signal. */
48
+ export class RenewableLifetime {
49
+ #controller = new AbortController();
50
+ /** Signal of the current lifetime. */
51
+ get signal() { return this.#controller.signal; }
52
+ /** Abort current holders and open a fresh lifetime. */
53
+ renew(reason) {
54
+ this.#controller.abort(reason);
55
+ this.#controller = new AbortController();
56
+ }
57
+ /** Abort current holders without opening a new lifetime (shutdown). */
58
+ end(reason) { this.#controller.abort(reason); }
59
+ }
@@ -0,0 +1,31 @@
1
+ import { type JsonObject, type JsonValue } from "./json.ts";
2
+ import type { SemanticState, StateScope } from "./state.ts";
3
+ /** Planes whose object keys an intent may own by structured reference. */
4
+ export type OwnedPlane = "working" | "lazy";
5
+ /** One same-scope object-key target of an intent ownership reference. */
6
+ export interface OwnedPath {
7
+ plane: OwnedPlane;
8
+ keys: string[];
9
+ }
10
+ /**
11
+ * Parse one structured `$ref` target as an ownership path of `scope`.
12
+ * Cross-scope, unscoped, `effective`, historical, plane-root, array-element
13
+ * and non-`working`/`lazy` targets are not ownership targets.
14
+ */
15
+ export declare function parseOwnedPath(scope: StateScope, ref: string): OwnedPath | undefined;
16
+ /** Extract unique ownership targets from structured references anywhere inside one intent value. */
17
+ export declare function extractOwnedPaths(scope: StateScope, value: JsonValue): OwnedPath[];
18
+ /**
19
+ * Compute the same-scope ownership cascade for intent keys removed between
20
+ * `before` and `after` (the state after authored operations). A target is
21
+ * kept while any remaining intent references it, an ancestor or a descendant;
22
+ * missing targets are skipped. The result is minimal (no target below
23
+ * another) and deterministically ordered.
24
+ */
25
+ export declare function computeIntentCascade(scope: StateScope, before: SemanticState, after: SemanticState): OwnedPath[];
26
+ /** Express cascade targets as explicit nested object-key deletions. */
27
+ export declare function cascadeDeletionPatch(paths: readonly OwnedPath[]): JsonObject;
28
+ /** Render an ownership target as its scoped `read_state` path. */
29
+ export declare function formatOwnedPath(scope: StateScope, path: OwnedPath): string;
30
+ /** Top-level `working`/`lazy` keys that at least one current intent of `scope` owns. */
31
+ export declare function ownedTopLevelKeys(scope: StateScope, state: SemanticState): Record<OwnedPlane, Set<string>>;
@@ -0,0 +1,117 @@
1
+ import { isObject } from "./json.js";
2
+ const OWNED_PLANES = new Set(["working", "lazy"]);
3
+ // Same key grammar as read_state value paths; array selectors never parse.
4
+ const OBJECT_KEY = /^[A-Za-z_$][A-Za-z0-9_$-]*$/;
5
+ /**
6
+ * Parse one structured `$ref` target as an ownership path of `scope`.
7
+ * Cross-scope, unscoped, `effective`, historical, plane-root, array-element
8
+ * and non-`working`/`lazy` targets are not ownership targets.
9
+ */
10
+ export function parseOwnedPath(scope, ref) {
11
+ const parts = ref.split(".");
12
+ if (parts.length < 3 || parts[0] !== scope || !OWNED_PLANES.has(parts[1]))
13
+ return undefined;
14
+ const keys = parts.slice(2);
15
+ if (!keys.every((key) => OBJECT_KEY.test(key)))
16
+ return undefined;
17
+ return { plane: parts[1], keys };
18
+ }
19
+ function pathId(path) {
20
+ return JSON.stringify([path.plane, ...path.keys]);
21
+ }
22
+ /** Extract unique ownership targets from structured references anywhere inside one intent value. */
23
+ export function extractOwnedPaths(scope, value) {
24
+ const found = new Map();
25
+ const visit = (node) => {
26
+ if (Array.isArray(node)) {
27
+ for (const item of node)
28
+ visit(item);
29
+ return;
30
+ }
31
+ if (!isObject(node))
32
+ return;
33
+ if (typeof node.$ref === "string") {
34
+ const path = parseOwnedPath(scope, node.$ref);
35
+ if (path)
36
+ found.set(pathId(path), path);
37
+ }
38
+ for (const key of Object.keys(node))
39
+ if (key !== "$ref" || typeof node[key] !== "string")
40
+ visit(node[key]);
41
+ };
42
+ visit(value);
43
+ return [...found.values()];
44
+ }
45
+ function related(left, right) {
46
+ if (left.plane !== right.plane)
47
+ return false;
48
+ const length = Math.min(left.keys.length, right.keys.length);
49
+ for (let index = 0; index < length; index++)
50
+ if (left.keys[index] !== right.keys[index])
51
+ return false;
52
+ return true;
53
+ }
54
+ function exists(state, path) {
55
+ let node = state[path.plane];
56
+ for (const key of path.keys) {
57
+ if (!isObject(node) || !Object.hasOwn(node, key))
58
+ return false;
59
+ node = node[key];
60
+ }
61
+ return true;
62
+ }
63
+ /**
64
+ * Compute the same-scope ownership cascade for intent keys removed between
65
+ * `before` and `after` (the state after authored operations). A target is
66
+ * kept while any remaining intent references it, an ancestor or a descendant;
67
+ * missing targets are skipped. The result is minimal (no target below
68
+ * another) and deterministically ordered.
69
+ */
70
+ export function computeIntentCascade(scope, before, after) {
71
+ const previous = isObject(before.intents) ? before.intents : {};
72
+ const remaining = isObject(after.intents) ? after.intents : {};
73
+ const deleted = Object.keys(previous).filter((key) => !Object.hasOwn(remaining, key));
74
+ if (deleted.length === 0)
75
+ return [];
76
+ const candidates = new Map();
77
+ for (const key of deleted)
78
+ for (const path of extractOwnedPaths(scope, previous[key]))
79
+ candidates.set(pathId(path), path);
80
+ if (candidates.size === 0)
81
+ return [];
82
+ const retained = Object.values(remaining).flatMap((value) => extractOwnedPaths(scope, value));
83
+ const owned = [...candidates.values()].filter((path) => !retained.some((other) => related(path, other)) && exists(after, path));
84
+ return owned
85
+ .filter((path) => !owned.some((other) => other.keys.length < path.keys.length && related(path, other)))
86
+ .sort((left, right) => pathId(left).localeCompare(pathId(right)));
87
+ }
88
+ /** Express cascade targets as explicit nested object-key deletions. */
89
+ export function cascadeDeletionPatch(paths) {
90
+ const patch = {};
91
+ const define = (target, key, value) => Object.defineProperty(target, key, { value, enumerable: true, configurable: true, writable: true });
92
+ for (const path of paths) {
93
+ if (!Object.hasOwn(patch, path.plane))
94
+ define(patch, path.plane, {});
95
+ let node = patch[path.plane];
96
+ for (const key of path.keys.slice(0, -1)) {
97
+ if (!Object.hasOwn(node, key))
98
+ define(node, key, {});
99
+ node = node[key];
100
+ }
101
+ define(node, path.keys.at(-1), null);
102
+ }
103
+ return patch;
104
+ }
105
+ /** Render an ownership target as its scoped `read_state` path. */
106
+ export function formatOwnedPath(scope, path) {
107
+ return [scope, path.plane, ...path.keys].join(".");
108
+ }
109
+ /** Top-level `working`/`lazy` keys that at least one current intent of `scope` owns. */
110
+ export function ownedTopLevelKeys(scope, state) {
111
+ const owned = { working: new Set(), lazy: new Set() };
112
+ const intents = isObject(state.intents) ? state.intents : {};
113
+ for (const value of Object.values(intents))
114
+ for (const path of extractOwnedPaths(scope, value))
115
+ owned[path.plane].add(path.keys[0]);
116
+ return owned;
117
+ }
@@ -84,24 +84,24 @@ export function stateFlowProtocol(bootstrap) {
84
84
  return `State Flow is enabled. It owns durable memory.
85
85
 
86
86
  ${bootstrapProtocol}STATE:
87
- - intents: chosen active commitments; detail may stay lazy; remove when fulfilled, abandoned, superseded, or impossible.
88
- - contract: durable requirements, decisions, rejections, interfaces, compiled knowledge.
89
- - working: facts, validation, failures, domain state, unresolved work, continuation.
87
+ - intents: queue of chosen actions; work from them; remove when fulfilled, abandoned, superseded, or impossible.
88
+ - contract: durable requirements, decisions, rejections, interfaces.
89
+ - working: temporary context of intents: facts, validation, failures, domain state.
90
90
  - artifacts: source-path routing metadata; descriptions do not imply body acquisition.
91
- - response: previous answer; runtime stores the exact accepted answer at turn_end (empty=""). Ordinary assistant completion needs no finalization patch.
91
+ - response: previous answer; runtime stores the exact accepted answer at turn_end (empty="").
92
92
  - lazy: retrieve explicitly.
93
93
 
94
94
  SCOPES: Use the narrowest scope: session=branch/run continuation by default; cwd=reusable project truth; global=established cross-project/user/environment knowledge.
95
95
 
96
- READ: Use read_state for concrete scope/retained-history gaps. lazy_navigation lists bounded effective lazy keys, not bodies. Unscoped=effective; effective/global/cwd/session select overlay or owner. Arrays use indices or [start..end]; keys gives structure, patch the intersected change. ${TASK_DRIVEN_HISTORY}
96
+ READ: Use read_state for concrete scope/retained-history gaps. lazy_navigation lists bounded effective lazy keys, not bodies. ${TASK_DRIVEN_HISTORY}
97
97
 
98
- WRITE: patch_state is the sole model-authored semantic mutation mechanism; all supplied scopes are validated and durably accepted as one atomic transition. Call alone in an assistant response; await acceptance. Global/CWD use current canonical values after cancelable lock waiting. Correct repeats succeed without new revisions. ${PATCH_RESULT_PROTOCOL}
98
+ WRITE: patch_state is the sole model-authored semantic mutation mechanism; all supplied scopes are validated and durably accepted as one atomic transition. Global/CWD use current canonical values after cancelable lock waiting. Correct repeats succeed without new revisions. ${PATCH_RESULT_PROTOCOL}
99
99
 
100
100
  PATCH: Use global/cwd/session object patches for material updates, not acknowledgments. Omit empty scopes. artifacts/contract/working/intents are objects; lazy is ordinary JSON. Omitted fields persist. Never patch runtime config/meta/response. Objects merge recursively; arrays/primitives replace. An object containing only canonical "[N]" keys recursively patches array elements. Indexed deletion is forbidden; nested object null deletes; materialized null is forbidden.
101
101
 
102
102
  MEMORY: Treat every patch as reconciliation rather than append-only notes: merge superseded fragments, remove obsolete progress. Preserve commitments, open questions, consequential results and exact continuation; distinguish requirements, decisions, observations, conclusions and hypotheses. Exclude secrets, raw history, transient progress, speculation and unsupported claims; retain decision-relevant uncertainty. Curate touched state; cleanup and scope reviews require an explicit user request. Proven moves use targeted read_state and one atomic multi-scope patch, then verify both owners. External transfers need verified acceptance before deletion. Never invent memory changes.
103
103
 
104
- REFS: State refs use {"$ref":"cwd.lazy.plan"} or \`$cwd.lazy.plan\` in text. Resolve only when needed; infer no authority, hydration, execution, or completion. Hint paths are current reference owners, not relocated targets or proof of staleness. Fix proven stale refs only as needed; never scan refs or history offsets.
104
+ REFS: State refs use {"$ref":"cwd.lazy.plan"} or \`$cwd.lazy.plan\` in text. In an intent, $ref owns a same-scope working/lazy key; deleting the intent deletes keys no other intent refs (supersede in one patch). Text refs only use. Before deleting, save survivors unowned: results to working/contract/broader scope, abandonment reasons to contract. Unowned entries are fine. Resolve only when needed; infer no authority, hydration, execution, or completion. Hint paths are current reference owners, not relocated targets or proof of staleness. Fix proven stale refs only as needed; never scan refs or history offsets.
105
105
 
106
106
  ACQUISITION: Read only for a concrete gap, exact source/edit, invalidation, contradiction/failure, or explicit request; changed source fingerprints require rereading.
107
107
  ARTIFACTS: Compile acquired invalidated artifacts at artifacts[exact path] in the reported scope (global/cwd/session), with a description; never relocate or invent global copies. Runtime owns all artifact/Skill provenance.
@@ -67,7 +67,7 @@ function parseValuePath(path) {
67
67
  rest = rest.slice(index[0].length);
68
68
  continue;
69
69
  }
70
- throw new Error("Invalid State Flow read path selector");
70
+ throw new Error("Invalid State Flow read path selector; object keys must match [A-Za-z_$][A-Za-z0-9_$-]* (ASCII), array selectors use [N] or [start..end]");
71
71
  }
72
72
  return { root, selectors };
73
73
  }
@@ -1,4 +1,4 @@
1
- import { type InactiveMode } from "./snapshot.ts";
1
+ import { type InactiveMode, type StateFlowMode } from "./snapshot.ts";
2
2
  export declare const SNAPSHOT_ENTRY_TYPE = "state-flow-snapshot";
3
3
  interface BranchEntry {
4
4
  type?: unknown;
@@ -26,6 +26,8 @@ export interface PassiveStopBoundary {
26
26
  persistenceError?: string;
27
27
  /** The inactive mode selected by that failed change; legacy markers omit it. */
28
28
  mode?: InactiveMode;
29
+ /** Native-only Off choice; canonical runtime mode is deliberately not updated. */
30
+ memoryDeferred?: true;
29
31
  }
30
32
  export interface SnapshotDiscovery {
31
33
  candidates: unknown[];
@@ -33,6 +35,13 @@ export interface SnapshotDiscovery {
33
35
  }
34
36
  /** Enumerate active-branch snapshots newest-first while containing hostile entries. */
35
37
  export declare function discoverSnapshotData(branch: readonly BranchEntry[]): SnapshotDiscovery;
38
+ /** Read native mode policy only; semantic checkpoint validity remains the recovery owner's concern. */
39
+ export declare function findBranchPolicy(branch: readonly BranchEntry[], sessionId: string | undefined, stopEntryType: string | undefined, inactiveMode: InactiveMode): {
40
+ mode: StateFlowMode;
41
+ persistenceError?: string;
42
+ } | undefined;
43
+ /** Native policy bookkeeping retains an unacquired fork across extension reloads. */
44
+ export declare function hasPendingFork(branch: readonly BranchEntry[], sessionId: string, entryType: string): boolean;
36
45
  export declare function snapshotDataNewestFirst(branch: readonly BranchEntry[]): unknown[];
37
46
  export declare function latestSnapshotData(branch: readonly BranchEntry[]): unknown;
38
47
  export declare function hasPriorConversation(branch: readonly BranchEntry[]): boolean;
@@ -1,4 +1,4 @@
1
- import { parseRetainedPiCheckpoint } from "./snapshot.js";
1
+ import { parseRetainedPiCheckpoint, readCheckpointMode } from "./snapshot.js";
2
2
  export const SNAPSHOT_ENTRY_TYPE = "state-flow-snapshot";
3
3
  /** Enumerate active-branch snapshots newest-first while containing hostile entries. */
4
4
  export function discoverSnapshotData(branch) {
@@ -16,6 +16,65 @@ export function discoverSnapshotData(branch) {
16
16
  }
17
17
  return { candidates, errors };
18
18
  }
19
+ /** Read native mode policy only; semantic checkpoint validity remains the recovery owner's concern. */
20
+ export function findBranchPolicy(branch, sessionId, stopEntryType, inactiveMode) {
21
+ let stopReset = false;
22
+ for (let index = branch.length - 1; index >= 0; index--) {
23
+ try {
24
+ const entry = branch[index];
25
+ if (entry?.type !== "custom")
26
+ continue;
27
+ if (entry.customType === SNAPSHOT_ENTRY_TYPE) {
28
+ const mode = readCheckpointMode(entry.data, inactiveMode);
29
+ if (mode !== undefined)
30
+ return { mode };
31
+ const data = entry.data;
32
+ if (data?.disabled === true && !Object.hasOwn(data, "mode") && !Object.hasOwn(data, "enabled"))
33
+ return { mode: inactiveMode };
34
+ }
35
+ else if (stopEntryType !== undefined && entry.customType === stopEntryType) {
36
+ const data = entry.data;
37
+ if (!data || stopReset || (sessionId === undefined ? typeof data.owner !== "string" || !data.owner.trim() : data.owner !== sessionId))
38
+ continue;
39
+ if (data.reset === true) {
40
+ stopReset = true;
41
+ continue;
42
+ }
43
+ if (Number.isSafeInteger(data.at) && data.at >= 0 && data.memoryDeferred === true && data.mode === "off") {
44
+ return { mode: "off", ...(typeof data.persistenceError === "string" && data.persistenceError.trim() ? { persistenceError: data.persistenceError } : {}) };
45
+ }
46
+ if (Number.isSafeInteger(data.at) && data.at >= 0 && typeof data.persistenceError === "string" && data.persistenceError.trim()) {
47
+ return { mode: data.mode === "off" || data.mode === "passive" ? data.mode : inactiveMode, persistenceError: data.persistenceError };
48
+ }
49
+ }
50
+ }
51
+ catch {
52
+ // Malformed native policy cannot prevent another explicit retained choice from being read.
53
+ }
54
+ }
55
+ return undefined;
56
+ }
57
+ /** Native policy bookkeeping retains an unacquired fork across extension reloads. */
58
+ export function hasPendingFork(branch, sessionId, entryType) {
59
+ for (let index = branch.length - 1; index >= 0; index--) {
60
+ try {
61
+ const entry = branch[index];
62
+ if (entry?.type !== "custom" || entry.customType !== entryType)
63
+ continue;
64
+ const data = entry.data;
65
+ if (data?.owner !== sessionId)
66
+ continue;
67
+ if (data.reset === true)
68
+ return false;
69
+ if (data.forkPending === true)
70
+ return true;
71
+ }
72
+ catch {
73
+ // Unrelated native entries grant no fork authority.
74
+ }
75
+ }
76
+ return false;
77
+ }
19
78
  export function snapshotDataNewestFirst(branch) {
20
79
  return discoverSnapshotData(branch).candidates;
21
80
  }
@@ -14,6 +14,12 @@ export declare function isStateFlowMode(value: unknown): value is StateFlowMode;
14
14
  export interface SnapshotConfig {
15
15
  mode: StateFlowMode;
16
16
  }
17
+ /**
18
+ * Read only mode policy, without validating or accessing semantic checkpoint metadata.
19
+ * Missing/invalid policy stays undecided; callers must not treat this as restoration proof.
20
+ * Legacy `enabled:false` follows the caller's inactive policy.
21
+ */
22
+ export declare function readCheckpointMode(value: unknown, inactiveMode?: InactiveMode): StateFlowMode | undefined;
17
23
  interface LegacyValidationFeedback {
18
24
  attempt: number;
19
25
  error: string;
@@ -15,10 +15,13 @@ export function isStateFlowMode(value) {
15
15
  return value === "active" || value === "passive" || value === "off";
16
16
  }
17
17
  /**
18
- * Read-only compatibility for session config and native checkpoints written before `mode`:
19
- * `enabled:true` stays active; `enabled:false` stays the caller's inactive policy.
18
+ * Read only mode policy, without validating or accessing semantic checkpoint metadata.
19
+ * Missing/invalid policy stays undecided; callers must not treat this as restoration proof.
20
+ * Legacy `enabled:false` follows the caller's inactive policy.
20
21
  */
21
- function decodeLegacyMode(value, inactiveMode) {
22
+ export function readCheckpointMode(value, inactiveMode = "passive") {
23
+ if (!isObject(value))
24
+ return undefined;
22
25
  if (Object.hasOwn(value, "mode"))
23
26
  return Object.hasOwn(value, "enabled") || !isStateFlowMode(value.mode) ? undefined : value.mode;
24
27
  return typeof value.enabled === "boolean" ? value.enabled ? "active" : inactiveMode : undefined;
@@ -82,7 +85,7 @@ export function parseSessionRuntime(config, runtimeSource, cwd, sessionId) {
82
85
  let runtime;
83
86
  try {
84
87
  const settings = JSON.parse(config);
85
- const mode = isObject(settings) && Object.keys(settings).length === 1 ? decodeLegacyMode(settings, "passive") : undefined;
88
+ const mode = isObject(settings) && Object.keys(settings).length === 1 ? readCheckpointMode(settings, "passive") : undefined;
86
89
  if (mode === undefined)
87
90
  throw new Error("Invalid State Flow runtime configuration or counters");
88
91
  runtime = { config: { mode }, meta: JSON.parse(runtimeSource) };
@@ -166,7 +169,7 @@ export function parseRetainedPiCheckpoint(value, inactiveMode = "passive") {
166
169
  if (keys.length === 1 && (value.mode === "passive" || value.mode === "off"))
167
170
  return { mode: value.mode };
168
171
  const allowed = new Set(["boundary", "mode", "enabled", "step", "bootstrap", "specification"]);
169
- const mode = decodeLegacyMode(value, inactiveMode);
172
+ const mode = readCheckpointMode(value, inactiveMode);
170
173
  if (keys.some((key) => !allowed.has(key))
171
174
  || typeof value.boundary !== "string" || value.boundary.trim().length === 0
172
175
  || mode === undefined
@@ -32,4 +32,6 @@ export interface StatusDiagnostics {
32
32
  }
33
33
  export declare function formatScopeRevisionVector(revisions: ScopeRevisions): string;
34
34
  export declare function compactStatus(snapshot: Snapshot, _revisions: ScopeRevisions, colorize: Colorize): string | undefined;
35
+ /** Operator-only footprint: serialized plane sizes and intent-owned share of top-level working/lazy entries. */
36
+ export declare function scopeMemoryLines(states: ScopedStates): string[];
35
37
  export declare function detailedStatus(snapshot: Snapshot, diagnostics: StatusDiagnostics): string;