opencode-self-improvement 0.15.4 → 0.15.5

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.
Files changed (98) hide show
  1. package/package.json +2 -2
  2. package/src/capture/candidates.ts +110 -0
  3. package/src/capture/lag.ts +18 -0
  4. package/src/capture/prompt.ts +50 -0
  5. package/src/capture/transcript.ts +59 -0
  6. package/src/{triggers.ts → capture/triggers.ts} +6 -5
  7. package/src/{command.ts → command/ensure.ts} +2 -2
  8. package/src/{consolidate.ts → consolidate/propose.ts} +7 -30
  9. package/src/consolidate/render.ts +30 -0
  10. package/src/core/cmp-ts.ts +16 -0
  11. package/src/core/config/budgets.ts +28 -0
  12. package/src/{config.ts → core/config/paths.ts} +1 -30
  13. package/src/core/logfmt/format.ts +82 -0
  14. package/src/{logfmt.ts → core/logfmt/publish.ts} +3 -92
  15. package/src/core/logfmt/read.ts +15 -0
  16. package/src/{state.ts → core/state.ts} +1 -1
  17. package/src/core/time.ts +6 -0
  18. package/src/{evidence.ts → evidence/record.ts} +7 -5
  19. package/src/{gates.ts → gate/gate.ts} +19 -21
  20. package/src/{resolver.ts → gate/resolver.ts} +1 -1
  21. package/src/{hits.ts → hits/ledger.ts} +8 -6
  22. package/src/index.ts +64 -943
  23. package/src/init/detect.ts +144 -0
  24. package/src/init/format.ts +25 -0
  25. package/src/init/run.ts +188 -0
  26. package/src/inject/anchor.ts +43 -0
  27. package/src/{attribution.ts → inject/attribution.ts} +2 -2
  28. package/src/inject/budget.ts +78 -0
  29. package/src/inject/digest.ts +89 -0
  30. package/src/{injection-epochs.ts → inject/epochs.ts} +15 -14
  31. package/src/inject/format.ts +32 -0
  32. package/src/inject/pull.ts +52 -0
  33. package/src/inject/version.ts +31 -0
  34. package/src/portable/decay.ts +20 -0
  35. package/src/portable/export.ts +194 -0
  36. package/src/portable/import.ts +173 -0
  37. package/src/recall/relevant.ts +72 -0
  38. package/src/recall/score.ts +106 -0
  39. package/src/recall/shared-terms.ts +15 -0
  40. package/src/status/format.ts +58 -0
  41. package/src/status/metrics.ts +65 -0
  42. package/src/status/payload.ts +143 -0
  43. package/src/status/report.ts +202 -0
  44. package/src/status/write.ts +102 -0
  45. package/src/{blocklist.ts → store/blocklist.ts} +4 -2
  46. package/src/store/files/append.ts +176 -0
  47. package/src/store/files/deletions.ts +31 -0
  48. package/src/store/files/load.ts +106 -0
  49. package/src/store/files/prune.ts +81 -0
  50. package/src/store/files/snapshots.ts +88 -0
  51. package/src/store/files/supersede.ts +123 -0
  52. package/src/store/files/target.ts +36 -0
  53. package/src/{lock.ts → store/lock.ts} +1 -1
  54. package/src/store/model/memory.ts +91 -0
  55. package/src/store/model/predicates.ts +12 -0
  56. package/src/store/model/visibility.ts +140 -0
  57. package/src/{prune.ts → store/prune.ts} +4 -3
  58. package/src/store/quarantine/release.ts +24 -0
  59. package/src/store/tombstones/rejection.ts +93 -0
  60. package/src/{tombstones.ts → store/tombstones/tombstone.ts} +12 -97
  61. package/src/{undo.ts → store/undo.ts} +6 -3
  62. package/src/tools/consolidate.ts +42 -0
  63. package/src/tools/decay.ts +83 -0
  64. package/src/tools/deps.ts +27 -0
  65. package/src/tools/evidence.ts +48 -0
  66. package/src/tools/export.ts +27 -0
  67. package/src/tools/forget.ts +23 -0
  68. package/src/tools/import.ts +57 -0
  69. package/src/tools/init.ts +30 -0
  70. package/src/tools/list.ts +36 -0
  71. package/src/tools/merge-review.ts +138 -0
  72. package/src/tools/recall.ts +72 -0
  73. package/src/tools/registry.ts +40 -0
  74. package/src/tools/remember.ts +49 -0
  75. package/src/{schema.ts → tools/schema.ts} +3 -3
  76. package/src/tools/status-tool.ts +59 -0
  77. package/src/tools/undo.ts +57 -0
  78. package/src/tools/update.ts +342 -0
  79. package/src/{tui.tsx → tui/panel.tsx} +7 -17
  80. package/src/viewer/mutate.ts +15 -15
  81. package/src/viewer/server.ts +10 -8
  82. package/tui.ts +1 -1
  83. package/src/capture.ts +0 -222
  84. package/src/init.ts +0 -333
  85. package/src/inject.ts +0 -471
  86. package/src/memory.ts +0 -851
  87. package/src/portable.ts +0 -379
  88. package/src/status.ts +0 -536
  89. /package/src/{sessions.ts → core/lru.ts} +0 -0
  90. /package/src/{runtime.ts → core/runtime.ts} +0 -0
  91. /package/src/{tokenize.ts → core/tokenize.ts} +0 -0
  92. /package/src/{types.ts → core/types.ts} +0 -0
  93. /package/src/{host.ts → identity/host-events.ts} +0 -0
  94. /package/src/{repokey.ts → identity/repokey.ts} +0 -0
  95. /package/src/{containment.ts → store/containment.ts} +0 -0
  96. /package/src/{quarantine.ts → store/quarantine/quarantine.ts} +0 -0
  97. /package/src/{sanitize.ts → store/sanitize.ts} +0 -0
  98. /package/src/{secrets.ts → store/secrets.ts} +0 -0
