@llblab/pi-state-flow 0.18.0 → 0.19.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 (63) hide show
  1. package/AGENTS.md +23 -17
  2. package/BACKLOG.md +5 -3
  3. package/CHANGELOG.md +17 -0
  4. package/README.md +19 -7
  5. package/dist/index.d.ts +2 -1
  6. package/dist/index.js +1 -0
  7. package/dist/lib/artifact.d.ts +2 -2
  8. package/dist/lib/artifact.js +5 -5
  9. package/dist/lib/context.d.ts +3 -2
  10. package/dist/lib/context.js +7 -2
  11. package/dist/lib/continuation.d.ts +5 -5
  12. package/dist/lib/continuation.js +54 -40
  13. package/dist/lib/durable.js +20 -20
  14. package/dist/lib/extension.js +772 -331
  15. package/dist/lib/git.d.ts +6 -2
  16. package/dist/lib/git.js +43 -18
  17. package/dist/lib/logging.d.ts +3 -0
  18. package/dist/lib/logging.js +33 -7
  19. package/dist/lib/protocol.d.ts +4 -0
  20. package/dist/lib/protocol.js +65 -23
  21. package/dist/lib/recovery.d.ts +16 -5
  22. package/dist/lib/recovery.js +32 -15
  23. package/dist/lib/runtime.d.ts +28 -2
  24. package/dist/lib/runtime.js +276 -26
  25. package/dist/lib/session.d.ts +5 -0
  26. package/dist/lib/session.js +36 -2
  27. package/dist/lib/snapshot.d.ts +3 -0
  28. package/dist/lib/snapshot.js +3 -0
  29. package/dist/lib/status.d.ts +1 -0
  30. package/dist/lib/status.js +3 -1
  31. package/dist/lib/storage.d.ts +11 -0
  32. package/dist/lib/storage.js +150 -24
  33. package/dist/lib/telegram.d.ts +14 -1
  34. package/dist/lib/telegram.js +52 -18
  35. package/dist/lib/transition.js +8 -8
  36. package/dist/package.json +1 -1
  37. package/dist/skills/state-flow-guide/SKILL.md +3 -1
  38. package/docs/architecture.md +53 -7
  39. package/docs/compatibility.md +84 -44
  40. package/docs/filesystem-recovery.md +12 -2
  41. package/docs/fork-contract.md +6 -4
  42. package/docs/performance.md +11 -3
  43. package/docs/temporal-acceptance.md +28 -8
  44. package/docs/usage.md +43 -16
  45. package/index.ts +3 -0
  46. package/lib/artifact.ts +5 -5
  47. package/lib/context.ts +8 -3
  48. package/lib/continuation.ts +57 -40
  49. package/lib/durable.ts +20 -20
  50. package/lib/extension.ts +734 -322
  51. package/lib/git.ts +40 -19
  52. package/lib/logging.ts +31 -6
  53. package/lib/protocol.ts +60 -24
  54. package/lib/recovery.ts +34 -21
  55. package/lib/runtime.ts +290 -25
  56. package/lib/session.ts +37 -2
  57. package/lib/snapshot.ts +3 -0
  58. package/lib/status.ts +4 -1
  59. package/lib/storage.ts +141 -22
  60. package/lib/telegram.ts +60 -19
  61. package/lib/transition.ts +8 -8
  62. package/package.json +1 -1
  63. package/skills/state-flow-guide/SKILL.md +3 -1
package/lib/storage.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  // Domain: exact file-cohort publication, current-only recovery, and cooperating worktree exclusion.
2
2
  // Excludes: temporal algebra, Pi lifecycle, Git objects/remotes, and backend fallback policy.
3
+ import { AsyncLocalStorage } from "node:async_hooks";
3
4
  import { createHash } from "node:crypto";
