@llblab/pi-state-flow 0.4.0 → 0.6.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.
@@ -0,0 +1,188 @@
1
+ # State Flow architecture
2
+
3
+ ## Purpose
4
+
5
+ State Flow is a Pi extension that materializes compact, scoped semantic state across agent runs while preserving Pi's native session trace and tool loop. It is inspired by SKILL.state but uses its own temporal model, storage plane, artifact compiler, and publication lifecycle.
6
+
7
+ The extension owns durable memory while enabled. Global semantic memory is always available; there are no ownership or global-memory feature switches.
8
+
9
+ ## Composition
10
+
11
+ `index.ts` is the public export and extension composition boundary. Independent modules under `lib/` own one concern each and are mirrored by tests:
12
+
13
+ - `state`, `json`: semantic shape, validation, recursive overlay and deletion.
14
+ - `temporal`, `history`: causal boundaries, checkpoint/tail folding and hot history.
15
+ - `durable`, `storage`, `git`: exact files, CAS publication, Git commits and restoration.
16
+ - `snapshot`, `session`, `runtime`, `recovery`, `episode`: Pi branch/runtime lifecycle.
17
+ - `transition`, `terminal`, `validation`, `context`: inference barriers and final reconciliation.
18
+ - `artifact`, `acquisition`, `maintenance`, `skills`, `rehydration`: source routing and compilation.
19
+ - `memory`: external promotion records and memory diagnostics.
20
+ - `continuation`: native-header discovery, runtime-provenance inspection, deterministic recommendation, and host startup precedence.
21
+ - `publication`: remote policy, durable CAS queue/store, cross-process leases, and asynchronous worker lifecycle.
22
+ - `status`, `extension`: operator projection and Pi adapter wiring.
23
+
24
+ ## Semantic state
25
+
26
+ Every materialized scope has exactly this shape:
27
+
28
+ ```json
29
+ {
30
+ "artifacts": {},
31
+ "contract": {},
32
+ "working": {},
33
+ "response": ""
34
+ }
35
+ ```
36
+
37
+ - `artifacts` maps exact source paths to compiled routing metadata.
38
+ - `contract` retains durable requirements, decisions, interfaces and rejected approaches.
39
+ - `working` retains verified current facts, unresolved work and exact continuation.
40
+ - `response` is the latest complete user-facing answer for the session scope.
41
+
42
+ Effective state recursively overlays:
43
+
44
+ ```text
45
+ global → CWD → session
46
+ ```
47
+
48
+ Later scopes win. A scope-local `null` deletion removes only that scope's key and may reveal an inherited value. Scope represents applicability and ownership, never instruction authority.
49
+
50
+ State Flow is the memory owner while enabled. Cross-project/user/environment knowledge belongs in global state, project-only knowledge in CWD, and branch/run continuation in session. Global availability is not a feature switch and does not authorize secrets, raw history, transient progress, speculative clutter, or unsupported assertions. Explicitly uncertain hypotheses remain eligible only when they can affect an open decision.
51
+
52
+ ## Temporal model
53
+
54
+ All scopes participate in one active causal lineage. One accepted semantic transition receives one opaque identity shared by every changed scope. Sparse transitions do not create records for unchanged scopes.
55
+
56
+ Each scope stores:
57
+
58
+ ```text
59
+ checkpoint.json + patches.jsonl
60
+ ```
61
+
62
+ The checkpoint is an older anchored materialization. The tail contains at most seven effective patches. On overflow, the oldest tail patch folds into the checkpoint before the new patch is appended.
63
+
64
+ `state[n]`, `state.global[n]`, `state.cwd[n]` and `state.session[n]` resolve the same nth previous causal boundary. They are not independent per-scope patch counters. Pre-origin history is unavailable rather than empty.
65
+
66
+ True semantic no-ops create no identity, commit or history step. A changed finalized response is semantic state and advances history.
67
+
68
+ ## Pi lifecycle
69
+
70
+ `patch_state` is the sole mutation tool. It validates and publishes one scope patch immediately, then acts as an inference barrier. Pi executes no sibling tools from the same assistant response; the next inference sees rematerialized `state[0]`.
71
+
72
+ `read_state` reads one cached effective or scoped projection at offsets zero through seven. It never publishes or advances history.
73
+
74
+ Every successful enabled run ends with terminal reconciliation. A private `state_flow` comment may provide multi-scope transitions, followed by one blank line and the visible answer. An ordinary answer means an empty model patch but still updates session `response` when changed. Pi's finalized message at `turn_end` is authoritative for response reconciliation.
75
+
76
+ The current user specification stays at user authority and appears only in synthetic user runtime context. State is fallible assistant-produced data. Completed trajectories leave model context at user-run boundaries, while Pi's full JSONL trace remains inspectable.
77
+
78
+ ## Storage and identity
79
+
80
+ The default store is `<agentDir>/state-flow`, independent from Markdown discovery at `<agentDir>/knowledge`.
81
+
82
+ Owned paths are:
83
+
84
+ ```text
85
+ checkpoint.json
86
+ patches.jsonl
87
+ <cwd-key>/checkpoint.json
88
+ <cwd-key>/patches.jsonl
89
+ <cwd-key>/<session-key>/checkpoint.json
90
+ <cwd-key>/<session-key>/patches.jsonl
91
+ <cwd-key>/<session-key>/config.json
92
+ <cwd-key>/<session-key>/meta.json
93
+ ```
94
+
95
+ CWD and session keys mirror Pi's native encoding. The Pi UUID remains authoritative; readable directory keys never replace identity validation.
96
+
97
+ `config.json` owns branch runtime behavior. `meta.json` owns lineage, counters, identity, publication provenance and remote-publication policy. Pi checkpoints retain only an exact Git revision, an exact `file:<hash>` cohort reference, or a proven ordinary-disabled marker.
98
+
99
+ All owned writes use same-directory atomic replacement, regular-file and symlink checks, prepared byte receipts and CAS validation. Unrelated files, staging and concurrent bytes are preserved. Rollback restores only bytes still matching the failed publisher's output.
100
+
101
+ ## Optional Git
102
+
103
+ If Git is unavailable specifically through executable `ENOENT`, State Flow uses file-only persistence. File mode retains exact current materialization and proven hot history but offers no arbitrary cold revisions.
104
+
105
+ With Git, each effective semantic cohort creates one local commit immediately through an isolated index. Git supplies cold history and exact branch restoration. Runtime `revision: "self"` resolves to the commit that owns the runtime record, never arbitrary `HEAD`. Runtime-only writes may use `temporalRevision` to select older semantic streams without rewinding live shared files.
106
+
107
+ Installing Git over a file-only store adopts the exact current cohort without fabricating earlier history. Legacy layouts remain read-only historical inputs until explicitly migrated.
108
+
109
+ ## Remote publication
110
+
111
+ Local acceptance and remote replication are separate.
112
+
113
+ The persisted `remotePublication` policy is:
114
+
115
+ - `turn-end`: default for new runtimes; local commits are immediate and the newest turn target is queued.
116
+ - `off`: local commits only.
117
+ - `transition`: synchronous compatibility behavior for legacy runtimes.
118
+
119
+ A destination is identified by canonical Git common directory, remote and full ref. Queue files live beneath the Git common directory and are not semantic history.
120
+
121
+ The queue uses exact commit targets, strict versioned JSON, symlink-safe atomic writes, CAS receipts and exclusive writer locks. A proven descendant may supersede an older target; divergent targets and changed destinations fail closed.
122
+
123
+ After terminal acceptance, an asynchronous non-interactive worker pushes the newest target. Queue failure never rolls back semantic state or regenerates an answer. Failed and interrupted attempts remain retryable across restart. Destination-scoped worker leases prevent cross-process overlap, preserve live owners, recover proven-dead owners and use exact release tokens. Confirmation removes only the exact completed target; a newer descendant remains queued.
124
+
125
+ ## Artifact routing
126
+
127
+ Markdown discovery recursively finds regular lowercase `*.md` beneath the configured Knowledge root, rejects symlinks, hashes opaque bytes and never injects source bodies.
128
+
129
+ Artifact metadata requires:
130
+
131
+ ```json
132
+ {
133
+ "description": "routing summary",
134
+ "hash": "sha256:<source bytes>",
135
+ "compiler": "artifact-v1"
136
+ }
137
+ ```
138
+
139
+ Compiler output may add arbitrary finite non-null JSON metadata. Known optional fields include `kind`, `compiled_at`, `tags` and `compilation`. Tags are unique trimmed non-empty strings and support deterministic candidate filtering, but never authorize reading.
140
+
141
+ Freshness depends on source hash and compiler revision. New, changed, compiler-stale, malformed or explicitly refreshed sources become invalidations. Exact successful native Pi reads are correlated with current candidates; stale reads require same-path compiler output before trusted hash/compiler metadata is attached.
142
+
143
+ Compilation is routing, not a substitute for source text. Full source is read only for a concrete unresolved gap, exact source/edit operation, invalidation, contradiction/failure, explicit request or bounded maintenance. The rehydration planner supports new-bootstrap, resume-bootstrap and later-step phases while limiting read count and source bytes without performing hidden I/O.
144
+
145
+ Skills are CWD artifacts with stricter compilation: `kind: "skill"` and a non-empty compilation describing applicability, constraints and failure conditions. Their source bodies do not persist in state. Matching source hash and compiler metadata proves source-version consistency, not semantic fidelity, truth, or higher instruction authority.
146
+
147
+ ## Memory curation and promotion
148
+
149
+ The optional packaged `state-flow-memory` Skill performs bounded explicit audits, scope narrowing, contradiction cleanup and external handoffs. It is not part of ordinary retention or background maintenance. Curation compiles a read Skill at CWD before accumulating global compilation obligations, writes and separately reads a migration destination before source deletion, then verifies the changed scope and effective overlay. Simultaneously pending CWD/global acquisitions use existing terminal multi-scope reconciliation; `patch_state` remains single-scope and separate calls are not atomic migration.
150
+
151
+ External promotion remains a semantic two-phase handoff, not a memory-owner mode. Optional global `working.memory_promotions` entries record `pending`, `accepted`, `failed` or `unknown` status plus owner. Accepted records additionally require destination pointer and revision. Failed or uncertain promotion preserves the State Flow candidate; the only accepted copy is never deleted.
152
+
153
+ ## Session continuation
154
+
155
+ The package exposes read-only host contracts that:
156
+
157
+ - read only native JSONL headers, never transcript bodies;
158
+ - inspect exact file/Git State Flow runtime provenance without mutation;
159
+ - rank exact profile, CWD, Git common-directory, worktree, branch and transport identity;
160
+ - fail closed for stopped, malformed, unavailable or ambiguous candidates;
161
+ - preserve explicit new/resume and native picker precedence;
162
+ - project new-bootstrap, resume-bootstrap and later-step rehydration phases.
163
+
164
+ Pi 0.84.4 chooses or creates `SessionManager` before package resources and extensions load. Therefore native default auto-resume cannot be installed safely by this extension alone. The remaining host integration requires an upstream pre-session resolver hook or an SDK/launcher that invokes the advisory resolver before constructing the session.
165
+
166
+ ## Configuration
167
+
168
+ `state-flow.json` is loaded once per extension load/reload:
169
+
170
+ ```json
171
+ {
172
+ "directory": "~/.pi/agent/state-flow",
173
+ "autoStart": false,
174
+ "remotePublication": "turn-end"
175
+ }
176
+ ```
177
+
178
+ Unknown keys fail loading. State Flow memory ownership and global availability are fixed invariants and have no configuration options.
179
+
180
+ ## Observability
181
+
182
+ `/state-flow-status` reports branch mode, runtime revision, temporal head/history depth, scope keys, patch tails, artifact freshness, memory-bearing scopes, external-promotion summaries, remote policy/queue state, pending publication and terminal retry state. Unavailable materialization is reported as unavailable, never fabricated as empty. Artifact source bodies are not read for status.
183
+
184
+ ## Validation boundaries
185
+
186
+ Structural validation proves JSON shape, exact identity, causal lineage, freshness, CAS and publication invariants. A valid state, receipt, source hash, or compiler revision cannot prove semantic importance, truth, sufficient compilation, correct scope, useful curation, or historical deletion. Those remain model-judgment concerns evaluated separately from deterministic transport checks.
187
+
188
+ The continuity requirement and deterministic evidence map is in [continuity-acceptance.md](continuity-acceptance.md). The executable temporal requirement map is in [temporal-acceptance.md](temporal-acceptance.md). Canonical remaining work is in [BACKLOG.md](../BACKLOG.md), and shipped outcomes belong in [CHANGELOG.md](../CHANGELOG.md).
package/index.ts CHANGED
@@ -1,111 +1,166 @@
1
1
  export {
2
- ArtifactReadTracker,
3
- decideArtifactAcquisition,
4
- type ArtifactAcquisitionDecision,
5
- type ArtifactAcquisitionIntent,
6
- type ArtifactAcquisitionOptions,
7
- type ArtifactAcquisitionReason,
8
- type SuccessfulArtifactRead,
2
+ ArtifactReadTracker,
3
+ decideArtifactAcquisition,
4
+ type ArtifactAcquisitionDecision,
5
+ type ArtifactAcquisitionIntent,
6
+ type ArtifactAcquisitionOptions,
7
+ type ArtifactAcquisitionReason,
8
+ type SuccessfulArtifactRead
9
9
  } from "./lib/acquisition.ts";
