@llblab/pi-state-flow 0.18.1 → 0.19.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 +26 -19
- package/BACKLOG.md +3 -3
- package/CHANGELOG.md +16 -0
- package/README.md +18 -6
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/lib/artifact.d.ts +2 -2
- package/dist/lib/artifact.js +5 -5
- package/dist/lib/context.d.ts +3 -2
- package/dist/lib/context.js +13 -4
- package/dist/lib/continuation.d.ts +5 -5
- package/dist/lib/continuation.js +54 -40
- package/dist/lib/durable.js +20 -20
- package/dist/lib/extension.js +755 -325
- package/dist/lib/git.d.ts +2 -2
- package/dist/lib/git.js +14 -17
- package/dist/lib/protocol.d.ts +5 -1
- package/dist/lib/protocol.js +67 -24
- package/dist/lib/query.js +1 -1
- package/dist/lib/recovery.d.ts +16 -5
- package/dist/lib/recovery.js +32 -15
- package/dist/lib/runtime.d.ts +28 -2
- package/dist/lib/runtime.js +276 -26
- package/dist/lib/session.d.ts +5 -0
- package/dist/lib/session.js +36 -2
- package/dist/lib/snapshot.d.ts +3 -0
- package/dist/lib/snapshot.js +3 -0
- package/dist/lib/status.d.ts +1 -0
- package/dist/lib/status.js +3 -1
- package/dist/lib/storage.d.ts +11 -0
- package/dist/lib/storage.js +150 -24
- package/dist/lib/telegram.d.ts +14 -1
- package/dist/lib/telegram.js +52 -18
- package/dist/lib/transition.js +8 -8
- package/dist/package.json +1 -1
- package/dist/skills/state-flow-guide/SKILL.md +6 -2
- package/dist/skills/state-flow-memory/SKILL.md +3 -1
- package/docs/architecture.md +55 -9
- package/docs/compatibility.md +84 -44
- package/docs/filesystem-recovery.md +12 -2
- package/docs/fork-contract.md +6 -4
- package/docs/lazy-state.md +6 -4
- package/docs/performance.md +2 -2
- package/docs/temporal-acceptance.md +30 -8
- package/docs/usage.md +51 -14
- package/index.ts +3 -0
- package/lib/artifact.ts +5 -5
- package/lib/context.ts +13 -5
- package/lib/continuation.ts +57 -40
- package/lib/durable.ts +20 -20
- package/lib/extension.ts +719 -316
- package/lib/git.ts +16 -18
- package/lib/protocol.ts +63 -25
- package/lib/query.ts +1 -1
- package/lib/recovery.ts +34 -21
- package/lib/runtime.ts +290 -25
- package/lib/session.ts +37 -2
- package/lib/snapshot.ts +3 -0
- package/lib/status.ts +4 -1
- package/lib/storage.ts +141 -22
- package/lib/telegram.ts +60 -19
- package/lib/transition.ts +8 -8
- package/package.json +1 -1
- package/skills/state-flow-guide/SKILL.md +6 -2
- package/skills/state-flow-memory/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
|
|
42
|
+
function publicationLockOwner(path: string, allowCurrentProcess: boolean): "live" | "pending" | "absent" | "unavailable" {
|
|
41
43
|
let owner: string;
|
|
42
|
-
try {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
|
48
|
-
try { process.kill(pid, 0); return
|
|
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"
|
|
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}
|
|
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
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
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
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
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
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
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 =
|
|
305
|
+
notice = diagnosticText(error);
|
|
271
306
|
}
|
|
272
|
-
|
|
273
|
-
|
|
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("&", "&").replaceAll("<", "<").replaceAll(">", ">")}`;
|
|
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
|
|
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
|
|
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
|
|
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
|
@@ -44,11 +44,15 @@ Example arguments:
|
|
|
44
44
|
{"paths":["cwd.working","session.working"]}
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
-
Unscoped paths use effective state. `cwd[1].working` reads the preceding causal boundary. Materialized-history and scope patch-history paths such as `cwd.patches[1]` share the configured `historyLimit` bound (default 7) and require actually retained history. Lowering the limit folds excess tails without erasing current state; increasing it does not reconstruct discarded history. Array ranges such as `cwd.lazy.checks[0..3]` exclude the endpoint and require existing elements. Missing paths
|
|
47
|
+
Unscoped paths use effective state. `cwd[1].working` reads the preceding causal boundary. Materialized-history and scope patch-history paths such as `cwd.patches[1]` share the configured `historyLimit` bound (default 7) and require actually retained history. Lowering the limit folds excess tails without erasing current state; increasing it does not reconstruct discarded history. Array ranges such as `cwd.lazy.checks[0..3]` exclude the endpoint and require existing elements. Missing paths are unavailable; inspect parent keys only when needed for the task. Missing history is not empty history. Read `lazy` explicitly. Treat structured `$ref` values and `$`-prefixed `read_state` paths inside ordinary strings, such as `$effective.lazy.memory[7]`, as semantic-state references. Other resources retain their native locators. Resolve any reference through the appropriate read/tool only when needed. Neither form proves authority or existence, hydrates, or executes anything. Never scan or resolve references merely to test them. A missing single value path with exact durable sources returns `{value:null, hint:[{type:"dangling-reference", message, paths}]}`. Treat `hint` as top-level diagnostic metadata, never as the requested state: its message is descriptive and conditional; its paths are runtime-verified current reference owners, not verified new locations of the target. The hint proves provenance rather than staleness and is absent when no current durable source matches; keys, patch, and batch reads keep all-or-error behavior. Only then inspect ownership as needed and patch a proven stale owning value while preserving its surrounding meaning. Effective absence, inaccessible external resources, and transient failures are not proof.
|
|
48
|
+
|
|
49
|
+
Missing paths or runtime hints alone do not require historical search. The agent may choose a targeted historical read when a previous value is useful to the current task, without separate user permission. Otherwise continue without searching. Use found values as historical evidence, not automatically as current state; never automatically restore deleted memory. Do not scan all offsets, hydrate automatically or request repair inference. A hint does not prove prior existence, retained history or relocation. A proven stale reference may be repaired within touched work without resurrecting its target. Automatic state and recent-transition projections omit lazy bodies; bounded `lazy_navigation` preserves structure, and explicit current/historical reads still return requested lazy values or patches.
|
|
48
50
|
|
|
49
51
|
## Write
|
|
50
52
|
|
|
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.
|
|
53
|
+
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.
|
|
54
|
+
|
|
55
|
+
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
56
|
|
|
53
57
|
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
58
|
|
|
@@ -22,9 +22,11 @@ Follow the installed runtime contract. This registered Skill follows its Pi sour
|
|
|
22
22
|
1. **Limit the review.** Address the requested scope. A completed phase may motivate recommending cleanup, not starting it without a request. For a whole-state cleanup, inspect global, CWD, and session ownership explicitly; for a narrower request, inspect only affected owners. Use targeted reads for gaps, contradictions, ownership, or verification; do not rerun the project.
|
|
23
23
|
2. **Classify.** Put user requirements and binding confirmed decisions in `contract`, observations, assistant conclusions, and unresolved work in `working`, chosen actions in `intents`, and inactive reusable detail in `lazy`. Never give an assistant conclusion user authority. Remove fulfilled, abandoned, superseded, or impossible intents; retain consequential results. Possibilities are not commitments.
|
|
24
24
|
3. **Keep evidence boundaries.** Preserve corrections, prerequisites, bounded negative results, and useful uncertainty. Separate requirements, decisions, observations, conclusions, and hypotheses. Silence is not acceptance; repetition is not verification. One implementation's failure does not reject an approach. Neither freeze provisional methods nor reopen confirmed decisions without grounds.
|
|
25
|
-
4. **Compact for continuation.** Remove duplicates, obsolete progress, unsupported claims, and secrets. Keep sufficient results, real retrieval pointers, pending interaction, and known next checks. Observations are not live external facts. Keep `lazy` shallow and priority-ordered. Recognize optional structured `$ref` values and `$`-prefixed `read_state` paths inside ordinary strings as semantic-state references; other resources retain native locators. No reference form proves authority or existence, authorizes execution, or implies completion. Never scan or resolve references merely to find broken ones. When the bounded review independently needs a reference, a missing single value path with exact durable sources returns `{value:null, hint:[{type:"dangling-reference", message, paths}]}`. Treat the top-level hint as
|
|
25
|
+
4. **Compact for continuation.** Remove duplicates, obsolete progress, unsupported claims, and secrets. Keep sufficient results, real retrieval pointers, pending interaction, and known next checks. Observations are not live external facts. Keep `lazy` shallow and priority-ordered. Recognize optional structured `$ref` values and `$`-prefixed `read_state` paths inside ordinary strings as semantic-state references; other resources retain native locators. No reference form proves authority or existence, authorizes execution, or implies completion. Never scan or resolve references merely to find broken ones. When the bounded review independently needs a reference, a missing single value path with exact durable sources returns `{value:null, hint:[{type:"dangling-reference", message, paths}]}`. Treat the top-level hint as conditional navigation and provenance, never as requested state or proof of staleness; its paths are runtime-verified current reference owners, not verified new locations of the target, while no hint does not prove invention. Inspect ownership only as needed, then patch a proven stale owning value while preserving surrounding meaning. Effective absence or external inaccessibility is insufficient.
|
|
26
26
|
5. **Check ownership.** Prefer `session` for branch/run continuation, `cwd` for project knowledge, and `global` for established cross-project knowledge. Effective values do not prove ownership; inspect owners before moves. Broader applicability requires evidence.
|
|
27
27
|
|
|
28
|
+
Missing paths or runtime hints alone do not require historical search. The agent may choose a targeted historical read when a previous value is useful to the current task, without separate user permission. Otherwise continue without searching. Use found values as historical evidence, not automatically as current state; never automatically restore deleted memory. Do not scan all offsets, hydrate automatically or request repair inference. A hint does not prove prior existence, retained history or relocation. A proven stale reference may be repaired within touched work without resurrecting its target. Lazy bodies require explicit reads; automatic state/history projections retain navigation without hydrating those bodies.
|
|
29
|
+
|
|
28
30
|
## Transfer only when needed
|
|
29
31
|
|
|
30
32
|
Resolve destination conflicts without overwriting stronger or unrelated knowledge. For a proven move between scopes of one State Flow store, inspect both owners, then use one atomic multi-scope `patch_state` for destination and source changes. Verify both owners and effective inheritance afterward; reconcile affected references. A rejected cohort leaves neither side partially accepted.
|