@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/index.ts CHANGED
@@ -1,4 +1,111 @@
1
+ export {
2
+ ArtifactReadTracker,
3
+ decideArtifactAcquisition,
4
+ type ArtifactAcquisitionDecision,
5
+ type ArtifactAcquisitionIntent,
6
+ type ArtifactAcquisitionOptions,
7
+ type ArtifactAcquisitionReason,
8
+ type SuccessfulArtifactRead,
9
+ } from "./lib/acquisition.ts";
10
+ export {
11
+ classifyArtifactFreshness,
12
+ hashArtifactSource,
13
+ isArtifactHash,
14
+ isArtifactMetadata,
15
+ isArtifactRegistry,
16
+ ORDINARY_ARTIFACT_COMPILER,
17
+ planArtifactInvalidation,
18
+ updateArtifactRegistry,
19
+ validateArtifactMetadata,
20
+ validateArtifactRegistry,
21
+ type ArtifactCompilationUpdate,
22
+ type ArtifactCompilerOutput,
23
+ type ArtifactFreshness,
24
+ type ArtifactInvalidationOptions,
25
+ type ArtifactInvalidationPlan,
26
+ type ArtifactInvalidationReason,
27
+ type ArtifactInvalidationRequest,
28
+ type ArtifactMetadata,
29
+ type ArtifactRegistry,
30
+ type ArtifactSourceIdentity,
31
+ } from "./lib/artifact.ts";
32
+ export {
33
+ discoverGlobalMarkdownSources,
34
+ getKnowledgeRoot,
35
+ GlobalMarkdownDiscovery,
36
+ type ArtifactSourceCandidate,
37
+ type GlobalMarkdownDiscoveryResult,
38
+ } from "./lib/discovery.ts";
39
+ export {
40
+ DEFAULT_ARTIFACT_MAINTENANCE_MAX_READS,
41
+ DEFAULT_ARTIFACT_MAINTENANCE_MAX_SOURCE_BYTES,
42
+ DEFAULT_ARTIFACT_MAINTENANCE_MINIMUM_AGE_MS,
43
+ planArtifactMaintenance,
44
+ type ArtifactMaintenanceOptions,
45
+ type ArtifactMaintenancePlan,
46
+ type ArtifactMaintenanceRequest,
47
+ } from "./lib/maintenance.ts";
48
+ export {
49
+ captureTemporalFileBases,
50
+ cwdScopeKey,
51
+ getDurableRepositoryRoot,
52
+ isStateFlowOwnedPath,
53
+ loadScopeStream,
54
+ parseScopeStream,
55
+ serializeScopeStream,
56
+ sessionScopeKey,
57
+ sessionStorageKey,
58
+ sessionRuntimePaths,
59
+ temporalScopePaths,
60
+ temporalStateFileUpdates,
61
+ type TemporalScopePaths,
62
+ type ScopeStreamSources,
63
+ } from "./lib/durable.ts";
64
+ export {
65
+ captureTemporalGitBase,
66
+ loadTemporalRevision,
67
+ migrateLegacyStorageToGit,
68
+ publishTemporalStateToGit,
69
+ pushGitCommit,
70
+ type TemporalGitBase,
71
+ type TemporalRevisionLoad,
72
+ type GitPushResult,
73
+ } from "./lib/git.ts";
74
+ export {
75
+ createAcceptedTransition,
76
+ projectRecentTransitionsWithLimit,
77
+ RECENT_TRANSITION_LIMIT,
78
+ validateRecentTransition,
79
+ type RecentScopePatch,
80
+ type RecentTransition,
81
+ type RecentTransitionWindow,
82
+ type AcceptedTransition,
83
+ } from "./lib/history.ts";
1
84
  export { applyPatch, canonicalJson, hashJson, isObject, validatePatch } from "./lib/json.ts";
2
85
  export type { JsonObject, JsonValue } from "./lib/json.ts";