10
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,
11
+ classifyArtifactFreshness,
12
+ hashArtifactSource,
13
+ isArtifactHash,
14
+ isArtifactMetadata,
15
+ isArtifactRegistry,
16
+ ORDINARY_ARTIFACT_COMPILER,
17
+ planArtifactInvalidation,
18
+ selectArtifactsByTags,
19
+ updateArtifactRegistry,
20
+ validateArtifactMetadata,
21
+ validateArtifactRegistry,
22
+ type ArtifactCompilationUpdate,
23
+ type ArtifactCompilerOutput,
24
+ type ArtifactFreshness,
25
+ type ArtifactInvalidationOptions,
26
+ type ArtifactInvalidationPlan,
27
+ type ArtifactInvalidationReason,
28
+ type ArtifactInvalidationRequest,
29
+ type ArtifactMetadata,
30
+ type ArtifactRegistry,
31
+ type ArtifactSourceIdentity
31
32
  } from "./lib/artifact.ts";
32
33
  export {
33
- discoverGlobalMarkdownSources,
34
- getKnowledgeRoot,
35
- GlobalMarkdownDiscovery,
36
- type ArtifactSourceCandidate,
37
- type GlobalMarkdownDiscoveryResult,
38
- } from "./lib/discovery.ts";
34
+ buildContinuationCandidates,
35
+ discoverNativeSessionHeaders,
36
+ inspectStateFlowContinuationProvenance,
37
+ readNativeSessionHeader,
38
+ recommendContinuationFromProvenance,
39
+ resolveContinuationStartup,
40
+ type ContinuationCandidateProvenance,
41
+ type ContinuationCandidateSummary,
42
+ type ContinuationHostContext,
43
+ type ContinuationHostIntent,
44
+ type ContinuationProjectIdentity,
45
+ type ContinuationRecommendation,
46
+ type ContinuationRecommender,
47
+ type ContinuationSessionCandidate,
48
+ type ContinuationStartupDecision,
49
+ type ContinuationTransport,
50
+ type NativeSessionHeader
51
+ } from "./lib/continuation.ts";
39
52
  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";
