opencode-self-improvement 0.14.10 → 0.14.12
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/README.md +11 -6
- package/package.json +1 -1
- package/src/config.ts +17 -0
- package/src/containment.ts +208 -0
- package/src/evidence.ts +31 -1
- package/src/gates.ts +13 -1
- package/src/index.ts +181 -57
- package/src/init.ts +16 -7
- package/src/inject.ts +27 -19
- package/src/memory.ts +140 -19
- package/src/portable.ts +108 -11
- package/src/prune.ts +18 -9
- package/src/repokey.ts +34 -0
- package/src/schema.ts +19 -5
- package/src/triggers.ts +24 -10
- package/src/undo.ts +4 -6
- package/src/viewer/mutate.ts +31 -3
- package/src/viewer/page.html +7 -5
- package/src/viewer/server.ts +21 -1
package/src/index.ts
CHANGED
|
@@ -16,14 +16,18 @@ import { evidenceDir, frontierBudget, injectBudget, memoryRoot, dateStr } from "
|
|
|
16
16
|
import { STATUSES, TYPES } from "./types.ts";
|
|
17
17
|
import {
|
|
18
18
|
clearSuperseded,
|
|
19
|
+
evidenceVisibleTo,
|
|
19
20
|
isActive,
|
|
20
21
|
isVisibleHere,
|
|
22
|
+
isVisibleTo,
|
|
21
23
|
loadAll,
|
|
22
24
|
malformedCount,
|
|
23
25
|
markManySuperseded,
|
|
24
26
|
markSuperseded,
|
|
27
|
+
readerFromSid,
|
|
25
28
|
resolveMemoryTarget,
|
|
26
29
|
snapshotFiles,
|
|
30
|
+
visibleTo,
|
|
27
31
|
type Memory,
|
|
28
32
|
} from "./memory.ts";
|
|
29
33
|
import { runWriteGate, type GateContext, type WriteCandidate } from "./gates.ts";
|
|
@@ -77,8 +81,8 @@ import {
|
|
|
77
81
|
onCompacting,
|
|
78
82
|
} from "./triggers.ts";
|
|
79
83
|
import { getCurrent, setCurrent } from "./state.ts";
|
|
80
|
-
import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir } from "./repokey.ts";
|
|
81
|
-
import { readLines } from "./logfmt.ts";
|
|
84
|
+
import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional } from "./repokey.ts";
|
|
85
|
+
import { parseLine, readLines } from "./logfmt.ts";
|
|
82
86
|
import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
|
|
83
87
|
import { redactSecrets } from "./secrets.ts";
|
|
84
88
|
import { flattenMemoryText } from "./sanitize.ts";
|
|
@@ -278,6 +282,10 @@ const impl = {
|
|
|
278
282
|
const setupRoot = ctx?.location?.directory;
|
|
279
283
|
const liveRoot = setupRoot ?? process.cwd();
|
|
280
284
|
setRepoScope(setupRoot ? resolveRepo(setupRoot) : null);
|
|
285
|
+
// THIS instance's own workspace. The module scope says who loaded last;
|
|
286
|
+
// this says who I am. An unbound session that calls into THIS instance
|
|
287
|
+
// resolves here — never to another instance's scope (#127, multi-setup).
|
|
288
|
+
const instanceDir = typeof setupRoot === "string" && setupRoot ? setupRoot : undefined;
|
|
281
289
|
|
|
282
290
|
// Character budgets: relevance injection and contextual pulls share the
|
|
283
291
|
// existing cap; the session-start frontier has its own larger cap. Plugin
|
|
@@ -320,6 +328,14 @@ const impl = {
|
|
|
320
328
|
const bound = sid ?? getCurrent().sid;
|
|
321
329
|
return {
|
|
322
330
|
sessionID: sid,
|
|
331
|
+
// NOTE (re-review): this one lookup is intentionally NON-firm — a
|
|
332
|
+
// provisional binding may supply the gate's verification TREE. The
|
|
333
|
+
// tree is where a referenced file is checked to exist, not who the
|
|
334
|
+
// caller is: "as far as the flow can know" is the right confidence
|
|
335
|
+
// level, and a wrong guess fails a code-reference gate loudly rather
|
|
336
|
+
// than leaking across repositories. Identity itself never resolves
|
|
337
|
+
// through here (readers and stamps use the firm-or-provisional split
|
|
338
|
+
// in repokey/memory); do not mistake this for one.
|
|
323
339
|
liveRoot: sessionDir(bound) ?? liveRoot,
|
|
324
340
|
evidenceCalls: evidenceCalls(bound),
|
|
325
341
|
hasGateCheck: hasGateCheck(bound),
|
|
@@ -327,6 +343,30 @@ const impl = {
|
|
|
327
343
|
};
|
|
328
344
|
};
|
|
329
345
|
|
|
346
|
+
// Identity of a tool call, captured SYNCHRONOUSLY at the tool's entry —
|
|
347
|
+
// the first await of the call comes after this. The V2 host hands every
|
|
348
|
+
// execute a per-call ToolContext carrying sessionID; the harness and any
|
|
349
|
+
// host that omits it fall back to the ambient current, which is correct
|
|
350
|
+
// exactly because execute.before ran immediately before this tool with
|
|
351
|
+
// no await between (#116's documented fallback). Never re-read the global
|
|
352
|
+
// after an await to learn who is calling (#127).
|
|
353
|
+
const toolIds = (context?: unknown): { sid: string; call: string } => {
|
|
354
|
+
const fromCtx = (context as { sessionID?: unknown; id?: unknown } | undefined)
|
|
355
|
+
?.sessionID;
|
|
356
|
+
const call = (context as { id?: unknown } | undefined)?.id;
|
|
357
|
+
// Entry binding: a session this instance has never seen is resolved to
|
|
358
|
+
// THIS workspace (provisional — a firm event/API identity still
|
|
359
|
+
// replaces it), so the tool's reader partitions by the repository the
|
|
360
|
+
// call reached, not by the last setup's module scope (#127).
|
|
361
|
+
if (typeof fromCtx === "string" && fromCtx && fromCtx !== "?") {
|
|
362
|
+
bindSessionProvisional(fromCtx, instanceDir);
|
|
363
|
+
}
|
|
364
|
+
return {
|
|
365
|
+
sid: typeof fromCtx === "string" && fromCtx ? fromCtx : getCurrent().sid,
|
|
366
|
+
call: typeof call === "string" && call ? call : getCurrent().call,
|
|
367
|
+
};
|
|
368
|
+
};
|
|
369
|
+
|
|
330
370
|
// Identity-event race backstop: a resumed session's FIRST turn can write
|
|
331
371
|
// before the subscription has delivered its execution.started, and the
|
|
332
372
|
// module-scope fallback is the last setup instance — possibly another
|
|
@@ -337,7 +377,7 @@ const impl = {
|
|
|
337
377
|
// One-shot: never overwrites an event-bound entry.
|
|
338
378
|
const bindingSids = new Set<string>();
|
|
339
379
|
async function bindSessionFromMessages(sid: string | undefined): Promise<void> {
|
|
340
|
-
if (!sid || sid === "?" ||
|
|
380
|
+
if (!sid || sid === "?" || sessionDirFirm(sid) || bindingSids.has(sid)) return;
|
|
341
381
|
bindingSids.add(sid);
|
|
342
382
|
try {
|
|
343
383
|
const msgs = await ctx.session?.context?.({ sessionID: sid });
|
|
@@ -369,7 +409,7 @@ const impl = {
|
|
|
369
409
|
const apiBindTried = new Set<string>();
|
|
370
410
|
const apiBindOrder = new SessionLru(SESSION_CAP, (evicted) => apiBindTried.delete(evicted));
|
|
371
411
|
async function bindSessionFromApi(sid: string | undefined): Promise<void> {
|
|
372
|
-
if (!sid || sid === "?" ||
|
|
412
|
+
if (!sid || sid === "?" || sessionDirFirm(sid) || apiBindTried.has(sid)) return;
|
|
373
413
|
apiBindTried.add(sid);
|
|
374
414
|
apiBindOrder.touch(sid);
|
|
375
415
|
try {
|
|
@@ -383,11 +423,16 @@ const impl = {
|
|
|
383
423
|
}
|
|
384
424
|
|
|
385
425
|
// Identity must resolve BEFORE a row is stamped or a read is partitioned:
|
|
386
|
-
// try the (legacy) message payloads, then the session row.
|
|
426
|
+
// try the (legacy) message payloads, then the session row. A session the
|
|
427
|
+
// host cannot describe (fresh, or a host without the lookup) is bound to
|
|
428
|
+
// THIS instance's workspace — the caller's repository as the flow knows
|
|
429
|
+
// it, and strictly better than an unbound read inheriting the module
|
|
430
|
+
// scope of whoever loaded last (#127's multi-setup residue).
|
|
387
431
|
async function bindSessionIdentity(sid: string | undefined): Promise<void> {
|
|
388
|
-
if (!sid || sid === "?" ||
|
|
432
|
+
if (!sid || sid === "?" || sessionDirFirm(sid)) return;
|
|
389
433
|
await bindSessionFromMessages(sid);
|
|
390
|
-
if (!
|
|
434
|
+
if (!sessionDirFirm(sid)) await bindSessionFromApi(sid);
|
|
435
|
+
bindSessionProvisional(sid, instanceDir);
|
|
391
436
|
}
|
|
392
437
|
|
|
393
438
|
// ---- tools --------------------------------------------------------------
|
|
@@ -399,7 +444,8 @@ const impl = {
|
|
|
399
444
|
description:
|
|
400
445
|
"Store a memory after the 4-gate write pipeline validates it (canonical graph, stale refs, dupes). Blocked writes record evidence instead of persisting. Add `kw` — 3-5 aliases, synonyms, verb forms or the literal command a FUTURE session would search with — to make a row findable when the wording differs; keywords are indexed, never injected.",
|
|
401
446
|
options: direct,
|
|
402
|
-
async execute(args): Promise<{ content: string }> {
|
|
447
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
448
|
+
const { sid } = toolIds(context);
|
|
403
449
|
const candidate: WriteCandidate = {
|
|
404
450
|
type: args.type,
|
|
405
451
|
scope: args.scope,
|
|
@@ -410,8 +456,8 @@ const impl = {
|
|
|
410
456
|
status: args.status,
|
|
411
457
|
repo: args.global ? "global" : undefined,
|
|
412
458
|
};
|
|
413
|
-
await bindSessionIdentity(
|
|
414
|
-
const outcome = await runWriteGate(candidate, gateContext());
|
|
459
|
+
await bindSessionIdentity(sid);
|
|
460
|
+
const outcome = await runWriteGate(candidate, gateContext(sid));
|
|
415
461
|
if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
|
|
416
462
|
if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
|
|
417
463
|
return {
|
|
@@ -427,8 +473,10 @@ const impl = {
|
|
|
427
473
|
description:
|
|
428
474
|
"Propose consolidations of near-duplicate settled rows — read-only, nothing is written. Clusters same-scope same-type rows by jaccard, picks the most recently used member as canonical (#42's rule: the row retrieval keeps landing on), and proposes it ONLY when replaying the cluster's own logged reads proves the merged row catches at least as many reads as the best single member did. A cluster with no recorded reads is reported as unmeasured, never merged on resemblance. Resolve a proposal with memory_merge_review; absorbed rows stay recoverable. The merge is deterministic — the canonical row is the survivor's prose plus the absorbed rows' aliases — because this plugin ships no model and a rewritten row cannot be diffed or audited.",
|
|
429
475
|
options: direct,
|
|
430
|
-
async execute(args): Promise<{ content: string }> {
|
|
431
|
-
const
|
|
476
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
477
|
+
const { sid } = toolIds(context);
|
|
478
|
+
const reader = readerFromSid(sid);
|
|
479
|
+
const all = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
|
|
432
480
|
const rows = args.scope ? all.filter((m) => m.scope === args.scope) : all;
|
|
433
481
|
const ledger = await readLedger();
|
|
434
482
|
const use = ledger.byRow;
|
|
@@ -452,9 +500,15 @@ const impl = {
|
|
|
452
500
|
description:
|
|
453
501
|
"Initialize repository memory and knowledge graph. Ensures the codebase-memory graph for this repo is indexed (one-shot `cli` spawn; no session MCP needed) and re-derives build/lint/test/typecheck command memories through the write gate, then stores an init stamp keyed on git HEAD. Idempotent: a no-op when the stamp matches HEAD, unless force=true (refresh after a refactor).",
|
|
454
502
|
options: direct,
|
|
455
|
-
async execute(args): Promise<{ content: string }> {
|
|
456
|
-
|
|
457
|
-
|
|
503
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
504
|
+
const { sid } = toolIds(context);
|
|
505
|
+
await bindSessionIdentity(sid);
|
|
506
|
+
const summary = await runInit({
|
|
507
|
+
liveRoot: gateContext(sid).liveRoot,
|
|
508
|
+
force: args.force,
|
|
509
|
+
mode: args.mode,
|
|
510
|
+
sessionID: sid,
|
|
511
|
+
});
|
|
458
512
|
return { content: formatInit(summary) };
|
|
459
513
|
},
|
|
460
514
|
}));
|
|
@@ -464,8 +518,10 @@ const impl = {
|
|
|
464
518
|
description:
|
|
465
519
|
"Look up durable project knowledge — build/test/lint commands, decisions, patterns, preferences, blockers — BEFORE searching the repo or reading files. Use for 'how do I run X', conventions, and past decisions. By scope, type, or free-text query; with no filters it returns the most recent memories.",
|
|
466
520
|
options: direct,
|
|
467
|
-
async execute(args): Promise<{ content: string }> {
|
|
468
|
-
|
|
521
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
522
|
+
const { sid, call } = toolIds(context);
|
|
523
|
+
const reader = readerFromSid(sid);
|
|
524
|
+
let results = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
|
|
469
525
|
if (!results.length) return { content: "No memories found" };
|
|
470
526
|
const total = results.length;
|
|
471
527
|
if (args.scope) results = results.filter((m) => m.scope.includes(args.scope!));
|
|
@@ -482,15 +538,19 @@ const impl = {
|
|
|
482
538
|
if (!limited.length) return { content: "No matching memories" };
|
|
483
539
|
const openIn = limited.filter((m) => m.status === "open").length;
|
|
484
540
|
if (openIn > 0) {
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
541
|
+
markFrontierTap(sid, call);
|
|
542
|
+
await record(
|
|
543
|
+
"frontier_tapped",
|
|
544
|
+
{
|
|
545
|
+
n_open: openIn,
|
|
546
|
+
in_results: limited.length,
|
|
547
|
+
turn: firstFrontierTap(sid)?.turn,
|
|
548
|
+
},
|
|
549
|
+
true,
|
|
550
|
+
sid,
|
|
551
|
+
);
|
|
492
552
|
}
|
|
493
|
-
if (args.query) await noteHits("recall",
|
|
553
|
+
if (args.query) await noteHits("recall", sid, limited, args.query);
|
|
494
554
|
return { content: `Found ${results.length} (${total} total)\n\n${limited.map(formatMemory).join("\n")}` };
|
|
495
555
|
},
|
|
496
556
|
}));
|
|
@@ -500,8 +560,10 @@ const impl = {
|
|
|
500
560
|
description:
|
|
501
561
|
"Update an existing memory (gated like remember; the prior entry is superseded, not erased). `query` selects which row to update: its exact id (ts), a clock fragment (e.g. HH:MM:SS.mmm), or a unique substring of its content. Omitting `query` targets the most recent active row of scope+type. An unmatched or ambiguous `query` fails closed and writes nothing.",
|
|
502
562
|
options: direct,
|
|
503
|
-
async execute(args): Promise<{ content: string }> {
|
|
504
|
-
|
|
563
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
564
|
+
const { sid } = toolIds(context);
|
|
565
|
+
await bindSessionIdentity(sid);
|
|
566
|
+
const reader = readerFromSid(sid);
|
|
505
567
|
// The whole update — resolve, gate, supersede — runs under one
|
|
506
568
|
// UPDATE-ORDER lock. Without it, two concurrent updates that both
|
|
507
569
|
// resolved the same still-active target both promoted and both
|
|
@@ -520,7 +582,7 @@ const impl = {
|
|
|
520
582
|
join(memoryRoot(), "update-order"),
|
|
521
583
|
async () => {
|
|
522
584
|
const prior = (await loadAll()).filter(
|
|
523
|
-
(m) => m.scope === args.scope && m.type === args.type && isActive(m) &&
|
|
585
|
+
(m) => m.scope === args.scope && m.type === args.type && isActive(m) && isVisibleTo(m, reader),
|
|
524
586
|
);
|
|
525
587
|
// Resolve the row BEFORE the gate: an update that cannot identify its
|
|
526
588
|
// target must write nothing, rather than silently superseding whichever
|
|
@@ -543,7 +605,7 @@ const impl = {
|
|
|
543
605
|
const target = resolved.target;
|
|
544
606
|
const outcome = await runWriteGate(
|
|
545
607
|
{ type: args.type, scope: args.scope, content: args.content, kw: args.kw, status: args.status },
|
|
546
|
-
{ ...gateContext(), supersedesTs: target.ts },
|
|
608
|
+
{ ...gateContext(sid), supersedesTs: target.ts },
|
|
547
609
|
);
|
|
548
610
|
if (outcome.action === "promoted" && outcome.ts && target) {
|
|
549
611
|
await markSuperseded(target.ts, {
|
|
@@ -581,8 +643,9 @@ const impl = {
|
|
|
581
643
|
description:
|
|
582
644
|
"Delete memories by scope and type. Snapshots first, logs the reason for audit, never touches a repo.",
|
|
583
645
|
options: direct,
|
|
584
|
-
async execute(args): Promise<{ content: string }> {
|
|
585
|
-
const
|
|
646
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
647
|
+
const { sid } = toolIds(context);
|
|
648
|
+
const res = await pruneMemory(args.scope, args.type, args.reason, sid);
|
|
586
649
|
if (!res.deleted.length) return { content: `No memories found for ${args.type} in ${args.scope}` };
|
|
587
650
|
return { content: `Deleted ${res.deleted.length} ${args.type} memory(s) from ${args.scope}. Audit: ${res.audit}` };
|
|
588
651
|
},
|
|
@@ -592,8 +655,10 @@ const impl = {
|
|
|
592
655
|
name: "memory_list",
|
|
593
656
|
description: "List memory scopes and types for discovery.",
|
|
594
657
|
options: direct,
|
|
595
|
-
async execute(): Promise<{ content: string }> {
|
|
596
|
-
const
|
|
658
|
+
async execute(_args, context): Promise<{ content: string }> {
|
|
659
|
+
const { sid } = toolIds(context);
|
|
660
|
+
const reader = readerFromSid(sid);
|
|
661
|
+
const mems = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
|
|
597
662
|
if (!mems.length) return { content: "No memories found" };
|
|
598
663
|
const scopes = new Map<string, number>();
|
|
599
664
|
const types = new Map<string, number>();
|
|
@@ -649,9 +714,22 @@ const impl = {
|
|
|
649
714
|
name: "memory_evidence",
|
|
650
715
|
description: "Read captured evidence (data only) for a date, optionally filtered by event.",
|
|
651
716
|
options: direct,
|
|
652
|
-
async execute(args): Promise<{ content: string }> {
|
|
717
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
718
|
+
const { sid } = toolIds(context);
|
|
719
|
+
const reader = readerFromSid(sid);
|
|
653
720
|
const file = join(evidenceDir(), `${args.date || dateStr()}.logfmt`);
|
|
654
721
|
let lines = await readLines(file);
|
|
722
|
+
// Data partitions too (#131's ownership rule, applied to evidence):
|
|
723
|
+
// a line stamped to another repository is not this session's data,
|
|
724
|
+
// and a line a NAMED session wrote while unresolved is private to
|
|
725
|
+
// that session — the caller's sid is what the private branch
|
|
726
|
+
// matches against (#128 re-review).
|
|
727
|
+
if (reader.kind !== "admin") {
|
|
728
|
+
lines = lines.filter((l) => {
|
|
729
|
+
const fields = parseLine(l);
|
|
730
|
+
return !fields || evidenceVisibleTo(fields, reader, sid);
|
|
731
|
+
});
|
|
732
|
+
}
|
|
655
733
|
if (args.ev) lines = lines.filter((l) => l.includes(`ev=${args.ev}`));
|
|
656
734
|
if (!lines.length) return { content: "No evidence" };
|
|
657
735
|
const limit = args.limit || 50;
|
|
@@ -716,26 +794,36 @@ const impl = {
|
|
|
716
794
|
editor.add(validated(ExportArgs, {
|
|
717
795
|
name: "memory_export",
|
|
718
796
|
description:
|
|
719
|
-
"Export active memories as a JSONL file for backup or transfer to another machine. The first line is a metadata header ({_export,version,exportedAt,count}); each later line is one JSON object {ts,type,scope,content,status,tags,issue}. The header is what lets memory_import keep repo-scoped status:\"open\" frontier rows — a hand-written file without it imports such rows as settled, as does an imported open row claiming repo:\"global\". Defaults to <memory-root>/exports/<timestamp>.jsonl;
|
|
797
|
+
"Export active memories as a JSONL file for backup or transfer to another machine. The first line is a metadata header ({_export,version,exportedAt,count}); each later line is one JSON object {ts,type,scope,content,status,tags,issue}. The header is what lets memory_import keep repo-scoped status:\"open\" frontier rows — a hand-written file without it imports such rows as settled, as does an imported open row claiming repo:\"global\". Defaults to <memory-root>/exports/<timestamp>.jsonl; `file` must name a path inside <memory-root>/exports (a relative path resolves against it), `scope` exports one scope. Superseded rows are not exported (history stays in the store).",
|
|
720
798
|
options: direct,
|
|
721
799
|
async execute(args): Promise<{ content: string }> {
|
|
722
|
-
|
|
723
|
-
|
|
800
|
+
try {
|
|
801
|
+
const res = await exportMemories({ scope: args.scope, file: args.file });
|
|
802
|
+
return { content: `Exported ${res.count} memories -> ${res.path}` };
|
|
803
|
+
} catch (err) {
|
|
804
|
+
return {
|
|
805
|
+
content: `memory_export failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
806
|
+
};
|
|
807
|
+
}
|
|
724
808
|
},
|
|
725
809
|
}));
|
|
726
810
|
|
|
727
811
|
editor.add(validated(ImportArgs, {
|
|
728
812
|
name: "memory_import",
|
|
729
813
|
description:
|
|
730
|
-
"Import memories from a JSONL export (see memory_export). Every row goes through the same 4-gate write pipeline as memory_remember (tagged `import`, original tags preserved), so duplicates collapse and ungrounded rows are blocked exactly as usual — those are normal tallied outcomes, not errors. Malformed lines are skipped and counted. Frontier policy: status:\"open\" exempts a row from ref grounding, so it requires a memory_export header and cannot claim global scope; imported repo stamps are kept only when they match the importing session's repo, otherwise the importing repo is stamped. A stamped open row is downgraded when there is no current repo scope to verify it. Imported content is unverified by construction: injected rows surface a `[via import]` provenance marker.",
|
|
814
|
+
"Import memories from a JSONL export (see memory_export). Every row goes through the same 4-gate write pipeline as memory_remember (tagged `import`, original tags preserved), so duplicates collapse and ungrounded rows are blocked exactly as usual — those are normal tallied outcomes, not errors. Malformed lines are skipped and counted. `file` must be inside the memory root — copy the export there first. Frontier policy: status:\"open\" exempts a row from ref grounding, so it requires a memory_export header and cannot claim global scope; imported repo stamps are kept only when they match the importing session's repo, otherwise the importing repo is stamped. A stamped open row is downgraded when there is no current repo scope to verify it. Imported content is unverified by construction: injected rows surface a `[via import]` provenance marker.",
|
|
731
815
|
options: direct,
|
|
732
|
-
async execute(args): Promise<{ content: string }> {
|
|
816
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
817
|
+
const { sid } = toolIds(context);
|
|
733
818
|
try {
|
|
734
|
-
const t = await importMemories(
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
819
|
+
const t = await importMemories(
|
|
820
|
+
args.file,
|
|
821
|
+
(c) =>
|
|
822
|
+
runWriteGate(
|
|
823
|
+
{ ...c, tags: [...new Set([...(c.tags ?? []), "import"])] },
|
|
824
|
+
gateContext(sid),
|
|
825
|
+
),
|
|
826
|
+
sid,
|
|
739
827
|
);
|
|
740
828
|
return {
|
|
741
829
|
content:
|
|
@@ -758,10 +846,11 @@ const impl = {
|
|
|
758
846
|
description:
|
|
759
847
|
"Retire stale open threads (status=open older than olderThanDays) by superseding them — never deleting; rows stay recoverable via memory_undo. DRY RUN BY DEFAULT: without an explicit dryRun=false this only LISTS what would retire and mutates nothing (fail-closed). A real run snapshots every affected file before the first mutation.",
|
|
760
848
|
options: direct,
|
|
761
|
-
async execute(args): Promise<{ content: string }> {
|
|
849
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
850
|
+
const { sid } = toolIds(context);
|
|
762
851
|
const days = Number(args.olderThanDays) > 0 ? Number(args.olderThanDays) : 14;
|
|
763
852
|
const dryRun = args.dryRun !== false; // only an explicit false mutates
|
|
764
|
-
const stale = await findStaleOpen(days);
|
|
853
|
+
const stale = await findStaleOpen(days, sid);
|
|
765
854
|
if (!stale.length) {
|
|
766
855
|
return { content: `No active open threads older than ${days} days.` };
|
|
767
856
|
}
|
|
@@ -818,9 +907,9 @@ const impl = {
|
|
|
818
907
|
description:
|
|
819
908
|
"Plain-text memory report for chat clients (desktop/web/IDE), same sections as the terminal /memory panel: CONTEXT (this session's injected block, budget use, cumulative ride and abstentions), CACHE (plain-language cache receipts: bust count, and the provider-reported share of prompt tokens served from cache — the proof that memory never mutates your prefix), the block verbatim, recent blocked writes with gate reasons, and store stats. Reads only — no model call.",
|
|
820
909
|
options: direct,
|
|
821
|
-
async execute(): Promise<{ content: string }> {
|
|
910
|
+
async execute(_args, context): Promise<{ content: string }> {
|
|
822
911
|
// In-process truth: the live epoch + ledger, fresher than any file.
|
|
823
|
-
const sid =
|
|
912
|
+
const sid = toolIds(context).sid;
|
|
824
913
|
const status = sid === "?" ? null : await buildPayload(sid);
|
|
825
914
|
const all = await loadAll();
|
|
826
915
|
const act = all.filter(isActive);
|
|
@@ -927,8 +1016,14 @@ const impl = {
|
|
|
927
1016
|
// at the injection decision on every model request. The latter keeps
|
|
928
1017
|
// removals fail-closed: an out-of-band redaction or a block during a tool
|
|
929
1018
|
// loop cannot ride one more request waiting for another user prompt.
|
|
930
|
-
|
|
931
|
-
|
|
1019
|
+
// The caller's sid is resolved to an immutable Reader BEFORE the store
|
|
1020
|
+
// read (#127): while loadAll awaits, another session's hooks may dispatch
|
|
1021
|
+
// and move the ambient current; filtering with THAT leaks the other
|
|
1022
|
+
// session's repo into this one's system prompt.
|
|
1023
|
+
const injectableRows = async (sid?: string): Promise<Memory[]> => {
|
|
1024
|
+
const reader = readerFromSid(sid);
|
|
1025
|
+
return (await loadAll()).filter((m) => isActive(m) && isVisibleTo(m, reader));
|
|
1026
|
+
};
|
|
932
1027
|
// Use ledger (#42). `query` is what retrieval was asked with; what gets
|
|
933
1028
|
// stored is the vocabulary the answer SHARES with the query, taken from the
|
|
934
1029
|
// memory side, so the ledger can never become a copy of user prompts.
|
|
@@ -941,7 +1036,7 @@ const impl = {
|
|
|
941
1036
|
};
|
|
942
1037
|
const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
|
|
943
1038
|
if (!latestPrompt.has(sid)) return;
|
|
944
|
-
const mems = rows ?? await injectableRows();
|
|
1039
|
+
const mems = rows ?? (await injectableRows(sid));
|
|
945
1040
|
const version = await storeVersion(mems);
|
|
946
1041
|
const cached = epoch.get(sid);
|
|
947
1042
|
if (cached?.version === version) return;
|
|
@@ -1010,6 +1105,13 @@ const impl = {
|
|
|
1010
1105
|
args: event?.input,
|
|
1011
1106
|
};
|
|
1012
1107
|
setCurrent(input);
|
|
1108
|
+
// Evidence lines written below stamp the RECORDING repository. Bind
|
|
1109
|
+
// an unbound caller to this instance first (SYNC provisional; the
|
|
1110
|
+
// prompt hook / events bind firmly in production) so a tool_result
|
|
1111
|
+
// can never carry another instance's stamp (#127).
|
|
1112
|
+
if (typeof event?.sessionID === "string") {
|
|
1113
|
+
bindSessionProvisional(event.sessionID, instanceDir);
|
|
1114
|
+
}
|
|
1013
1115
|
const out = { output: resultText(event?.result), metadata: resultMeta(event?.result) };
|
|
1014
1116
|
await afterTool(input, out);
|
|
1015
1117
|
const pulled = await contextualPull(input, out as { output?: unknown }, budget, await useSignals());
|
|
@@ -1025,11 +1127,21 @@ const impl = {
|
|
|
1025
1127
|
// Tiny system digest + open-thread frontier block, injected into the system prompt.
|
|
1026
1128
|
await ctx.session?.hook("context", (event: any) =>
|
|
1027
1129
|
guarded("session.context (systemDigest)", async () => {
|
|
1028
|
-
// Route store reads in this hook through the right session's scope
|
|
1130
|
+
// Route store reads in this hook through the right session's scope:
|
|
1131
|
+
// the sid is captured from the event BEFORE any await and carried
|
|
1132
|
+
// explicitly — the global current set here is legacy bookkeeping
|
|
1133
|
+
// only, never the identity this flow filters with (#127).
|
|
1134
|
+
const sid = typeof event?.sessionID === "string" ? event.sessionID : undefined;
|
|
1029
1135
|
setCurrent({ sessionID: event?.sessionID });
|
|
1030
|
-
const sid = event?.sessionID;
|
|
1031
1136
|
if (typeof sid === "string") sessions.touch(sid);
|
|
1032
|
-
|
|
1137
|
+
// Resolve WHOSE repository this injection reads before the store
|
|
1138
|
+
// read below: an unbound session would otherwise fall to global-only
|
|
1139
|
+
// and silently lose its own frontier rows. SYNC provisional bind to
|
|
1140
|
+
// this instance's workspace — the prompt hook (or an event) has
|
|
1141
|
+
// already bound firmly in production, so no host lookup belongs in
|
|
1142
|
+
// this hot path (#127).
|
|
1143
|
+
if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
|
|
1144
|
+
const mems = await injectableRows(sid);
|
|
1033
1145
|
if (typeof sid === "string") await refreshEpoch(sid, mems);
|
|
1034
1146
|
const parts: string[] = [];
|
|
1035
1147
|
await systemDigest(
|
|
@@ -1087,20 +1199,25 @@ const impl = {
|
|
|
1087
1199
|
// while it still exists, BEFORE the summarizer replaces it.
|
|
1088
1200
|
await ctx.session?.hook("compaction", (event: any) =>
|
|
1089
1201
|
guarded("session.compaction (onCompacting)", async () => {
|
|
1202
|
+
const sid = typeof event?.sessionID === "string" ? event.sessionID : undefined;
|
|
1090
1203
|
setCurrent({ sessionID: event?.sessionID });
|
|
1204
|
+
// The anchor read and the capture pass below partition by the session's
|
|
1205
|
+
// repository; SYNC provisional bind only — a host lookup from this
|
|
1206
|
+
// hook would violate the zero-token promise (#127, see capture).
|
|
1207
|
+
if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
|
|
1091
1208
|
await onCompacting({ sessionID: event?.sessionID });
|
|
1092
1209
|
if (typeof event?.sessionID === "string") {
|
|
1093
1210
|
epoch.delete(event.sessionID);
|
|
1094
1211
|
latestPrompt.delete(event.sessionID);
|
|
1095
1212
|
}
|
|
1096
|
-
const anchor = await compactionAnchor();
|
|
1213
|
+
const anchor = await compactionAnchor(12, sid);
|
|
1097
1214
|
if (anchor) event?.system?.push?.({ type: "text", text: anchor });
|
|
1098
1215
|
// Fire-and-forget: a capture model call must never delay the compaction
|
|
1099
1216
|
// the user is waiting for, and failures stay inside the guarded path.
|
|
1100
1217
|
// The payload's own messages ride along so the mining sees the
|
|
1101
1218
|
// pre-compaction transcript even if the store moves under it.
|
|
1102
|
-
if (onCompactCapture &&
|
|
1103
|
-
onCompactCapture(
|
|
1219
|
+
if (onCompactCapture && sid) {
|
|
1220
|
+
onCompactCapture(sid, event.messages);
|
|
1104
1221
|
}
|
|
1105
1222
|
}),
|
|
1106
1223
|
);
|
|
@@ -1235,6 +1352,13 @@ const impl = {
|
|
|
1235
1352
|
// move current, so the gate context and the persisted rows thread
|
|
1236
1353
|
// `sid` explicitly instead of reading it back from the global (#116).
|
|
1237
1354
|
setCurrent({ sessionID: sid });
|
|
1355
|
+
// The capture's dedup reads and the rows it writes partition by the
|
|
1356
|
+
// CAPTURED session's repository — an unbound sid would otherwise
|
|
1357
|
+
// read global-only and mine duplicates into the store (#127; in
|
|
1358
|
+
// production the prompt hook already bound it firmly, so this is a
|
|
1359
|
+
// no-op there). SYNC only: a lookup call here would break the
|
|
1360
|
+
// zero-token promise of the capture tests.
|
|
1361
|
+
bindSessionProvisional(sid, instanceDir);
|
|
1238
1362
|
let transcript = seeded;
|
|
1239
1363
|
let msgs = seededMsgs;
|
|
1240
1364
|
if (transcript.length < 200) {
|
package/src/init.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import { basename, join } from "node:path";
|
|
9
9
|
import { existsSync } from "node:fs";
|
|
10
10
|
import { cbmBin } from "./config.ts";
|
|
11
|
-
import {
|
|
11
|
+
import { isVisibleTo, loadAll, markSuperseded, readerFromSid } from "./memory.ts";
|
|
12
12
|
import { runWriteGate, type GateContext } from "./gates.ts";
|
|
13
13
|
import { record } from "./evidence.ts";
|
|
14
14
|
import { evidenceCalls, hasGateCheck } from "./triggers.ts";
|
|
@@ -30,6 +30,10 @@ export interface InitArgs {
|
|
|
30
30
|
liveRoot: string;
|
|
31
31
|
force?: boolean;
|
|
32
32
|
mode?: string;
|
|
33
|
+
// The calling session (#127): rows this writes are stamped for the CALLER,
|
|
34
|
+
// resolved after runInit's own awaits (git probing) rather than from the
|
|
35
|
+
// ambient current, which a concurrent session may have moved.
|
|
36
|
+
sessionID?: string;
|
|
33
37
|
}
|
|
34
38
|
|
|
35
39
|
export interface InitSummary {
|
|
@@ -184,12 +188,14 @@ export interface InitStamp {
|
|
|
184
188
|
head: string;
|
|
185
189
|
}
|
|
186
190
|
|
|
187
|
-
export async function initStamp(scope: string): Promise<InitStamp | null> {
|
|
191
|
+
export async function initStamp(scope: string, sid?: string): Promise<InitStamp | null> {
|
|
188
192
|
// Scope is a basename, so two different repos can share one
|
|
189
193
|
// ("api" next to "api", a fork beside its upstream). Visibility filtering
|
|
190
194
|
// makes each repo see only its own stamp — basename collisions no longer
|
|
191
|
-
// alias init state between repos.
|
|
192
|
-
|
|
195
|
+
// alias init state between repos. The reader comes from the CALLER's
|
|
196
|
+
// session, not from the global current after this await (#127).
|
|
197
|
+
const reader = readerFromSid(sid);
|
|
198
|
+
const mems = (await loadAll()).filter((m) => !m.superseded_by && isVisibleTo(m, reader));
|
|
193
199
|
for (const m of mems) {
|
|
194
200
|
if (m.type !== "context" || m.scope !== scope) continue;
|
|
195
201
|
if (!m.tags?.some((t) => t === "init-stamp")) continue;
|
|
@@ -208,12 +214,15 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
|
|
|
208
214
|
|
|
209
215
|
const gateCtx: GateContext = {
|
|
210
216
|
liveRoot: root,
|
|
211
|
-
evidenceCalls: evidenceCalls(getCurrent().sid),
|
|
212
|
-
hasGateCheck: hasGateCheck(getCurrent().sid),
|
|
217
|
+
evidenceCalls: evidenceCalls(args.sessionID ?? getCurrent().sid),
|
|
218
|
+
hasGateCheck: hasGateCheck(args.sessionID ?? getCurrent().sid),
|
|
219
|
+
// Stamps land on the caller's session even though runInit awaits git
|
|
220
|
+
// probing before the gate writes (#127 / #121's write-side root cause).
|
|
221
|
+
sessionID: args.sessionID,
|
|
213
222
|
trusted: true,
|
|
214
223
|
};
|
|
215
224
|
|
|
216
|
-
const prior = await initStamp(scope);
|
|
225
|
+
const prior = await initStamp(scope, args.sessionID);
|
|
217
226
|
if (prior && !force && prior.head === head) {
|
|
218
227
|
await record("init_skip", { scope, head, since: prior.ts }, false);
|
|
219
228
|
return {
|
package/src/inject.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// "open") get a single capped frontier block in the digest so planning sessions
|
|
7
7
|
// start at the previous session's frontier instead of re-deriving it.
|
|
8
8
|
import { createHash } from "node:crypto";
|
|
9
|
-
import { isActive, loadAll, visibleHere, type Memory } from "./memory.ts";
|
|
9
|
+
import { isActive, loadAll, readerFromSid, visibleTo, visibleHere, type Memory } from "./memory.ts";
|
|
10
10
|
import { record } from "./evidence.ts";
|
|
11
11
|
import { dateStr, frontierBudget, injectBudget } from "./config.ts";
|
|
12
12
|
import { bracketList } from "./logfmt.ts";
|
|
@@ -20,6 +20,9 @@ export interface TransformOutput {
|
|
|
20
20
|
export interface PullInput {
|
|
21
21
|
tool?: unknown;
|
|
22
22
|
args?: unknown;
|
|
23
|
+
// The session the pull runs FOR (#127): resolved to an immutable Reader at
|
|
24
|
+
// entry so the loadAll await below cannot drift into another session's repo.
|
|
25
|
+
sessionID?: unknown;
|
|
23
26
|
}
|
|
24
27
|
|
|
25
28
|
export interface PullOutput {
|
|
@@ -277,8 +280,16 @@ export async function systemDigest(
|
|
|
277
280
|
output: TransformOutput,
|
|
278
281
|
opts: DigestOptions = {},
|
|
279
282
|
): Promise<void> {
|
|
280
|
-
|
|
281
|
-
|
|
283
|
+
const sid =
|
|
284
|
+
typeof _input === "object" && _input !== null &&
|
|
285
|
+
"sessionID" in _input &&
|
|
286
|
+
typeof (_input as Record<string, unknown>).sessionID === "string"
|
|
287
|
+
? String((_input as Record<string, unknown>).sessionID)
|
|
288
|
+
: "?";
|
|
289
|
+
// Repo-scoped: model-facing reads see the CALLER's repo + global rows, via
|
|
290
|
+
// the sid carried on this flow's input (#127) — never a global re-read
|
|
291
|
+
// after the loadAll await.
|
|
292
|
+
const mems = opts.rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
|
|
282
293
|
if (!mems.length) return;
|
|
283
294
|
const latest = flattenMemoryText(mems.map((m) => m.ts).sort().pop() ?? "?");
|
|
284
295
|
output.system.push(
|
|
@@ -302,12 +313,6 @@ export async function systemDigest(
|
|
|
302
313
|
const conv = await recentConvergenceSummary();
|
|
303
314
|
if (conv) output.system.push(`\nConvergence tracking: ${conv}`);
|
|
304
315
|
|
|
305
|
-
const sid =
|
|
306
|
-
typeof _input === "object" && _input !== null &&
|
|
307
|
-
"sessionID" in _input &&
|
|
308
|
-
typeof (_input as Record<string, unknown>).sessionID === "string"
|
|
309
|
-
? String((_input as Record<string, unknown>).sessionID)
|
|
310
|
-
: "?";
|
|
311
316
|
if (frontierInjectedSessions.has(sid)) return;
|
|
312
317
|
frontierInjectedSessions.add(sid);
|
|
313
318
|
const openMems = mems.filter((m) => m.status === "open");
|
|
@@ -335,11 +340,13 @@ export async function selectRelevant(
|
|
|
335
340
|
limit = 3,
|
|
336
341
|
rows?: Memory[],
|
|
337
342
|
use?: UseSignals,
|
|
343
|
+
sid?: string,
|
|
338
344
|
): Promise<{ block: string; selected: Memory[] }> {
|
|
339
345
|
const text = message.trim();
|
|
340
346
|
if (!text) return { block: "", selected: [] };
|
|
341
|
-
// Repo-scoped: model-facing reads see
|
|
342
|
-
|
|
347
|
+
// Repo-scoped: model-facing reads see the caller's repo + global rows
|
|
348
|
+
// (their session when one was threaded, #127).
|
|
349
|
+
const mems = rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
|
|
343
350
|
const top = scoreMemories(text, mems, limit, use);
|
|
344
351
|
if (!top.length) return { block: "", selected: [] };
|
|
345
352
|
return {
|
|
@@ -367,9 +374,9 @@ export function injectedRows(block: string, candidates: Memory[]): Memory[] {
|
|
|
367
374
|
// changes and supersession all invalidate an epoch, while evidence, hidden
|
|
368
375
|
// rows and non-rendered metadata do not. This is only a linear hash over rows
|
|
369
376
|
// loadAll() already had to read and parse for the request.
|
|
370
|
-
export async function storeVersion(rows?: Memory[]): Promise<string> {
|
|
371
|
-
// Repo-scoped: model-facing reads see
|
|
372
|
-
const mems = rows ??
|
|
377
|
+
export async function storeVersion(rows?: Memory[], sid?: string): Promise<string> {
|
|
378
|
+
// Repo-scoped: model-facing reads see the caller's repo + global rows.
|
|
379
|
+
const mems = rows ?? visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
|
|
373
380
|
if (!mems.length) return "0:";
|
|
374
381
|
let max = "";
|
|
375
382
|
const hash = createHash("sha256");
|
|
@@ -412,9 +419,9 @@ const ANCHOR_OPEN_LIMIT = 10;
|
|
|
412
419
|
const ANCHOR_SETTLED_LIMIT = 5;
|
|
413
420
|
const ANCHOR_BUDGET = 2500;
|
|
414
421
|
|
|
415
|
-
export async function compactionAnchor(limit = 12): Promise<string> {
|
|
416
|
-
// Repo-scoped: model-facing reads see
|
|
417
|
-
const mems =
|
|
422
|
+
export async function compactionAnchor(limit = 12, sid?: string): Promise<string> {
|
|
423
|
+
// Repo-scoped: model-facing reads see the caller's repo + global rows.
|
|
424
|
+
const mems = visibleTo((await loadAll()).filter(isActive), readerFromSid(sid));
|
|
418
425
|
if (!mems.length) return "";
|
|
419
426
|
const byNewest = (a: Memory, b: Memory) => cmpTs(b.ts, a.ts);
|
|
420
427
|
const open = mems
|
|
@@ -444,8 +451,9 @@ export async function contextualPull(
|
|
|
444
451
|
if (!["grep", "glob", "read"].includes(tool)) return [];
|
|
445
452
|
const term = argText(input.args);
|
|
446
453
|
if (!term) return [];
|
|
447
|
-
// Repo-scoped: model-facing reads see
|
|
448
|
-
|
|
454
|
+
// Repo-scoped: model-facing reads see the CALLER's repo + global rows —
|
|
455
|
+
// the pull's own sessionID, resolved before the store read (#127).
|
|
456
|
+
const mems = visibleTo((await loadAll()).filter(isActive), readerFromSid(input.sessionID));
|
|
449
457
|
const top = scoreMemories(term, mems, 3, use);
|
|
450
458
|
if (!top.length) return [];
|
|
451
459
|
// Held to the injection budget too: three long rows were ~12 KB per call.
|