@llblab/pi-state-flow 0.2.3 → 0.4.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.
package/lib/status.ts CHANGED
@@ -1,16 +1,112 @@
1
+ import type { ArtifactInvalidationReason } from "./artifact.ts";
2
+ import { projectRecentTransitionsWithLimit, type RecentTransitionWindow } from "./history.ts";
1
3
  import type { Snapshot } from "./snapshot.ts";
4
+ import { overlayStates, type ScopedStates, type StateScope } from "./state.ts";
5
+ import type { TransitionBoundary } from "./temporal.ts";
2
6
 
3
7
  export const STATUS_KEY = "state-flow";
4
8
 
5
9
  export type Colorize = (color: "accent" | "dim", text: string) => string;
6
10
 
11
+ export type StaleArtifactReason = ArtifactInvalidationReason | "source-removed";
12
+
13
+ export interface StaleArtifactDiagnostic {
14
+ scope: StateScope;
15
+ path: string;
16
+ reason: StaleArtifactReason;
17
+ }
18
+
19
+ export interface PendingPublicationDiagnostic {
20
+ commit: string;
21
+ error: string;
22
+ }
23
+
24
+ export interface StatusDiagnostics {
25
+ repositoryRoot: string;
26
+ cwdScopeKey: string;
27
+ sessionScopeKey: string;
28
+ scopeStates: ScopedStates;
29
+ recent: RecentTransitionWindow;
30
+ temporal?: { head: TransitionBoundary; historyDepth: number; tailCounts: Record<StateScope, number> };
31
+ staleArtifacts: readonly StaleArtifactDiagnostic[];
32
+ artifactFreshnessError?: string;
33
+ durableStateError?: string;
34
+ pendingPublication?: PendingPublicationDiagnostic;
35
+ retryQueued: boolean;
36
+ }
37
+
7
38
  export function compactStatus(snapshot: Snapshot, colorize: Colorize): string | undefined {
8
- if (!snapshot.enabled) return undefined;
9
- return `${colorize("accent", "state-flow")} ${colorize("dim", `#${snapshot.step}`)}`;
39
+ if (!snapshot.config.enabled) return undefined;
40
+ return `${colorize("accent", "state-flow")} ${colorize("dim", `#${snapshot.meta.step}`)}`;
41
+ }
42
+
43
+ function countArtifacts(states: ScopedStates, scope: StateScope): number {
44
+ return Object.keys(states[scope].artifacts).length;
10
45
  }
11
46
 