53
+ discoverGlobalMarkdownSources,
54
+ getKnowledgeRoot,
55
+ GlobalMarkdownDiscovery,
56
+ type ArtifactSourceCandidate,
57
+ type GlobalMarkdownDiscoveryResult
58
+ } from "./lib/discovery.ts";
48
59
  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,
60
+ captureTemporalFileBases,
61
+ cwdScopeKey,
62
+ getDurableRepositoryRoot,
63
+ isStateFlowOwnedPath,
64
+ loadScopeStream,
65
+ parseScopeStream,
66
+ serializeScopeStream, sessionRuntimePaths, sessionScopeKey,
67
+ sessionStorageKey, temporalScopePaths,
68
+ temporalStateFileUpdates, type ScopeStreamSources, type TemporalScopePaths
63
69
  } from "./lib/durable.ts";
70
+ export { default, PATCH_STATE_TOOL_NAME, READ_STATE_TOOL_NAME, type StateFlowExtensionOptions } from "./lib/extension.ts";
64
71
  export {
65
- captureTemporalGitBase,
66
- loadTemporalRevision,
67
- migrateLegacyStorageToGit,
68
- publishTemporalStateToGit,
69
- pushGitCommit,
70
- type TemporalGitBase,
71
- type TemporalRevisionLoad,
72
- type GitPushResult,
72
+ captureTemporalGitBase,
73
+ isGitCommitAncestor,
74
+ loadTemporalRevision,
75
+ migrateLegacyStorageToGit,
76
+ publishTemporalStateToGit,
77
+ pushGitCommit,
78
+ resolveGitPushDestination, type GitPushResult, type TemporalGitBase,
79
+ type TemporalRevisionLoad
73
80
  } from "./lib/git.ts";
