@llblab/pi-state-flow 0.14.0 → 0.15.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 +2 -2
- package/BACKLOG.md +1 -1
- package/CHANGELOG.md +8 -0
- package/README.md +3 -2
- package/dist/lib/durable.d.ts +1 -1
- package/dist/lib/durable.js +7 -0
- package/dist/lib/history.js +1 -1
- package/dist/lib/migration.d.ts +2 -2
- package/dist/lib/migration.js +21 -3
- package/dist/lib/protocol.js +8 -5
- package/dist/lib/query.js +1 -1
- package/dist/lib/state.d.ts +5 -0
- package/dist/lib/state.js +10 -2
- package/dist/lib/telegram.d.ts +1 -0
- package/dist/lib/telegram.js +1 -1
- package/dist/lib/transition.js +4 -3
- package/dist/package.json +1 -1
- package/dist/skills/state-flow-memory/SKILL.md +5 -3
- package/docs/architecture.md +9 -7
- package/docs/lazy-state.md +3 -2
- package/lib/durable.ts +6 -1
- package/lib/history.ts +1 -1
- package/lib/migration.ts +18 -4
- package/lib/protocol.ts +8 -5
- package/lib/query.ts +1 -1
- package/lib/state.ts +13 -2
- package/lib/telegram.ts +2 -1
- package/lib/transition.ts +4 -3
- package/package.json +1 -1
- package/skills/state-flow-memory/SKILL.md +5 -3
package/AGENTS.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
- Keep independent domain modules under `lib/`, mirror every domain with a same-named file under `tests/`, place cross-domain architecture checks in `tests/invariants.test.ts`, and keep `index.ts` as a minimal composition/public-export boundary.
|
|
4
4
|
- Keep the extension opt-in and preserve clear attribution to SKILL.state wherever the inherited explicit-state approach is described.
|
|
5
5
|
- Preserve Pi's native tool loop and complete inspectable session trace; project completed-run history only at user-run boundaries. The runtime-context builder owns model projection of the raw scope overlay; callers must not pre-project it. Retain persistent and current-run context-bearing custom messages from other extensions, plus the complete current-run trajectory, except State Flow's own validation feedback when it is represented separately.
|
|
6
|
-
- Expose one canonical materialized state shape across global, CWD, and session scopes with exactly `artifacts`, `contract`, `working`, and `response`; the first
|
|
6
|
+
- Expose one canonical materialized state shape across global, CWD, and session scopes with exactly `artifacts`, `contract`, `working`, `intents`, and `response`, plus optional `lazy`; the first four are flexible semantic objects and `response` is the latest complete user-facing answer string where applicable. `intents` contains only active commitments to future action, remains hot by default, and must not become a planner, scheduler, task manager, or execution loop.
|
|
7
7
|
- Key artifacts directly by their source path. Model-visible artifact entries require only a non-empty `description` plus optional forward-compatible metadata; runtime-owned freshness evidence (`sourceHash`, `compilerRevision`, `compiledAt`) belongs in the scope `meta.json` provenance registry, never in projected semantic state. Retired embedded `hash`/`compiler`/`compiled_at` fields remain readable compatibility evidence and are stripped from model projection. Validate provenance restrictions on every authored artifact entry, not on retained legacy state: individual runtime/legacy provenance fields cannot be set or deleted by model patches in any scope.
|
|
8
8
|
- After local activation and before the next enabled inference, discover regular lowercase `*.md` files recursively beneath the configured Knowledge repository root; use canonical absolute paths, hash opaque source bytes and retain their byte counts without decoding or retaining bodies, skip symlinks, and never traverse outside that canonical root. Treat the current candidate set plus explicit owner-confirmed removals as generic global artifact input without invoking Knowledge validators. Partial candidate sets, unavailable roots, and symlink/external/non-Markdown paths never authorize deletion. Re-derive removals from the retained global registry so status inspection and restart cannot consume uncommitted observations; unavailable roots mean unknown freshness. Materialize removals deterministically as runtime-owned global transitions without rereading missing bodies or requesting model compiler output. Never reserve Knowledge document names, provide built-in Knowledge templates, or implement `save_knowledge`.
|
|
9
9
|
- Derive artifact freshness per available evidence: a new source always requires compilation, a matching `sourceHash` or `compilerRevision` detects its own change, malformed present evidence fails closed for the capability that depends on it, and missing evidence degrades to an unknown-but-usable artifact rather than corrupt state or a migration. Never treat `compiled_at` as a correctness signal. Plan acquisition from path/hash identity without source bodies, project stale global candidates as runtime-owned `artifact_invalidations` containing only `{path, reason}`, and publish accepted compilation semantics plus matching provenance in one durable cohort.
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
- Keep historical reads lazy through the smallest runtime/model read interface. Normal inference gets only current effective state and useful bounded compact transition context, never eight full snapshots. `patch_state` is the sole semantic mutation tool. `read_state` treats unscoped semantic paths as current effective aliases, accepts explicit effective/scoped materializations and scope-local retained accepted patches, and rejects the retired top-level `state` segment; materialization indices share the composed causal lineage while `patches[n]` walks the selected scope's retained patch tail. The public reader accepts only `path` or `paths`; temporal offsets and scope selection are expressed in path syntax. Reads return the exact boundary and never publish, append a checkpoint, or advance history. Both tools follow branch enablement and host tool restrictions; the patch barrier blocks reader siblings too. Live/cached checkpoint plus tails own the hot path; use Git for branch restoration and explicit cold inspection, not to rebuild current state on every inference.
|
|
20
20
|
- Store runtime state in its own directory with optional Git durability, defaulting to `state-flow/` beneath Pi's configured agent directory (`~/.pi/agent/state-flow/` normally), independently from the Knowledge Markdown source root. Use exactly these owned paths: `checkpoint.json`, `patches.jsonl`, and `meta.json` for global; `<cwd-key>/checkpoint.json`, `<cwd-key>/patches.jsonl`, and `<cwd-key>/meta.json` for CWD; `<cwd-key>/<session-key>/checkpoint.json`, `patches.jsonl`, `meta.json`, `config.json`, and `runtime.json` for session. Do not create `.state-flow`, `scopes`, or another storage/history namespace. Mirror Pi's native CWD session-directory encoding and JSONL-basename session key (deriving `<header timestamp>_<UUID>` for in-memory sessions), while retaining separately verifiable canonical identity provenance in owned state. Keep the UUID authoritative, reject unsafe segments and mismatches rather than selecting another scope, and use CWD `meta.json` ownership to fail closed on Pi-name collisions.
|
|
21
21
|
- Classify every filesystem cohort before recovery: complete valid evidence is usable; total absence is recoverable only from an explicit semantic default or exact surviving authority; partial, malformed, contradictory, or authority-losing evidence fails closed at the smallest dependent capability. A wholly absent untouched global/CWD checkpoint-tail pair is current empty shared reality and must not resurrect selected cold values; a patch targeting that disappeared scope is stale and must fail for reinference. Missing provenance means unavailable freshness, not semantic corruption. Perform every repair through normal locked/CAS publication, never ad-hoc writes.
|
|
22
|
-
- Support the release-owned storage migration chain through the migration domain: complete predecessor checkpoint/tail envelopes convert into semantic-only checkpoint/tail files plus temporal `meta.json`,
|
|
22
|
+
- Support the release-owned storage migration chain through the migration domain: complete predecessor checkpoint/tail envelopes convert into semantic-only checkpoint/tail files plus temporal `meta.json`, the 0.13 → 0.14 step splits every owner-proven session's combined `meta.json` into scope-only `meta.json` plus branch/run `runtime.json`; and the 0.14 → 0.15 step adds empty `intents` to retained semantic checkpoints without inferring commitments. Execute the applicable steps through one normal locked/CAS publication. Replace a Git-backed semantic-envelope store's history with one new root commit for the complete migrated tree; apply the same cohort without Git in file-only mode. `state.json`, pre-0.4 hashed layouts, and semantic Pi checkpoint envelopes are unsupported and never become recovery authority. Exercise migrations in temporary repositories rather than modifying the user's active data during development.
|
|
23
23
|
- Read and write only regular non-symlink State Flow-owned files at those exact paths, publish each file by same-directory atomic rename, preserve arbitrary repository contents, and classify ownership exactly. Git acceptance follows the complete-delta isolated-index contract below. Retain opaque source bytes for file identity and rollback, not decoded-text reconstructions. Use validated structural JSON equality for in-process semantic comparisons; reserve cryptographic hashes for compact identities that cross inference, persistence, process, or source-freshness boundaries. Serialize cooperating Git publications through a common-Git-directory publication lock; low-level file helpers require caller exclusion. Recheck prepared bases before each replacement/deletion and restore only bytes still matching the publisher's own output. Preserve detected concurrent changes and report unresolved rollback conflicts; do not claim kernel-atomic multi-file CAS against nonparticipating writers. Markdown discovery uses its independently configured source root, defaulting to `knowledge/` beneath Pi's agent directory; a storage-root override must not redirect source discovery.
|
|
24
24
|
- At instance initialization resolve the repository, CWD key, and session key; load each scope's anchored checkpoint and tail, materialize at the selected temporal boundary, then overlay `global → cwd → session`. Install cached view and publication basis atomically only after successful restoration/initialization; unavailable publication is an error, not a semantic no-op. Branch recovery may reuse one owner-bound, single-use inspection of the exact selected immutable Git revision, with a detached inspection snapshot and a freshly acquired live publication basis at installation. Revalidate mutable file cohorts, legacy snapshot fallbacks, and redirected runtime owners; never turn inspection into a long-lived revision or publication-basis cache. Preserve the selected revision across transient restore failure so an explicit start can retry it. A genuinely new session gets an empty session layer and inherits only global/CWD values; it must never reuse another same-CWD session layer. Explicit native fork adoption instead follows the [session-copy contract](docs/fork-contract.md): copy the proven source session checkpoint/tail and provenance into a distinct owner over current shared streams, without pruning shared provenance or modifying the parent. Use a fresh origin, preserve copied replay records, reject occupied live/HEAD targets, and publish/checkpoint the child only after CAS acceptance. Inherited parent pointers never authorize an empty reset; fence parent passive Stop projection across child reload.
|
|
25
25
|
- Bind every loaded scope and active Pi branch/checkpoint to the corresponding State Flow Git revision. Resume and tree restoration must recover branch-correct runtime config and semantic layers from that revision without blindly importing Git `HEAD`; reading an older revision must use object-level Git reads and never reset or check out the shared repository worktree.
|
package/BACKLOG.md
CHANGED
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,14 @@
|
|
|
4
4
|
|
|
5
5
|
## Unreleased
|
|
6
6
|
|
|
7
|
+
## 0.15.0: Intentional agency
|
|
8
|
+
|
|
9
|
+
- `Intent semantic plane`: Adds hot, object-valued `intents` to global, CWD, session, and effective state. An intent is a selected commitment to future action, distinct from requirements in `contract`, observations or possibilities in `working`, and inactive supporting memory in `lazy`.
|
|
10
|
+
- `Intent lifecycle`: Supports ordinary atomic creation, update, scope overlay, supersession, and removal. Active intents survive intermediate handoffs; fulfilled, abandoned, superseded, or impossible intents disappear while consequential results and referenced state remain independently retained.
|
|
11
|
+
- `Explicit semantic references`: Intents may carry conventional `{"$ref":"cwd.lazy.plan"}` pointers. Reads return references exactly and follow their targets only through a separate explicit `read_state`; State Flow adds no dependency graph, automatic hydration, scheduling, execution, or completion behavior.
|
|
12
|
+
- `Durability and migration`: Preserves intents across hot history, Git and file-only persistence, passive and active operation, forks, compaction, and CAS conflicts. The explicit 0.14 → 0.15 migration adds empty intents to retained scopes without inferring commitments from working state, plans, requirements, lazy memory, or response prose.
|
|
13
|
+
- `Inspection and guidance`: Extends current, scoped, historical, key, patch, and batch reads; adds read-only Telegram intent inspection; and updates the model protocol and bundled memory Skill to reconcile active commitments without introducing a task manager or second agent loop.
|
|
14
|
+
|
|
7
15
|
## 0.14.0: Passive and progressive memory
|
|
8
16
|
|
|
9
17
|
- `Default passive memory`: Repository-root configuration now adds independently configurable passive bootstrap and `read_state`/`patch_state` access, both enabled by default. Passive reads project durable memory without mutation; explicit patches may materialize storage while episode barriers, continuation, response reconciliation, and compaction remain inactive. Start promotes to active semantics and Stop returns to passive mode.
|
package/README.md
CHANGED
|
@@ -58,12 +58,13 @@ Active State Flow episodes remain **opt-in**, while passive durable memory boots
|
|
|
58
58
|
The same semantic planes exist at every scope:
|
|
59
59
|
|
|
60
60
|
- `contract`: Requirements, decisions, constraints, and interface commitments.
|
|
61
|
-
- `working`: Observations, results, unresolved questions, and
|
|
61
|
+
- `working`: Observations, results, unresolved questions, and possible next steps.
|
|
62
|
+
- `intents`: Courses of action the agent has actually committed to pursue.
|
|
62
63
|
- `artifacts`: Source-addressed descriptions and reusable compiled knowledge.
|
|
63
64
|
- `response`: The latest complete answer, captured by the runtime.
|
|
64
65
|
- `lazy`: Durable, versioned memory omitted from ordinary context until explicitly read.
|
|
65
66
|
|
|
66
|
-
Memory overlays **global → project CWD → session**. Put reusable cross-project knowledge in global, project knowledge in CWD, and private task continuation in session. Hot planes carry what must matter now; `lazy` retains what may matter later without hydrating its body into every prompt.
|
|
67
|
+
Memory overlays **global → project CWD → session**. Put reusable cross-project knowledge in global, project knowledge in CWD, and private task continuation in session. Hot planes carry what must matter now; `lazy` retains what may matter later without hydrating its body into every prompt. An intent stays hot only while its course remains chosen and disappears when fulfilled, abandoned, superseded, or impossible. It may carry a plain `{"$ref":"cwd.lazy.plan"}` pointer to supporting detail; State Flow never hydrates, executes, or completes that reference automatically.
|
|
67
68
|
|
|
68
69
|
**Resuming an existing Pi session restores its selected State Flow state and enablement.** A genuinely new session starts with an empty session layer and inherits only shared global/CWD memory; it does not resume another session's private work. Tree navigation follows the selected branch, not whichever state happens to be at Git `HEAD`.
|
|
69
70
|
|
package/dist/lib/durable.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type ArtifactProvenanceRegistry } from "./artifact.ts";
|
|
2
2
|
import { type ScopeStream, type TemporalState } from "./temporal.ts";
|
|
3
|
-
import type
|
|
3
|
+
import { type StateScope } from "./state.ts";
|
|
4
4
|
/** Canonical semantic sources plus runtime-owned temporal metadata. */
|
|
5
5
|
export interface ScopeStreamSources {
|
|
6
6
|
checkpoint: string;
|
package/dist/lib/durable.js
CHANGED
|
@@ -5,6 +5,7 @@ import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
|
5
5
|
import { parseArtifactProvenanceRegistry, serializeArtifactProvenanceRegistry, } from "./artifact.js";
|
|
6
6
|
import { canonicalJson, isJsonValue, isObject } from "./json.js";
|
|
7
7
|
import { validateScopeStream, validateTemporalState } from "./temporal.js";
|
|
8
|
+
import { migratePreIntentState } from "./state.js";
|
|
8
9
|
const SESSION_KEY_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
|
|
9
10
|
const STATE_FILE = "state.json";
|
|
10
11
|
const CHECKPOINT_FILE = "checkpoint.json";
|
|
@@ -65,6 +66,7 @@ export function classifyScopeStream(checkpointSource, patchesSource, scope, expe
|
|
|
65
66
|
}
|
|
66
67
|
const temporal = meta?.temporal;
|
|
67
68
|
if (isObject(temporal) && Object.hasOwn(temporal, "checkpoint") && Array.isArray(temporal.patches)) {
|
|
69
|
+
checkpoint = migratePreIntentState(checkpoint) ?? checkpoint;
|
|
68
70
|
const owner = meta?.owner;
|
|
69
71
|
if (scope === "cwd" && expectedCwd !== undefined
|
|
70
72
|
&& (!isObject(owner) || Object.keys(owner).join(",") !== "cwd" || owner.cwd !== resolve(expectedCwd))) {
|
|
@@ -94,6 +96,11 @@ export function classifyScopeStream(checkpointSource, patchesSource, scope, expe
|
|
|
94
96
|
else if (scope === "cwd" && expectedCwd !== undefined) {
|
|
95
97
|
throw new Error("State Flow CWD scope identity is missing");
|
|
96
98
|
}
|
|
99
|
+
if (isObject(legacyCheckpoint) && isObject(legacyCheckpoint.state)) {
|
|
100
|
+
const migrated = migratePreIntentState(legacyCheckpoint.state);
|
|
101
|
+
if (migrated)
|
|
102
|
+
legacyCheckpoint = { ...legacyCheckpoint, state: migrated };
|
|
103
|
+
}
|
|
97
104
|
const stream = { checkpoint: legacyCheckpoint, patches };
|
|
98
105
|
validateScopeStream(stream, scope);
|
|
99
106
|
return { kind: "present", stream };
|
package/dist/lib/history.js
CHANGED
|
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { isJsonValue, isObject, sameJson, validatePatch } from "./json.js";
|
|
3
3
|
export const RECENT_TRANSITION_LIMIT = 7;
|
|
4
4
|
const SCOPES = new Set(["global", "cwd", "session"]);
|
|
5
|
-
const PATCH_KEYS = new Set(["artifacts", "contract", "working", "response", "lazy"]);
|
|
5
|
+
const PATCH_KEYS = new Set(["artifacts", "contract", "working", "intents", "response", "lazy"]);
|
|
6
6
|
/** Normalize accepted replacements into recursive-merge replay, including removals. */
|
|
7
7
|
function replayPatch(before, after) {
|
|
8
8
|
const entries = [];
|
package/dist/lib/migration.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type DurableFileBase, type OwnedFileUpdate } from "./durable.ts";
|
|
2
|
-
import type
|
|
2
|
+
import { type StateScope } from "./state.ts";
|
|
3
3
|
export interface LegacyStorageMigration {
|
|
4
4
|
bases: DurableFileBase[];
|
|
5
5
|
updates: OwnedFileUpdate[];
|
|
@@ -7,7 +7,7 @@ export interface LegacyStorageMigration {
|
|
|
7
7
|
}
|
|
8
8
|
/** Read-only activation eligibility, before global migration or any repository publication. */
|
|
9
9
|
export declare function hasCwdMaterialization(cwd: string, repositoryRoot: string): boolean;
|
|
10
|
-
/** Detect predecessor snapshots
|
|
10
|
+
/** Detect predecessor snapshots, temporal envelopes, or pre-intents semantic states without mutating the store. */
|
|
11
11
|
export declare function hasLegacyStateSources(cwd: string, sessionId: string, repositoryRoot: string, sessionKey?: string): boolean;
|
|
12
12
|
/** Plan from current scope snapshots only; old explanatory journals are never replay input. */
|
|
13
13
|
export declare function planLegacyStorageMigration(cwd: string, sessionId: string, repositoryRoot: string, _origin?: string, sessionKey?: string): LegacyStorageMigration;
|
package/dist/lib/migration.js
CHANGED
|
@@ -3,6 +3,7 @@ import { lstatSync, readFileSync, readdirSync } from "node:fs";
|
|
|
3
3
|
import { join, resolve } from "node:path";
|
|
4
4
|
import { captureOwnedFileBases, cwdScopePaths, parseScopeStream, serializeScopeMetadata, serializeScopeStream, sessionScopeKey, sessionScopePaths, } from "./durable.js";
|
|
5
5
|
import { parseSessionRuntime, serializeSessionRuntime } from "./snapshot.js";
|
|
6
|
+
import { migratePreIntentState } from "./state.js";
|
|
6
7
|
/** Discover every owner-proven CWD and session cohort beneath the configured store. */
|
|
7
8
|
function migrationDirectories(cwd, sessionId, root, sessionKey) {
|
|
8
9
|
const selectedCwd = cwdScopePaths(cwd, root).directory;
|
|
@@ -48,13 +49,20 @@ function migrationDirectories(cwd, sessionId, root, sessionKey) {
|
|
|
48
49
|
}
|
|
49
50
|
const directory = join(cwdDirectory, entry.name);
|
|
50
51
|
let meta;
|
|
52
|
+
let runtime;
|
|
51
53
|
try {
|
|
52
54
|
meta = JSON.parse(readFileSync(join(directory, "meta.json"), "utf8"));
|
|
53
55
|
}
|
|
54
56
|
catch {
|
|
55
57
|
continue;
|
|
56
58
|
}
|
|
57
|
-
|
|
59
|
+
try {
|
|
60
|
+
runtime = JSON.parse(readFileSync(join(directory, "runtime.json"), "utf8"));
|
|
61
|
+
}
|
|
62
|
+
catch { /* predecessor sessions keep identity in meta.json */ }
|
|
63
|
+
const identity = meta && typeof meta === "object" && !Array.isArray(meta) && meta.identity !== undefined
|
|
64
|
+
? meta.identity
|
|
65
|
+
: runtime && typeof runtime === "object" && !Array.isArray(runtime) ? runtime.identity : undefined;
|
|
58
66
|
if (!identity || typeof identity !== "object" || Array.isArray(identity))
|
|
59
67
|
continue;
|
|
60
68
|
const owner = identity;
|
|
@@ -81,13 +89,23 @@ export function hasCwdMaterialization(cwd, repositoryRoot) {
|
|
|
81
89
|
throw new Error(`State Flow tail has no provable checkpoint: ${directory}`);
|
|
82
90
|
return false;
|
|
83
91
|
}
|
|
84
|
-
|
|
92
|
+
function checkpointNeedsIntentMigration(source) {
|
|
93
|
+
const checkpoint = JSON.parse(source);
|
|
94
|
+
if (migratePreIntentState(checkpoint) !== undefined)
|
|
95
|
+
return true;
|
|
96
|
+
return checkpoint !== null && typeof checkpoint === "object" && !Array.isArray(checkpoint)
|
|
97
|
+
&& migratePreIntentState(checkpoint.state) !== undefined;
|
|
98
|
+
}
|
|
99
|
+
/** Detect predecessor snapshots, temporal envelopes, or pre-intents semantic states without mutating the store. */
|
|
85
100
|
export function hasLegacyStateSources(cwd, sessionId, repositoryRoot, sessionKey = sessionId) {
|
|
86
101
|
const root = resolve(repositoryRoot);
|
|
87
102
|
return migrationDirectories(cwd, sessionId, root, sessionKey).some(({ directory, scope }) => {
|
|
88
|
-
|
|
103
|
+
const checkpointPath = join(directory, "checkpoint.json");
|
|
104
|
+
if (lstatSync(checkpointPath, { throwIfNoEntry: false }) === undefined)
|
|
89
105
|
return false;
|
|
90
106
|
try {
|
|
107
|
+
if (checkpointNeedsIntentMigration(readFileSync(checkpointPath, "utf8")))
|
|
108
|
+
return true;
|
|
91
109
|
const meta = JSON.parse(readFileSync(join(directory, "meta.json"), "utf8"));
|
|
92
110
|
if (meta === null || typeof meta !== "object" || !("temporal" in meta))
|
|
93
111
|
return true;
|
package/dist/lib/protocol.js
CHANGED
|
@@ -8,25 +8,28 @@ export function stateFlowProtocol(bootstrap) {
|
|
|
8
8
|
: "";
|
|
9
9
|
return `State Flow is enabled.
|
|
10
10
|
${bootstrapProtocol}
|
|
11
|
-
STATE: {"artifacts":{},"contract":{},"working":{},"response":"latest complete answer"}
|
|
11
|
+
STATE: {"artifacts":{},"contract":{},"working":{},"intents":{},"response":"latest complete answer"}
|
|
12
12
|
- artifacts: source-path routing metadata; descriptions do not imply body acquisition.
|
|
13
13
|
- contract: durable requirements, decisions, rejections, interfaces, compiled knowledge.
|
|
14
14
|
- working: facts, validation, failures, domain state, unresolved work, continuation.
|
|
15
|
+
- intents: active commitments; remove when fulfilled, abandoned, superseded, or impossible.
|
|
15
16
|
- response: previous complete answer; runtime-owned.
|
|
16
17
|
|
|
17
|
-
READ: Use read_state
|
|
18
|
+
READ: Use read_state for concrete scope/history gaps. lazy_navigation exposes the effective lazy root's bounded key kinds, not bodies. Unscoped paths alias effective; effective/global/cwd/session select overlay or owner. Arrays support indices and [start..end]; keys gives structure and patch the intersected change.
|
|
18
19
|
|
|
19
20
|
WRITE: patch_state is the sole model-authored semantic mutation mechanism. Supply global/cwd/session patches in any combination; all supplied scopes are validated and durably accepted as one atomic transition. Call it alone in an assistant response, then continue only after its acknowledgement.
|
|
20
21
|
|
|
21
|
-
FINAL: Every enabled iteration starts terminal-ineligible.
|
|
22
|
+
FINAL: Every enabled iteration starts terminal-ineligible. Successful patch_state final:true permits a later turn_end without stopping later work; use {"final":true} when no state change is needed. Otherwise runtime preserves the answer and allows at most two fallback turns only for final:true; never restate it. A final-only call creates no transition. Runtime owns response.
|
|
23
|
+
|
|
24
|
+
INTENTS: Store selected actions, not requirements, observations, possibilities, alternatives, or completed work. Preserve them across handoffs at the narrowest scope; detail may stay lazy. A {"$ref":"cwd.lazy.plan"} is an ordinary pointer: follow it with read_state only when needed; infer no dependency, hydration, execution, or completion.
|
|
22
25
|
|
|
23
26
|
SCOPES: global=cross-project; cwd=project and Skills; session=branch/run. Deleting an override may reveal its parent.
|
|
24
27
|
|
|
25
28
|
${baselineMemoryProtocol()}
|
|
26
29
|
|
|
27
|
-
PATCH: Optional global/cwd/session object patches plus optional final:true; require at least one. Omit empty/materially no-op scopes. Semantic fields are object-valued artifacts/contract/working and ordinary-JSON lazy; omitted fields persist. Never patch runtime config/meta/response. Objects merge recursively; arrays/primitives replace. An object containing only canonical "[N]" keys recursively patches array elements. Indexed deletion is forbidden; nested object null deletes; materialized null is forbidden.
|
|
30
|
+
PATCH: Optional global/cwd/session object patches plus optional final:true; require at least one. Omit empty/materially no-op scopes. Semantic fields are object-valued artifacts/contract/working/intents and ordinary-JSON lazy; omitted fields persist. Never patch runtime config/meta/response. Objects merge recursively; arrays/primitives replace. An object containing only canonical "[N]" keys recursively patches array elements. Indexed deletion is forbidden; nested object null deletes; materialized null is forbidden.
|
|
28
31
|
|
|
29
|
-
HANDOFF: Preserve active commitments,
|
|
32
|
+
HANDOFF: Preserve active commitments, open questions, consequential results, and exact continuation; distinguish requirements, decisions, observations, conclusions, and hypotheses. Curate touched and obviously stale/mis-scoped state. At feature/release/campaign or project/version completion, reconcile once: remove obsolete work, retain consequences, and use targeted read_state plus destination-verify-source-delete for moves. Never invent memory changes.
|
|
30
33
|
|
|
31
34
|
ACQUISITION: Start materialized. Read only for a compilation gap, exact source/edit, invalidation, contradiction/failure, or explicit request; changed hashes require rereading.
|
|
32
35
|
ARTIFACTS: For each acquired new/invalidated ordinary artifact, patch global.artifacts[exact path] with a compact non-empty description. Runtime owns provenance.
|
package/dist/lib/query.js
CHANGED
|
@@ -35,7 +35,7 @@ export function readStatePath(view, path) {
|
|
|
35
35
|
}
|
|
36
36
|
function parseValuePath(path) {
|
|
37
37
|
const explicitRoot = /^(?:effective|global|cwd|session)(?:\[\d+\])?(?=\.|$)/.exec(path)?.[0];
|
|
38
|
-
const implicitRoot = /^(?:artifacts|contract|working|response|lazy)(?=\.|\[|$)/.exec(path)?.[0];
|
|
38
|
+
const implicitRoot = /^(?:artifacts|contract|working|intents|response|lazy)(?=\.|\[|$)/.exec(path)?.[0];
|
|
39
39
|
if (explicitRoot === undefined && implicitRoot === undefined) {
|
|
40
40
|
throw new Error("State Flow read path requires a semantic path or an effective, global, cwd, or session root");
|
|
41
41
|
}
|
package/dist/lib/state.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export type MaterializedState = JsonObject & {
|
|
|
5
5
|
artifacts: ArtifactRegistry;
|
|
6
6
|
contract: JsonObject;
|
|
7
7
|
working: JsonObject;
|
|
8
|
+
intents: JsonObject;
|
|
8
9
|
response: string;
|
|
9
10
|
/** Absent is the canonical empty lazy plane and preserves predecessor-store compatibility. */
|
|
10
11
|
lazy?: JsonValue;
|
|
@@ -16,6 +17,7 @@ export interface StatePatch extends JsonObject {
|
|
|
16
17
|
artifacts: JsonObject;
|
|
17
18
|
contract: JsonObject;
|
|
18
19
|
working: JsonObject;
|
|
20
|
+
intents: JsonObject;
|
|
19
21
|
response: string;
|
|
20
22
|
}
|
|
21
23
|
export type StateScope = "global" | "cwd" | "session";
|
|
@@ -24,6 +26,7 @@ export interface ScopePatch {
|
|
|
24
26
|
artifacts?: JsonObject;
|
|
25
27
|
contract?: JsonObject;
|
|
26
28
|
working?: JsonObject;
|
|
29
|
+
intents?: JsonObject;
|
|
27
30
|
lazy?: JsonValue;
|
|
28
31
|
}
|
|
29
32
|
export interface ScopedPatch {
|
|
@@ -50,6 +53,8 @@ export interface ScopedStates {
|
|
|
50
53
|
export declare function emptyState(): MaterializedState;
|
|
51
54
|
export declare function isMaterializedState(value: unknown): value is MaterializedState;
|
|
52
55
|
export declare const isStateDocument: typeof isMaterializedState;
|
|
56
|
+
/** Upgrade one exact pre-intents materialized state without inferring commitments. */
|
|
57
|
+
export declare function migratePreIntentState(value: unknown): MaterializedState | undefined;
|
|
53
58
|
/** Atomically replace compiled and removed artifacts inside one materialized scope. */
|
|
54
59
|
export declare function updateMaterializedArtifacts(state: MaterializedState, updates: readonly ArtifactCompilationUpdate[], removed?: readonly string[]): MaterializedState;
|
|
55
60
|
/** Overlay lower-to-higher scopes without mutating any scope document. */
|
package/dist/lib/state.js
CHANGED
|
@@ -1,18 +1,26 @@
|
|
|
1
1
|
import { isArtifactRegistry, projectArtifactsForModel, updateArtifactRegistry, } from "./artifact.js";
|
|
2
2
|
import { applyPatch, isJsonValue, isObject } from "./json.js";
|
|
3
3
|
export function emptyState() {
|
|
4
|
-
return { artifacts: {}, contract: {}, working: {}, response: "" };
|
|
4
|
+
return { artifacts: {}, contract: {}, working: {}, intents: {}, response: "" };
|
|
5
5
|
}
|
|
6
6
|
export function isMaterializedState(value) {
|
|
7
7
|
return isObject(value)
|
|
8
8
|
&& isArtifactRegistry(value.artifacts)
|
|
9
9
|
&& isObject(value.contract)
|
|
10
10
|
&& isObject(value.working)
|
|
11
|
+
&& isObject(value.intents)
|
|
11
12
|
&& typeof value.response === "string"
|
|
12
13
|
&& (!Object.hasOwn(value, "lazy") || (isJsonValue(value.lazy) && value.lazy !== null))
|
|
13
|
-
&& Object.keys(value).every((key) => key === "artifacts" || key === "contract" || key === "working" || key === "response" || key === "lazy");
|
|
14
|
+
&& Object.keys(value).every((key) => key === "artifacts" || key === "contract" || key === "working" || key === "intents" || key === "response" || key === "lazy");
|
|
14
15
|
}
|
|
15
16
|
export const isStateDocument = isMaterializedState;
|
|
17
|
+
/** Upgrade one exact pre-intents materialized state without inferring commitments. */
|
|
18
|
+
export function migratePreIntentState(value) {
|
|
19
|
+
if (!isObject(value) || Object.hasOwn(value, "intents"))
|
|
20
|
+
return undefined;
|
|
21
|
+
const candidate = { ...structuredClone(value), intents: {} };
|
|
22
|
+
return isMaterializedState(candidate) ? candidate : undefined;
|
|
23
|
+
}
|
|
16
24
|
/** Atomically replace compiled and removed artifacts inside one materialized scope. */
|
|
17
25
|
export function updateMaterializedArtifacts(state, updates, removed = []) {
|
|
18
26
|
if (!isMaterializedState(state))
|
package/dist/lib/telegram.d.ts
CHANGED
package/dist/lib/telegram.js
CHANGED
|
@@ -94,7 +94,7 @@ function renderStateFlowTelegramField(value) {
|
|
|
94
94
|
return rendered;
|
|
95
95
|
}
|
|
96
96
|
export function renderStateFlowRichState(scope, step, state) {
|
|
97
|
-
const fields = ["artifacts", "contract", "working", "response", "lazy"];
|
|
97
|
+
const fields = ["artifacts", "contract", "working", "intents", "response", "lazy"];
|
|
98
98
|
return {
|
|
99
99
|
blocks: [
|
|
100
100
|
{
|
package/dist/lib/transition.js
CHANGED
|
@@ -3,7 +3,7 @@ import { createAcceptedTransition } from "./history.js";
|
|
|
3
3
|
import { applyPatch, containsNull, hashJson, isObject, validatePatch } from "./json.js";
|
|
4
4
|
import { hasCompiledSkillArtifact, SKILL_ARTIFACT_COMPILER } from "./skills.js";
|
|
5
5
|
const SCOPES = new Set(["global", "cwd", "session"]);
|
|
6
|
-
const PATCH_KEYS = new Set(["artifacts", "contract", "working", "lazy"]);
|
|
6
|
+
const PATCH_KEYS = new Set(["artifacts", "contract", "working", "intents", "lazy"]);
|
|
7
7
|
function compileReadArtifacts(nextState, patch, successfulArtifactReads, provenance) {
|
|
8
8
|
for (const read of successfulArtifactReads) {
|
|
9
9
|
const output = patch.artifacts[read.path];
|
|
@@ -77,10 +77,10 @@ function validateScopePatch(scope, patch) {
|
|
|
77
77
|
validatePatch(patch);
|
|
78
78
|
for (const key of Object.keys(patch)) {
|
|
79
79
|
if (!PATCH_KEYS.has(key)) {
|
|
80
|
-
throw new Error(`Scoped State Flow patches cannot modify ${key}; only artifacts, contract, working, and lazy are model-owned`);
|
|
80
|
+
throw new Error(`Scoped State Flow patches cannot modify ${key}; only artifacts, contract, working, intents, and lazy are model-owned`);
|
|
81
81
|
}
|
|
82
82
|
}
|
|
83
|
-
for (const key of ["artifacts", "contract", "working"]) {
|
|
83
|
+
for (const key of ["artifacts", "contract", "working", "intents"]) {
|
|
84
84
|
if (Object.hasOwn(patch, key) && !isObject(patch[key])) {
|
|
85
85
|
throw new Error(`Scoped State Flow patch field ${key} must be a JSON object`);
|
|
86
86
|
}
|
|
@@ -96,6 +96,7 @@ function completePatch(patch, response) {
|
|
|
96
96
|
artifacts: patch.artifacts ?? {},
|
|
97
97
|
contract: patch.contract ?? {},
|
|
98
98
|
working: patch.working ?? {},
|
|
99
|
+
intents: patch.intents ?? {},
|
|
99
100
|
response,
|
|
100
101
|
...(Object.hasOwn(patch, "lazy") ? { lazy: structuredClone(patch.lazy) } : {}),
|
|
101
102
|
};
|
package/dist/package.json
CHANGED
|
@@ -19,7 +19,7 @@ Use this Skill for one bounded maintenance cohort: either an explicit curation r
|
|
|
19
19
|
|
|
20
20
|
## Inventory
|
|
21
21
|
|
|
22
|
-
Read only the smallest required projections with `read_state`: session for branch/run continuation, CWD for project-specific knowledge, and global for established cross-project, user, or environment knowledge. Use older offsets only for a concrete contradiction or provenance question. Do not reread current effective state already in context without a specific verification or ownership need.
|
|
22
|
+
Read only the smallest required projections with `read_state`: session for branch/run continuation, CWD for project-specific knowledge, and global for established cross-project, user, or environment knowledge. Distinguish `contract` requirements, `working` observations and unresolved state, active commitments in `intents`, and inactive reusable memory in `lazy`. Use older offsets only for a concrete contradiction or provenance question. Do not reread current effective state already in context without a specific verification or ownership need.
|
|
23
23
|
|
|
24
24
|
Distinguish user requirements, confirmed decisions, observations, assistant conclusions, and hypotheses. Do not infer user acceptance from silence, repetition, or an earlier assistant assertion.
|
|
25
25
|
|
|
@@ -38,6 +38,8 @@ These are audit decisions, not required stored labels. Do not manufacture timest
|
|
|
38
38
|
|
|
39
39
|
### Preserve commitments without freezing methods
|
|
40
40
|
|
|
41
|
+
Treat every value in `intents` as an active commitment to future action. Keep it only while that course remains chosen; remove it when fulfilled, abandoned, superseded, or impossible, retaining only consequential results in `working`, `contract`, or `lazy`. Alternatives, possible next steps, observations, and historical plans are not intents. Check touched intent references for moved or missing targets, but never auto-hydrate, rewrite, execute, or complete a `{"$ref":"..."}` pointer.
|
|
42
|
+
|
|
41
43
|
Preserve active goals, explicit constraints, confirmed decisions, completed prerequisites, and obligations that still affect future work. Preserve corrections and their consequences.
|
|
42
44
|
|
|
43
45
|
Separate a binding requirement from the method currently proposed to satisfy it. Do not turn an assistant preference into a user requirement, or a provisional approach into a settled decision. Conversely, do not demote a confirmed decision merely to encourage exploration. Retain its scope and known reconsideration conditions when relevant; do not invent them.
|
|
@@ -106,14 +108,14 @@ Adjust only identified defects. This is a semantic review, not a request for ext
|
|
|
106
108
|
|
|
107
109
|
## Apply one reconciliation cohort
|
|
108
110
|
|
|
109
|
-
Use `patch_state` only for material changes to `artifacts`, `contract`, or `
|
|
111
|
+
Use `patch_state` only for material changes to `artifacts`, `contract`, `working`, `intents`, or `lazy`. 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.
|
|
110
112
|
|
|
111
113
|
Schedule acquisition and migration barriers in this order:
|
|
112
114
|
|
|
113
115
|
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.
|
|
114
116
|
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.
|
|
115
117
|
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.
|
|
116
|
-
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.
|
|
118
|
+
4. Complete one terminal reconciliation without repeating accepted compilations or inventing memory changes. Review touched intents explicitly: retain active commitments, remove completed or impossible ones, replace superseded ones, and preserve their consequential results in the appropriate plane. 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.
|
|
117
119
|
|
|
118
120
|
Scope-local deletion may reveal a lower-scope value. Deleting an override is not necessarily removal from effective state.
|
|
119
121
|
|
package/docs/architecture.md
CHANGED
|
@@ -78,7 +78,7 @@ Every enabled assistant iteration starts terminal-ineligible. Only a successful
|
|
|
78
78
|
## Lifecycle planes
|
|
79
79
|
|
|
80
80
|
```text
|
|
81
|
-
SEMANTIC STATE artifacts + contract + working
|
|
81
|
+
SEMANTIC STATE artifacts + contract + working + intents
|
|
82
82
|
TURN ELIGIBILITY false → patch_state(..., final:true) → latched true
|
|
83
83
|
CONTEXT PROJECTION active State Flow projection | passive post-stop handoff
|
|
84
84
|
```
|
|
@@ -198,23 +198,25 @@ Both [tested Pi SDKs](compatibility.md) choose or create `SessionManager` before
|
|
|
198
198
|
|
|
199
199
|
### Model tools
|
|
200
200
|
|
|
201
|
-
`patch_state` accepts optional fixed `global`, `cwd`, and `session` semantic patches plus optional `final:true`. At least one scope or `final:true` is required in the canonical model contract. Supplied scopes contain
|
|
201
|
+
`patch_state` accepts optional fixed `global`, `cwd`, and `session` semantic patches plus optional `final:true`. At least one scope or `final:true` is required in the canonical model contract. Supplied scopes contain object-valued `artifacts`, `contract`, `working`, and `intents`, plus ordinary-JSON `lazy`; omitted fields preserve their values, recursive object merge updates them, arrays/primitives replace, and nested object-key `null` deletes. Materialized null, empty supplied scopes, material no-ops, unknown top-level fields, model-authored `response`, and retired grammars are rejected. A final-only true call changes ephemeral eligibility, not semantic history. Runtime quietly accepts unambiguous false-like `final` input as non-terminal intent, including an inert false-only call, but this compatibility layer is deliberately absent from model guidance.
|
|
202
202
|
|
|
203
203
|
```json
|
|
204
|
-
{"session":{"
|
|
204
|
+
{"session":{"intents":{"next":"Verify the corrected behavior"}},"final":true}
|
|
205
205
|
```
|
|
206
206
|
|
|
207
|
-
`
|
|
207
|
+
`intents` is the hot plane for active commitments, not requirements, observations, alternatives, or completed plans. Removing an intent does not remove its consequences or any referenced state. A conventional `{"$ref":"cwd.lazy.plan"}` value remains ordinary JSON and is followed explicitly with `read_state`; it creates no dependency, hydration, execution, or completion semantics.
|
|
208
|
+
|
|
209
|
+
`read_state` accepts one unified path. `effective == effective[0]` is the current effective materialization; `global == global[0]` (and CWD/session equivalents) selects that scope at the same composed causal boundary. `global.patches == global.patches[0]` reads the latest accepted retained global patch, with higher patch indices walking only that scope's retained accepted patches. Indices are bounded to zero through seven; unavailable pre-origin or pre-tail history is an error. Resolver aliases are not literal JSON containers. Reads stay cached and create no Git query, publication, checkpoint append, or semantic step.
|
|
208
210
|
|
|
209
211
|
```json
|
|
210
|
-
{"path":"
|
|
212
|
+
{"path":"cwd[1].intents"}
|
|
211
213
|
```
|
|
212
214
|
|
|
213
215
|
```json
|
|
214
|
-
{"path":"
|
|
216
|
+
{"path":"global.patches[0]"}
|
|
215
217
|
```
|
|
216
218
|
|
|
217
|
-
|
|
219
|
+
Unscoped semantic paths such as `intents.next` alias the current effective overlay. `value`, `keys`, and `patch` projections plus ordered `paths` batches remain all-or-error.
|
|
218
220
|
|
|
219
221
|
Both tools follow branch enablement and host restrictions. The patch barrier also blocks reader siblings. These tools do not impose project schemas or state-size caps; semantic usefulness, scope choice, and compression remain model responsibilities. Every ordinary handoff reconciles touched and obviously stale visible state. Feature/release/campaign completion, project switches, and active-version changes additionally require one bounded scoped ownership and obsolescence pass: global retains only established cross-project/user/environment knowledge, CWD owns reusable project truth, and session owns branch/run continuation. Scope movement uses targeted reads and destination verification before source deletion rather than an automatic maintenance loop.
|
|
220
222
|
|
package/docs/lazy-state.md
CHANGED
|
@@ -34,18 +34,19 @@ The model-facing surface remains small:
|
|
|
34
34
|
|
|
35
35
|
## Semantic model
|
|
36
36
|
|
|
37
|
-
Each scope may contain
|
|
37
|
+
Each scope may contain six semantic planes:
|
|
38
38
|
|
|
39
39
|
```text
|
|
40
40
|
global | CWD | session
|
|
41
41
|
├── artifacts
|
|
42
42
|
├── contract
|
|
43
43
|
├── working
|
|
44
|
+
├── intents
|
|
44
45
|
├── response (session-owned where applicable)
|
|
45
46
|
└── lazy
|
|
46
47
|
```
|
|
47
48
|
|
|
48
|
-
`artifacts`, `contract`, `working`, and `response` remain hot. `lazy` differs only in projection policy:
|
|
49
|
+
`artifacts`, `contract`, `working`, `intents`, and `response` remain hot. `intents` may keep compact active direction while pointing to large supporting detail in `lazy` with an ordinary `{"$ref":"cwd.lazy.plan"}` value. References are read explicitly and never auto-hydrated, rewritten, executed, or completed. `lazy` differs only in projection policy:
|
|
49
50
|
|
|
50
51
|
- It is canonical semantic JSON, validated and versioned with its owning scope.
|
|
51
52
|
- It is excluded from the ordinary baseline effective-state body.
|
package/lib/durable.ts
CHANGED
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
} from "./artifact.ts";
|
|
21
21
|
import { canonicalJson, isJsonValue, isObject } from "./json.ts";
|
|
22
22
|
import { validateScopeStream, validateTemporalState, type ScopeStream, type TemporalState } from "./temporal.ts";
|
|
23
|
-
import type
|
|
23
|
+
import { migratePreIntentState, type StateScope } from "./state.ts";
|
|
24
24
|
|
|
25
25
|
const SESSION_KEY_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
|
|
26
26
|
const STATE_FILE = "state.json";
|
|
@@ -100,6 +100,7 @@ export function classifyScopeStream(
|
|
|
100
100
|
}
|
|
101
101
|
const temporal = meta?.temporal;
|
|
102
102
|
if (isObject(temporal) && Object.hasOwn(temporal, "checkpoint") && Array.isArray(temporal.patches)) {
|
|
103
|
+
checkpoint = migratePreIntentState(checkpoint) ?? checkpoint;
|
|
103
104
|
const owner = meta?.owner;
|
|
104
105
|
if (scope === "cwd" && expectedCwd !== undefined
|
|
105
106
|
&& (!isObject(owner) || Object.keys(owner).join(",") !== "cwd" || owner.cwd !== resolve(expectedCwd))) {
|
|
@@ -126,6 +127,10 @@ export function classifyScopeStream(
|
|
|
126
127
|
} else if (scope === "cwd" && expectedCwd !== undefined) {
|
|
127
128
|
throw new Error("State Flow CWD scope identity is missing");
|
|
128
129
|
}
|
|
130
|
+
if (isObject(legacyCheckpoint) && isObject(legacyCheckpoint.state)) {
|
|
131
|
+
const migrated = migratePreIntentState(legacyCheckpoint.state);
|
|
132
|
+
if (migrated) legacyCheckpoint = { ...legacyCheckpoint, state: migrated };
|
|
133
|
+
}
|
|
129
134
|
const stream = { checkpoint: legacyCheckpoint, patches };
|
|
130
135
|
validateScopeStream(stream, scope);
|
|
131
136
|
return { kind: "present", stream };
|
package/lib/history.ts
CHANGED
|
@@ -22,7 +22,7 @@ export interface RecentTransition extends AcceptedTransition {
|
|
|
22
22
|
|
|
23
23
|
export type RecentTransitionWindow = RecentTransition[];
|
|
24
24
|
const SCOPES = new Set<StateScope>(["global", "cwd", "session"]);
|
|
25
|
-
const PATCH_KEYS = new Set(["artifacts", "contract", "working", "response", "lazy"]);
|
|
25
|
+
const PATCH_KEYS = new Set(["artifacts", "contract", "working", "intents", "response", "lazy"]);
|
|
26
26
|
|
|
27
27
|
/** Normalize accepted replacements into recursive-merge replay, including removals. */
|
|
28
28
|
function replayPatch(before: JsonObject, after: JsonObject): JsonObject {
|
package/lib/migration.ts
CHANGED
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
type OwnedFileUpdate,
|
|
14
14
|
} from "./durable.ts";
|
|
15
15
|
import { parseSessionRuntime, serializeSessionRuntime } from "./snapshot.ts";
|
|
16
|
-
import type
|
|
16
|
+
import { migratePreIntentState, type StateScope } from "./state.ts";
|
|
17
17
|
|
|
18
18
|
export interface LegacyStorageMigration {
|
|
19
19
|
bases: DurableFileBase[];
|
|
@@ -57,9 +57,14 @@ function migrationDirectories(cwd: string, sessionId: string, root: string, sess
|
|
|
57
57
|
try { sessionScopeKey(entry.name); } catch { continue; }
|
|
58
58
|
const directory = join(cwdDirectory, entry.name);
|
|
59
59
|
let meta: unknown;
|
|
60
|
+
let runtime: unknown;
|
|
60
61
|
try { meta = JSON.parse(readFileSync(join(directory, "meta.json"), "utf8")); }
|
|
61
62
|
catch { continue; }
|
|
62
|
-
|
|
63
|
+
try { runtime = JSON.parse(readFileSync(join(directory, "runtime.json"), "utf8")); }
|
|
64
|
+
catch { /* predecessor sessions keep identity in meta.json */ }
|
|
65
|
+
const identity = meta && typeof meta === "object" && !Array.isArray(meta) && (meta as { identity?: unknown }).identity !== undefined
|
|
66
|
+
? (meta as { identity?: unknown }).identity
|
|
67
|
+
: runtime && typeof runtime === "object" && !Array.isArray(runtime) ? (runtime as { identity?: unknown }).identity : undefined;
|
|
63
68
|
if (!identity || typeof identity !== "object" || Array.isArray(identity)) continue;
|
|
64
69
|
const owner = identity as { cwd?: unknown; sessionId?: unknown };
|
|
65
70
|
if (owner.cwd === cwdOwner && typeof owner.sessionId === "string" && owner.sessionId.length > 0) {
|
|
@@ -85,7 +90,14 @@ export function hasCwdMaterialization(cwd: string, repositoryRoot: string): bool
|
|
|
85
90
|
return false;
|
|
86
91
|
}
|
|
87
92
|
|
|
88
|
-
|
|
93
|
+
function checkpointNeedsIntentMigration(source: string): boolean {
|
|
94
|
+
const checkpoint = JSON.parse(source) as unknown;
|
|
95
|
+
if (migratePreIntentState(checkpoint) !== undefined) return true;
|
|
96
|
+
return checkpoint !== null && typeof checkpoint === "object" && !Array.isArray(checkpoint)
|
|
97
|
+
&& migratePreIntentState((checkpoint as { state?: unknown }).state) !== undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Detect predecessor snapshots, temporal envelopes, or pre-intents semantic states without mutating the store. */
|
|
89
101
|
export function hasLegacyStateSources(
|
|
90
102
|
cwd: string,
|
|
91
103
|
sessionId: string,
|
|
@@ -94,8 +106,10 @@ export function hasLegacyStateSources(
|
|
|
94
106
|
): boolean {
|
|
95
107
|
const root = resolve(repositoryRoot);
|
|
96
108
|
return migrationDirectories(cwd, sessionId, root, sessionKey).some(({ directory, scope }) => {
|
|
97
|
-
|
|
109
|
+
const checkpointPath = join(directory, "checkpoint.json");
|
|
110
|
+
if (lstatSync(checkpointPath, { throwIfNoEntry: false }) === undefined) return false;
|
|
98
111
|
try {
|
|
112
|
+
if (checkpointNeedsIntentMigration(readFileSync(checkpointPath, "utf8"))) return true;
|
|
99
113
|
const meta = JSON.parse(readFileSync(join(directory, "meta.json"), "utf8"));
|
|
100
114
|
if (meta === null || typeof meta !== "object" || !("temporal" in meta)) return true;
|
|
101
115
|
return scope === "session"
|
package/lib/protocol.ts
CHANGED
|
@@ -13,25 +13,28 @@ export function stateFlowProtocol(bootstrap: boolean): string {
|
|
|
13
13
|
: "";
|
|
14
14
|
return `State Flow is enabled.
|
|
15
15
|
${bootstrapProtocol}
|
|
16
|
-
STATE: {"artifacts":{},"contract":{},"working":{},"response":"latest complete answer"}
|
|
16
|
+
STATE: {"artifacts":{},"contract":{},"working":{},"intents":{},"response":"latest complete answer"}
|
|
17
17
|
- artifacts: source-path routing metadata; descriptions do not imply body acquisition.
|
|
18
18
|
- contract: durable requirements, decisions, rejections, interfaces, compiled knowledge.
|
|
19
19
|
- working: facts, validation, failures, domain state, unresolved work, continuation.
|
|
20
|
+
- intents: active commitments; remove when fulfilled, abandoned, superseded, or impossible.
|
|
20
21
|
- response: previous complete answer; runtime-owned.
|
|
21
22
|
|
|
22
|
-
READ: Use read_state
|
|
23
|
+
READ: Use read_state for concrete scope/history gaps. lazy_navigation exposes the effective lazy root's bounded key kinds, not bodies. Unscoped paths alias effective; effective/global/cwd/session select overlay or owner. Arrays support indices and [start..end]; keys gives structure and patch the intersected change.
|
|
23
24
|
|
|
24
25
|
WRITE: patch_state is the sole model-authored semantic mutation mechanism. Supply global/cwd/session patches in any combination; all supplied scopes are validated and durably accepted as one atomic transition. Call it alone in an assistant response, then continue only after its acknowledgement.
|
|
25
26
|
|
|
26
|
-
FINAL: Every enabled iteration starts terminal-ineligible.
|
|
27
|
+
FINAL: Every enabled iteration starts terminal-ineligible. Successful patch_state final:true permits a later turn_end without stopping later work; use {"final":true} when no state change is needed. Otherwise runtime preserves the answer and allows at most two fallback turns only for final:true; never restate it. A final-only call creates no transition. Runtime owns response.
|
|
28
|
+
|
|
29
|
+
INTENTS: Store selected actions, not requirements, observations, possibilities, alternatives, or completed work. Preserve them across handoffs at the narrowest scope; detail may stay lazy. A {"$ref":"cwd.lazy.plan"} is an ordinary pointer: follow it with read_state only when needed; infer no dependency, hydration, execution, or completion.
|
|
27
30
|
|
|
28
31
|
SCOPES: global=cross-project; cwd=project and Skills; session=branch/run. Deleting an override may reveal its parent.
|
|
29
32
|
|
|
30
33
|
${baselineMemoryProtocol()}
|
|
31
34
|
|
|
32
|
-
PATCH: Optional global/cwd/session object patches plus optional final:true; require at least one. Omit empty/materially no-op scopes. Semantic fields are object-valued artifacts/contract/working and ordinary-JSON lazy; omitted fields persist. Never patch runtime config/meta/response. Objects merge recursively; arrays/primitives replace. An object containing only canonical "[N]" keys recursively patches array elements. Indexed deletion is forbidden; nested object null deletes; materialized null is forbidden.
|
|
35
|
+
PATCH: Optional global/cwd/session object patches plus optional final:true; require at least one. Omit empty/materially no-op scopes. Semantic fields are object-valued artifacts/contract/working/intents and ordinary-JSON lazy; omitted fields persist. Never patch runtime config/meta/response. Objects merge recursively; arrays/primitives replace. An object containing only canonical "[N]" keys recursively patches array elements. Indexed deletion is forbidden; nested object null deletes; materialized null is forbidden.
|
|
33
36
|
|
|
34
|
-
HANDOFF: Preserve active commitments,
|
|
37
|
+
HANDOFF: Preserve active commitments, open questions, consequential results, and exact continuation; distinguish requirements, decisions, observations, conclusions, and hypotheses. Curate touched and obviously stale/mis-scoped state. At feature/release/campaign or project/version completion, reconcile once: remove obsolete work, retain consequences, and use targeted read_state plus destination-verify-source-delete for moves. Never invent memory changes.
|
|
35
38
|
|
|
36
39
|
ACQUISITION: Start materialized. Read only for a compilation gap, exact source/edit, invalidation, contradiction/failure, or explicit request; changed hashes require rereading.
|
|
37
40
|
ARTIFACTS: For each acquired new/invalidated ordinary artifact, patch global.artifacts[exact path] with a compact non-empty description. Runtime owns provenance.
|
package/lib/query.ts
CHANGED
|
@@ -51,7 +51,7 @@ export function readStatePath(view: TemporalState, path: string): StateReadResul
|
|
|
51
51
|
|
|
52
52
|
function parseValuePath(path: string): { root: string; selectors: ValueSelector[] } {
|
|
53
53
|
const explicitRoot = /^(?:effective|global|cwd|session)(?:\[\d+\])?(?=\.|$)/.exec(path)?.[0];
|
|
54
|
-
const implicitRoot = /^(?:artifacts|contract|working|response|lazy)(?=\.|\[|$)/.exec(path)?.[0];
|
|
54
|
+
const implicitRoot = /^(?:artifacts|contract|working|intents|response|lazy)(?=\.|\[|$)/.exec(path)?.[0];
|
|
55
55
|
if (explicitRoot === undefined && implicitRoot === undefined) {
|
|
56
56
|
throw new Error("State Flow read path requires a semantic path or an effective, global, cwd, or session root");
|
|
57
57
|
}
|
package/lib/state.ts
CHANGED
|
@@ -12,6 +12,7 @@ export type MaterializedState = JsonObject & {
|
|
|
12
12
|
artifacts: ArtifactRegistry;
|
|
13
13
|
contract: JsonObject;
|
|
14
14
|
working: JsonObject;
|
|
15
|
+
intents: JsonObject;
|
|
15
16
|
response: string;
|
|
16
17
|
/** Absent is the canonical empty lazy plane and preserves predecessor-store compatibility. */
|
|
17
18
|
lazy?: JsonValue;
|
|
@@ -25,6 +26,7 @@ export interface StatePatch extends JsonObject {
|
|
|
25
26
|
artifacts: JsonObject;
|
|
26
27
|
contract: JsonObject;
|
|
27
28
|
working: JsonObject;
|
|
29
|
+
intents: JsonObject;
|
|
28
30
|
response: string;
|
|
29
31
|
}
|
|
30
32
|
|
|
@@ -35,6 +37,7 @@ export interface ScopePatch {
|
|
|
35
37
|
artifacts?: JsonObject;
|
|
36
38
|
contract?: JsonObject;
|
|
37
39
|
working?: JsonObject;
|
|
40
|
+
intents?: JsonObject;
|
|
38
41
|
lazy?: JsonValue;
|
|
39
42
|
}
|
|
40
43
|
|
|
@@ -65,7 +68,7 @@ export interface ScopedStates {
|
|
|
65
68
|
}
|
|
66
69
|
|
|
67
70
|
export function emptyState(): MaterializedState {
|
|
68
|
-
return { artifacts: {}, contract: {}, working: {}, response: "" } as MaterializedState;
|
|
71
|
+
return { artifacts: {}, contract: {}, working: {}, intents: {}, response: "" } as MaterializedState;
|
|
69
72
|
}
|
|
70
73
|
|
|
71
74
|
export function isMaterializedState(value: unknown): value is MaterializedState {
|
|
@@ -73,13 +76,21 @@ export function isMaterializedState(value: unknown): value is MaterializedState
|
|
|
73
76
|
&& isArtifactRegistry(value.artifacts)
|
|
74
77
|
&& isObject(value.contract)
|
|
75
78
|
&& isObject(value.working)
|
|
79
|
+
&& isObject(value.intents)
|
|
76
80
|
&& typeof value.response === "string"
|
|
77
81
|
&& (!Object.hasOwn(value, "lazy") || (isJsonValue(value.lazy) && value.lazy !== null))
|
|
78
|
-
&& Object.keys(value).every((key) => key === "artifacts" || key === "contract" || key === "working" || key === "response" || key === "lazy");
|
|
82
|
+
&& Object.keys(value).every((key) => key === "artifacts" || key === "contract" || key === "working" || key === "intents" || key === "response" || key === "lazy");
|
|
79
83
|
}
|
|
80
84
|
|
|
81
85
|
export const isStateDocument = isMaterializedState;
|
|
82
86
|
|
|
87
|
+
/** Upgrade one exact pre-intents materialized state without inferring commitments. */
|
|
88
|
+
export function migratePreIntentState(value: unknown): MaterializedState | undefined {
|
|
89
|
+
if (!isObject(value) || Object.hasOwn(value, "intents")) return undefined;
|
|
90
|
+
const candidate = { ...structuredClone(value), intents: {} };
|
|
91
|
+
return isMaterializedState(candidate) ? candidate : undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
83
94
|
/** Atomically replace compiled and removed artifacts inside one materialized scope. */
|
|
84
95
|
export function updateMaterializedArtifacts(
|
|
85
96
|
state: MaterializedState,
|
package/lib/telegram.ts
CHANGED
|
@@ -26,6 +26,7 @@ export interface StateFlowTelegramState {
|
|
|
26
26
|
artifacts: Record<string, unknown>;
|
|
27
27
|
contract: Record<string, unknown>;
|
|
28
28
|
working: Record<string, unknown>;
|
|
29
|
+
intents: Record<string, unknown>;
|
|
29
30
|
response: string;
|
|
30
31
|
lazy?: unknown;
|
|
31
32
|
}
|
|
@@ -191,7 +192,7 @@ function renderStateFlowTelegramField(value: unknown): string {
|
|
|
191
192
|
}
|
|
192
193
|
|
|
193
194
|
export function renderStateFlowRichState(scope: StateFlowTelegramScope, step: number, state: StateFlowTelegramState): StateFlowTelegramRichMessage {
|
|
194
|
-
const fields = ["artifacts", "contract", "working", "response", "lazy"] as const;
|
|
195
|
+
const fields = ["artifacts", "contract", "working", "intents", "response", "lazy"] as const;
|
|
195
196
|
return {
|
|
196
197
|
blocks: [
|
|
197
198
|
{
|
package/lib/transition.ts
CHANGED
|
@@ -35,7 +35,7 @@ export interface StagedScopedTransition {
|
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
const SCOPES = new Set<StateScope>(["global", "cwd", "session"]);
|
|
38
|
-
const PATCH_KEYS = new Set(["artifacts", "contract", "working", "lazy"]);
|
|
38
|
+
const PATCH_KEYS = new Set(["artifacts", "contract", "working", "intents", "lazy"]);
|
|
39
39
|
|
|
40
40
|
function compileReadArtifacts(
|
|
41
41
|
nextState: StateDocument,
|
|
@@ -123,10 +123,10 @@ function validateScopePatch(scope: unknown, patch: unknown): asserts patch is Sc
|
|
|
123
123
|
validatePatch(patch);
|
|
124
124
|
for (const key of Object.keys(patch)) {
|
|
125
125
|
if (!PATCH_KEYS.has(key)) {
|
|
126
|
-
throw new Error(`Scoped State Flow patches cannot modify ${key}; only artifacts, contract, working, and lazy are model-owned`);
|
|
126
|
+
throw new Error(`Scoped State Flow patches cannot modify ${key}; only artifacts, contract, working, intents, and lazy are model-owned`);
|
|
127
127
|
}
|
|
128
128
|
}
|
|
129
|
-
for (const key of ["artifacts", "contract", "working"] as const) {
|
|
129
|
+
for (const key of ["artifacts", "contract", "working", "intents"] as const) {
|
|
130
130
|
if (Object.hasOwn(patch, key) && !isObject(patch[key])) {
|
|
131
131
|
throw new Error(`Scoped State Flow patch field ${key} must be a JSON object`);
|
|
132
132
|
}
|
|
@@ -142,6 +142,7 @@ function completePatch(patch: ScopePatch, response: string): StatePatch {
|
|
|
142
142
|
artifacts: patch.artifacts ?? {},
|
|
143
143
|
contract: patch.contract ?? {},
|
|
144
144
|
working: patch.working ?? {},
|
|
145
|
+
intents: patch.intents ?? {},
|
|
145
146
|
response,
|
|
146
147
|
...(Object.hasOwn(patch, "lazy") ? { lazy: structuredClone(patch.lazy!) } : {}),
|
|
147
148
|
};
|
package/package.json
CHANGED
|
@@ -19,7 +19,7 @@ Use this Skill for one bounded maintenance cohort: either an explicit curation r
|
|
|
19
19
|
|
|
20
20
|
## Inventory
|
|
21
21
|
|
|
22
|
-
Read only the smallest required projections with `read_state`: session for branch/run continuation, CWD for project-specific knowledge, and global for established cross-project, user, or environment knowledge. Use older offsets only for a concrete contradiction or provenance question. Do not reread current effective state already in context without a specific verification or ownership need.
|
|
22
|
+
Read only the smallest required projections with `read_state`: session for branch/run continuation, CWD for project-specific knowledge, and global for established cross-project, user, or environment knowledge. Distinguish `contract` requirements, `working` observations and unresolved state, active commitments in `intents`, and inactive reusable memory in `lazy`. Use older offsets only for a concrete contradiction or provenance question. Do not reread current effective state already in context without a specific verification or ownership need.
|
|
23
23
|
|
|
24
24
|
Distinguish user requirements, confirmed decisions, observations, assistant conclusions, and hypotheses. Do not infer user acceptance from silence, repetition, or an earlier assistant assertion.
|
|
25
25
|
|
|
@@ -38,6 +38,8 @@ These are audit decisions, not required stored labels. Do not manufacture timest
|
|
|
38
38
|
|
|
39
39
|
### Preserve commitments without freezing methods
|
|
40
40
|
|
|
41
|
+
Treat every value in `intents` as an active commitment to future action. Keep it only while that course remains chosen; remove it when fulfilled, abandoned, superseded, or impossible, retaining only consequential results in `working`, `contract`, or `lazy`. Alternatives, possible next steps, observations, and historical plans are not intents. Check touched intent references for moved or missing targets, but never auto-hydrate, rewrite, execute, or complete a `{"$ref":"..."}` pointer.
|
|
42
|
+
|
|
41
43
|
Preserve active goals, explicit constraints, confirmed decisions, completed prerequisites, and obligations that still affect future work. Preserve corrections and their consequences.
|
|
42
44
|
|
|
43
45
|
Separate a binding requirement from the method currently proposed to satisfy it. Do not turn an assistant preference into a user requirement, or a provisional approach into a settled decision. Conversely, do not demote a confirmed decision merely to encourage exploration. Retain its scope and known reconsideration conditions when relevant; do not invent them.
|
|
@@ -106,14 +108,14 @@ Adjust only identified defects. This is a semantic review, not a request for ext
|
|
|
106
108
|
|
|
107
109
|
## Apply one reconciliation cohort
|
|
108
110
|
|
|
109
|
-
Use `patch_state` only for material changes to `artifacts`, `contract`, or `
|
|
111
|
+
Use `patch_state` only for material changes to `artifacts`, `contract`, `working`, `intents`, or `lazy`. 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.
|
|
110
112
|
|
|
111
113
|
Schedule acquisition and migration barriers in this order:
|
|
112
114
|
|
|
113
115
|
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.
|
|
114
116
|
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.
|
|
115
117
|
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.
|
|
116
|
-
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.
|
|
118
|
+
4. Complete one terminal reconciliation without repeating accepted compilations or inventing memory changes. Review touched intents explicitly: retain active commitments, remove completed or impossible ones, replace superseded ones, and preserve their consequential results in the appropriate plane. 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.
|
|
117
119
|
|
|
118
120
|
Scope-local deletion may reveal a lower-scope value. Deleting an override is not necessarily removal from effective state.
|
|
119
121
|
|