3
- export { emptyState, isStateDocument, type StateDocument } from "./lib/state.ts";
4
- export { default } from "./lib/extension.ts";
86
+ export {
87
+ emptyState,
88
+ isMaterializedState,
89
+ isStateDocument,
90
+ overlayStates,
91
+ updateMaterializedArtifacts,
92
+ type MaterializedState,
93
+ type ScopePatch,
94
+ type ScopedPatch,
95
+ type ScopedStates,
96
+ type SemanticTransition,
97
+ type StateDocument,
98
+ type StatePatch,
99
+ type StateScope,
100
+ type TerminalTransition,
101
+ } from "./lib/state.ts";
102
+ export {
103
+ hasCompiledSkillArtifact,
104
+ hashSkillSource,
105
+ migrateLegacySkillCompilations,
106
+ SKILL_ARTIFACT_COMPILER,
107
+ type SuccessfulSkillRead,
108
+ } from "./lib/skills.ts";
109
+ export { default, PATCH_STATE_TOOL_NAME, READ_STATE_TOOL_NAME, type StateFlowExtensionOptions } from "./lib/extension.ts";
110
+ export { TemporalRuntime } from "./lib/runtime.ts";
111
+ export { advanceTemporalState, readTemporalState, type TemporalState } from "./lib/temporal.ts";
@@ -0,0 +1,138 @@
1
+ import {
2
+ classifyArtifactFreshness,
3
+ type ArtifactInvalidationReason,
4
+ type ArtifactInvalidationRequest,
5
+ type ArtifactSourceIdentity,
6
+ } from "./artifact.ts";
7
+ import { isObject } from "./json.ts";
8
+
9
+ /** Why the caller is considering source-body acquisition. */
10
+ export type ArtifactAcquisitionIntent =
11
+ | "routine"
12
+ | "new-session"
13
+ | "relevant-gap"
14
+ | "exact-source"
15
+ | "exact-edit"
16
+ | "contradiction-or-failure"
17
+ | "explicit-request"
18
+ | "maintenance";
19
+
20
+ export type ArtifactAcquisitionReason =
21
+ | ArtifactInvalidationReason
22
+ | "materialized-gap"
23
+ | "exact-source"
24
+ | "exact-edit"
25
+ | "contradiction-or-failure"
26
+ | "explicit-request"
27
+ | "maintenance";
28
+
29
+ export type ArtifactAcquisitionDecision =
30
+ | { kind: "use-materialized"; reason: "no-concrete-need" | "materialized-sufficient" }
31
+ | { kind: "read-source"; reason: ArtifactAcquisitionReason };
32
+
33
+ export interface ArtifactAcquisitionOptions {
34
+ intent: ArtifactAcquisitionIntent;
35
+ /** Caller-assessed semantic sufficiency; only relevant to a concrete relevant gap. */
36
+ materializedSufficient?: boolean;
37
+ explicitRefresh?: boolean;
38
+ }
39
+
40
+ /** A successful read correlated to a runtime-observed invalidation candidate. */
41
+ export interface SuccessfulArtifactRead extends ArtifactInvalidationRequest {}
42
+
43
+ interface PendingRead {
44
+ toolName: string;
45
+ args: unknown;
46
+ }
47
+
48
+ function readPath(toolName: unknown, args: unknown): string | undefined {
49
+ return toolName === "read" && isObject(args) && typeof args.path === "string"
50
+ ? args.path
51
+ : undefined;
52
+ }
53
+
54
+ /** Correlate successful read-tool executions with the current ordinary artifact invalidation plan. */
55
+ export class ArtifactReadTracker {
56
+ readonly successful = new Map<string, SuccessfulArtifactRead>();
57
+ readonly #pending = new Map<string, PendingRead>();
58
+ readonly #candidates = new Map<string, ArtifactInvalidationRequest>();
59
+
60
+ setCandidates(candidates: Iterable<ArtifactInvalidationRequest>): void {
61
+ this.#candidates.clear();
62
+ for (const candidate of candidates) this.#candidates.set(candidate.path, structuredClone(candidate));
63
+ }
64
+
65
+ clear(): void {
66
+ this.successful.clear();
67
+ this.#pending.clear();
68
+ }
69
+
70
+ recordStart(toolCallId: string, toolName: string, args: unknown): void {
71
+ this.#record(toolCallId, toolName, args);
72
+ }
73
+
74
+ recordCall(toolCallId: string, toolName: string, input: unknown): void {
75
+ this.#record(toolCallId, toolName, input);
76
+ }
77
+
78
+ recordEnd(toolCallId: string, toolName: string, isError: boolean): void {
79
+ const pending = this.#pending.get(toolCallId);
80
+ this.#pending.delete(toolCallId);
81
+ if (isError || !pending || toolName !== pending.toolName) return;
82
+ const path = readPath(pending.toolName, pending.args);
83
+ if (path === undefined) return;
84
+ const candidate = this.#candidates.get(path);
85
+ if (candidate !== undefined) this.successful.set(path, structuredClone(candidate));
86
+ }
87
+
88
+ #record(toolCallId: string, toolName: string, args: unknown): void {
89
+ if (toolName !== "read") {
90
+ this.#pending.delete(toolCallId);
91
+ return;
92
+ }
93
+ this.#pending.set(toolCallId, { toolName, args });
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Apply one materialized-first source acquisition policy.
99
+ *
100
+ * Freshness invalidation always wins. Otherwise routine use and a new session
101
+ * stay on materialized state; only a concrete source need permits rereading.
102
+ */
103
+ export function decideArtifactAcquisition(
104
+ source: ArtifactSourceIdentity,
105
+ metadata: unknown,
106
+ compiler: string,
107
+ options: ArtifactAcquisitionOptions,
108
+ ): ArtifactAcquisitionDecision {
109
+ const freshness = classifyArtifactFreshness(
110
+ source,
111
+ metadata,
112
+ compiler,
113
+ options.explicitRefresh ?? false,
114
+ );
115
+ if (freshness.kind === "requires-compilation") {
116
+ return { kind: "read-source", reason: freshness.reason };
117
+ }
118
+
119
+ switch (options.intent) {
120
+ case "routine":
121
+ case "new-session":
122
+ return { kind: "use-materialized", reason: "no-concrete-need" };
123
+ case "relevant-gap":
124
+ return options.materializedSufficient === true
125
+ ? { kind: "use-materialized", reason: "materialized-sufficient" }
126
+ : { kind: "read-source", reason: "materialized-gap" };
127
+ case "exact-source":
128
+ return { kind: "read-source", reason: "exact-source" };
129
+ case "exact-edit":
130
+ return { kind: "read-source", reason: "exact-edit" };
131
+ case "contradiction-or-failure":
132
+ return { kind: "read-source", reason: "contradiction-or-failure" };
133
+ case "explicit-request":
134
+ return { kind: "read-source", reason: "explicit-request" };
135
+ case "maintenance":
136
+ return { kind: "read-source", reason: "maintenance" };
137
+ }
138
+ }
@@ -0,0 +1,245 @@
1
+ import { createHash } from "node:crypto";
2
+ import { containsNull, isJsonValue, isObject, type JsonObject } from "./json.ts";
3
+
4
+ const SHA256_PATTERN = /^sha256:[0-9a-f]{64}$/;
5
+
6
+ /** Current compiler protocol for ordinary source artifacts such as Knowledge Markdown. */
7
+ export const ORDINARY_ARTIFACT_COMPILER = "artifact-v1";
8
+
9
+ /** Source-addressed metadata retained after artifact compilation. */
10
+ export type ArtifactMetadata = JsonObject & {
11
+ description: string;
12
+ hash: string;
13
+ compiler: string;
14
+ compiled_at?: string;
15
+ compilation?: JsonObject;
16
+ kind?: string;
17
+ };
18
+
19
+ /** Artifact source paths are the canonical registry keys. */
20
+ export type ArtifactRegistry = JsonObject & Record<string, ArtifactMetadata>;
21
+
22
+ /** Source identity is sufficient for freshness decisions; it never contains the source body. */
23
+ export interface ArtifactSourceIdentity {
24
+ path: string;
25
+ hash: string;
26
+ }
27
+
28
+ export type ArtifactInvalidationReason =
29
+ | "new"
30
+ | "source-changed"
31
+ | "compiler-changed"
32
+ | "invalid-metadata"
33
+ | "explicit-refresh";
34
+
35
+ export type ArtifactFreshness =
36
+ | { kind: "fresh" }
37
+ | { kind: "requires-compilation"; reason: ArtifactInvalidationReason };
38
+
39
+ export interface ArtifactInvalidationRequest extends ArtifactSourceIdentity {
40
+ reason: ArtifactInvalidationReason;
41
+ }
42
+
43
+ export interface ArtifactInvalidationPlan {
44
+ fresh: ArtifactSourceIdentity[];
45
+ requiresCompilation: ArtifactInvalidationRequest[];
46
+ removed: string[];
47
+ }
48
+
49
+ export interface ArtifactInvalidationOptions {
50
+ /** Refresh every source, or only paths in the supplied set. */
51
+ explicitRefresh?: boolean | ReadonlySet<string>;
52
+ }
53
+
54
+ /** Compiler-owned fields before State Flow attaches trusted source freshness metadata. */
55
+ export type ArtifactCompilerOutput = JsonObject & {
56
+ description: string;
57
+ compiled_at?: string;
58
+ compilation?: JsonObject;
59
+ kind?: string;
60
+ };
61
+
62
+ export interface ArtifactCompilationUpdate {
63
+ source: ArtifactSourceIdentity;
64
+ compiler: string;
65
+ output: ArtifactCompilerOutput;
66
+ }
67
+
68
+ export function hashArtifactSource(source: string | Uint8Array): string {
69
+ return `sha256:${createHash("sha256").update(source).digest("hex")}`;
70
+ }
71
+
72
+ export function isArtifactHash(value: unknown): value is string {
73
+ return typeof value === "string" && SHA256_PATTERN.test(value);
74
+ }
75
+
76
+ export function validateArtifactMetadata(value: unknown, path = "<unknown>"): asserts value is ArtifactMetadata {
77
+ if (!isObject(value) || !isJsonValue(value)) {
78
+ throw new Error(`Artifact metadata at ${path} must be finite, acyclic JSON data`);
79
+ }
80
+ if (containsNull(value)) throw new Error(`Artifact metadata at ${path} cannot contain null`);
81
+ if (typeof value.description !== "string" || value.description.trim().length === 0) {
82
+ throw new Error(`Artifact metadata at ${path} must have a non-empty description`);
83
+ }
84
+ if (!isArtifactHash(value.hash)) {
85
+ throw new Error(`Artifact metadata at ${path} must have a sha256:<64 lowercase hex characters> hash`);
86
+ }
87
+ if (typeof value.compiler !== "string" || value.compiler.trim().length === 0) {
88
+ throw new Error(`Artifact metadata at ${path} must have a non-empty compiler revision`);
89
+ }
90
+ if (Object.hasOwn(value, "compiled_at") && typeof value.compiled_at !== "string") {
91
+ throw new Error(`Artifact metadata at ${path} compiled_at must be a string`);
92
+ }
93
+ if (Object.hasOwn(value, "compilation") && !isObject(value.compilation)) {
94
+ throw new Error(`Artifact metadata at ${path} compilation must be an object`);
95
+ }
96
+ if (Object.hasOwn(value, "kind")
97
+ && (typeof value.kind !== "string" || value.kind.trim().length === 0)) {
98
+ throw new Error(`Artifact metadata at ${path} kind must be a non-empty string`);
99
+ }
100
+ }
101
+
102
+ export function isArtifactMetadata(value: unknown): value is ArtifactMetadata {
103
+ try {
104
+ validateArtifactMetadata(value);
105
+ return true;
106
+ } catch {
107
+ return false;
108
+ }
109
+ }
110
+
111
+ export function validateArtifactRegistry(value: unknown): asserts value is ArtifactRegistry {
112
+ if (!isObject(value)) throw new Error("Artifacts must be a path-keyed JSON object");
113
+ for (const [path, metadata] of Object.entries(value)) {
114
+ if (path.trim().length === 0) throw new Error("Artifact path keys must be non-empty");
115
+ validateArtifactMetadata(metadata, path);
116
+ }
117
+ }
118
+
119
+ export function isArtifactRegistry(value: unknown): value is ArtifactRegistry {
120
+ try {
121
+ validateArtifactRegistry(value);
122
+ return true;
123
+ } catch {
124
+ return false;
125
+ }
126
+ }
127
+
128
+ function validateSourceIdentity(source: ArtifactSourceIdentity): void {
129
+ if (typeof source.path !== "string" || source.path.trim().length === 0) {
130
+ throw new Error("Artifact source path must be non-empty");
131
+ }
132
+ if (!isArtifactHash(source.hash)) {
133
+ throw new Error(`Artifact source at ${source.path} must have a sha256:<64 lowercase hex characters> hash`);
134
+ }
135
+ }
136
+
137
+ function validateCompilerRevision(compiler: string, path?: string): void {
138
+ if (typeof compiler !== "string" || compiler.trim().length === 0) {
139
+ throw new Error(path === undefined
140
+ ? "Artifact compiler revision must be non-empty"
141
+ : `Artifact compiler revision at ${path} must be non-empty`);
142
+ }
143
+ }
144
+
145
+ function refreshRequested(path: string, explicitRefresh: boolean | ReadonlySet<string> | undefined): boolean {
146
+ if (explicitRefresh === true) return true;
147
+ if (!explicitRefresh || typeof explicitRefresh !== "object" || typeof explicitRefresh.has !== "function") return false;
148
+ return explicitRefresh.has(path);
149
+ }
150
+
151
+ /** Classify freshness from source identity and metadata without acquiring the source body. */
152
+ export function classifyArtifactFreshness(
153
+ source: ArtifactSourceIdentity,
154
+ metadata: unknown,
155
+ compiler: string,
156
+ explicitRefresh = false,
157
+ ): ArtifactFreshness {
158
+ validateSourceIdentity(source);
159
+ validateCompilerRevision(compiler);
160
+ if (metadata === undefined) return { kind: "requires-compilation", reason: "new" };
161
+ if (!isArtifactMetadata(metadata)) return { kind: "requires-compilation", reason: "invalid-metadata" };
162
+ if (metadata.hash !== source.hash) return { kind: "requires-compilation", reason: "source-changed" };
163
+ if (metadata.compiler !== compiler) return { kind: "requires-compilation", reason: "compiler-changed" };
164
+ if (explicitRefresh) return { kind: "requires-compilation", reason: "explicit-refresh" };
165
+ return { kind: "fresh" };
166
+ }
167
+
168
+ /** Produce a deterministic acquisition plan from path/hash candidates alone. */
169
+ export function planArtifactInvalidation(
170
+ sources: readonly ArtifactSourceIdentity[],
171
+ registry: Readonly<Record<string, unknown>>,
172
+ compiler: string,
173
+ options: ArtifactInvalidationOptions = {},
174
+ ): ArtifactInvalidationPlan {
175
+ if (!isObject(registry)) throw new Error("Artifacts must be a path-keyed JSON object");
176
+ validateCompilerRevision(compiler);
177
+ const ordered = [...sources].sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
178
+ const seen = new Set<string>();
179
+ const fresh: ArtifactSourceIdentity[] = [];
180
+ const requiresCompilation: ArtifactInvalidationRequest[] = [];
181
+ for (const source of ordered) {
182
+ if (seen.has(source.path)) throw new Error(`Duplicate artifact source path: ${source.path}`);
183
+ seen.add(source.path);
184
+ const metadata = Object.hasOwn(registry, source.path) ? registry[source.path] : undefined;
185
+ const freshness = classifyArtifactFreshness(
186
+ source,
187
+ metadata,
188
+ compiler,
189
+ refreshRequested(source.path, options.explicitRefresh),
190
+ );
191
+ const identity = { path: source.path, hash: source.hash };
192
+ if (freshness.kind === "fresh") fresh.push(identity);
193
+ else requiresCompilation.push({ ...identity, reason: freshness.reason });
194
+ }
195
+ const removed = Object.keys(registry).filter((path) => !seen.has(path)).sort();
196
+ return { fresh, requiresCompilation, removed };
197
+ }
198
+
199
+ function compilationMetadata(update: ArtifactCompilationUpdate): ArtifactMetadata {
200
+ validateSourceIdentity(update.source);
201
+ validateCompilerRevision(update.compiler, update.source.path);
202
+ if (!isObject(update.output) || Object.hasOwn(update.output, "hash") || Object.hasOwn(update.output, "compiler")) {
203
+ throw new Error(`Artifact compiler output at ${update.source.path} cannot set runtime-owned hash or compiler fields`);
204
+ }
205
+ const metadata = {
206
+ ...structuredClone(update.output),
207
+ hash: update.source.hash,
208
+ compiler: update.compiler,
209
+ };
210
+ validateArtifactMetadata(metadata, update.source.path);
211
+ return metadata;
212
+ }
213
+
214
+ /** Validate and apply a whole compilation/removal cohort without mutating the prior registry. */
215
+ export function updateArtifactRegistry(
216
+ registry: ArtifactRegistry,
217
+ updates: readonly ArtifactCompilationUpdate[],
218
+ removed: readonly string[] = [],
219
+ ): ArtifactRegistry {
220
+ validateArtifactRegistry(registry);
221
+ const compiled = new Map<string, ArtifactMetadata>();
222
+ for (const update of updates) {
223
+ if (compiled.has(update.source.path)) throw new Error(`Duplicate artifact compilation: ${update.source.path}`);
224
+ compiled.set(update.source.path, compilationMetadata(update));
225
+ }
226
+ const removals = new Set<string>();
227
+ for (const path of removed) {
228
+ if (typeof path !== "string" || path.trim().length === 0) throw new Error("Removed artifact paths must be non-empty");
229
+ if (removals.has(path)) throw new Error(`Duplicate artifact removal: ${path}`);
230
+ if (compiled.has(path)) throw new Error(`Artifact cannot be compiled and removed atomically: ${path}`);
231
+ removals.add(path);
232
+ }
233
+
234
+ const next = structuredClone(registry);
235
+ for (const path of removals) delete next[path];
236
+ for (const [path, metadata] of compiled) {
237
+ Object.defineProperty(next, path, {
238
+ value: metadata,
239
+ enumerable: true,
240
+ configurable: true,
241
+ writable: true,
242
+ });
243
+ }
244
+ return next;
245
+ }
package/lib/config.ts ADDED
@@ -0,0 +1,36 @@
1
+ // Domain: agent-level State Flow configuration, independent of session runtime and semantic state.
2
+ import { lstatSync, readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, resolve } from "node:path";
5
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ import { getDurableRepositoryRoot } from "./durable.ts";
7
+ import { isObject } from "./json.ts";
8
+
9
+ export interface StateFlowConfig {
10
+ directory: string;
11
+ autoStart: boolean;
12
+ }
13
+
14
+ /** Read once at extension load/reload. Missing config uses defaults; invalid config never falls back. */
15
+ export function loadStateFlowConfig(agentDir = getAgentDir()): StateFlowConfig {
16
+ const path = resolve(agentDir, "state-flow.json");
17
+ const defaults = { directory: getDurableRepositoryRoot(agentDir), autoStart: false };
18
+ let value: unknown;
19
+ try {
20
+ if (!lstatSync(path, { throwIfNoEntry: false })) return defaults;
21
+ value = JSON.parse(readFileSync(path, "utf8"));
22
+ } catch (error) {
23
+ throw new Error(`Cannot read State Flow configuration: ${path}`, { cause: error });
24
+ }
25
+ if (!isObject(value) || Object.keys(value).some((key) => key !== "directory" && key !== "autoStart")) {
26
+ throw new Error(`State Flow configuration must be an object with only directory and autoStart: ${path}`);
27
+ }
28
+ if (Object.hasOwn(value, "autoStart") && typeof value.autoStart !== "boolean") throw new Error(`State Flow autoStart must be a boolean: ${path}`);
29
+ if (Object.hasOwn(value, "directory") && (typeof value.directory !== "string" || !value.directory.trim() || value.directory.includes("\0"))) {
30
+ throw new Error(`State Flow directory must be a non-empty path: ${path}`);
31
+ }
32
+ const directory = value.directory as string | undefined;
33
+ if (directory?.startsWith("~") && directory !== "~" && !directory.startsWith("~/")) throw new Error(`State Flow directory supports ~ or ~/ paths, not named-user expansion: ${path}`);
34
+ const expanded = directory === "~" ? homedir() : directory?.startsWith("~/") ? resolve(homedir(), directory.slice(2)) : directory;
35
+ return { directory: expanded === undefined ? defaults.directory : resolve(dirname(path), expanded), autoStart: value.autoStart === true };
36
+ }
package/lib/context.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type { ArtifactInvalidationRequest } from "./artifact.ts";
3
+ import type { RecentTransitionWindow } from "./history.ts";
2
4
  import { canonicalJson } from "./json.ts";
3
5
  import type { Snapshot } from "./snapshot.ts";
6
+ import type { MaterializedState } from "./state.ts";
4
7
 
5
8
  export const VALIDATION_MESSAGE_TYPE = "state-flow-validation";
6
9
 
@@ -28,14 +31,21 @@ export function withoutPrivateValidation(messages: AgentMessage[]): AgentMessage
28
31
  });