74
81
  export {
75
- createAcceptedTransition,
76
- projectRecentTransitionsWithLimit,
77
- RECENT_TRANSITION_LIMIT,
78
- validateRecentTransition,
79
- type RecentScopePatch,
80
- type RecentTransition,
81
- type RecentTransitionWindow,
82
- type AcceptedTransition,
82
+ createAcceptedTransition,
83
+ projectRecentTransitionsWithLimit,
84
+ RECENT_TRANSITION_LIMIT,
85
+ validateRecentTransition, type AcceptedTransition, type RecentScopePatch,
86
+ type RecentTransition,
87
+ type RecentTransitionWindow
83
88
  } from "./lib/history.ts";
84
89
  export { applyPatch, canonicalJson, hashJson, isObject, validatePatch } from "./lib/json.ts";
85
90
  export type { JsonObject, JsonValue } from "./lib/json.ts";
86
91
  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";
92
+ DEFAULT_ARTIFACT_MAINTENANCE_MAX_READS,
93
+ DEFAULT_ARTIFACT_MAINTENANCE_MAX_SOURCE_BYTES,
94
+ DEFAULT_ARTIFACT_MAINTENANCE_MINIMUM_AGE_MS,
95
+ planArtifactMaintenance,
96
+ type ArtifactMaintenanceOptions,
97
+ type ArtifactMaintenancePlan,
98
+ type ArtifactMaintenanceRequest
99
+ } from "./lib/maintenance.ts";
102
100
  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";
