@llblab/pi-state-flow 0.6.0 → 0.8.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/transition.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  import {
2
+ compileArtifact,
2
3
  ORDINARY_ARTIFACT_COMPILER,
3
4
  validateArtifactMetadata,
4
5
  validateArtifactRegistry,
5
- type ArtifactMetadata,
6
+ type ArtifactCompilerOutput,
7
+ type ArtifactProvenance,
6
8
  } from "./artifact.ts";
7
9
  import type { SuccessfulArtifactRead } from "./acquisition.ts";
8
10
  import { createAcceptedTransition, type AcceptedTransition } from "./history.ts";
@@ -10,6 +12,7 @@ import { applyPatch, containsNull, hashJson, isObject, validatePatch } from "./j
10
12
  import { hasCompiledSkillArtifact, SKILL_ARTIFACT_COMPILER, type SuccessfulSkillRead } from "./skills.ts";
11
13
  import type { Snapshot } from "./snapshot.ts";
12
14
  import type {
15
+ AtomicScopePatches,
13
16
  MaterializedState,
14
17
  ScopePatch,
15
18
  ScopedPatch,
@@ -24,6 +27,8 @@ import type {
24
27
  export interface StagedScopedTransition {
25
28
  nextStates: ScopedStates;
26
29
  stateHashes: Record<StateScope, string>;
30
+ /** Fresh runtime-owned provenance for artifacts compiled in this transition. */
31
+ provenanceUpdates: Record<StateScope, Record<string, ArtifactProvenance>>;
27
32
  causalBasis: string;
28
33
  committed: boolean;
29
34
  }
@@ -35,27 +40,26 @@ function compileReadArtifacts(
35
40
  nextState: StateDocument,
36
41
  patch: Pick<StatePatch, "artifacts">,
37
42
  successfulArtifactReads: Iterable<SuccessfulArtifactRead>,
43
+ provenance: Record<string, ArtifactProvenance>,
38
44
  ): void {
39
45
  for (const read of successfulArtifactReads) {
40
46
  const output = patch.artifacts[read.path];
41
47
  if (!isObject(output)) {
42
48
  throw new Error(`Every successfully read invalidated artifact must have a global compiler output at artifacts[exact candidate path]; missing: ${read.path}`);
43
49
  }
44
- if (Object.hasOwn(output, "hash") || Object.hasOwn(output, "compiler")) {
45
- throw new Error(`Artifact compiler output at ${read.path} cannot set runtime-owned hash or compiler fields`);
46
- }
47
- const metadata = {
48
- ...structuredClone(output),
49
- hash: read.hash,
50
+ const compiled = compileArtifact({
51
+ source: { path: read.path, hash: read.hash },
50
52
  compiler: ORDINARY_ARTIFACT_COMPILER,
51
- } as ArtifactMetadata;
52
- validateArtifactMetadata(metadata, read.path);
53
+ output: output as ArtifactCompilerOutput,
54
+ });
55
+ validateArtifactMetadata(compiled.semantic, read.path);
53
56
  Object.defineProperty(nextState.artifacts, read.path, {
54
- value: metadata,
57
+ value: compiled.semantic,
55
58
  enumerable: true,
56
59
  configurable: true,
57
60
  writable: true,
58
61
  });
62
+ provenance[read.path] = compiled.provenance;
59
63
  }
60
64
  }
61
65
 
@@ -63,6 +67,7 @@ function compileReadSkills(
63
67
  nextState: StateDocument,
64
68
  patch: Pick<StatePatch, "artifacts">,
65
69
  successfulSkillReads: Iterable<SuccessfulSkillRead>,
70
+ provenance: Record<string, ArtifactProvenance>,
66
71
  ): void {
67
72
  for (const read of successfulSkillReads) {
68
73
  if (read.hash === undefined) {
@@ -84,20 +89,20 @@ function compileReadSkills(
84
89
  if (!isObject(output.compilation) || Object.keys(output.compilation).length === 0) {
85
90
  throw new Error(`Skill artifact compiler output at ${read.path} must have a non-empty compilation object`);
86
91
  }
87
- const metadata = {
88
- ...structuredClone(output),
89
- hash: read.hash,
92
+ const compiled = compileArtifact({
93
+ source: { path: read.path, hash: read.hash },
90
94
  compiler: SKILL_ARTIFACT_COMPILER,
91
- kind: "skill",
92
- } as ArtifactMetadata;
93
- validateArtifactMetadata(metadata, read.path);
95
+ output: { ...structuredClone(output), kind: "skill" } as ArtifactCompilerOutput,
96
+ });
97
+ validateArtifactMetadata(compiled.semantic, read.path);
94
98
  Object.defineProperty(nextState.artifacts, read.path, {
95
- value: metadata,
99
+ value: compiled.semantic,
96
100
  enumerable: true,
97
101
  configurable: true,
98
102
  writable: true,
99
103
  });
100
- if (!hasCompiledSkillArtifact(nextState.artifacts, read.path, read.hash)) {
104
+ provenance[read.path] = compiled.provenance;
105
+ if (!hasCompiledSkillArtifact(nextState.artifacts, provenance[read.path], read.path, read.hash)) {
101
106
  throw new Error(`Skill artifact compilation at ${read.path} is not locally materialized for its executed source identity`);
102
107
  }
103
108
  }
@@ -146,7 +151,7 @@ function stageScopedSemanticTransition(
146
151
  successfulSkillReads: Iterable<SuccessfulSkillRead>,
147
152
  causalBasis: string,
148
153
  successfulArtifactReads: Iterable<SuccessfulArtifactRead>,
149
- terminalResponse?: string,
154
+ acceptedResponse?: string,
150
155
  ): StagedScopedTransition {
151
156
  if (!Array.isArray(transition.transitions)) throw new Error("State Flow transitions must be an array");
152
157
  const patches = new Map<StateScope, ScopePatch>();
@@ -164,20 +169,22 @@ function stageScopedSemanticTransition(
164
169
 
165
170
  const cwdPatch = patches.get("cwd") ?? {};
166
171
  const nextStates = structuredClone(currentStates);
172
+ const provenanceUpdates: Record<StateScope, Record<string, ArtifactProvenance>> = { global: {}, cwd: {}, session: {} };
167
173
  for (const scope of SCOPES) {
168
174
  const authored = patches.get(scope) ?? {};
169
- const response = scope === "session" && terminalResponse !== undefined
170
- ? terminalResponse
175
+ const response = scope === "session" && acceptedResponse !== undefined
176
+ ? acceptedResponse
171
177
  : currentStates[scope].response;
172
178
  const patch = completePatch(authored, response);
173
179
  const nextState = applyPatch(structuredClone(currentStates[scope]), patch) as MaterializedState;
174
- compileReadArtifacts(nextState, { artifacts: scope === "global" ? authored.artifacts ?? {} : {} }, scope === "global" ? successfulArtifactReads : []);
175
- compileReadSkills(nextState, { artifacts: scope === "cwd" ? cwdPatch.artifacts ?? {} : {} }, scope === "cwd" ? successfulSkillReads : []);
180
+ compileReadArtifacts(nextState, { artifacts: scope === "global" ? authored.artifacts ?? {} : {} }, scope === "global" ? successfulArtifactReads : [], provenanceUpdates.global);
181
+ compileReadSkills(nextState, { artifacts: scope === "cwd" ? cwdPatch.artifacts ?? {} : {} }, scope === "cwd" ? successfulSkillReads : [], provenanceUpdates.cwd);
176
182
  validateMaterializedTransition(nextState);
177
183
  nextStates[scope] = nextState;
178
184
  }
179
185
  return {
180
186
  nextStates,
187
+ provenanceUpdates,
181
188
  stateHashes: {
182
189
  global: hashJson(currentStates.global),
183
190
  cwd: hashJson(currentStates.cwd),
@@ -188,17 +195,41 @@ function stageScopedSemanticTransition(
188
195
  };
189
196
  }
190
197
 
191
- /** Stage one intermediate state barrier without changing the finalized response. */
192
- export function stageScopedPatch(
198
+ /** Validate that final eligibility has no pending acquisition/compilation obligation. */
199
+ export function validateFinalEligibility(
200
+ currentStates: ScopedStates,
201
+ successfulSkillReads: Iterable<SuccessfulSkillRead>,
202
+ causalBasis: string,
203
+ successfulArtifactReads: Iterable<SuccessfulArtifactRead> = [],
204
+ ): void {
205
+ stageScopedSemanticTransition(
206
+ currentStates,
207
+ { transitions: [] },
208
+ successfulSkillReads,
209
+ causalBasis,
210
+ successfulArtifactReads,
211
+ );
212
+ }
213
+
214
+ /** Stage one canonical atomic scope cohort without changing the finalized response. */
215
+ export function stageAtomicScopePatches(
193
216
  currentStates: ScopedStates,
194
- transition: ScopedPatch,
217
+ patches: AtomicScopePatches,
195
218
  successfulSkillReads: Iterable<SuccessfulSkillRead>,
196
219
  causalBasis: string,
197
220
  successfulArtifactReads: Iterable<SuccessfulArtifactRead> = [],
198
221
  ): StagedScopedTransition {
222
+ if (!isObject(patches)) throw new Error("Atomic State Flow scope patches must be an object");
223
+ for (const key of Object.keys(patches)) {
224
+ if (!SCOPES.has(key as StateScope)) throw new Error(`Unknown atomic State Flow scope: ${key}`);
225
+ }
226
+ const transitions: ScopedPatch[] = [];
227
+ for (const scope of ["global", "cwd", "session"] as const) {
228
+ if (Object.hasOwn(patches, scope)) transitions.push({ scope, patch: patches[scope] as ScopePatch });
229
+ }
199
230
  return stageScopedSemanticTransition(
200
231
  currentStates,
201
- { transitions: [transition] },
232
+ { transitions },
202
233
  successfulSkillReads,
203
234
  causalBasis,
204
235
  successfulArtifactReads,
@@ -213,7 +244,7 @@ export function stageScopedTransition(
213
244
  successfulArtifactReads: Iterable<SuccessfulArtifactRead> = [],
214
245
  ): StagedScopedTransition {
215
246
  if (typeof transition.response !== "string" || transition.response.trim().length === 0) {
216
- throw new Error("Terminal State Flow response body must be non-empty");
247
+ throw new Error("Accepted State Flow response body must be non-empty");
217
248
  }
218
249
  return stageScopedSemanticTransition(
219
250
  currentStates,
@@ -227,7 +258,7 @@ export function stageScopedTransition(
227
258
 
228
259
  /** Commit one accepted transition; durable publication receives all changed scopes as one cohort. */
229
260
  export interface CommitScopedTransitionOptions {
230
- /** Terminal reconciliation finalizes bootstrap and validation lifecycle state. */
261
+ /** Runtime response reconciliation finalizes bootstrap lifecycle state. */
231
262
  finalizeRun?: boolean;
232
263
  }
233
264
 
@@ -240,10 +271,10 @@ export function commitScopedTransition(
240
271
  options: CommitScopedTransitionOptions = {},
241
272
  ): boolean {
242
273
  if (stage.committed) return false;
243
- if (causalBasis !== stage.causalBasis) throw new Error("State Flow causal basis changed after response validation; regenerate the terminal response");
274
+ if (causalBasis !== stage.causalBasis) throw new Error("State Flow causal basis changed before response reconciliation; rematerialize state before retrying");
244
275
  for (const scope of SCOPES) {
245
276
  if (hashJson(states[scope]) !== stage.stateHashes[scope]) {
246
- throw new Error(`State Flow ${scope} scope changed after response validation; regenerate the terminal response`);
277
+ throw new Error(`State Flow ${scope} scope changed before response reconciliation; rematerialize state before retrying`);
247
278
  }
248
279
  }
249
280
  // The finalized response may differ from message_end after chained handlers.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llblab/pi-state-flow",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "private": false,
5
5
  "description": "Incremental scoped state/context compiler for Pi, inspired by SKILL.state",
6
6
  "keywords": [
@@ -88,18 +88,18 @@ Adjust only identified defects. This is a semantic review, not a request for ext
88
88
 
89
89
  ## Apply one reconciliation cohort
90
90
 
91
- Use `patch_state` only for material changes to `artifacts`, `contract`, or `working`. Each call must be alone in its assistant response; reconsider subsequent actions from the rematerialized state. Do not patch runtime-owned `response`, config, or metadata, or bypass validation by editing backing files.
91
+ Use `patch_state` only for material changes to `artifacts`, `contract`, or `working`. One call may supply `global`, `cwd`, and `session` patches as one atomic cohort; each call must be alone in its assistant response, and subsequent actions must use the rematerialized state. Set `final:true` only when the iteration is eligible to finish at a later `turn_end`. Do not patch runtime-owned `response`, config, or metadata, or bypass validation by editing backing files.
92
92
 
93
93
  Schedule acquisition and migration barriers in this order:
94
94
 
95
95
  1. After reading this Skill, compile it into its exact-path CWD artifact before acquiring a stale global Markdown source or attempting an unrelated state write.
96
- 2. Read only the smallest required state projections. If a justified stale Markdown read creates a global compilation obligation, accept that compilation before an unrelated single-scope write.
96
+ 2. Read only the smallest required state projections. If a justified stale Markdown read creates a global compilation obligation, include every pending compilation scope in the next atomic patch before unrelated work.
97
97
  3. Write the migration destination with `patch_state`, verify it with a separate `read_state`, then delete or narrow the source and verify both its scope and the effective overlay. Do all readback before the terminal answer.
98
- 4. Complete one terminal reconciliation without repeating accepted compilations or inventing memory changes. Simultaneously pending CWD and global acquisitions require complete compilation through the existing terminal multi-scope reconciliation; do not bypass them with an insufficient single-scope patch.
98
+ 4. Complete one terminal reconciliation without repeating accepted compilations or inventing memory changes. Simultaneously pending CWD and global acquisitions must be compiled together in one atomic `patch_state` call; set `final:true` in that call only when the iteration is otherwise ready to finish.
99
99
 
100
100
  Scope-local deletion may reveal a lower-scope value. Deleting an override is not necessarily removal from effective state.
101
101
 
102
- For movement between State Flow scopes, resolve destination conflicts before writing; do not overwrite stronger or unrelated knowledge. Write and verify the destination before deleting the source. Separate calls are not an atomic multi-scope transaction; allow a temporary duplicate rather than a gap. Do not claim migration is complete until source cleanup and the effective result are verified.
102
+ For movement between State Flow scopes, resolve destination conflicts before writing; do not overwrite stronger or unrelated knowledge. Write and verify the destination before deleting the source. Do not combine destination creation and source deletion merely because multi-scope publication is atomic: preserve a temporary duplicate until readback proves the destination. Do not claim migration is complete until source cleanup and the effective result are verified.
103
103
 
104
104
  On rejection, interruption, or conflicting state, inspect what was actually accepted before continuing. Never assume the entire cohort succeeded or failed. Keep recovery bounded; report a blocker rather than repeatedly regenerating patches.
105
105
 
package/lib/validation.ts DELETED
@@ -1,27 +0,0 @@
1
- import { terminalRegenerationInstruction } from "./terminal.ts";
2
-
3
- export const MAX_VALIDATION_RETRIES = 3;
4
-
5
- export interface ValidationFeedback {
6
- attempt: number;
7
- error: string;
8
- instruction: string;
9
- }
10
-
11
- export type ValidationDecision =
12
- | { kind: "retry"; feedback: ValidationFeedback }
13
- | { kind: "exhausted"; error: string };
14
-
15
- /** Decide retry progression without mutating persistent runtime state. */
16
- export function nextValidation(previous: ValidationFeedback | undefined, error: string): ValidationDecision {
17
- const attempt = (previous?.attempt ?? 0) + 1;
18
- if (attempt > MAX_VALIDATION_RETRIES) return { kind: "exhausted", error };
19
- return {
20
- kind: "retry",
21
- feedback: {
22
- attempt,
23
- error,
24
- instruction: terminalRegenerationInstruction(error),
25
- },
26
- };
27
- }