@llblab/pi-state-flow 0.3.0 → 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/AGENTS.md +33 -12
- package/BACKLOG.md +14 -2
- package/CHANGELOG.md +24 -0
- package/README.md +195 -107
- package/docs/README.md +6 -0
- package/docs/temporal-acceptance.md +42 -0
- package/index.ts +109 -2
- package/lib/acquisition.ts +138 -0
- package/lib/artifact.ts +245 -0
- package/lib/config.ts +36 -0
- package/lib/context.ts +15 -5
- package/lib/discovery.ts +117 -0
- package/lib/durable.ts +552 -0
- package/lib/episode.ts +24 -12
- package/lib/extension.ts +486 -71
- package/lib/git.ts +646 -0
- package/lib/history.ts +95 -0
- package/lib/maintenance.ts +141 -0
- package/lib/migration.ts +88 -0
- package/lib/recovery.ts +23 -7
- package/lib/runtime.ts +259 -0
- package/lib/session.ts +6 -0
- package/lib/skills.ts +99 -7
- package/lib/snapshot.ts +294 -48
- package/lib/state.ts +74 -7
- package/lib/status.ts +102 -6
- package/lib/storage.ts +196 -0
- package/lib/temporal.ts +233 -0
- package/lib/terminal.ts +64 -24
- package/lib/transition.ts +254 -29
- package/package.json +4 -2
package/lib/history.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { hashJson, isJsonValue, isObject, validatePatch, type JsonObject } from "./json.ts";
|
|
3
|
+
import type { ScopePatch, ScopedStates, StateScope } from "./state.ts";
|
|
4
|
+
|
|
5
|
+
export const RECENT_TRANSITION_LIMIT = 7;
|
|
6
|
+
|
|
7
|
+
export interface RecentScopePatch {
|
|
8
|
+
scope: StateScope;
|
|
9
|
+
patch: ScopePatch & { response?: string };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Exact accepted replay cohort; temporal runtime owns its causal boundary. */
|
|
13
|
+
export interface AcceptedTransition {
|
|
14
|
+
id: string;
|
|
15
|
+
transitions: RecentScopePatch[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Compact lineage projection; at is a branch-local position, not a clock. */
|
|
19
|
+
export interface RecentTransition extends AcceptedTransition {
|
|
20
|
+
at: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type RecentTransitionWindow = RecentTransition[];
|
|
24
|
+
const SCOPES = new Set<StateScope>(["global", "cwd", "session"]);
|
|
25
|
+
const PATCH_KEYS = new Set(["artifacts", "contract", "working", "response"]);
|
|
26
|
+
|
|
27
|
+
/** Normalize accepted replacements into recursive-merge replay, including removals. */
|
|
28
|
+
function replayPatch(before: JsonObject, after: JsonObject): JsonObject {
|
|
29
|
+
const entries: Array<[string, JsonObject[string]]> = [];
|
|
30
|
+
for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
|
|
31
|
+
if (!Object.hasOwn(after, key)) {
|
|
32
|
+
entries.push([key, null]);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (Object.hasOwn(before, key) && hashJson(before[key]) === hashJson(after[key])) continue;
|
|
36
|
+
const previous = before[key];
|
|
37
|
+
const next = after[key]!;
|
|
38
|
+
entries.push([key, isObject(previous) && isObject(next) ? replayPatch(previous, next) : structuredClone(next)]);
|
|
39
|
+
}
|
|
40
|
+
return Object.fromEntries(entries);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function validateScopedPatch(value: unknown): asserts value is RecentScopePatch {
|
|
44
|
+
if (!isObject(value) || Object.keys(value).sort().join(",") !== "patch,scope") {
|
|
45
|
+
throw new Error('Recent State Flow transition entries must contain exactly "scope" and "patch"');
|
|
46
|
+
}
|
|
47
|
+
if (typeof value.scope !== "string" || !SCOPES.has(value.scope as StateScope)) {
|
|
48
|
+
throw new Error(`Recent State Flow transition has an unknown scope: ${String(value.scope)}`);
|
|
49
|
+
}
|
|
50
|
+
validatePatch(value.patch);
|
|
51
|
+
for (const [key, field] of Object.entries(value.patch)) {
|
|
52
|
+
if (!PATCH_KEYS.has(key) || (key === "response"
|
|
53
|
+
? value.scope !== "session" || typeof field !== "string" : !isObject(field))) {
|
|
54
|
+
throw new Error("Recent State Flow patches may contain object-valued artifacts, contract, and working plus a session response string");
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function validateRecentTransition(value: unknown): asserts value is RecentTransition {
|
|
60
|
+
if (!isObject(value) || Object.keys(value).sort().join(",") !== "at,id,transitions") throw new Error("Recent State Flow transition has an invalid envelope");
|
|
61
|
+
if (typeof value.id !== "string" || value.id.length === 0) throw new Error("Recent State Flow transition must have a non-empty id");
|
|
62
|
+
if (!Number.isSafeInteger(value.at) || (value.at as number) < 0) throw new Error("Recent State Flow transition must have a safe non-negative position");
|
|
63
|
+
if (!Array.isArray(value.transitions) || value.transitions.length === 0 || !isJsonValue(value.transitions)) throw new Error("Recent State Flow transition must contain semantic patches");
|
|
64
|
+
const seen = new Set<StateScope>();
|
|
65
|
+
for (const transition of value.transitions) {
|
|
66
|
+
validateScopedPatch(transition);
|
|
67
|
+
if (seen.has(transition.scope)) throw new Error(`Duplicate recent State Flow transition scope: ${transition.scope}`);
|
|
68
|
+
seen.add(transition.scope);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function createAcceptedTransition(currentStates: ScopedStates, nextStates: ScopedStates, id?: string): AcceptedTransition | undefined {
|
|
73
|
+
const transitions: RecentScopePatch[] = [];
|
|
74
|
+
for (const scope of SCOPES) {
|
|
75
|
+
const patch = replayPatch(currentStates[scope], nextStates[scope]);
|
|
76
|
+
if (Object.keys(patch).length > 0) transitions.push({ scope, patch });
|
|
77
|
+
}
|
|
78
|
+
if (transitions.length === 0) return undefined;
|
|
79
|
+
return { id: id ?? randomUUID(), transitions };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Preserve the configured per-scope budget, filtering in selected-lineage order. */
|
|
83
|
+
export function projectRecentTransitionsWithLimit(limit: number, lineage: readonly RecentTransition[]): RecentTransitionWindow {
|
|
84
|
+
if (!Number.isSafeInteger(limit) || limit < 0 || limit > RECENT_TRANSITION_LIMIT) {
|
|
85
|
+
throw new Error(`Recent State Flow transition limit must be an integer from 0 to ${RECENT_TRANSITION_LIMIT}`);
|
|
86
|
+
}
|
|
87
|
+
const remaining = { global: limit, cwd: limit, session: limit };
|
|
88
|
+
const result: RecentTransitionWindow = [];
|
|
89
|
+
for (let index = lineage.length - 1; index >= 0; index--) {
|
|
90
|
+
const record = lineage[index]!;
|
|
91
|
+
const transitions = record.transitions.filter(({ scope }) => remaining[scope]-- > 0);
|
|
92
|
+
if (transitions.length) result.push({ ...record, transitions });
|
|
93
|
+
}
|
|
94
|
+
return structuredClone(result.reverse());
|
|
95
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import {
|
|
2
|
+
classifyArtifactFreshness,
|
|
3
|
+
type ArtifactMetadata,
|
|
4
|
+
type ArtifactRegistry,
|
|
5
|
+
type ArtifactSourceIdentity,
|
|
6
|
+
} from "./artifact.ts";
|
|
7
|
+
import type { ArtifactSourceCandidate } from "./discovery.ts";
|
|
8
|
+
import { isObject } from "./json.ts";
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_ARTIFACT_MAINTENANCE_MAX_READS = 1;
|
|
11
|
+
export const DEFAULT_ARTIFACT_MAINTENANCE_MAX_SOURCE_BYTES = 16 * 1024;
|
|
12
|
+
export const DEFAULT_ARTIFACT_MAINTENANCE_MINIMUM_AGE_MS = 30 * 24 * 60 * 60 * 1_000;
|
|
13
|
+
|
|
14
|
+
export interface ArtifactMaintenanceOptions {
|
|
15
|
+
/** Stable cycle time supplied by the caller. */
|
|
16
|
+
now?: Date | number | string;
|
|
17
|
+
/** A source must be at least this old. Missing/unparseable timestamps rank as oldest. */
|
|
18
|
+
minimumAgeMs?: number;
|
|
19
|
+
/** Strict source-read count ceiling for this cycle. */
|
|
20
|
+
maxReads?: number;
|
|
21
|
+
/** Strict source-byte ceiling; bytes conservatively upper-bound source tokenizer input. */
|
|
22
|
+
maxSourceBytes?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ArtifactMaintenanceRequest extends ArtifactSourceIdentity {
|
|
26
|
+
reason: "maintenance";
|
|
27
|
+
sourceBytes: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ArtifactMaintenancePlan {
|
|
31
|
+
requiresCompilation: ArtifactMaintenanceRequest[];
|
|
32
|
+
deferred: ArtifactMaintenanceRequest[];
|
|
33
|
+
budget: {
|
|
34
|
+
maxReads: number;
|
|
35
|
+
maxSourceBytes: number;
|
|
36
|
+
usedReads: number;
|
|
37
|
+
usedSourceBytes: number;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function nonNegativeSafeInteger(value: number, name: string): number {
|
|
42
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${name} must be a non-negative safe integer`);
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function cycleTime(value: Date | number | string | undefined): number {
|
|
47
|
+
const timestamp = value === undefined
|
|
48
|
+
? Date.now()
|
|
49
|
+
: value instanceof Date
|
|
50
|
+
? value.getTime()
|
|
51
|
+
: typeof value === "number"
|
|
52
|
+
? value
|
|
53
|
+
: Date.parse(value);
|
|
54
|
+
if (!Number.isFinite(timestamp)) throw new Error("Artifact maintenance cycle time must be valid");
|
|
55
|
+
return timestamp;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function compiledTime(metadata: ArtifactMetadata): number {
|
|
59
|
+
if (typeof metadata.compiled_at !== "string") return Number.NEGATIVE_INFINITY;
|
|
60
|
+
const timestamp = Date.parse(metadata.compiled_at);
|
|
61
|
+
return Number.isFinite(timestamp) ? timestamp : Number.NEGATIVE_INFINITY;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function request(source: ArtifactSourceCandidate): ArtifactMaintenanceRequest {
|
|
65
|
+
return {
|
|
66
|
+
path: source.path,
|
|
67
|
+
hash: source.hash,
|
|
68
|
+
reason: "maintenance",
|
|
69
|
+
sourceBytes: source.bytes,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Select a bounded, oldest-first maintenance cohort from otherwise fresh artifacts.
|
|
75
|
+
*
|
|
76
|
+
* This planner is opt-in and side-effect free. Correctness invalidations remain the
|
|
77
|
+
* responsibility of planArtifactInvalidation; they are never displaced by maintenance.
|
|
78
|
+
*/
|
|
79
|
+
export function planArtifactMaintenance(
|
|
80
|
+
sources: readonly ArtifactSourceCandidate[],
|
|
81
|
+
registry: Readonly<Record<string, unknown>>,
|
|
82
|
+
compiler: string,
|
|
83
|
+
options: ArtifactMaintenanceOptions = {},
|
|
84
|
+
): ArtifactMaintenancePlan {
|
|
85
|
+
if (!isObject(registry)) throw new Error("Artifacts must be a path-keyed JSON object");
|
|
86
|
+
const now = cycleTime(options.now);
|
|
87
|
+
const minimumAgeMs = nonNegativeSafeInteger(
|
|
88
|
+
options.minimumAgeMs ?? DEFAULT_ARTIFACT_MAINTENANCE_MINIMUM_AGE_MS,
|
|
89
|
+
"Artifact maintenance minimum age",
|
|
90
|
+
);
|
|
91
|
+
const maxReads = nonNegativeSafeInteger(
|
|
92
|
+
options.maxReads ?? DEFAULT_ARTIFACT_MAINTENANCE_MAX_READS,
|
|
93
|
+
"Artifact maintenance read budget",
|
|
94
|
+
);
|
|
95
|
+
const maxSourceBytes = nonNegativeSafeInteger(
|
|
96
|
+
options.maxSourceBytes ?? DEFAULT_ARTIFACT_MAINTENANCE_MAX_SOURCE_BYTES,
|
|
97
|
+
"Artifact maintenance source-byte budget",
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
const seen = new Set<string>();
|
|
101
|
+
const eligible: { source: ArtifactSourceCandidate; compiledAt: number }[] = [];
|
|
102
|
+
for (const source of sources) {
|
|
103
|
+
if (seen.has(source.path)) throw new Error(`Duplicate artifact source path: ${source.path}`);
|
|
104
|
+
seen.add(source.path);
|
|
105
|
+
nonNegativeSafeInteger(source.bytes, `Artifact source bytes at ${source.path}`);
|
|
106
|
+
const metadata = Object.hasOwn(registry, source.path) ? registry[source.path] : undefined;
|
|
107
|
+
const freshness = classifyArtifactFreshness(source, metadata, compiler);
|
|
108
|
+
if (freshness.kind !== "fresh") continue;
|
|
109
|
+
const compiledAt = compiledTime(metadata as ArtifactMetadata);
|
|
110
|
+
if (compiledAt !== Number.NEGATIVE_INFINITY && now - compiledAt < minimumAgeMs) continue;
|
|
111
|
+
eligible.push({ source, compiledAt });
|
|
112
|
+
}
|
|
113
|
+
eligible.sort((left, right) => {
|
|
114
|
+
if (left.compiledAt !== right.compiledAt) return left.compiledAt - right.compiledAt;
|
|
115
|
+
return left.source.path < right.source.path ? -1 : left.source.path > right.source.path ? 1 : 0;
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
const requiresCompilation: ArtifactMaintenanceRequest[] = [];
|
|
119
|
+
const deferred: ArtifactMaintenanceRequest[] = [];
|
|
120
|
+
let usedSourceBytes = 0;
|
|
121
|
+
for (const candidate of eligible) {
|
|
122
|
+
const next = request(candidate.source);
|
|
123
|
+
if (requiresCompilation.length >= maxReads
|
|
124
|
+
|| candidate.source.bytes > maxSourceBytes - usedSourceBytes) {
|
|
125
|
+
deferred.push(next);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
requiresCompilation.push(next);
|
|
129
|
+
usedSourceBytes += candidate.source.bytes;
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
requiresCompilation,
|
|
133
|
+
deferred,
|
|
134
|
+
budget: {
|
|
135
|
+
maxReads,
|
|
136
|
+
maxSourceBytes,
|
|
137
|
+
usedReads: requiresCompilation.length,
|
|
138
|
+
usedSourceBytes,
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
}
|
package/lib/migration.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Domain: conservative current-snapshot migration planning; Git owns publication and rollback.
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
captureOwnedFileBases,
|
|
6
|
+
cwdScopePaths,
|
|
7
|
+
parseScopeStream,
|
|
8
|
+
parseStateSource,
|
|
9
|
+
serializeScopeStream,
|
|
10
|
+
sessionScopePaths,
|
|
11
|
+
type DurableFileBase,
|
|
12
|
+
type OwnedFileUpdate,
|
|
13
|
+
} from "./durable.ts";
|
|
14
|
+
import type { StateScope } from "./state.ts";
|
|
15
|
+
import type { ScopeStream } from "./temporal.ts";
|
|
16
|
+
|
|
17
|
+
export interface LegacyStorageMigration {
|
|
18
|
+
bases: DurableFileBase[];
|
|
19
|
+
updates: OwnedFileUpdate[];
|
|
20
|
+
scopes: StateScope[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Read-only activation eligibility, before global migration or any repository publication. */
|
|
24
|
+
export function hasCwdMaterialization(cwd: string, repositoryRoot: string): boolean {
|
|
25
|
+
const root = resolve(repositoryRoot);
|
|
26
|
+
const directory = cwdScopePaths(cwd, root).directory;
|
|
27
|
+
const [legacy, checkpoint, patches] = captureOwnedFileBases([
|
|
28
|
+
join(directory, "state.json"), join(directory, "checkpoint.json"), join(directory, "patches.jsonl"),
|
|
29
|
+
], root);
|
|
30
|
+
if (checkpoint!.content !== undefined) {
|
|
31
|
+
if (legacy!.content !== undefined) throw new Error(`Ambiguous State Flow storage has both current and checkpoint snapshots: ${directory}`);
|
|
32
|
+
return parseScopeStream(checkpoint!.content, patches!.content, "cwd", cwd) !== undefined;
|
|
33
|
+
}
|
|
34
|
+
if (legacy!.content !== undefined) return parseStateSource(legacy!.content, legacy!.path) !== undefined;
|
|
35
|
+
if (patches!.content !== undefined) throw new Error(`State Flow tail has no provable snapshot: ${directory}`);
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Plan from current scope snapshots only; old explanatory journals are never replay input. */
|
|
40
|
+
export function planLegacyStorageMigration(
|
|
41
|
+
cwd: string,
|
|
42
|
+
sessionId: string,
|
|
43
|
+
repositoryRoot: string,
|
|
44
|
+
origin: string = randomUUID(),
|
|
45
|
+
sessionKey = sessionId,
|
|
46
|
+
): LegacyStorageMigration {
|
|
47
|
+
const root = resolve(repositoryRoot);
|
|
48
|
+
const directories: Record<StateScope, string> = {
|
|
49
|
+
global: root,
|
|
50
|
+
cwd: cwdScopePaths(cwd, root).directory,
|
|
51
|
+
session: sessionScopePaths(cwd, sessionId, root, sessionKey).directory,
|
|
52
|
+
};
|
|
53
|
+
const paths = Object.values(directories).flatMap((directory) => [
|
|
54
|
+
join(directory, "state.json"), join(directory, "checkpoint.json"), join(directory, "patches.jsonl"),
|
|
55
|
+
]);
|
|
56
|
+
const bases = captureOwnedFileBases(paths, root);
|
|
57
|
+
const byPath = new Map(bases.map((base) => [base.path, base]));
|
|
58
|
+
const updates: OwnedFileUpdate[] = [];
|
|
59
|
+
const scopes: StateScope[] = [];
|
|
60
|
+
for (const scope of ["global", "cwd", "session"] as const) {
|
|
61
|
+
const directory = directories[scope];
|
|
62
|
+
const legacy = byPath.get(join(directory, "state.json"))!;
|
|
63
|
+
const checkpoint = byPath.get(join(directory, "checkpoint.json"))!;
|
|
64
|
+
const patches = byPath.get(join(directory, "patches.jsonl"))!;
|
|
65
|
+
if (checkpoint.content !== undefined) {
|
|
66
|
+
if (legacy.content !== undefined) throw new Error(`Ambiguous State Flow storage has both current and checkpoint snapshots: ${directory}`);
|
|
67
|
+
parseScopeStream(checkpoint.content, patches.content, scope, scope === "cwd" ? cwd : undefined);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (legacy.content === undefined) {
|
|
71
|
+
if (patches.content !== undefined) throw new Error(`State Flow tail has no provable snapshot: ${directory}`);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const state = parseStateSource(legacy.content, legacy.path)!;
|
|
75
|
+
const stream: ScopeStream = {
|
|
76
|
+
checkpoint: { through: { id: origin, position: 0, parent: null }, state },
|
|
77
|
+
patches: [],
|
|
78
|
+
};
|
|
79
|
+
const source = serializeScopeStream(stream, scope, scope === "cwd" ? cwd : undefined);
|
|
80
|
+
scopes.push(scope);
|
|
81
|
+
updates.push(
|
|
82
|
+
{ path: checkpoint.path, content: source.checkpoint },
|
|
83
|
+
{ path: patches.path, content: source.patches },
|
|
84
|
+
{ path: legacy.path },
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
return { bases, updates, scopes };
|
|
88
|
+
}
|
package/lib/recovery.ts
CHANGED
|
@@ -1,26 +1,42 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { migrateSnapshot, migrationFailure, type Snapshot } from "./snapshot.ts";
|
|
1
|
+
import { RevisionUnavailableError, emptySnapshot, parsePiCheckpoint, migrationFailure, type Snapshot } from "./snapshot.ts";
|
|
3
2
|
|
|
4
3
|
export interface SnapshotRecovery {
|
|
5
4
|
snapshot: Snapshot;
|
|
6
5
|
skipped: string[];
|
|
6
|
+
disabledMarker?: true;
|
|
7
7
|
}
|
|
8
8
|
|
|
9
9
|
function failureMessage(snapshot: Snapshot): string | undefined {
|
|
10
|
-
return !snapshot.enabled && snapshot.validation?.attempt === 0
|
|
11
|
-
? snapshot.validation.error
|
|
10
|
+
return !snapshot.config.enabled && snapshot.meta.validation?.attempt === 0
|
|
11
|
+
? snapshot.meta.validation.error
|
|
12
12
|
: undefined;
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
/** Recover the newest valid snapshot, falling back through the active branch. */
|
|
16
|
-
export function recoverSnapshot(candidates: readonly unknown[]): SnapshotRecovery {
|
|
16
|
+
export function recoverSnapshot(candidates: readonly unknown[], resolveRevision?: (revision: string, legacy?: Snapshot) => Snapshot): SnapshotRecovery {
|
|
17
17
|
const skipped: string[] = [];
|
|
18
18
|
let newestFailure: Snapshot | undefined;
|
|
19
19
|
for (const candidate of candidates) {
|
|
20
20
|
let migrated: Snapshot;
|
|
21
|
+
let selectedRevision: string | undefined;
|
|
21
22
|
try {
|
|
22
|
-
|
|
23
|
+
const parsed = parsePiCheckpoint(candidate);
|
|
24
|
+
if ("revision" in parsed) {
|
|
25
|
+
selectedRevision = parsed.revision;
|
|
26
|
+
if (!resolveRevision) throw new Error("Checkpoint pointer requires immutable runtime resolution");
|
|
27
|
+
return { snapshot: resolveRevision(parsed.revision), skipped };
|
|
28
|
+
}
|
|
29
|
+
if ("disabled" in parsed) return { snapshot: emptySnapshot(), skipped, disabledMarker: true };
|
|
30
|
+
migrated = parsed;
|
|
31
|
+
if (failureMessage(migrated) === undefined && migrated.meta.durableBase) {
|
|
32
|
+
selectedRevision = migrated.meta.durableBase;
|
|
33
|
+
if (!resolveRevision) throw new Error("Legacy checkpoint requires immutable runtime resolution");
|
|
34
|
+
return { snapshot: resolveRevision(migrated.meta.durableBase, migrated), skipped };
|
|
35
|
+
}
|
|
23
36
|
} catch (error) {
|
|
37
|
+
if (selectedRevision && error instanceof RevisionUnavailableError) {
|
|
38
|
+
return { snapshot: migrationFailure({ meta: { durableBase: selectedRevision } }, `Snapshot restoration failed: ${error.message}`), skipped };
|
|
39
|
+
}
|
|
24
40
|
migrated = migrationFailure(
|
|
25
41
|
{},
|
|
26
42
|
`Snapshot restoration failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
@@ -32,7 +48,7 @@ export function recoverSnapshot(candidates: readonly unknown[]): SnapshotRecover
|
|
|
32
48
|
skipped.push(failure);
|
|
33
49
|
}
|
|
34
50
|
return {
|
|
35
|
-
snapshot: newestFailure ??
|
|
51
|
+
snapshot: newestFailure ?? emptySnapshot(),
|
|
36
52
|
skipped,
|
|
37
53
|
};
|
|
38
54
|
}
|
package/lib/runtime.ts
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { lstatSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { parseScopeStream, sessionRuntimePaths, temporalScopePaths } from "./durable.ts";
|
|
5
|
+
import { adoptFileStateToGit, initializeGitRepository, isLocalGitRepository, captureTemporalGitBase, loadLegacyStatesAtRevision, loadTemporalRevision, migrateHashedCwdAtHead, migrateHashedLayoutAtHead, migrateLegacyStorageToGit, publishTemporalStateToGit, type TemporalGitBase } from "./git.ts";
|
|
6
|
+
import { captureTemporalFileBase, detectGitCapability, initializeFileStore, loadTemporalFileRevision, migrateLegacyStorageToFiles, publishTemporalStateToFiles } from "./storage.ts";
|
|
7
|
+
import { type AcceptedTransition, type RecentTransitionWindow } from "./history.ts";
|
|
8
|
+
import { hashJson } from "./json.ts";
|
|
9
|
+
import { hasCwdMaterialization } from "./migration.ts";
|
|
10
|
+
import { RevisionUnavailableError, createSessionRuntime, isFileRevision, parseSessionRuntime, resolveFileSessionRuntime, resolveSessionRuntime, type Snapshot } from "./snapshot.ts";
|
|
11
|
+
import { emptyState, type MaterializedState, type ScopedStates, type StateScope } from "./state.ts";
|
|
12
|
+
import { adoptTemporalStreams, advanceTemporalState, createTemporalState, readTemporalState, validateTemporalState, type TemporalState } from "./temporal.ts";
|
|
13
|
+
|
|
14
|
+
const SCOPES = ["global", "cwd", "session"] as const;
|
|
15
|
+
export type RuntimePublication = ReturnType<typeof publishTemporalStateToGit> & { revision?: string };
|
|
16
|
+
|
|
17
|
+
/** Immutable target validation is independent of acquiring the live publication basis. */
|
|
18
|
+
export function inspectRuntimeRevision(cwd: string, sessionId: string, root: string, revision: string, sessionKey = sessionId) {
|
|
19
|
+
const loaded = loadTemporalRevision(cwd, sessionId, root, revision, sessionKey);
|
|
20
|
+
if (!loaded.runtime) throw new Error("Linked State Flow revision has no session runtime");
|
|
21
|
+
const resolved = resolveSessionRuntime(loaded.runtime.document, loaded.runtime.revision);
|
|
22
|
+
if (!loaded.scopes.global || !loaded.scopes.cwd || !loaded.scopes.session) throw new Error("Incomplete temporal scope cohort");
|
|
23
|
+
const view = { lineage: resolved.lineage, scopes: { global: loaded.scopes.global, cwd: loaded.scopes.cwd, session: loaded.scopes.session } };
|
|
24
|
+
validateTemporalState(view);
|
|
25
|
+
return { runtime: loaded.runtime, resolved, view, ...(loaded.legacyLayout ? { legacyLayout: true as const } : {}) };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Both checkpoint generations validate their immutable target before any live migration/publication. */
|
|
29
|
+
export function inspectSnapshotRevision(cwd: string, sessionId: string, root: string, revision: string, legacySnapshot?: Snapshot, sessionKey = sessionId) {
|
|
30
|
+
if (isFileRevision(revision)) {
|
|
31
|
+
const file = loadTemporalFileRevision(cwd, sessionId, root, revision, sessionKey);
|
|
32
|
+
return { snapshot: resolveFileSessionRuntime(file.runtime, revision), file };
|
|
33
|
+
}
|
|
34
|
+
if (detectGitCapability() === "files") throw new RevisionUnavailableError("Git is unavailable; cannot restore a Git-linked revision");
|
|
35
|
+
try {
|
|
36
|
+
const temporal = inspectRuntimeRevision(cwd, sessionId, root, revision, sessionKey);
|
|
37
|
+
return { snapshot: temporal.resolved.snapshot, temporal };
|
|
38
|
+
} catch (error) {
|
|
39
|
+
if (!legacySnapshot || !(error instanceof Error) || !error.message.includes("Historical legacy storage requires explicit migration")) throw error;
|
|
40
|
+
const historical = loadLegacyStatesAtRevision(cwd, sessionId, root, revision, sessionKey);
|
|
41
|
+
const snapshot = structuredClone(legacySnapshot);
|
|
42
|
+
if (historical.session !== undefined) snapshot.legacySession = { state: historical.session };
|
|
43
|
+
return { snapshot, shared: { global: historical.global ?? emptyState(), cwd: historical.cwd ?? emptyState() } };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Cached branch-selected temporal state and publication basis; excludes Pi event policy. */
|
|
48
|
+
export class TemporalRuntime {
|
|
49
|
+
view: TemporalState | undefined;
|
|
50
|
+
private base: TemporalGitBase | undefined;
|
|
51
|
+
private semanticRevision: string | undefined;
|
|
52
|
+
private savedRuntime: string | undefined;
|
|
53
|
+
private backend: "git" | "files" | undefined;
|
|
54
|
+
readonly cwd: string;
|
|
55
|
+
readonly sessionId: string;
|
|
56
|
+
readonly sessionKey: string;
|
|
57
|
+
readonly root: string;
|
|
58
|
+
constructor(cwd: string, sessionId: string, root: string, sessionKey = sessionId) {
|
|
59
|
+
this.cwd = cwd;
|
|
60
|
+
this.sessionId = sessionId;
|
|
61
|
+
this.sessionKey = sessionKey;
|
|
62
|
+
this.root = root;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Explicit start owns directory/repository creation; reads never call this. */
|
|
66
|
+
prepare(): void {
|
|
67
|
+
const backend = detectGitCapability();
|
|
68
|
+
if (backend === "git") initializeGitRepository(this.root);
|
|
69
|
+
else initializeFileStore(this.root);
|
|
70
|
+
this.backend = backend;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Explicit start can upgrade a proven file cohort; failed adoption leaves the cache in file mode. */
|
|
74
|
+
promote(snapshot: Snapshot): RuntimePublication | undefined {
|
|
75
|
+
if (this.backend !== "files" || !this.view || detectGitCapability() === "files") return undefined;
|
|
76
|
+
if (!snapshot.meta.durableBase || snapshot.meta.durableBase !== this.semanticRevision) throw new Error("Git adoption requires the selected file revision");
|
|
77
|
+
const result = adoptFileStateToGit(this.cwd, this.sessionId, this.root, snapshot.meta.durableBase, snapshot, this.sessionKey);
|
|
78
|
+
const savedRuntime = hashJson(createSessionRuntime(snapshot, this.cwd, this.sessionId, result.view.lineage));
|
|
79
|
+
this.view = result.view;
|
|
80
|
+
this.base = result.base;
|
|
81
|
+
this.backend = "git";
|
|
82
|
+
this.semanticRevision = result.revision;
|
|
83
|
+
this.savedRuntime = savedRuntime;
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
read(offset = 0, scope?: StateScope): MaterializedState {
|
|
88
|
+
if (!this.view) throw new Error("State Flow temporal runtime is unavailable");
|
|
89
|
+
return readTemporalState(this.view, offset, scope);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
states(): ScopedStates {
|
|
93
|
+
return { global: this.read(0, "global"), cwd: this.read(0, "cwd"), session: this.read(0, "session") };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
causalBasis(): string {
|
|
97
|
+
if (!this.view) throw new Error("State Flow temporal runtime is unavailable");
|
|
98
|
+
return this.view.lineage.at(-1)!.id;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
recent(): RecentTransitionWindow {
|
|
102
|
+
const result: RecentTransitionWindow = [];
|
|
103
|
+
for (const boundary of this.view?.lineage.slice(1) ?? []) {
|
|
104
|
+
const transitions = SCOPES.flatMap((scope) => {
|
|
105
|
+
const record = this.view!.scopes[scope].patches.find(({ transition }) => transition.id === boundary.id);
|
|
106
|
+
return record ? [{ scope, patch: structuredClone(record.patch) }] : [];
|
|
107
|
+
});
|
|
108
|
+
if (transitions.length) result.push({ id: boundary.id, at: boundary.position, transitions });
|
|
109
|
+
}
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
restore(revision: string, legacySnapshot?: Snapshot): Snapshot {
|
|
114
|
+
const inspected = inspectSnapshotRevision(this.cwd, this.sessionId, this.root, revision, legacySnapshot, this.sessionKey);
|
|
115
|
+
if (inspected.file) {
|
|
116
|
+
const savedRuntime = hashJson(createSessionRuntime(inspected.snapshot, this.cwd, this.sessionId, inspected.file.view.lineage, "files"));
|
|
117
|
+
this.view = inspected.file.view;
|
|
118
|
+
this.base = inspected.file.base;
|
|
119
|
+
this.backend = "files";
|
|
120
|
+
this.semanticRevision = revision;
|
|
121
|
+
this.savedRuntime = savedRuntime;
|
|
122
|
+
return inspected.snapshot;
|
|
123
|
+
}
|
|
124
|
+
if (!inspected.temporal) {
|
|
125
|
+
const migrated = inspected.snapshot;
|
|
126
|
+
const publication = this.initialize(migrated, true, inspected.shared);
|
|
127
|
+
if (publication?.commit) migrated.meta.durableBase = publication.commit;
|
|
128
|
+
if (publication?.push?.status === "pending") migrated.meta.pendingPublication = { commit: publication.push.commit, error: publication.push.error ?? "Unconfirmed publication" };
|
|
129
|
+
else delete migrated.meta.pendingPublication;
|
|
130
|
+
delete migrated.legacySession;
|
|
131
|
+
return migrated;
|
|
132
|
+
}
|
|
133
|
+
const loaded = inspected.temporal;
|
|
134
|
+
const { resolved, view } = loaded;
|
|
135
|
+
let base = captureTemporalGitBase(this.cwd, this.sessionId, this.root, this.sessionKey);
|
|
136
|
+
const reference = loaded.runtime.document.meta.temporalRevision;
|
|
137
|
+
let semanticRevision = reference === undefined || reference === "self" ? loaded.runtime.revision : reference;
|
|
138
|
+
let publicationTarget = resolved.publicationTarget;
|
|
139
|
+
let migrationPush;
|
|
140
|
+
if (loaded.legacyLayout && base.head) {
|
|
141
|
+
const liveRevision = base.head;
|
|
142
|
+
const migration = migrateHashedLayoutAtHead(this.cwd, this.sessionId, this.root, liveRevision, this.sessionKey);
|
|
143
|
+
if (migration?.commit) {
|
|
144
|
+
base = migration.base;
|
|
145
|
+
if (liveRevision === revision) {
|
|
146
|
+
semanticRevision = migration.commit;
|
|
147
|
+
publicationTarget = migration.commit;
|
|
148
|
+
migrationPush = migration.push;
|
|
149
|
+
}
|
|
150
|
+
} else {
|
|
151
|
+
migrateHashedCwdAtHead(this.cwd, this.root);
|
|
152
|
+
base = captureTemporalGitBase(this.cwd, this.sessionId, this.root, this.sessionKey);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
resolved.snapshot.meta.durableBase = publicationTarget;
|
|
156
|
+
const savedRuntime = hashJson(createSessionRuntime(resolved.snapshot, this.cwd, this.sessionId, view.lineage));
|
|
157
|
+
resolved.snapshot.meta.pendingPublication = { commit: publicationTarget, error: "Durable publication intent is unconfirmed" };
|
|
158
|
+
if (migrationPush?.status === "pending") {
|
|
159
|
+
resolved.snapshot.meta.pendingPublication = { commit: migrationPush.commit, error: migrationPush.error ?? "Unconfirmed publication" };
|
|
160
|
+
} else if (migrationPush !== undefined) {
|
|
161
|
+
delete resolved.snapshot.meta.pendingPublication;
|
|
162
|
+
} else {
|
|
163
|
+
try {
|
|
164
|
+
if (isLocalGitRepository(this.root)) delete resolved.snapshot.meta.pendingPublication;
|
|
165
|
+
} catch {
|
|
166
|
+
// Invalid remote/branch configuration retains unconfirmed publication for explicit retry.
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
this.view = view;
|
|
170
|
+
this.base = base;
|
|
171
|
+
this.backend = "git";
|
|
172
|
+
this.semanticRevision = semanticRevision;
|
|
173
|
+
this.savedRuntime = savedRuntime;
|
|
174
|
+
return resolved.snapshot;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
initialize(snapshot: Snapshot, allowCreateCwd: boolean, expectedShared?: Pick<ScopedStates, "global" | "cwd">, newSessionOrigin = false): RuntimePublication | undefined {
|
|
178
|
+
if (!allowCreateCwd && !hasCwdMaterialization(this.cwd, this.root)) return undefined;
|
|
179
|
+
const backend = this.backend ?? (detectGitCapability() === "git" && lstatSync(join(this.root, ".git"), { throwIfNoEntry: false }) ? "git" : "files");
|
|
180
|
+
if (backend === "git") {
|
|
181
|
+
migrateHashedCwdAtHead(this.cwd, this.root);
|
|
182
|
+
migrateLegacyStorageToGit(this.cwd, this.sessionId, this.root, this.sessionKey);
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
if (allowCreateCwd) initializeFileStore(this.root);
|
|
186
|
+
migrateLegacyStorageToFiles(this.cwd, this.sessionId, this.root, this.sessionKey);
|
|
187
|
+
}
|
|
188
|
+
const base: TemporalGitBase = backend === "git" ? captureTemporalGitBase(this.cwd, this.sessionId, this.root, this.sessionKey) : captureTemporalFileBase(this.cwd, this.sessionId, this.root, this.sessionKey);
|
|
189
|
+
const files = new Map(base.files.map((file) => [file.path, file.content]));
|
|
190
|
+
const streams = Object.fromEntries(SCOPES.map((scope) => {
|
|
191
|
+
const paths = temporalScopePaths(this.cwd, this.sessionId, scope, this.root, this.sessionKey);
|
|
192
|
+
return [scope, parseScopeStream(files.get(paths.checkpoint), files.get(paths.patches), scope, scope === "cwd" ? this.cwd : undefined)];
|
|
193
|
+
})) as Record<StateScope, TemporalState["scopes"][StateScope] | undefined>;
|
|
194
|
+
if (!streams.cwd && !allowCreateCwd) return undefined;
|
|
195
|
+
const paths = sessionRuntimePaths(this.cwd, this.sessionId, this.root, this.sessionKey);
|
|
196
|
+
const existingRuntime = parseSessionRuntime(files.get(paths.config), files.get(paths.meta), this.cwd, this.sessionId);
|
|
197
|
+
if (existingRuntime && !snapshot.legacySession && !newSessionOrigin) throw new Error("Existing session runtime requires a branch revision pointer");
|
|
198
|
+
// Explicit start before any branch runtime is a new origin, never inheritance of a later session layer.
|
|
199
|
+
if (snapshot.legacySession || newSessionOrigin) streams.session = undefined;
|
|
200
|
+
const fresh = createTemporalState({ global: emptyState(), cwd: emptyState(), session: snapshot.legacySession?.state ?? emptyState() }, randomUUID());
|
|
201
|
+
const candidate = new TemporalRuntime(this.cwd, this.sessionId, this.root, this.sessionKey);
|
|
202
|
+
candidate.backend = backend;
|
|
203
|
+
candidate.base = base;
|
|
204
|
+
candidate.view = adoptTemporalStreams({ global: streams.global ?? fresh.scopes.global, cwd: streams.cwd ?? fresh.scopes.cwd, session: streams.session ?? fresh.scopes.session }, `${base.head ?? "unborn"}:${randomUUID()}`);
|
|
205
|
+
if (expectedShared && (["global", "cwd"] as const).some((scope) => hashJson(candidate.read(0, scope)) !== hashJson(expectedShared[scope]))) {
|
|
206
|
+
throw new Error("Legacy branch shared scopes diverged from the selected revision; migration cannot overwrite them");
|
|
207
|
+
}
|
|
208
|
+
const publication = candidate.publish(snapshot, true);
|
|
209
|
+
this.view = candidate.view;
|
|
210
|
+
this.base = candidate.base;
|
|
211
|
+
this.backend = backend;
|
|
212
|
+
this.semanticRevision = candidate.semanticRevision;
|
|
213
|
+
this.savedRuntime = candidate.savedRuntime;
|
|
214
|
+
return publication;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
publish(snapshot: Snapshot, semantic = false, accepted?: AcceptedTransition): RuntimePublication | undefined {
|
|
218
|
+
if (!this.view || !this.base) throw new Error("State Flow temporal publication is unavailable; restore or initialize before accepting a transition");
|
|
219
|
+
const next = accepted ? advanceTemporalState(this.view, accepted.transitions, accepted.id) : this.view;
|
|
220
|
+
const runtime = createSessionRuntime(snapshot, this.cwd, this.sessionId, next.lineage, this.backend === "files" ? "files" : "unconfirmed");
|
|
221
|
+
const fingerprint = hashJson(runtime);
|
|
222
|
+
if (!semantic && fingerprint === this.savedRuntime) return undefined;
|
|
223
|
+
if (semantic && this.semanticRevision) {
|
|
224
|
+
// Session files may branch; shared scopes may not be silently merged or rewound.
|
|
225
|
+
const live = new Map(this.base.files.map((file) => [file.path, file.content]));
|
|
226
|
+
for (const scope of ["global", "cwd"] as const) {
|
|
227
|
+
const paths = temporalScopePaths(this.cwd, this.sessionId, scope, this.root, this.sessionKey);
|
|
228
|
+
const stream = parseScopeStream(live.get(paths.checkpoint), live.get(paths.patches), scope, scope === "cwd" ? this.cwd : undefined);
|
|
229
|
+
if (hashJson(stream) !== hashJson(this.view.scopes[scope])) throw new Error("State Flow cannot publish this restored branch because its global or CWD scope changed concurrently after the linked revision");
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (this.backend === "files") {
|
|
233
|
+
runtime.meta.temporalRevision = "self";
|
|
234
|
+
const result = publishTemporalStateToFiles(this.cwd, this.sessionId, next, semantic ? SCOPES : [], this.base, this.root, runtime, this.sessionKey);
|
|
235
|
+
this.base = result.base;
|
|
236
|
+
this.view = next;
|
|
237
|
+
this.savedRuntime = fingerprint;
|
|
238
|
+
this.semanticRevision = result.revision;
|
|
239
|
+
return { base: result.base, revision: result.revision };
|
|
240
|
+
}
|
|
241
|
+
if (!semantic) {
|
|
242
|
+
const current = captureTemporalGitBase(this.cwd, this.sessionId, this.root, this.sessionKey);
|
|
243
|
+
const paths = sessionRuntimePaths(this.cwd, this.sessionId, this.root, this.sessionKey);
|
|
244
|
+
for (const path of [paths.config, paths.meta]) {
|
|
245
|
+
if (current.files.find((file) => file.path === path)?.identity !== this.base.files.find((file) => file.path === path)?.identity) {
|
|
246
|
+
throw new Error("Temporal State Flow runtime changed concurrently");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
this.base = current;
|
|
250
|
+
}
|
|
251
|
+
runtime.meta.temporalRevision = semantic ? "self" : this.semanticRevision!;
|
|
252
|
+
const result = publishTemporalStateToGit(this.cwd, this.sessionId, next, semantic ? SCOPES : [], this.base, this.root, runtime, this.sessionKey);
|
|
253
|
+
this.base = result.base;
|
|
254
|
+
this.view = next;
|
|
255
|
+
this.savedRuntime = fingerprint;
|
|
256
|
+
if (semantic && result.commit) this.semanticRevision = result.commit;
|
|
257
|
+
return result;
|
|
258
|
+
}
|
|
259
|
+
}
|
package/lib/session.ts
CHANGED
|
@@ -47,3 +47,9 @@ export function hasPriorConversation(branch: readonly BranchEntry[]): boolean {
|
|
|
47
47
|
}
|
|
48
48
|
return false;
|
|
49
49
|
}
|
|
50
|
+
|
|
51
|
+
/** Auto-start eligibility is session identity/lifecycle, not the presence of CWD materialization. */
|
|
52
|
+
export function isNewSession(reason: unknown, branch: readonly BranchEntry[]): boolean {
|
|
53
|
+
if (reason === "new") return true;
|
|
54
|
+
return reason === "startup" && !hasPriorConversation(branch);
|
|
55
|
+
}
|