package/src/capture.ts DELETED
@@ -1,222 +0,0 @@
1
- // Opt-in auto-capture parsing, prompt, and lag helpers. Host access and model
2
- // calls live in src/index.ts. Every candidate that leaves this module flows
3
- // through runWriteGate in index.ts: capture NEVER writes memories directly,
4
- // so dupes/stale/canonical rules keep the moat (same as model-authored writes).
5
- // All parsing functions are TOTAL: any malformed input yields [] / "" / null,
6
- // never a throw.
7
- import { TYPES } from "./types.ts";
8
- import { flattenMemoryText } from "./sanitize.ts";
9
- import { redactSecrets } from "./secrets.ts";
10
-
11
- export interface CaptureCandidate {
12
- type: string;
13
- scope: string;
14
- content: string;
15
- status?: "open" | "settled";
16
- /** Retrieval keywords (#40): indexed by the store, never rendered. */
17
- kw?: string[];
18
- }
19
-
20
- // Keywords are the vocabulary bridge for the strict-paraphrase wall, mined from
21
- // the transcript the model just saw. Cap and shape mirror the store's own
22
- // limits; the store normalises again at write, so this only has to stay
23
- // junk-proof (capture.ts never imports the store — it stays dependency-free).
24
- const CAPTURE_KEYWORD_CAP = 8;
25
- const CAPTURE_KEYWORD_CHARS = 48;
26
-
27
- function cleanKeywords(value: unknown): string[] | undefined {
28
- if (!Array.isArray(value)) return undefined;
29
- const out: string[] = [];
30
- for (const item of value) {
31
- if (typeof item !== "string") continue;
32
- const k = item.trim().toLowerCase();
33
- if (!k || k.length > CAPTURE_KEYWORD_CHARS || flattenMemoryText(k) !== k) continue;
34
- if (!out.includes(k)) out.push(k);
35
- if (out.length === CAPTURE_KEYWORD_CAP) break;
36
- }
37
- return out.length ? out : undefined;
38
- }
39
-
40
- // Prompt for the cheap capture model. The output contract is a bare JSON
41
- // array so parseCandidates can trust it; anything else parses to [].
42
- export function buildCapturePrompt(transcript: string, max = 3): string {
43
- return [
44
- "You mine one coding-agent session transcript for durable memories worth keeping across future sessions.",
45
- "",
46
- `Output ONLY a JSON array of at most ${max} objects (a fenced json block is fine), each:`,
47
- '{"type": "...", "scope": "...", "content": "...", "status": "...", "kw": ["...", "..."]}',
48
- "",
49
- "Rules:",
50
- `- type: one of ${TYPES.join(", ")}.`,
51
- "- scope: short area name (e.g. auth, api, build).",
52
- '- status: "open" for a live planning thread; otherwise "settled".',
53
- "- content: one self-contained fact, 20-600 characters, useful in a NEW session.",
54
- '- kw: 3-5 search keywords for how a DIFFERENT session would ask for this — synonyms and alternate names, other verb forms, the literal command or file name. They are indexed for retrieval and never shown to a model. Omit (or []) when the content already uses those words.',
55
- "- Keep: decisions made, working commands, user preferences, blockers hit, durable context, conventions.",
56
- "- Skip: anything derivable from the code or git history, small talk, and details that only mattered inside this conversation.",
57
- "- If nothing is worth remembering, output [ ].",
58
- "",
59
- "Transcript:",
60
- redactSecrets(transcript),
61
- ].join("\n");
62
- }
63
-
64
- const VALID_TYPES = new Set<string>(TYPES);
65
-
66
- // Remove markdown code-fence marker lines, keeping the fenced payload.
67
- function stripFences(text: string): string {
68
- return text.replace(/^[ \t]*```[^\n]*$/gm, "");
69
- }
70
-
71
- // First balanced [...] span, string-literal aware. null when absent or
72
- // unbalanced (a model that truncates mid-array yields nothing, not garbage).
73
- function firstJsonArray(text: string): string | null {
74
- const start = text.indexOf("[");
75
- if (start === -1) return null;
76
- let depth = 0;
77
- let inString = false;
78
- let escaped = false;
79
- for (let i = start; i < text.length; i++) {
80
- const ch = text[i];
81
- if (inString) {
82
- if (escaped) escaped = false;
83
- else if (ch === "\\") escaped = true;
84
- else if (ch === '"') inString = false;
85
- continue;
86
- }
87
- if (ch === '"') inString = true;
88
- else if (ch === "[") depth++;
89
- else if (ch === "]") {
90
- depth--;
91
- if (depth === 0) return text.slice(start, i + 1);
92
- }
93
- }
94
- return null;
95
- }
96
-
97
- // Extract memory candidates from a model reply. Never throws: any malformed
98
- // input yields []. Items missing fields, with unknown types, or with content
99
- // outside 20-600 chars are dropped; the result is clamped to `max`.
100
- export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
101
- try {
102
- if (typeof raw !== "string" || !raw.trim() || !(max > 0)) return [];
103
- const span = firstJsonArray(stripFences(raw));
104
- if (!span) return [];
105
- const parsed = JSON.parse(span);
106
- if (!Array.isArray(parsed)) return [];
107
- const out: CaptureCandidate[] = [];
108
- for (const item of parsed) {
109
- if (out.length >= max) break;
110
- if (!item || typeof item !== "object" || Array.isArray(item)) continue;
111
- const o = item as Record<string, unknown>;
112
- const rawType = typeof o.type === "string" ? o.type : "";
113
- const rawScope = typeof o.scope === "string" ? o.scope : "";
114
- const type = rawType.trim();
115
- const scope = rawScope.trim();
116
- const content = typeof o.content === "string" ? o.content.trim() : "";
117
- if (!type || !scope || !content) continue;
118
- if (
119
- flattenMemoryText(rawType) !== rawType ||
120
- flattenMemoryText(rawScope) !== rawScope
121
- ) continue;
122
- if (!VALID_TYPES.has(type)) continue;
123
- if (content.length < 20 || content.length > 600) continue;
124
- const status = o.status === "open" || o.status === "settled" ? o.status : undefined;
125
- // A bad kw list costs the row its keywords, never the row itself.
126
- const kw = cleanKeywords(o.kw);
127
- out.push({
128
- ...(status ? { type, scope, content, status } : { type, scope, content }),
129
- ...(kw ? { kw } : {}),
130
- });
131
- }
132
- return out;
133
- } catch {
134
- return [];
135
- }
136
- }
137
-
138
- // "provider/id" -> { providerID, id }, splitting on the FIRST "/". Returns
139
- // null when the string has no slash or either half is empty — the caller then
140
- // skips capture entirely rather than guessing a model.
141
- export function parseModelRef(ref: unknown): { providerID: string; id: string } | null {
142
- if (typeof ref !== "string") return null;
143
- const i = ref.indexOf("/");
144
- if (i <= 0) return null;
145
- const providerID = ref.slice(0, i).trim();
146
- const id = ref.slice(i + 1).trim();
147
- if (!providerID || !id) return null;
148
- return { providerID, id };
149
- }
150
-
151
- // Render an array of session-context messages of unknown shape into
152
- // "role: text" lines. Defensive by construction (the API shape varies and is
153
- // not ours to trust): non-arrays and junk entries are skipped; role comes
154
- // from info.role | role, text from parts[].text | text | content (strings
155
- // only); capped at 40 user turns. Never throws.
156
- const TRANSCRIPT_USER_TURN_CAP = 40;
157
-
158
- /**
159
- * Age of the newest message in a session context, in ms, or null when no
160
- * message carries a timestamp. Capture uses this to say how stale a transcript
161
- * was at the moment the model was asked for candidates (#44).
162
- */
163
- export function lagSince(messages: unknown, now = Date.now()): number | null {
164
- let newest = 0;
165
- for (const raw of Array.isArray(messages) ? messages : []) {
166
- const m = raw as Record<string, any>;
167
- const at = m?.time?.updated ?? m?.createdAt ?? m?.created ?? m?.timestamp;
168
- const ms = typeof at === "number" ? at : typeof at === "string" ? Date.parse(at) : Number.NaN;
169
- if (Number.isFinite(ms) && ms > newest) newest = ms;
170
- }
171
- return newest ? now - newest : null;
172
- }
173
-
174
- export function flattenTranscript(msgs: unknown): string {
175
- try {
176
- if (!Array.isArray(msgs)) return "";
177
- const lines: string[] = [];
178
- let userTurns = 0;
179
- for (const msg of msgs) {
180
- if (!msg || typeof msg !== "object") continue;
181
- const m = msg as Record<string, unknown>;
182
- const info =
183
- m.info && typeof m.info === "object" ? (m.info as Record<string, unknown>) : undefined;
184
- const role =
185
- typeof info?.role === "string" ? info.role : typeof m.role === "string" ? m.role : "";
186
- let text = "";
187
- let hadPrivatePart = false;
188
- if (Array.isArray(m.parts)) {
189
- text = m.parts
190
- .map((p) => {
191
- if (!p || typeof p !== "object") return undefined;
192
- const part = p as Record<string, unknown>;
193
- const partType = typeof part.type === "string" ? part.type.toLowerCase() : "";
194
- if (partType === "reasoning" || partType === "thinking") {
195
- hadPrivatePart = true;
196
- return undefined;
197
- }
198
- return part.text;
199
- })
200
- .filter((t): t is string => typeof t === "string" && t.length > 0)
201
- .join(" ");
202
- }
203
- if (!text && !hadPrivatePart) {
204
- for (const k of ["text", "content"]) {
205
- if (typeof m[k] === "string") {
206
- text = m[k] as string;
207
- break;
208
- }
209
- }
210
- }
211
- if (!role || !text.trim()) continue;
212
- if (role === "user") {
213
- userTurns++;
214
- if (userTurns > TRANSCRIPT_USER_TURN_CAP) break;
215
- }
216
- lines.push(`${role}: ${text.trim()}`);
217
- }
218
- return lines.join("\n");
219
- } catch {
220
- return "";
221
- }
222
- }
package/src/init.ts DELETED
@@ -1,333 +0,0 @@
1
- // Repository init: ensure the codebase-memory graph exists for this repo and
2
- // re-derive build/test command memories through the write gate. Deterministic
3
- // (no model calls): the graph binary is spawned one-shot via `cli`, manifests
4
- // are parsed locally, and every write goes through the 4-gate pipeline with the
5
- // `trusted` flag (plugin-authored bookkeeping, not model claims). Degrades
6
- // gracefully when the binary or git is absent, so install-from-scratch still
7
- // writes script memories.
8
- import { basename, join } from "node:path";
9
- import { existsSync } from "node:fs";
10
- import { cbmBin } from "./config.ts";
11
- import { isVisibleTo, loadAll, markSuperseded, readerFromSid, type Reader } from "./memory.ts";
12
- import { runWriteGate, type GateContext } from "./gates.ts";
13
- import { captureEvidenceContext, record } from "./evidence.ts";
14
- import { writeEvidence, hasGateCheck } from "./triggers.ts";
15
- import { writeTarget } from "./repokey.ts";
16
- import { getCurrent } from "./state.ts";
17
-
18
- export interface ScriptRecord {
19
- key: string;
20
- cmd: string;
21
- source: string;
22
- }
23
-
24
- export interface GraphStatus {
25
- action: "indexed" | "unavailable" | "index-failed";
26
- name?: string;
27
- mode: string;
28
- }
29
-
30
- export interface InitArgs {
31
- liveRoot: string;
32
- force?: boolean;
33
- mode?: string;
34
- // The calling session (#127): rows this writes are stamped for the CALLER,
35
- // resolved after runInit's own awaits (git probing) rather than from the
36
- // ambient current, which a concurrent session may have moved.
37
- sessionID?: string;
38
- }
39
-
40
- export interface InitSummary {
41
- scope: string;
42
- root: string;
43
- head: string;
44
- graph: GraphStatus;
45
- scripts: ScriptRecord[];
46
- stampTs?: string;
47
- skipped: boolean;
48
- written: number;
49
- collapsed: number;
50
- blocked: number;
51
- /** Written rows whose write_promoted audit line fell (#155 review). */
52
- unaudited?: number;
53
- }
54
-
55
- const NOTABLE_KEYS = ["test", "e2e", "lint", "typecheck", "check", "build", "format"];
56
-
57
- function isNotable(key: string): boolean {
58
- return NOTABLE_KEYS.includes(key) || NOTABLE_KEYS.some((k) => key.startsWith(k));
59
- }
60
-
61
- async function run(cmd: string[], cwd: string): Promise<{ ok: boolean; out: string }> {
62
- try {
63
- const p = Bun.spawn(cmd, { cwd, stdout: "pipe", stderr: "pipe" });
64
- const [so, se] = await Promise.all([
65
- new Response(p.stdout).text(),
66
- new Response(p.stderr).text(),
67
- ]);
68
- const code = await p.exited;
69
- return { ok: code === 0, out: (so || se || "").trim() };
70
- } catch {
71
- return { ok: false, out: "" };
72
- }
73
- }
74
-
75
- function runSync(cmd: string[], cwd: string): { ok: boolean; out: string } {
76
- try {
77
- const p = Bun.spawnSync(cmd, { cwd, stdout: "pipe", stderr: "pipe" });
78
- const out = p.stdout?.toString() ?? "";
79
- const err = p.stderr?.toString() ?? "";
80
- return { ok: p.exitCode === 0, out: (out || err).trim() };
81
- } catch {
82
- return { ok: false, out: "" };
83
- }
84
- }
85
-
86
- export async function gitRootOf(dir: string): Promise<string> {
87
- const r = runSync(["git", "rev-parse", "--show-toplevel"], dir);
88
- return r.ok && r.out ? r.out : dir;
89
- }
90
-
91
- export async function gitHead(root: string): Promise<string> {
92
- const r = runSync(["git", "rev-parse", "--short", "HEAD"], root);
93
- return r.ok && r.out ? r.out : "-";
94
- }
95
-
96
- async function readText(root: string, file: string): Promise<string | null> {
97
- const p = join(root, file);
98
- if (!existsSync(p)) return null;
99
- try {
100
- return await Bun.file(p).text();
101
- } catch {
102
- return null;
103
- }
104
- }
105
-
106
- async function detectPackageScripts(root: string, records: ScriptRecord[]): Promise<void> {
107
- const text = await readText(root, "package.json");
108
- if (!text) return;
109
- let pkg: Record<string, unknown>;
110
- try {
111
- pkg = JSON.parse(text);
112
- } catch {
113
- return;
114
- }
115
- if (!pkg.scripts || typeof pkg.scripts !== "object") return;
116
- const seen = new Set<string>();
117
- for (const name of Object.keys(pkg.scripts as Record<string, unknown>)) {
118
- if (seen.has(name) || !isNotable(name.toLowerCase())) continue;
119
- seen.add(name);
120
- records.push({ key: name, cmd: `npm run ${name}`, source: "package.json" });
121
- }
122
- }
123
-
124
- async function detectMakeTargets(root: string, records: ScriptRecord[]): Promise<void> {
125
- const targetRe = /^([A-Za-z0-9_-]+)\s*:/;
126
- const seen = new Set<string>();
127
- for (const file of ["Makefile", "Justfile"]) {
128
- const text = await readText(root, file);
129
- if (!text) continue;
130
- for (const line of text.split("\n")) {
131
- if (/^[\t ]|^\s*#|^\./.test(line)) continue;
132
- const m = targetRe.exec(line);
133
- if (!m) continue;
134
- const name = m[1].toLowerCase();
135
- if (!isNotable(name) || seen.has(name)) continue;
136
- seen.add(name);
137
- const runner = file === "Justfile" ? "just" : "make";
138
- records.push({ key: name, cmd: `${runner} ${m[1]}`, source: file });
139
- }
140
- }
141
- }
142
-
143
- async function detectLangManifests(root: string, records: ScriptRecord[]): Promise<void> {
144
- if (existsSync(join(root, "Cargo.toml"))) {
145
- records.push({ key: "test", cmd: "cargo test", source: "Cargo.toml" });
146
- }
147
- const py = await readText(root, "pyproject.toml");
148
- if (py && /pytest|tool\.pytest|\[tool\]\.poetry/.test(py)) {
149
- records.push({ key: "test", cmd: "pytest", source: "pyproject.toml" });
150
- }
151
- }
152
-
153
- export async function detectScripts(root: string): Promise<ScriptRecord[]> {
154
- const records: ScriptRecord[] = [];
155
- await detectPackageScripts(root, records);
156
- await detectMakeTargets(root, records);
157
- await detectLangManifests(root, records);
158
- return records.slice(0, 8);
159
- }
160
-
161
- async function cbmProject(bin: string, root: string): Promise<{ name: string } | null> {
162
- const r = await run(
163
- [bin, "cli", "--quiet", "list_projects", "--format", "json", "--metadata-only"],
164
- root,
165
- );
166
- if (!r.ok || !r.out) return null;
167
- try {
168
- const env = JSON.parse(r.out) as { projects?: { name: string; root_path: string }[] };
169
- const hit = env.projects?.find((p) => p.root_path === root);
170
- return hit ? { name: hit.name } : null;
171
- } catch {
172
- return null;
173
- }
174
- }
175
-
176
- async function ensureGraph(root: string, mode: string, force: boolean): Promise<GraphStatus> {
177
- const bin = cbmBin() ?? "codebase-memory-mcp";
178
- const existing = await cbmProject(bin, root);
179
- if (existing && !force) return { action: "indexed", name: existing.name, mode };
180
- const r = await run(
181
- [bin, "cli", "--quiet", "index_repository", "--repo-path", root, "--mode", mode],
182
- root,
183
- );
184
- if (!r.ok) return { action: "unavailable", mode };
185
- const after = await cbmProject(bin, root);
186
- return { action: after ? "indexed" : "index-failed", name: after?.name, mode };
187
- }
188
-
189
- export interface InitStamp {
190
- ts: string;
191
- head: string;
192
- }
193
-
194
- export async function initStamp(scope: string, sid?: string, reader: Reader = readerFromSid(sid)): Promise<InitStamp | null> {
195
- // Scope is a basename, so two different repos can share one
196
- // ("api" next to "api", a fork beside its upstream). Visibility filtering
197
- // makes each repo see only its own stamp — basename collisions no longer
198
- // alias init state between repos. The reader comes from the CALLER's
199
- // session, not from the global current after this await (#127).
200
- const mems = (await loadAll()).filter((m) => !m.superseded_by && isVisibleTo(m, reader));
201
- for (const m of mems) {
202
- if (m.type !== "context" || m.scope !== scope) continue;
203
- if (!m.tags?.some((t) => t === "init-stamp")) continue;
204
- const head = /head=([^ ,]+)/.exec(m.content)?.[1] ?? "-";
205
- return { ts: m.ts, head };
206
- }
207
- return null;
208
- }
209
-
210
- export async function runInit(args: InitArgs): Promise<InitSummary> {
211
- const reader = readerFromSid(args.sessionID);
212
- const writeAt = writeTarget(args.sessionID ?? getCurrent().sid);
213
- const evidenceContext = captureEvidenceContext(args.sessionID);
214
- const root = await gitRootOf(args.liveRoot);
215
- const scope = basename(root) || basename(args.liveRoot);
216
- const head = await gitHead(root);
217
- const force = Boolean(args.force);
218
- const mode = args.mode ?? "moderate";
219
-
220
- const gateCtx: GateContext = {
221
- liveRoot: root,
222
- reader,
223
- writeAt,
224
- evidenceContext,
225
- ...writeEvidence(args.sessionID ?? getCurrent().sid),
226
- hasGateCheck: hasGateCheck(args.sessionID ?? getCurrent().sid),
227
- // Stamps land on the caller's session even though runInit awaits git
228
- // probing before the gate writes (#127 / #121's write-side root cause).
229
- sessionID: args.sessionID,
230
- trusted: true,
231
- };
232
-
233
- const prior = await initStamp(scope, args.sessionID, reader);
234
- if (prior && !force && prior.head === head) {
235
- await record("init_skip", { scope, head, since: prior.ts }, false, args.sessionID, evidenceContext);
236
- return {
237
- scope,
238
- root,
239
- head,
240
- graph: { action: "indexed", mode },
241
- scripts: [],
242
- stampTs: prior.ts,
243
- skipped: true,
244
- written: 0,
245
- collapsed: 0,
246
- blocked: 0,
247
- };
248
- }
249
-
250
- await record("init_start", { scope, head, force, mode }, false, args.sessionID, evidenceContext);
251
-
252
- const graph = await ensureGraph(root, mode, force);
253
- const scripts = await detectScripts(root);
254
-
255
- let written = 0;
256
- let collapsed = 0;
257
- let blocked = 0;
258
- // Promoted rows whose write_promoted audit line fell (#155 review: the
259
- // fault must be visible to every writer, bookkeeping included).
260
- let unaudited = 0;
261
- for (const s of scripts) {
262
- const content = `${scope} ${s.key} command: run "${s.cmd}" from the repo root (${s.source}).`;
263
- const outcome = await runWriteGate(
264
- { type: "pattern", scope, content, tags: ["init", s.source] },
265
- gateCtx,
266
- );
267
- if (outcome.action === "promoted") {
268
- written++;
269
- if (outcome.evidenceError !== undefined) unaudited++;
270
- } else if (outcome.action === "collapsed") collapsed++;
271
- else blocked++;
272
- }
273
-
274
- const stampContent = `Init stamp: repo=${scope}, head=${head}, graph=${graph.action}, mode=${graph.mode}, scripts=${scripts.length}`;
275
- const stampOutcome = await runWriteGate(
276
- { type: "context", scope, content: stampContent, tags: ["init-stamp"] },
277
- gateCtx,
278
- );
279
- const stampTs = stampOutcome.ts ?? prior?.ts;
280
- if (stampOutcome.action === "promoted" && prior && stampOutcome.ts) {
281
- await markSuperseded(prior.ts, { superseded_by: stampOutcome.ts, reason: "init" });
282
- }
283
- if (stampOutcome.action === "promoted" && stampOutcome.evidenceError !== undefined) unaudited++;
284
-
285
- await record(
286
- "init_complete",
287
- {
288
- scope,
289
- head,
290
- force,
291
- mode,
292
- graph: graph.action,
293
- scripts: scripts.length,
294
- written,
295
- collapsed,
296
- blocked,
297
- unaudited,
298
- stamp: stampTs ?? "-",
299
- },
300
- false,
301
- args.sessionID,
302
- evidenceContext,
303
- );
304
-
305
- return {
306
- scope,
307
- root,
308
- head,
309
- graph,
310
- scripts,
311
- stampTs,
312
- skipped: false,
313
- written,
314
- collapsed,
315
- blocked,
316
- unaudited,
317
- };
318
- }
319
-
320
- export function formatInit(s: InitSummary): string {
321
- if (s.skipped) {
322
- return `Already initialized for ${s.scope} at head ${s.head} (stamp ${s.stampTs}). Nothing to do.`;
323
- }
324
- const scr = s.scripts.map((r) => `- ${r.source}: "${r.cmd}"`).join("\n");
325
- return [
326
- `Initialized ${s.scope} (root ${s.root}, head ${s.head}).`,
327
- `Graph: ${s.graph.action}${s.graph.name ? ` (${s.graph.name})` : ""} [mode=${s.graph.mode}]`,
328
- scr ? `Scripts (${s.scripts.length}):\n${scr}` : "Scripts: none detected",
329
- `Memories: written=${s.written}, collapsed=${s.collapsed}, blocked=${s.blocked}` +
330
- (s.unaudited ? `, ${s.unaudited} without an audit line` : "") +
331
- `; stamp=${s.stampTs ?? "-"}`,
332
- ].join("\n");
333
- }