101
+ inspectMemoryPromotions, MEMORY_PROMOTION_STATUSES, MEMORY_PROMOTIONS_KEY, retainedMemoryScopes,
102
+ type MemoryPromotionDiagnostic,
103
+ type MemoryPromotionStatus
104
+ } from "./lib/memory.ts";
105
+ export {
106
+ acquirePublicationWorkerLease,
107
+ beginPublicationAttempt,
108
+ coalescePublicationTarget,
109
+ confirmPublicationTarget,
110
+ createPublicationQueue,
111
+ failPublicationAttempt,
112
+ loadPublicationQueue,
113
+ parsePublicationQueue,
114
+ parseRemotePublicationPolicyDocument,
115
+ publicationQueuePath,
116
+ recoverPublicationQueue,
117
+ remotePublicationDestinationKey,
118
+ removePublicationQueue,
119
+ resolveRemotePublicationPolicy,
120
+ runPublicationWorker,
121
+ savePublicationQueue,
122
+ serializePublicationQueue,
123
+ serializeRemotePublicationPolicyDocument,
124
+ validatePublicationQueue,
125
+ type CommitAncestor,
126
+ type PublicationPush,
127
+ type PublicationQueueReceipt,
128
+ type PublicationQueueState,
129
+ type PublicationQueueStatus,
130
+ type PublicationWorkerLease,
131
+ type PublicationWorkerResult,
132
+ type RemotePublicationDestination,
133
+ type RemotePublicationMode,
134
+ type RemotePublicationPolicy,
135
+ type RemotePublicationPolicyDocument
136
+ } from "./lib/publication.ts";
137
+ export {
138
+ planKnowledgeRehydration,
139
+ type RehydrationOptions,
140
+ type RehydrationPhase,
141
+ type RehydrationPlan,
142
+ type RehydrationRead,
143
+ type RehydrationRoute
144
+ } from "./lib/rehydration.ts";
110
145
  export { TemporalRuntime } from "./lib/runtime.ts";