4
- import { closeSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
6
  import { dirname, relative, resolve } from "node:path";
7
+ import { setTimeout as delay } from "node:timers/promises";
6
8
  import {
7
9
  assertOwnedFileUpdates, captureTemporalFileBases, parseScopeProvenance, parseScopeStream, restoreDurableFileBases,
8
10
  serializeScopeMetadata, sessionRuntimePaths, temporalScopePaths, temporalStateFileUpdates, writeOwnedFileUpdates,
@@ -24,7 +26,7 @@ export function assertStorageDirectory(path: string): void {
24
26
  const parent = dirname(root);
25
27
  if (parent !== root) assertStorageDirectory(parent);
26
28
  const stat = lstatSync(root, { throwIfNoEntry: false });
27
- if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error(`State Flow repository path is not a regular directory: ${root}`);
29
+ if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error(`State Flow repository path is not a regular directory: ${JSON.stringify(root)}`);
28
30
  }
29
31
 
30
32
  /** Explicit creation only; existing bytes and unrelated files are never adopted or rewritten here. */
@@ -37,16 +39,23 @@ const PUBLICATION_LOCK_WAIT_MS = 2_000;
37
39
  const PUBLICATION_LOCK_POLL_MS = 25;
38
40
  const publicationLockWait = new Int32Array(new SharedArrayBuffer(4));
39
41
 
40
- function liveForeignLockOwner(path: string): boolean {
42
+ function publicationLockOwner(path: string, allowCurrentProcess: boolean): "live" | "pending" | "absent" | "unavailable" {
41
43
  let owner: string;
42
- try { owner = readFileSync(path, "utf8").trim(); }
43
- catch { return true; }
44
- if (owner.length === 0) return true;
45
- if (!/^[1-9]\d*$/.test(owner)) return false;
44
+ try {
45
+ const stat = lstatSync(path, { throwIfNoEntry: false });
46
+ if (!stat) return "absent";
47
+ if (!stat.isFile() || stat.isSymbolicLink()) return "unavailable";
48
+ owner = readFileSync(path, { encoding: "utf8", flag: constants.O_RDONLY | constants.O_NOFOLLOW }).trim();
49
+ } catch (error) {
50
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "absent";
51
+ throw error;
52
+ }
53
+ if (owner.length === 0) return "pending";
54
+ if (!/^[1-9]\d*$/.test(owner)) return "unavailable";
46
55
  const pid = Number(owner);
47
- if (!Number.isSafeInteger(pid) || pid === process.pid) return false;
48
- try { process.kill(pid, 0); return true; }
49
- catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
56
+ if (!Number.isSafeInteger(pid) || (pid === process.pid && !allowCurrentProcess)) return "unavailable";
57
+ try { process.kill(pid, 0); return "live"; }
58
+ catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM" ? "live" : "unavailable"; }
50
59
  }
51
60
 
52
61
  /** Wait only for a cooperating live owner; interrupted or malformed locks remain explicit recovery errors. */
@@ -55,7 +64,11 @@ export function acquirePublicationLock(path: string, unavailable: (cause: unknow
55
64
  while (true) {
56
65
  try { return openSync(path, "wx", 0o600); }
57
66
  catch (error) {
58
- if ((error as NodeJS.ErrnoException).code !== "EEXIST" || !liveForeignLockOwner(path) || Date.now() >= deadline) throw unavailable(error);
67
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw unavailable(error);
68
+ let owner: ReturnType<typeof publicationLockOwner>;
69
+ try { owner = publicationLockOwner(path, false); }
70
+ catch (cause) { throw unavailable(cause); }
71
+ if (owner === "unavailable" || Date.now() >= deadline) throw unavailable(error);
59
72
  Atomics.wait(publicationLockWait, 0, 0, Math.min(PUBLICATION_LOCK_POLL_MS, deadline - Date.now()));
60
73
  }
61
74
  }
@@ -67,7 +80,7 @@ export function withStoragePublicationLock<T>(repositoryRoot: string, action: (r
67
80
  assertStorageDirectory(root);
68
81
  const path = resolve(root, ".state-flow-publication.lock");
69
82
  const descriptor = acquirePublicationLock(path, (cause) => new RevisionUnavailableError(
70
- `State Flow publication lock is unavailable at ${path}; reconcile the active or interrupted publisher before retrying`, { cause },
83
+ `State Flow publication lock is unavailable at ${JSON.stringify(path)}`, { cause },
71
84
  ));
72
85
  try {
73
86
  writeFileSync(descriptor, `${process.pid}\n`);
@@ -78,6 +91,103 @@ export function withStoragePublicationLock<T>(repositoryRoot: string, action: (r
78
91
  }
79
92
  }
80
93
 
94
+ export interface StorageTransaction {
95
+ readonly capture: typeof captureTemporalFileBase;
96
+ readonly publish: typeof publishTemporalStateToFiles;
97
+ }
98
+
99
+ export class PublicationBusyError extends Error {
100
+ constructor(path: string) { super(`State Flow publication lock is busy at ${JSON.stringify(path)}`); }
101
+ }
102
+
103
+ const storageLockContext = new AsyncLocalStorage<readonly { path: string; active: boolean }[]>();
104
+
105
+ /** Await an exact file mutex; shared by canonical transactions and the independent Git backup owner. */
106
+ export async function withFilePublicationLock<T>(
107
+ lockPath: string, action: () => T | Promise<T>, signal?: AbortSignal,
108
+ unavailable: (cause: unknown) => Error = (cause) => new RevisionUnavailableError(
109
+ `State Flow publication lock is unavailable at ${JSON.stringify(resolve(lockPath))}`, { cause },
110
+ ), waitForLock = true,
111
+ ): Promise<T> {
112
+ const path = resolve(lockPath);
113
+ const inherited = storageLockContext.getStore();
114
+ if (inherited?.some((held) => held.active && held.path === path)) throw new Error(`Recursive State Flow publication lock at ${JSON.stringify(path)}`);
115
+ let descriptor: number;
116
+ let pendingSince: number | undefined;
117
+ while (true) {
118
+ signal?.throwIfAborted();
119
+ assertStorageDirectory(dirname(path));
120
+ try { descriptor = openSync(path, "wx", 0o600); break; }
121
+ catch (error) {
122
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw unavailable(error);
123
+ let owner: ReturnType<typeof publicationLockOwner>;
124
+ try { owner = publicationLockOwner(path, true); }
125
+ catch (cause) { throw unavailable(cause); }
126
+ if (owner === "unavailable") throw unavailable(error);
127
+ if (!waitForLock) throw new PublicationBusyError(path);
128
+ // An empty file may be between exclusive creation and PID publication, but not forever.
129
+ if (owner === "pending") pendingSince ??= performance.now();
130
+ else pendingSince = undefined;
131
+ if (pendingSince !== undefined && performance.now() - pendingSince >= PUBLICATION_LOCK_WAIT_MS) throw unavailable(error);
132
+ }
133
+ await delay(PUBLICATION_LOCK_POLL_MS, undefined, { signal });
134
+ }
135
+ let identity: ReturnType<typeof fstatSync> | undefined;
136
+ const held = { path, active: true };
137
+ let failed: { error: unknown } | undefined;
138
+ try {
139
+ identity = fstatSync(descriptor);
140
+ writeFileSync(descriptor, `${process.pid}\n`);
141
+ signal?.throwIfAborted();
142
+ return await storageLockContext.run([...(inherited?.filter((owner) => owner.active) ?? []), held], action);
143
+ } catch (error) {
144
+ failed = { error };
145
+ throw error;
146
+ } finally {
147
+ held.active = false;
148
+ try {
149
+ const current = lstatSync(path, { throwIfNoEntry: false });
150
+ if (!identity || !current?.isFile() || current.dev !== identity.dev || current.ino !== identity.ino
151
+ || readFileSync(path, { encoding: "utf8", flag: constants.O_RDONLY | constants.O_NOFOLLOW }) !== `${process.pid}\n`) {
152
+ throw new Error(`State Flow publication lock changed during transaction at ${JSON.stringify(path)}; current owner preserved`);
153
+ }
154
+ rmSync(path);
155
+ } catch (error) {
156
+ if (failed) throw new AggregateError([failed.error, error], "State Flow storage transaction and lock release failed");
157
+ throw error;
158
+ } finally {
159
+ closeSync(descriptor);
160
+ }
161
+ }
162
+ }
163
+
164
+ /** Await store-wide exclusion, then capture/apply/publish through callback-scoped operations. */
165
+ export async function withStorageTransaction<T>(
166
+ repositoryRoot: string, action: (transaction: StorageTransaction) => T | Promise<T>, signal?: AbortSignal, waitForLock = true,
167
+ ): Promise<T> {
168
+ const root = resolve(repositoryRoot);
169
+ return withFilePublicationLock(resolve(root, ".state-flow-publication.lock"), async () => {
170
+ let active = true;
171
+ const guard = (requestedRoot: string): void => {
172
+ if (!active) throw new Error("State Flow storage transaction has ended");
173
+ if (resolve(requestedRoot) !== root) throw new Error("State Flow storage transaction belongs to a different store");
174
+ signal?.throwIfAborted();
175
+ };
176
+ const transaction = Object.freeze<StorageTransaction>({
177
+ capture: (cwd, sessionId, requestedRoot, sessionKey = sessionId) => {
178
+ guard(requestedRoot);
179
+ return { files: captureTemporalFileBases(cwd, sessionId, root, sessionKey) };
180
+ },
181
+ publish: (cwd, sessionId, view, scopes, base, requestedRoot, runtime, sessionKey, provenance, runtimeOnly) => {
182
+ guard(requestedRoot);
183
+ return publishLockedTemporalStateToFiles(cwd, sessionId, view, scopes, base, root, runtime, sessionKey, provenance, runtimeOnly);
184
+ },
185
+ });
186
+ try { return await action(transaction); }
187
+ finally { active = false; }
188
+ }, signal, undefined, waitForLock);
189
+ }
190
+
81
191
  export function assertTemporalFileBase(expected: TemporalFileBase, current: TemporalFileBase): void {
82
192
  if (expected.files.length !== current.files.length || current.files.some((file, index) => {
83
193
  const previous = expected.files[index]!;
@@ -194,16 +304,25 @@ export function publishTemporalStateToFiles(
194
304
  base: TemporalFileBase, root: string, runtime: SessionRuntime, sessionKey = sessionId,
195
305
  provenance?: Readonly<Record<StateScope, ArtifactProvenanceRegistry>>, runtimeOnly = false,
196
306
  ): { base: TemporalFileBase; revision: FileRevision; changed: boolean } {
197
- return withStoragePublicationLock(root, (locked) => {
198
- const current = { files: captureTemporalFileBases(cwd, sessionId, locked, sessionKey) };
199
- assertTemporalFileBase(base, current);
200
- const { updates } = planTemporalPublication(cwd, sessionId, view, scopes, current, locked, runtime, runtimeOnly, sessionKey, provenance);
201
- const next = { files: temporalFileReceipts(current, updates) };
202
- decodeFileCohort(cwd, sessionId, locked, next, sessionKey);
203
- const revision = fileRevision(next, locked);
204
- publishFileUpdates(current.files, updates, locked);
205
- return { base: next, revision, changed: updates.length > 0 };
206
- });
307
+ return withStoragePublicationLock(root, (locked) => publishLockedTemporalStateToFiles(
308
+ cwd, sessionId, view, scopes, base, locked, runtime, sessionKey, provenance, runtimeOnly,
309
+ ));
310
+ }
311
+
312
+ /** Shared publication owner; callers must hold the matching store lock for the complete cohort. */
313
+ function publishLockedTemporalStateToFiles(
314
+ cwd: string, sessionId: string, view: TemporalState, scopes: readonly StateScope[],
315
+ base: TemporalFileBase, root: string, runtime: SessionRuntime, sessionKey = sessionId,
316
+ provenance?: Readonly<Record<StateScope, ArtifactProvenanceRegistry>>, runtimeOnly = false,
317
+ ): { base: TemporalFileBase; revision: FileRevision; changed: boolean } {
318
+ const current = { files: captureTemporalFileBases(cwd, sessionId, root, sessionKey) };
319
+ assertTemporalFileBase(base, current);
320
+ const { updates } = planTemporalPublication(cwd, sessionId, view, scopes, current, root, runtime, runtimeOnly, sessionKey, provenance);
321
+ const next = { files: temporalFileReceipts(current, updates) };
322
+ decodeFileCohort(cwd, sessionId, root, next, sessionKey);
323
+ const revision = fileRevision(next, root);
324
+ publishFileUpdates(current.files, updates, root);
325
+ return { base: next, revision, changed: updates.length > 0 };
207
326
  }
208
327
 
209
328
  function publishFileUpdates(bases: readonly DurableFileBase[], updates: readonly OwnedFileUpdate[], root: string): void {
package/lib/telegram.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  // This is a leaf adapter. Core semantics, storage, and inference never depend on it; when
4
4
  // pi-telegram is absent or its registry is not ready, registration fails open and retries.
5
5
 
6
+ import { conciseDiagnostic, diagnosticText } from "./protocol.ts";
6
7
  import { formatScopeRevisionVector } from "./status.ts";
7
8
  import type { ScopeRevisions } from "./temporal.ts";
8
9
 
@@ -93,6 +94,15 @@ export type StateFlowTelegramLoader = () => Promise<StateFlowTelegramModules>;
93
94
  export interface StateFlowTelegramControlResult {
94
95
  ok: boolean;
95
96
  message: string;
97
+ /** A completed control can lose its presentation authority after a mode or selection change. */
98
+ signal?: AbortSignal;
99
+ }
100
+
101
+ export interface StateFlowTelegramInspection {
102
+ state: StateFlowTelegramState;
103
+ revisions: ScopeRevisions;
104
+ /** A selection can revoke a completed observation before the adapter presents it. */
105
+ signal?: AbortSignal;
96
106
  }
97
107
 
98
108
  export interface StateFlowTelegramPort {
@@ -107,6 +117,12 @@ export interface StateFlowTelegramPort {
107
117
  cancelStart(): void;
108
118
  }
109
119
 
120
+ export interface StateFlowTelegramInspectionPort extends Omit<StateFlowTelegramPort, "state" | "revisions" | "start" | "stop"> {
121
+ inspect(scope: StateFlowTelegramScope): StateFlowTelegramInspection | Promise<StateFlowTelegramInspection>;
122
+ start(): StateFlowTelegramControlResult | Promise<StateFlowTelegramControlResult>;
123
+ stop(): StateFlowTelegramControlResult | Promise<StateFlowTelegramControlResult>;
124
+ }
125
+
110
126
  export interface StateFlowTelegramAdapter {
111
127
  ensure(): Promise<boolean>;
112
128
  dispose(): void;
@@ -228,7 +244,8 @@ function isStateFlowTelegramScope(value: string): value is StateFlowTelegramScop
228
244
  return value === "global" || value === "cwd" || value === "session" || value === "effective";
229
245
  }
230
246
 
231
- function buildStateFlowTelegramSection(port: StateFlowTelegramPort) {
247
+ function buildStateFlowTelegramSection(port: StateFlowTelegramPort | StateFlowTelegramInspectionPort, isActive: () => boolean) {
248
+ let interaction = 0;
232
249
  return {
233
250
  id: STATE_FLOW_TELEGRAM_ID,
234
251
  label: "🌀 State Flow",
@@ -238,7 +255,9 @@ function buildStateFlowTelegramSection(port: StateFlowTelegramPort) {
238
255
  handleCallback: async (ctx: StateFlowTelegramCallbackContext) => {
239
256
  // cancel/refresh remain routable for keyboards sent by earlier versions.
240
257
  if (ctx.action !== "start" && ctx.action !== "stop" && ctx.action !== "cancel" && ctx.action !== "refresh" && ctx.action !== "show-state" && ctx.action !== "inspect" && ctx.action !== "back") return "pass" as const;
258
+ const request = ++interaction;
241
259
  let notice: string | undefined;
260
+ let acknowledged = false;
242
261
  try {
243
262
  if (ctx.action === "show-state") {
244
263
  await ctx.answerCallback();
@@ -247,30 +266,52 @@ function buildStateFlowTelegramSection(port: StateFlowTelegramPort) {
247
266
  }
248
267
  if (ctx.action === "inspect") {
249
268
  if (!isStateFlowTelegramScope(ctx.payload)) throw new Error("Unknown State Flow scope");
250
- const state = port.state(ctx.payload);
251
- const live = port.snapshot();
252
- const revisions = port.revisions?.() ?? live.revisions ?? { global: live.step, cwd: live.step, session: live.step };
253
- await ctx.openRich(renderStateFlowRichState(ctx.payload, revisions, state));
254
- await ctx.answerCallback();
269
+ let observation: StateFlowTelegramInspection;
270
+ if ("inspect" in port) {
271
+ await ctx.answerCallback("Reading State Flow memory");
272
+ acknowledged = true;
273
+ observation = await port.inspect(ctx.payload);
274
+ } else {
275
+ const state = port.state(ctx.payload);
276
+ const live = port.snapshot();
277
+ observation = { state, revisions: port.revisions?.() ?? live.revisions ?? { global: live.step, cwd: live.step, session: live.step } };
278
+ }
279
+ observation.signal?.throwIfAborted();
280
+ if (request !== interaction || !isActive()) return "handled" as const;
281
+ await ctx.openRich(renderStateFlowRichState(ctx.payload, observation.revisions, observation.state));
282
+ if (!acknowledged) await ctx.answerCallback();
255
283
  return "handled" as const;
256
284
  }
257
- if (ctx.action === "start") {
258
- if (port.canStartNow()) notice = port.start().message;
259
- else {
260
- port.deferStart();
261
- notice = "State Flow will start after the current turn";
262
- }
263
- } else if (ctx.action === "stop") {
264
- notice = port.stop().message;
285
+ const action = ctx.action === "stop" || (ctx.action === "start" && port.canStartNow()) ? ctx.action : undefined;
286
+ if (action) {
287
+ if ("inspect" in port) {
288
+ acknowledged = true;
289
+ // Start the control immediately and acknowledge in parallel; neither promise can reject unobserved.
290
+ const [, result] = await Promise.all([
291
+ ctx.answerCallback(action === "stop" ? "Stopping State Flow" : "Starting State Flow"),
292
+ Promise.resolve().then(() => port[action]()),
293
+ ]);
294
+ if (result.signal?.aborted) return "handled" as const;
295
+ notice = result.message;
296
+ } else notice = port[action]().message;
297
+ } else if (ctx.action === "start") {
298
+ port.deferStart();
299
+ notice = "State Flow will start after the current turn";
265
300
  } else if (ctx.action === "cancel") {
266
301
  port.cancelStart();
267
302
  notice = "Pending start cancelled";
268
303
  }
269
304
  } catch (error) {
270
- notice = error instanceof Error ? error.message : String(error);
305
+ notice = diagnosticText(error);
271
306
  }
272
- await ctx.answerCallback(notice);
273
- await ctx.edit(buildStateFlowSectionView(port.snapshot(), (action) => ctx.callbackData(action)));
307
+ if (request !== interaction || !isActive()) return "handled" as const;
308
+ const summary = notice === undefined ? undefined : conciseDiagnostic(notice, 200);
309
+ const view = buildStateFlowSectionView(port.snapshot(), (action) => ctx.callbackData(action));
310
+ if (acknowledged && summary !== undefined) {
311
+ // Callback queries can expire during storage waits; retain errors in the existing menu instead.
312
+ view.text += `\n\n${summary.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")}`;
313
+ } else if (!acknowledged) await ctx.answerCallback(summary);
314
+ await ctx.edit(view);
274
315
  return "handled" as const;
275
316
  },
276
317
  };
@@ -302,7 +343,7 @@ export async function loadStateFlowTelegramModules(): Promise<StateFlowTelegramM
302
343
  }
303
344
 
304
345
  export function createStateFlowTelegramAdapter(options: {
305
- port: StateFlowTelegramPort;
346
+ port: StateFlowTelegramPort | StateFlowTelegramInspectionPort;
306
347
  load?: StateFlowTelegramLoader;
307
348
  }): StateFlowTelegramAdapter {
308
349
  const load = options.load ?? loadStateFlowTelegramModules;
@@ -323,7 +364,7 @@ export function createStateFlowTelegramAdapter(options: {
323
364
  if (epoch !== generation) return false;
324
365
  if (!sectionRegistered && modules.sections) {
325
366
  try {
326
- const dispose = modules.sections.registerTelegramSection(buildStateFlowTelegramSection(options.port));
367
+ const dispose = modules.sections.registerTelegramSection(buildStateFlowTelegramSection(options.port, () => epoch === generation));
327
368
  if (epoch === generation) {
328
369
  disposers.push(dispose);
329
370
  sectionRegistered = true;
package/lib/transition.ts CHANGED
@@ -68,13 +68,13 @@ function validateSkillCompilerOutput(scope: StateScope, path: string, output: un
68
68
  const problems: string[] = [];
69
69
  if (!isObject(output)) problems.push("artifact entry is missing");
70
70
  else {
71
- if (typeof output.description !== "string" || output.description.trim().length === 0) problems.push("description must be a non-empty string");
71
+ if (typeof output.description !== "string" || output.description.trim().length === 0) problems.push("description must be non-empty");
72
72
  if (output.kind !== "skill") problems.push('kind must be "skill"');
73
- if (!isObject(output.compilation) || Object.keys(output.compilation).length === 0) problems.push("compilation must be a non-empty object");
73
+ if (!isObject(output.compilation) || Object.keys(output.compilation).length === 0) problems.push("compilation object must be non-empty");
74
74
  }
75
75
  if (problems.length === 0) return;
76
76
  const target = `${scope}.artifacts[${JSON.stringify(path)}]`;
77
- throw new Error(`Skill compiler output at ${target} is invalid: ${problems.join("; ")}. Example: {${JSON.stringify(scope)}:{"artifacts":{${JSON.stringify(path)}:{"description":"What this Skill provides","kind":"skill","compilation":{"rules":["Operational rule retained from the Skill"]}}}}}`);
77
+ throw new Error(`Invalid Skill at ${target}: ${problems.join("; ")}`);
78
78
  }
79
79
 
80
80
  function validateSkillCompilerTargets(
@@ -107,7 +107,7 @@ function compileReadSkills(
107
107
  const output = patch.artifacts[read.path];
108
108
  validateSkillCompilerOutput(scope, read.path, output);
109
109
  const compiled = compileArtifact({
110
- source: { path: read.path, hash: read.hash },
110
+ source: { path: read.path, scope, hash: read.hash },
111
111
  compiler: SKILL_ARTIFACT_COMPILER,
112
112
  output: { ...structuredClone(output), kind: "skill" } as ArtifactCompilerOutput,
113
113
  });
@@ -125,11 +125,11 @@ function compileReadSkills(
125
125
  }
126
126
  }
127
127
 
128
- function validateMaterializedTransition(nextState: StateDocument): void {
128
+ function validateMaterializedTransition(nextState: StateDocument, scope: StateScope): void {
129
129
  if (containsNull(nextState)) {
130
130
  throw new Error("Materialized state cannot contain null; use null only as an object-key deletion marker");
131
131
  }
132
- validateArtifactRegistry(nextState.artifacts);
132
+ validateArtifactRegistry(nextState.artifacts, `${scope}.artifacts`);
133
133
  if (Object.hasOwn(nextState.contract, "compiled_skills")) {
134
134
  throw new Error("contract.compiled_skills is retired; Skill compilations belong only in source-addressed artifacts");
135
135
  }
@@ -153,7 +153,7 @@ function validateScopePatch(scope: unknown, patch: unknown): asserts patch is Sc
153
153
  if (Object.hasOwn(patch, "lazy") && !isObject(patch.lazy)) {
154
154
  throw new Error("Scoped State Flow patch field lazy must be a JSON object");
155
155
  }
156
- if (isObject(patch.artifacts)) validateModelArtifactPatch(patch.artifacts);
156
+ if (isObject(patch.artifacts)) validateModelArtifactPatch(patch.artifacts, `${scope}.artifacts`);
157
157
  }
158
158
 
159
159
  function completePatch(patch: ScopePatch, response: string): StatePatch {
@@ -209,7 +209,7 @@ function stageScopedSemanticTransition(
209
209
  provenanceUpdates[scope],
210
210
  );
211
211
  compileReadSkills(scope, nextState, { artifacts: authored.artifacts ?? {} }, skillReads.filter((read) => read.scope === scope), provenanceUpdates[scope]);
212
- validateMaterializedTransition(nextState);
212
+ validateMaterializedTransition(nextState, scope);
213
213
  nextStates[scope] = nextState;
214
214
  }
215
215
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llblab/pi-state-flow",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "private": false,
5
5
  "description": "Incremental scoped state/context/memory compiler for Pi, inspired by SKILL.state",
6
6
  "keywords": [
@@ -48,7 +48,9 @@ Unscoped paths use effective state. `cwd[1].working` reads the preceding causal
48
48
 
49
49
  ## Write
50
50
 
51
- Call `patch_state` alone per assistant response; await acceptance before dependent work. Supply one or more of `global`, `cwd`, and `session`; supplied scopes commit atomically. Omit unchanged scopes.
51
+ Call `patch_state` alone per assistant response; await acceptance before dependent work. Supply one or more of `global`, `cwd`, and `session`; supplied scopes commit atomically. Default to Session for current work, CWD for reusable project knowledge, and Global for established cross-project knowledge. Omit unchanged scopes.
52
+
53
+ The runtime waits cancelably for publication ownership, then applies authored Global/CWD operations to current canonical values. Untouched fields survive; overlapping targets follow successful acceptance order. Correct repeats succeed as `State already current.` without another semantic revision. Do not repeat external actions during a memory wait, or rebuild an entire scope from an older snapshot. Session ownership/history fences remain private, not a universal merge.
52
54
 
53
55
  Semantic planes `intents`, `contract`, `working`, `artifacts`, and the required `lazy` root are objects; nested lazy values may contain ordinary JSON without stored nulls. Objects merge, arrays/scalars replace, omitted fields persist. Nested `null` removes an owned object key; inherited content may reappear. Canonical `"[N]"` keys patch array elements; indexed deletion is forbidden.
54
56