12
- export function detailedStatus(snapshot: Snapshot): string {
13
- const stateJson = JSON.stringify(snapshot.state, null, 2);
14
- const stateBytes = Buffer.byteLength(stateJson, "utf8");
15
- return `State Flow ${snapshot.enabled ? "enabled" : "disabled"}; iteration #${snapshot.step}; state ${stateBytes} bytes; validation attempts ${snapshot.validation?.attempt ?? 0}.\n\n${stateJson}`;
47
+ function abbreviatedCommit(commit: string): string {
48
+ return commit.length > 12 ? commit.slice(0, 12) : commit;
49
+ }
50
+
51
+ export function detailedStatus(snapshot: Snapshot, diagnostics: StatusDiagnostics): string {
52
+ const projectedRecent = projectRecentTransitionsWithLimit(
53
+ snapshot.config.transitionWindow,
54
+ diagnostics.recent,
55
+ );
56
+ const available = diagnostics.temporal !== undefined && diagnostics.durableStateError === undefined;
57
+ const materialized = !available ? undefined : {
58
+ global: diagnostics.scopeStates.global,
59
+ cwd: diagnostics.scopeStates.cwd,
60
+ session: diagnostics.scopeStates.session,
61
+ effective: overlayStates(
62
+ diagnostics.scopeStates.global,
63
+ diagnostics.scopeStates.cwd,
64
+ diagnostics.scopeStates.session,
65
+ ),
66
+ };
67
+ const stateJson = materialized === undefined ? undefined : JSON.stringify(materialized, null, 2);
68
+ const freshnessError = diagnostics.artifactFreshnessError ?? (available ? undefined : "temporal global artifact registry is unavailable");
69
+ const stale = freshnessError === undefined
70
+ ? String(diagnostics.staleArtifacts.length)
71
+ : "unknown";
72
+ const publication = diagnostics.pendingPublication === undefined
73
+ ? "idle"
74
+ : `pending ${abbreviatedCommit(diagnostics.pendingPublication.commit)} — ${diagnostics.pendingPublication.error}`;
75
+ const retry = diagnostics.retryQueued
76
+ ? `queued (attempt ${snapshot.meta.validation?.attempt ?? 0})`
77
+ : "idle";
78
+ const staleLines = freshnessError !== undefined
79
+ ? [`Artifact freshness unavailable: ${freshnessError}`]
80
+ : diagnostics.staleArtifacts.length === 0
81
+ ? ["Stale artifacts: none"]
82
+ : [
83
+ "Stale artifacts:",
84
+ ...diagnostics.staleArtifacts.map(({ scope, path, reason }) => `- [${scope}] ${path} — ${reason}`),
85
+ ];
86
+ const temporal = available ? diagnostics.temporal : undefined;
87
+ const temporalLines = temporal === undefined
88
+ ? [`Temporal materialization unavailable: ${diagnostics.durableStateError ?? "no selected branch runtime"}`,
89
+ "Hot history: unavailable; offsets beyond 7 require explicit cold Git inspection",
90
+ "Retained patch tails: unavailable"]
91
+ : [`Temporal head: ${JSON.stringify(temporal.head.id)}; branch-local position ${temporal.head.position}`,
92
+ `Hot history: offsets 0..${temporal.historyDepth}; maximum depth 7`,
93
+ `Retained patch tails: global ${temporal.tailCounts.global}; CWD ${temporal.tailCounts.cwd}; session ${temporal.tailCounts.session}`];
94
+ const artifacts = (scope: StateScope) => available ? countArtifacts(diagnostics.scopeStates, scope) : "unknown";
95
+
96
+ return [
97
+ `State Flow diagnostics — config.enabled=${snapshot.config.enabled}; config.transitionWindow=${snapshot.config.transitionWindow}; branch mode=${snapshot.config.enabled ? "active" : "inactive"}`,
98
+ `Repository: ${diagnostics.repositoryRoot}`,
99
+ `Scope keys: CWD ${diagnostics.cwdScopeKey}; session ${diagnostics.sessionScopeKey}`,
100
+ "Session files: config.json owns behavior; meta.json owns lineage and provenance",
101
+ `Runtime metadata: step #${snapshot.meta.step}; active revision ${snapshot.meta.durableBase ?? "none"}; bootstrap ${snapshot.meta.bootstrap === true}; validation attempts ${snapshot.meta.validation?.attempt ?? 0}`,
102
+ ...temporalLines,
103
+ `Artifacts: global ${artifacts("global")}; CWD ${artifacts("cwd")}; session ${artifacts("session")}; stale ${stale}`,
104
+ available ? `Recent transitions: global ${diagnostics.recent.filter(({ transitions }) => transitions.some(({ scope }) => scope === "global")).length}; CWD ${diagnostics.recent.filter(({ transitions }) => transitions.some(({ scope }) => scope === "cwd")).length}; session ${diagnostics.recent.filter(({ transitions }) => transitions.some(({ scope }) => scope === "session")).length}; active ${projectedRecent.length}` : "Recent transitions: unavailable",
105
+ `Publication: ${publication}`,
106
+ `Terminal retry: ${retry}`,
107
+ ...staleLines,
108
+ ...(stateJson === undefined
109
+ ? ["Materialized states: unavailable (global/CWD/session/effective)"]
110
+ : [`Materialized states (${Buffer.byteLength(stateJson, "utf8")} bytes; global/CWD/session Git-backed, effective overlay):`, "", stateJson]),
111
+ ].join("\n");
16
112
  }
package/lib/storage.ts ADDED
@@ -0,0 +1,196 @@
1
+ // Domain: exact file-cohort publication, current-only recovery, and cooperating worktree exclusion.
2
+ // Excludes: temporal algebra, Pi lifecycle, Git objects/remotes, and backend fallback policy.
3
+ import { spawnSync } from "node:child_process";
4
+ import { createHash } from "node:crypto";
5
+ import { closeSync, lstatSync, mkdirSync, openSync, rmSync, writeFileSync } from "node:fs";
6
+ import { dirname, relative, resolve } from "node:path";
7
+ import {
8
+ assertOwnedFileUpdates, captureTemporalFileBases, parseScopeStream, restoreDurableFileBases,
9
+ sessionRuntimePaths, temporalScopePaths, temporalStateFileUpdates, writeOwnedFileUpdates,
10
+ type DurableFileBase, type OwnedFileUpdate,
11
+ } from "./durable.ts";
12
+ import { hashJson } from "./json.ts";
13
+ import { RevisionUnavailableError, isFileRevision, parseSessionRuntime, serializeSessionRuntime, type FileRevision, type SessionRuntime } from "./snapshot.ts";
14
+ import { planLegacyStorageMigration } from "./migration.ts";
15
+ export { isFileRevision, type FileRevision } from "./snapshot.ts";
16
+ import type { StateScope } from "./state.ts";
17
+ import { validateTemporalState, type TemporalState } from "./temporal.ts";
18
+
19
+ const SCOPES = ["global", "cwd", "session"] as const;
20
+ export interface TemporalFileBase { files: DurableFileBase[] }
21
+
22
+ /** Probe once at a lifecycle boundary, never on cached state reads. Only spawn ENOENT is absence. */
23
+ export function detectGitCapability(): "git" | "files" {
24
+ const result = spawnSync("git", ["--version"], { encoding: "utf8", timeout: 15_000 });
25
+ if (result.error && (result.error as NodeJS.ErrnoException).code === "ENOENT") return "files";
26
+ if (result.error || result.status !== 0) {
27
+ throw new RevisionUnavailableError(`Cannot resolve Git capability: ${result.error?.message ?? result.stderr ?? `exit ${result.status}`}`);
28
+ }
29
+ return "git";
30
+ }
31
+
32
+ export function assertStorageDirectory(path: string): void {
33
+ const root = resolve(path);
34
+ const parent = dirname(root);
35
+ if (parent !== root) assertStorageDirectory(parent);
36
+ const stat = lstatSync(root, { throwIfNoEntry: false });
37
+ if (stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error(`State Flow repository path is not a regular directory: ${root}`);
38
+ }
39
+
40
+ /** Explicit creation only; existing bytes and unrelated files are never adopted or rewritten here. */
41
+ export function initializeFileStore(root: string): void {
42
+ assertStorageDirectory(root);
43
+ mkdirSync(resolve(root), { recursive: true });
44
+ }
45
+
46
+ /** Git writers also acquire this lock before their common-Git-directory lock. */
47
+ export function withStoragePublicationLock<T>(repositoryRoot: string, action: (root: string) => T): T {
48
+ const root = resolve(repositoryRoot);
49
+ assertStorageDirectory(root);
50
+ const path = resolve(root, ".state-flow-publication.lock");
51
+ let descriptor: number;
52
+ try {
53
+ descriptor = openSync(path, "wx", 0o600);
54
+ } catch (error) {
55
+ throw new RevisionUnavailableError(`State Flow publication lock is unavailable at ${path}; reconcile the active or interrupted publisher before retrying`, { cause: error });
56
+ }
57
+ try {
58
+ writeFileSync(descriptor, `${process.pid}\n`);
59
+ return action(root);
60
+ } finally {
61
+ closeSync(descriptor);
62
+ rmSync(path);
63
+ }
64
+ }
65
+
66
+ export function assertTemporalFileBase(expected: TemporalFileBase, current: TemporalFileBase): void {
67
+ if (expected.files.length !== current.files.length || current.files.some((file, index) => {
68
+ const previous = expected.files[index]!;
69
+ return file.path !== previous.path || file.identity !== previous.identity;
70
+ })) throw new Error("Temporal State Flow base or scope identity changed concurrently");
71
+ }
72
+
73
+ /** One shared publication plan for Git and files; neither backend invents semantic changes. */
74
+ export function planTemporalPublication(
75
+ cwd: string, sessionId: string, view: TemporalState, scopes: readonly StateScope[],
76
+ current: TemporalFileBase, root: string, runtime?: SessionRuntime, runtimeOnly = false, sessionKey = sessionId,
77
+ ): { updates: OwnedFileUpdate[]; changedScopes: StateScope[] } {
78
+ const candidates = temporalStateFileUpdates(cwd, sessionId, view, scopes, root, sessionKey);
79
+ const files = new Map(current.files.map((file) => [file.path, file]));
80
+ if (runtimeOnly && scopes.length !== 0) throw new Error("Runtime-only publication cannot write semantic scopes");
81
+ const changedScopes: StateScope[] = [];
82
+ for (const scope of SCOPES) {
83
+ const paths = temporalScopePaths(cwd, sessionId, scope, root, sessionKey);
84
+ if (files.get(resolve(paths.directory, "state.json"))!.identity !== "missing") throw new Error("Legacy State Flow storage requires explicit migration");
85
+ const previous = parseScopeStream(files.get(paths.checkpoint)!.content, files.get(paths.patches)!.content, scope, scope === "cwd" ? cwd : undefined);
86
+ if (runtimeOnly || (previous !== undefined && hashJson(previous) === hashJson(view.scopes[scope]))) continue;
87
+ if (!scopes.includes(scope)) throw new Error(`Temporal scope update omitted a changed stream: ${scope}`);
88
+ changedScopes.push(scope);
89
+ }
90
+ const runtimePaths = sessionRuntimePaths(cwd, sessionId, root, sessionKey);
91
+ const previousRuntime = parseSessionRuntime(files.get(runtimePaths.config)!.content, files.get(runtimePaths.meta)!.content, cwd, sessionId);
92
+ if (previousRuntime !== undefined && changedScopes.length > 0 && runtime === undefined) throw new Error("Temporal semantic publication requires its session runtime cohort");
93
+ const runtimeUpdates: OwnedFileUpdate[] = [];
94
+ if (runtime !== undefined) {
95
+ const sources = serializeSessionRuntime(runtime, cwd, sessionId);
96
+ if (hashJson(runtime.meta.lineage) !== hashJson(view.lineage)) throw new Error("Runtime lineage does not match the temporal cohort");
97
+ if (previousRuntime === undefined || hashJson(previousRuntime) !== hashJson(runtime)) {
98
+ runtimeUpdates.push({ path: runtimePaths.config, content: sources.config }, { path: runtimePaths.meta, content: sources.meta });
99
+ }
100
+ }
101
+ const changedPaths = new Set(changedScopes.flatMap((scope) => {
102
+ const paths = temporalScopePaths(cwd, sessionId, scope, root, sessionKey);
103
+ return [paths.checkpoint, paths.patches];
104
+ }));
105
+ return { updates: [...candidates.filter(({ path }) => changedPaths.has(path)), ...runtimeUpdates], changedScopes };
106
+ }
107
+
108
+ /** The accepted basis comes from prepared outputs, never a post-publication worktree reread. */
109
+ export function temporalFileReceipts(current: TemporalFileBase, updates: readonly OwnedFileUpdate[]): DurableFileBase[] {
110
+ const receipts = new Map(updates.map((update) => [update.path, update.content]));
111
+ return current.files.map((file) => {
112
+ if (!receipts.has(file.path)) return file;
113
+ const content = receipts.get(file.path);
114
+ return content === undefined ? { path: file.path, identity: "missing" } : {
115
+ path: file.path, content, bytes: Buffer.from(content),
116
+ identity: `sha256:${createHash("sha256").update(content).digest("hex")}`,
117
+ };
118
+ });
119
+ }
120
+
121
+ function fileRevision(base: TemporalFileBase, root: string): FileRevision {
122
+ return `file:${hashJson({ root: resolve(root), files: base.files.map(({ path, identity }) => [relative(root, path), identity]) })}`;
123
+ }
124
+
125
+ function decodeFileCohort(cwd: string, sessionId: string, root: string, base: TemporalFileBase, sessionKey = sessionId) {
126
+ const files = new Map(base.files.map((file) => [file.path, file.content]));
127
+ const scopes = {} as TemporalState["scopes"];
128
+ for (const scope of SCOPES) {
129
+ const paths = temporalScopePaths(cwd, sessionId, scope, root, sessionKey);
130
+ if (files.get(resolve(paths.directory, "state.json")) !== undefined) throw new Error("Legacy State Flow storage requires explicit migration");
131
+ const stream = parseScopeStream(files.get(paths.checkpoint), files.get(paths.patches), scope, scope === "cwd" ? cwd : undefined);
132
+ if (!stream) throw new Error("Incomplete file-only temporal scope cohort");
133
+ scopes[scope] = stream;
134
+ }
135
+ const paths = sessionRuntimePaths(cwd, sessionId, root, sessionKey);
136
+ const runtime = parseSessionRuntime(files.get(paths.config), files.get(paths.meta), cwd, sessionId);
137
+ if (!runtime || runtime.meta.publication !== "files") throw new Error("File-only recovery requires file publication provenance, not a Git self reference");
138
+ const view = { scopes, lineage: runtime.meta.lineage };
139
+ validateTemporalState(view);
140
+ return { runtime, view };
141
+ }
142
+
143
+ export function captureTemporalFileBase(cwd: string, sessionId: string, root: string, sessionKey = sessionId): TemporalFileBase {
144
+ return withStoragePublicationLock(root, (locked) => ({ files: captureTemporalFileBases(cwd, sessionId, locked, sessionKey) }));
145
+ }
146
+
147
+ /** Current-only reference: exact bytes, complete identities and lineage, no aliases or history store. */
148
+ export function loadTemporalFileRevision(cwd: string, sessionId: string, root: string, revision: string, sessionKey = sessionId) {
149
+ if (!isFileRevision(revision)) throw new Error("File recovery requires an exact file revision");
150
+ return withStoragePublicationLock(root, (locked) => {
151
+ const base = { files: captureTemporalFileBases(cwd, sessionId, locked, sessionKey) };
152
+ if (fileRevision(base, locked) !== revision) throw new RevisionUnavailableError(`State Flow file revision is unavailable: ${revision}`);
153
+ return { base, revision, ...decodeFileCohort(cwd, sessionId, locked, base, sessionKey) };
154
+ });
155
+ }
156
+
157
+ /** Publish a validated full runtime/scoped cohort; no Git commands, success receipts, or pending pushes. */
158
+ export function publishTemporalStateToFiles(
159
+ cwd: string, sessionId: string, view: TemporalState, scopes: readonly StateScope[],
160
+ base: TemporalFileBase, root: string, runtime: SessionRuntime, sessionKey = sessionId,
161
+ ): { base: TemporalFileBase; revision: FileRevision; changed: boolean } {
162
+ return withStoragePublicationLock(root, (locked) => {
163
+ if (runtime.meta.publication !== "files") throw new Error("File publication requires explicit file provenance");
164
+ const current = { files: captureTemporalFileBases(cwd, sessionId, locked, sessionKey) };
165
+ assertTemporalFileBase(base, current);
166
+ const { updates } = planTemporalPublication(cwd, sessionId, view, scopes, current, locked, runtime, false, sessionKey);
167
+ const next = { files: temporalFileReceipts(current, updates) };
168
+ decodeFileCohort(cwd, sessionId, locked, next, sessionKey);
169
+ const revision = fileRevision(next, locked);
170
+ publishFileUpdates(current.files, updates, locked);
171
+ return { base: next, revision, changed: updates.length > 0 };
172
+ });
173
+ }
174
+
175
+ function publishFileUpdates(bases: readonly DurableFileBase[], updates: readonly OwnedFileUpdate[], root: string): void {
176
+ writeOwnedFileUpdates(updates, bases, root);
177
+ try {
178
+ assertOwnedFileUpdates(updates, root);
179
+ } catch (error) {
180
+ try {
181
+ const touched = new Set(updates.map(({ path }) => path));
182
+ restoreDurableFileBases(bases.filter(({ path }) => touched.has(path)), root, updates);
183
+ } catch (rollbackError) {
184
+ throw new AggregateError([error, rollbackError], "State Flow file publication and rollback failed");
185
+ }
186
+ throw error;
187
+ }
188
+ }
189
+
190
+ /** In-store format conversion only; no Git history or cross-repository import. */
191
+ export function migrateLegacyStorageToFiles(cwd: string, sessionId: string, root: string, sessionKey = sessionId): void {
192
+ withStoragePublicationLock(root, (locked) => {
193
+ const plan = planLegacyStorageMigration(cwd, sessionId, locked, undefined, sessionKey);
194
+ if (plan.updates.length) publishFileUpdates(plan.bases, plan.updates, locked);
195
+ });
196
+ }
@@ -0,0 +1,233 @@
1
+ import { RECENT_TRANSITION_LIMIT, validateRecentTransition, type RecentScopePatch } from "./history.ts";
2
+ import { applyPatch, containsNull, hashJson, isJsonValue, isObject, type JsonObject } from "./json.ts";
3
+ import { isMaterializedState, overlayStates, type MaterializedState, type ScopedStates, type StateScope } from "./state.ts";
4
+
5
+ /** Owns hot temporal algebra; excludes filesystem, Git, identity allocation, and Pi lifecycle. */
6
+ export interface TransitionBoundary {
7
+ id: string;
8
+ /** Branch-local order only. Identity and parent links distinguish forks at equal positions. */
9
+ position: number;
10
+ parent: string | null;
11
+ }
12
+
13
+ export interface ScopeCheckpoint {
14
+ through: TransitionBoundary;
15
+ state: MaterializedState;
16
+ }
17
+
18
+ export interface TemporalPatch {
19
+ transition: TransitionBoundary;
20
+ patch: RecentScopePatch["patch"];
21
+ }
22
+
23
+ export interface ScopeStream {
24
+ checkpoint: ScopeCheckpoint;
25
+ patches: TemporalPatch[];
26
+ }
27
+
28
+ export interface TemporalState {
29
+ /** Oldest to newest, including the boundary immediately before the retained transitions. */
30
+ lineage: TransitionBoundary[];
31
+ scopes: Record<StateScope, ScopeStream>;
32
+ }
33
+
34
+ const SCOPES: StateScope[] = ["global", "cwd", "session"];
35
+
36
+ function validateBoundary(boundary: TransitionBoundary): void {
37
+ if (!isObject(boundary) || Object.keys(boundary).sort().join(",") !== "id,parent,position"
38
+ || typeof boundary.id !== "string" || boundary.id.trim().length === 0
39
+ || !Number.isSafeInteger(boundary.position) || boundary.position < 0
40
+ || (boundary.parent !== null && (typeof boundary.parent !== "string" || boundary.parent.trim().length === 0))
41
+ || boundary.parent === boundary.id || (boundary.position === 0 && boundary.parent !== null)) {
42
+ throw new Error("Invalid State Flow temporal boundary");
43
+ }
44
+ }
45
+
46
+ function validateState(state: MaterializedState): void {
47
+ if (!isJsonValue(state) || !isMaterializedState(state) || containsNull(state)) {
48
+ throw new Error("Invalid temporal materialized semantic state");
49
+ }
50
+ }
51
+
52
+ function apply(state: MaterializedState, patch: TemporalPatch["patch"]): MaterializedState {
53
+ const next = applyPatch(state, patch as JsonObject) as MaterializedState;
54
+ validateState(next);
55
+ return next;
56
+ }
57
+
58
+ function sameBoundary(left: TransitionBoundary, right: TransitionBoundary): boolean {
59
+ return left.id === right.id && left.position === right.position && left.parent === right.parent;
60
+ }
61
+
62
+ /** Replay validation is shared by disk codecs and active-lineage materialization. */
63
+ export function validateScopeStream(value: unknown, scope: StateScope): asserts value is ScopeStream {
64
+ if (!SCOPES.includes(scope)) throw new Error("Unknown temporal scope");
65
+ if (!isJsonValue(value) || !isObject(value) || Object.keys(value).sort().join(",") !== "checkpoint,patches"
66
+ || !isObject(value.checkpoint) || Object.keys(value.checkpoint).sort().join(",") !== "state,through"
67
+ || !Array.isArray(value.patches)) {
68
+ throw new Error("Invalid temporal checkpoint/tail envelope");
69
+ }
70
+ const stream = value as unknown as ScopeStream;
71
+ validateBoundary(stream.checkpoint.through);
72
+ validateState(stream.checkpoint.state);
73
+ if (stream.patches.length > RECENT_TRANSITION_LIMIT) throw new Error("Temporal scope tail exceeds seven patches");
74
+ let previous = stream.checkpoint.through;
75
+ let state = stream.checkpoint.state;
76
+ const identities = new Set([previous.id]);
77
+ for (const record of stream.patches) {
78
+ if (!isObject(record) || Object.keys(record).sort().join(",") !== "patch,transition") {
79
+ throw new Error("Invalid temporal patch envelope");
80
+ }
81
+ validateBoundary(record.transition);
82
+ if (record.transition.position <= previous.position || identities.has(record.transition.id)) {
83
+ throw new Error("Temporal scope tail is not ordered after its checkpoint");
84
+ }
85
+ if (record.transition.position === previous.position + 1 && record.transition.parent !== previous.id) {
86
+ throw new Error("Disconnected State Flow temporal ancestry");
87
+ }
88
+ validateRecentTransition({ id: record.transition.id, at: 0, transitions: [{ scope, patch: record.patch }] });
89
+ const next = apply(state, record.patch);
90
+ if (hashJson(next) === hashJson(state)) throw new Error("Temporal scope tail contains a semantic no-op");
91
+ state = next;
92
+ previous = record.transition;
93
+ identities.add(previous.id);
94
+ }
95
+ }
96
+
97
+ export function validateTemporalLineage(value: unknown): asserts value is TransitionBoundary[] {
98
+ if (!isJsonValue(value) || !Array.isArray(value) || value.length === 0 || value.length > RECENT_TRANSITION_LIMIT + 1) {
99
+ throw new Error("Temporal lineage must contain between one and eight boundaries");
100
+ }
101
+ const seen = new Set<string>();
102
+ for (let index = 0; index < value.length; index++) {
103
+ const boundary = value[index] as unknown as TransitionBoundary;
104
+ validateBoundary(boundary);
105
+ if (seen.has(boundary.id)) throw new Error("Duplicate State Flow temporal boundary");
106
+ seen.add(boundary.id);
107
+ const previous = value[index - 1] as unknown as TransitionBoundary | undefined;
108
+ if (previous && (boundary.position !== previous.position + 1 || boundary.parent !== previous.id)) {
109
+ throw new Error("Disconnected State Flow temporal lineage");
110
+ }
111
+ }
112
+ }
113
+
114
+ /** Validate one revision-selected cohort. Its older ancestry must be bound by the durable loader. */
115
+ export function validateTemporalState(view: TemporalState): void {
116
+ validateTemporalLineage(view.lineage);
117
+ const oldest = view.lineage[0]!;
118
+ const identities = new Map<string, TransitionBoundary>();
119
+ const positions = new Map<number, TransitionBoundary>();
120
+ const remember = (boundary: TransitionBoundary): void => {
121
+ validateBoundary(boundary);
122
+ const identity = identities.get(boundary.id);
123
+ const position = boundary.position >= oldest.position ? positions.get(boundary.position) : undefined;
124
+ if ((identity && !sameBoundary(identity, boundary)) || (position && !sameBoundary(position, boundary))) {
125
+ throw new Error("Conflicting State Flow temporal lineage");
126
+ }
127
+ identities.set(boundary.id, boundary);
128
+ if (boundary.position >= oldest.position) positions.set(boundary.position, boundary);
129
+ };
130
+ for (const boundary of view.lineage) remember(boundary);
131
+ const head = view.lineage.at(-1)!;
132
+ for (const scope of SCOPES) {
133
+ const stream = view.scopes[scope];
134
+ validateScopeStream(stream, scope);
135
+ remember(stream.checkpoint.through);
136
+ if (stream.checkpoint.through.position > oldest.position) {
137
+ throw new Error("Scope checkpoint is newer than the guaranteed hot boundary");
138
+ }
139
+ for (const record of stream.patches) {
140
+ remember(record.transition);
141
+ if (record.transition.position > head.position) throw new Error("Temporal scope patch is beyond the active head");
142
+ }
143
+ }
144
+ for (const boundary of identities.values()) {
145
+ const previous = positions.get(boundary.position - 1);
146
+ if (previous && boundary.parent !== previous.id) throw new Error("Disconnected State Flow temporal ancestry");
147
+ }
148
+ for (const boundary of view.lineage.slice(1)) {
149
+ if (!SCOPES.some((scope) => view.scopes[scope].patches.some((record) => record.transition.id === boundary.id))) {
150
+ throw new Error("Temporal boundary has no semantic patch");
151
+ }
152
+ }
153
+ }
154
+
155
+ /** Adopt revision-proven inherited streams without rewriting their checkpoints or tails. */
156
+ export function adoptTemporalStreams(scopes: Record<StateScope, ScopeStream>, id: string): TemporalState {
157
+ const boundaries = Object.values(scopes).flatMap((stream) => [stream.checkpoint.through, ...stream.patches.map((record) => record.transition)]);
158
+ const origin: TransitionBoundary = { id, position: Math.max(...boundaries.map((boundary) => boundary.position)) + 1, parent: null };
159
+ const view = { lineage: [origin], scopes: structuredClone(scopes) };
160
+ validateTemporalState(view);
161
+ return view;
162
+ }
163
+
164
+ /** New or migrated state starts at a proven current boundary, with no invented past. */
165
+ export function createTemporalState(states: ScopedStates, id: string): TemporalState {
166
+ const through: TransitionBoundary = { id, position: 0, parent: null };
167
+ const stream = (scope: StateScope): ScopeStream => ({
168
+ checkpoint: { through: structuredClone(through), state: structuredClone(states[scope]) },
169
+ patches: [],
170
+ });
171
+ const view: TemporalState = { lineage: [through], scopes: { global: stream("global"), cwd: stream("cwd"), session: stream("session") } };
172
+ validateTemporalState(view);
173
+ return view;
174
+ }
175
+
176
+ function scopeAt(stream: ScopeStream, boundary: TransitionBoundary): MaterializedState {
177
+ let state = structuredClone(stream.checkpoint.state);
178
+ for (const record of stream.patches) {
179
+ if (record.transition.position > boundary.position) break;
180
+ state = apply(state, record.patch);
181
+ }
182
+ return state;
183
+ }
184
+
185
+ /** Lazy scope/effective read at one shared transition boundary, never by local patch count. */
186
+ export function readTemporalState(view: TemporalState, offset = 0, scope?: StateScope): MaterializedState {
187
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > RECENT_TRANSITION_LIMIT) {
188
+ throw new Error("State Flow hot-history offset must be an integer from 0 to 7");
189
+ }
190
+ if (scope !== undefined && !SCOPES.includes(scope)) throw new Error("Unknown temporal scope");
191
+ validateTemporalState(view);
192
+ const boundary = view.lineage[view.lineage.length - 1 - offset];
193
+ if (!boundary) throw new Error("Requested history predates the proven temporal origin");
194
+ if (scope !== undefined) return scopeAt(view.scopes[scope], boundary);
195
+ return overlayStates(...SCOPES.map((owner) => scopeAt(view.scopes[owner], boundary)));
196
+ }
197
+
198
+ /** Allocate the identity outside this algebra; only materially effective patches accept it. */
199
+ export function advanceTemporalState(
200
+ view: TemporalState,
201
+ transitions: readonly RecentScopePatch[],
202
+ id: string,
203
+ ): TemporalState {
204
+ validateTemporalState(view);
205
+ if (transitions.length === 0) return view;
206
+ validateRecentTransition({ id, at: 0, transitions });
207
+ const head = view.lineage.at(-1)!;
208
+ const changes = transitions.filter(({ scope, patch }) => {
209
+ const current = scopeAt(view.scopes[scope], head);
210
+ return hashJson(current) !== hashJson(apply(current, patch));
211
+ });
212
+ if (changes.length === 0) return view;
213
+ const knownIds = new Set(view.lineage.map((boundary) => boundary.id));
214
+ for (const scope of SCOPES) {
215
+ knownIds.add(view.scopes[scope].checkpoint.through.id);
216
+ for (const record of view.scopes[scope].patches) knownIds.add(record.transition.id);
217
+ }
218
+ if (knownIds.has(id)) throw new Error("State Flow transition identity has already been used");
219
+ const boundary: TransitionBoundary = { id, position: head.position + 1, parent: head.id };
220
+ validateBoundary(boundary);
221
+ const next = structuredClone(view);
222
+ for (const { scope, patch } of changes) {
223
+ const stream = next.scopes[scope];
224
+ if (stream.patches.length === RECENT_TRANSITION_LIMIT) {
225
+ const folded = stream.patches.shift()!;
226
+ stream.checkpoint = { through: folded.transition, state: apply(stream.checkpoint.state, folded.patch) };
227
+ }
228
+ stream.patches.push({ transition: structuredClone(boundary), patch: structuredClone(patch) });
229
+ }
230
+ next.lineage = [...next.lineage, boundary].slice(-(RECENT_TRANSITION_LIMIT + 1));
231
+ validateTemporalState(next);
232
+ return next;
233
+ }