146
+ export {
147
+ hasCompiledSkillArtifact,
148
+ hashSkillSource,
149
+ migrateLegacySkillCompilations,
150
+ SKILL_ARTIFACT_COMPILER,
151
+ type SuccessfulSkillRead
152
+ } from "./lib/skills.ts";
153
+ export {
154
+ emptyState,
155
+ isMaterializedState,
156
+ isStateDocument,
157
+ overlayStates,
158
+ updateMaterializedArtifacts,
159
+ type MaterializedState, type ScopedPatch,
160
+ type ScopedStates, type ScopePatch, type SemanticTransition,
161
+ type StateDocument,
162
+ type StatePatch,
163
+ type StateScope,
164
+ type TerminalTransition
165
+ } from "./lib/state.ts";
111
166
  export { advanceTemporalState, readTemporalState, type TemporalState } from "./lib/temporal.ts";
package/lib/artifact.ts CHANGED
@@ -14,6 +14,7 @@ export type ArtifactMetadata = JsonObject & {
14
14
  compiled_at?: string;
15
15
  compilation?: JsonObject;
16
16
  kind?: string;
17
+ tags?: string[];
17
18
  };
18
19
 
19
20
  /** Artifact source paths are the canonical registry keys. */
@@ -57,6 +58,7 @@ export type ArtifactCompilerOutput = JsonObject & {
57
58
  compiled_at?: string;
58
59
  compilation?: JsonObject;
59
60
  kind?: string;
61
+ tags?: string[];
60
62
  };
61
63
 
62
64
  export interface ArtifactCompilationUpdate {
@@ -97,6 +99,11 @@ export function validateArtifactMetadata(value: unknown, path = "<unknown>"): as
97
99
  && (typeof value.kind !== "string" || value.kind.trim().length === 0)) {
98
100
  throw new Error(`Artifact metadata at ${path} kind must be a non-empty string`);
99
101
  }
102
+ if (Object.hasOwn(value, "tags") && (!Array.isArray(value.tags)
103
+ || value.tags.some((tag) => typeof tag !== "string" || tag.trim().length === 0 || tag !== tag.trim())
104
+ || new Set(value.tags).size !== value.tags.length)) {
105
+ throw new Error(`Artifact metadata at ${path} tags must be unique non-empty trimmed strings`);
106
+ }
100
107
  }
101
108
 
102
109
  export function isArtifactMetadata(value: unknown): value is ArtifactMetadata {
@@ -116,6 +123,27 @@ export function validateArtifactRegistry(value: unknown): asserts value is Artif
116
123
  }
117
124
  }
118
125
 