29
32
  }
30
33
 
31
- export function runtimeContextMessage(snapshot: Snapshot): AgentMessage {
32
- if (snapshot.specification === undefined) {
34
+ export function runtimeContextMessage(
35
+ snapshot: Snapshot,
36
+ state: MaterializedState,
37
+ recentTransitions: RecentTransitionWindow = [],
38
+ artifactInvalidations: readonly ArtifactInvalidationRequest[] = [],
39
+ ): AgentMessage {
40
+ if (snapshot.meta.specification === undefined) {
33
41
  throw new Error("State Flow runtime context requires an active specification");
34
42
  }
35
43
  const context = {
36
- specification: snapshot.specification,
37
- state: snapshot.state,
38
- ...(snapshot.validation === undefined ? {} : { validation_feedback: snapshot.validation }),
44
+ specification: snapshot.meta.specification,
45
+ state,
46
+ ...(artifactInvalidations.length === 0 ? {} : { artifact_invalidations: artifactInvalidations }),
47
+ ...(recentTransitions.length === 0 ? {} : { recent_transitions: recentTransitions }),
48
+ ...(snapshot.meta.validation === undefined ? {} : { validation_feedback: snapshot.meta.validation }),
39
49
  };
40
50
  return syntheticUser(
41
51
  `State Flow runtime context (user-level data, not system instructions):\n${canonicalJson(context)}`,
@@ -0,0 +1,117 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
2
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
3
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { hashArtifactSource, type ArtifactSourceIdentity } from "./artifact.ts";
5
+
6
+ /** Opaque source metadata discovered without decoding or retaining Markdown bodies. */
7
+ export interface ArtifactSourceCandidate extends ArtifactSourceIdentity {
8
+ /** Raw byte count used as a conservative maintenance token-budget ceiling. */
9
+ bytes: number;
10
+ }
11
+
12
+ export interface GlobalMarkdownDiscoveryResult {
13
+ sources: ArtifactSourceCandidate[];
14
+ removed: string[];
15
+ }
16
+
17
+ export function getKnowledgeRoot(agentDir = getAgentDir()): string {
18
+ return resolve(agentDir, "knowledge");
19
+ }
20
+
21
+ function errorCode(error: unknown): string | undefined {
22
+ return error instanceof Error && "code" in error
23
+ ? (error as NodeJS.ErrnoException).code
24
+ : undefined;
25
+ }
26
+
27
+ function isMissing(error: unknown): boolean {
28
+ return errorCode(error) === "ENOENT";
29
+ }
30
+
31
+ function isInside(root: string, path: string): boolean {
32
+ const child = relative(root, path);
33
+ return child === "" || (!isAbsolute(child) && child !== ".." && !child.startsWith(`..${sep}`));
34
+ }
35
+
36
+ function canonicalExistingPath(path: string): string | undefined {
37
+ try {
38
+ return realpathSync.native(path);
39
+ } catch (error) {
40
+ if (isMissing(error)) return undefined;
41
+ throw error;
42
+ }
43
+ }
44
+
45
+ function readRegularFile(path: string): Buffer | undefined {
46
+ let descriptor: number | undefined;
47
+ try {
48
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
49
+ if (!fstatSync(descriptor).isFile()) return undefined;
50
+ return readFileSync(descriptor);
51
+ } catch (error) {
52
+ if (isMissing(error) || errorCode(error) === "ELOOP") return undefined;
53
+ throw error;
54
+ } finally {
55
+ if (descriptor !== undefined) closeSync(descriptor);
56
+ }
57
+ }
58
+
59
+ /** Discover regular `*.md` files beneath a Knowledge root without following directory or file symlinks. */
60
+ export function discoverGlobalMarkdownSources(knowledgeRoot = getKnowledgeRoot()): ArtifactSourceCandidate[] {
61
+ const configuredRoot = resolve(knowledgeRoot);
62
+ const root = canonicalExistingPath(configuredRoot);
63
+ if (root === undefined) return [];
64
+ if (!statSync(root).isDirectory()) throw new Error(`Knowledge root is not a directory: ${configuredRoot}`);
65
+
66
+ const sources: ArtifactSourceCandidate[] = [];
67
+ const visit = (directory: string): void => {
68
+ const entries = readdirSync(directory, { withFileTypes: true })
69
+ .sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
70
+ for (const entry of entries) {
71
+ const candidate = join(directory, entry.name);
72
+ let metadata;
73
+ try {
74
+ metadata = lstatSync(candidate);
75
+ } catch (error) {
76
+ if (isMissing(error)) continue;
77
+ throw error;
78
+ }
79
+ if (metadata.isSymbolicLink()) continue;
80
+
81
+ const canonical = canonicalExistingPath(candidate);
82
+ if (canonical === undefined || !isInside(root, canonical)) continue;
83
+ if (metadata.isDirectory()) {
84
+ visit(canonical);
85
+ continue;
86
+ }
87
+ if (!metadata.isFile() || !entry.name.endsWith(".md")) continue;
88
+
89
+ const body = readRegularFile(canonical);
90
+ if (body === undefined) continue;
91
+ sources.push({ path: canonical, hash: hashArtifactSource(body), bytes: body.byteLength });
92
+ }
93
+ };
94
+
95
+ visit(root);
96
+ return sources.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
97
+ }
98
+
99
+ /** Session-lifetime index that makes source removals explicit on each initialization refresh. */
100
+ export class GlobalMarkdownDiscovery {
101
+ readonly knowledgeRoot: string;
102
+ #knownPaths = new Set<string>();
103
+
104
+ constructor(knowledgeRoot = getKnowledgeRoot()) {
105
+ this.knowledgeRoot = resolve(knowledgeRoot);
106
+ }
107
+
108
+ refresh(): GlobalMarkdownDiscoveryResult {
109
+ const sources = discoverGlobalMarkdownSources(this.knowledgeRoot);
110
+ const currentPaths = new Set(sources.map((source) => source.path));
111
+ const removed = [...this.#knownPaths]
112
+ .filter((path) => !currentPaths.has(path))
113
+ .sort();
114
+ this.#knownPaths = currentPaths;
115
+ return { sources, removed };
116
+ }
117
+ }