126
+ export function selectArtifactsByTags(
127
+ registry: ArtifactRegistry,
128
+ tags: readonly string[],
129
+ match: "all" | "any" = "all",
130
+ ): string[] {
131
+ validateArtifactRegistry(registry);
132
+ if (tags.length === 0 || tags.some((tag) => typeof tag !== "string" || tag.trim().length === 0 || tag !== tag.trim())) {
133
+ throw new Error("Artifact tag query requires one or more non-empty trimmed strings");
134
+ }
135
+ const requested = new Set(tags);
136
+ return Object.entries(registry)
137
+ .filter(([, metadata]) => {
138
+ const available = new Set(metadata.tags ?? []);
139
+ return match === "all"
140
+ ? [...requested].every((tag) => available.has(tag))
141
+ : [...requested].some((tag) => available.has(tag));
142
+ })
143
+ .map(([path]) => path)
144
+ .sort();
145
+ }
146
+
119
147
  export function isArtifactRegistry(value: unknown): value is ArtifactRegistry {
120
148
  try {
121
149
  validateArtifactRegistry(value);
package/lib/config.ts CHANGED
@@ -9,12 +9,16 @@ import { isObject } from "./json.ts";
9
9
  export interface StateFlowConfig {
10
10
  directory: string;
11
11
  autoStart: boolean;
12
+ remotePublication?: "off" | "turn-end" | "transition";
12
13
  }
13
14
 
14
15
  /** Read once at extension load/reload. Missing config uses defaults; invalid config never falls back. */
15
16
  export function loadStateFlowConfig(agentDir = getAgentDir()): StateFlowConfig {
16
17
  const path = resolve(agentDir, "state-flow.json");
17
- const defaults = { directory: getDurableRepositoryRoot(agentDir), autoStart: false };
18
+ const defaults: StateFlowConfig = {
19
+ directory: getDurableRepositoryRoot(agentDir),
20
+ autoStart: false,
21
+ };
18
22
  let value: unknown;
19
23
  try {
20
24
  if (!lstatSync(path, { throwIfNoEntry: false })) return defaults;
@@ -22,15 +26,23 @@ export function loadStateFlowConfig(agentDir = getAgentDir()): StateFlowConfig {
22
26
  } catch (error) {
23
27
  throw new Error(`Cannot read State Flow configuration: ${path}`, { cause: error });
24
28
  }
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}`);
29
+ const allowed = new Set(["directory", "autoStart", "remotePublication"]);
30
+ if (!isObject(value) || Object.keys(value).some((key) => !allowed.has(key))) {
31
+ throw new Error(`State Flow configuration contains unknown settings: ${path}`);
27
32
  }
28
33
  if (Object.hasOwn(value, "autoStart") && typeof value.autoStart !== "boolean") throw new Error(`State Flow autoStart must be a boolean: ${path}`);
34
+ if (Object.hasOwn(value, "remotePublication") && value.remotePublication !== "off" && value.remotePublication !== "turn-end" && value.remotePublication !== "transition") {
35
+ throw new Error(`State Flow remotePublication must be off, turn-end, or transition: ${path}`);
36
+ }
29
37
  if (Object.hasOwn(value, "directory") && (typeof value.directory !== "string" || !value.directory.trim() || value.directory.includes("\0"))) {
30
38
  throw new Error(`State Flow directory must be a non-empty path: ${path}`);
31
39
  }
32
40
  const directory = value.directory as string | undefined;
33
41
  if (directory?.startsWith("~") && directory !== "~" && !directory.startsWith("~/")) throw new Error(`State Flow directory supports ~ or ~/ paths, not named-user expansion: ${path}`);
34
42
  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 };
43
+ return {
44
+ directory: expanded === undefined ? defaults.directory : resolve(dirname(path), expanded),
45
+ autoStart: value.autoStart === true,
46
+ ...(value.remotePublication === undefined ? {} : { remotePublication: value.remotePublication as "off" | "turn-end" | "transition" }),
47
+ };
36
48
  }
package/lib/context.ts CHANGED
@@ -3,6 +3,7 @@ import type { ArtifactInvalidationRequest } from "./artifact.ts";
3
3
  import type { RecentTransitionWindow } from "./history.ts";
4
4
  import { canonicalJson } from "./json.ts";
5
5
  import type { Snapshot } from "./snapshot.ts";
6
+ import type { RehydrationPhase } from "./rehydration.ts";
6
7
  import type { MaterializedState } from "./state.ts";
7
8
 
8
9
  export const VALIDATION_MESSAGE_TYPE = "state-flow-validation";
@@ -36,6 +37,7 @@ export function runtimeContextMessage(
36
37
  state: MaterializedState,
37
38
  recentTransitions: RecentTransitionWindow = [],
38
39
  artifactInvalidations: readonly ArtifactInvalidationRequest[] = [],
40
+ rehydrationPhase?: RehydrationPhase,
39
41
  ): AgentMessage {
40
42
  if (snapshot.meta.specification === undefined) {
41
43
  throw new Error("State Flow runtime context requires an active specification");
@@ -43,6 +45,7 @@ export function runtimeContextMessage(
43
45
  const context = {
44
46
  specification: snapshot.meta.specification,
45
47
  state,
48
+ ...(rehydrationPhase === undefined ? {} : { knowledge_rehydration: { phase: rehydrationPhase } }),
46
49
  ...(artifactInvalidations.length === 0 ? {} : { artifact_invalidations: artifactInvalidations }),
47
50
  ...(recentTransitions.length === 0 ? {} : { recent_transitions: recentTransitions }),
48
51
  ...(snapshot.meta.validation === undefined ? {} : { validation_feedback: snapshot.meta.validation }),