opencode-self-improvement 0.14.16 → 0.14.18
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 +7 -5
- package/package.json +1 -1
- package/src/gates.ts +113 -26
- package/src/index.ts +311 -27
- package/src/init.ts +15 -3
- package/src/memory.ts +50 -38
- package/src/portable.ts +13 -4
- package/src/schema.ts +4 -1
- package/src/state.ts +35 -0
- package/src/status.ts +4 -3
package/README.md
CHANGED
|
@@ -89,7 +89,7 @@ Four gates run before anything is stored, and each emits an ordered evidence lin
|
|
|
89
89
|
3. **GATE-3 — no duplicates.** Near-duplicates collapse into the existing row; a contradiction with a superseded memory is rejected.
|
|
90
90
|
4. **GATE-4 — promotion or block.** The row lands, or the call returns the reason.
|
|
91
91
|
|
|
92
|
-
Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget` records a retirement, and `memory_undo` restores a snapshot. `memory_update` takes a `query` that picks the row — its id, a clock fragment such as `00:11:22.123`, or a unique substring of its text. Omit it to update the newest entry of that scope and type. A `query` that matches nothing, or several rows, writes nothing and says so.
|
|
92
|
+
Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget` records a retirement, and `memory_undo` restores a snapshot. `memory_update` takes a `query` that picks the row — its id, a clock fragment such as `00:11:22.123`, or a unique substring of its text. Omit it to update the newest entry of that scope and type. A `query` that matches nothing, or several rows, writes nothing and says so. A prose edit changes only the prose: the row's tags, issue link, retrieval keywords, open/settled standing, and repository all carry over to the new row — updating a `global` row from one machine keeps it global for every other. Naming a row an earlier update already superseded reports the duplicate when the live successor already holds that exact content; when only the metadata you name differs, the update runs against the successor instead of dead-ending. And a failure after the new row is durable is reported as `PARTIAL` — the message names what failed, the replacement stands on disk, and `memory_undo` (merge or force) brings the old row back.
|
|
93
93
|
|
|
94
94
|
## Repo scoping
|
|
95
95
|
|
|
@@ -99,22 +99,24 @@ Injection, recall, the frontier block, compaction, `memory_forget` and decay onl
|
|
|
99
99
|
|
|
100
100
|
## Token cost and caching
|
|
101
101
|
|
|
102
|
-
- **Section-frozen injection.** The whole memory section — standing digest, open-thread frontier, relevance block — is computed once per epoch and delivered byte-identically until something the model
|
|
102
|
+
- **Section-frozen injection.** The whole memory section — standing digest, open-thread frontier, relevance block — is computed once per epoch and delivered byte-identically until something the model actually needs changes. The epoch's authority is the **rendered bytes**, not the store fingerprint: a promoted row that changes nothing visible costs no cache bust.
|
|
103
|
+
- **A session never pays for bytes it is not riding.** A memory *you* saved in this session is a fact you already produced — it is in your own transcript — so it never busts your cache. The test is not "did the store change" but "would the frozen bytes still have been produced from the same inputs, minus the rows this session authored since": a correction, blocklisting, redaction or supersession of a row you are riding, and anything another session, the viewer or an import wrote, all still land on your next request.
|
|
103
104
|
- **Two-concept threshold.** A free-text prompt must share at least two distinct concepts with a memory for it to be injected; keyword-length queries (one or two words) need only one. Silence on single-word coincidences is deliberate; `memory_recall` still reaches them on the pull path.
|
|
104
105
|
- **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
|
|
105
106
|
- **Nothing volatile on the cached prefix.** The standing digest carries no row count and no latest timestamp. Both used to ride the very front of the system prompt, so every saved memory rewrote the prefix and made the next request re-bill the whole conversation; the exact numbers now live where they are free — the footer badge, `/memory`, `memory_status`, the viewer.
|
|
106
107
|
- **Evidence is never injected**, and the standing system digest is two lines.
|
|
107
108
|
- **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge.
|
|
108
109
|
|
|
109
|
-
Deterministic workload (50 memories, 20 prompts, 3 mid-session store writes) through the plugin's real injection code. Every column is measured on the full memory section — the bytes a request actually sends — because prompt caching is a property of those bytes:
|
|
110
|
+
Deterministic workload (50 memories, 20 prompts, 3 mid-session store writes made *by the measured session*) through the plugin's real injection code. Every column is measured on the full memory section — the bytes a request actually sends — because prompt caching is a property of those bytes:
|
|
110
111
|
|
|
111
112
|
| Policy | Recomputes | Cache busts | Injected chars (20 turns) | Avg/turn | Worst section |
|
|
112
113
|
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
113
114
|
| A — recompute per prompt, uncapped (naive) | 20 | 19 | 60996 | 3049.8 | 3404 |
|
|
114
115
|
| B — block frozen on store fingerprint, digest rebuilt per turn | 4 | 3 | 55478 | 2773.9 | 2867 |
|
|
115
|
-
| C — section frozen on rendered bytes
|
|
116
|
+
| C — section frozen on rendered bytes | 4 | 3 | 55258 | 2762.9 | 2856 |
|
|
117
|
+
| D — C + riding bytes (shipped) | 1 | 0 | 53500 | 2675.0 | 2675 |
|
|
116
118
|
|
|
117
|
-
A "cache bust" is a turn whose memory-section bytes differ from the turn before — each one re-bills the entire conversation as fresh input.
|
|
119
|
+
A "cache bust" is a turn whose memory-section bytes differ from the turn before — each one re-bills the entire conversation as fresh input. All three synthetic writes change what the session is shown, so B and C each pay for them; D pays nothing, because the session wrote them itself. What D still pays for is a riding row being corrected, blocklisted or redacted, or another session writing a row — that half of the contract is pinned by `test/epoch.test.ts` rather than by this table, since a benchmark that only writes never exercises it. D also injects 12.3% fewer characters than the naive policy — the denominator here is the whole section, not the relevance block alone, so it is not comparable with the block-only figure this README quoted before. Reproduce (byte-identical output):
|
|
118
120
|
|
|
119
121
|
```sh
|
|
120
122
|
bun run bench
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.18",
|
|
4
4
|
"description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
|
|
5
5
|
"main": "index.ts",
|
|
6
6
|
"exports": {
|
package/src/gates.ts
CHANGED
|
@@ -8,13 +8,14 @@ import {
|
|
|
8
8
|
appendMemory,
|
|
9
9
|
loadAll,
|
|
10
10
|
loadScope,
|
|
11
|
-
|
|
11
|
+
markManySupersededReport,
|
|
12
12
|
snapshotFiles,
|
|
13
13
|
MAX_CONTENT_CHARS,
|
|
14
14
|
type Memory,
|
|
15
15
|
type SupersedeFields,
|
|
16
16
|
} from "./memory.ts";
|
|
17
17
|
import { chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
|
|
18
|
+
import { noteAuthored } from "./state.ts";
|
|
18
19
|
import { flattenMemoryText } from "./sanitize.ts";
|
|
19
20
|
import { containsSecret, redactSecrets } from "./secrets.ts";
|
|
20
21
|
import { readerForSession } from "./memory.ts";
|
|
@@ -47,6 +48,25 @@ export interface WriteCandidate {
|
|
|
47
48
|
repoPath?: string;
|
|
48
49
|
}
|
|
49
50
|
|
|
51
|
+
// Metadata-list equality (retrieval keywords, tags): pairwise, undefined and
|
|
52
|
+
// empty counting as the same content. Shared by GATE-3's update carve-out and
|
|
53
|
+
// memory_update's successor verdict so both sides ask the same question.
|
|
54
|
+
// ORDER-SENSITIVE on purpose: ["a","b"] vs ["b","a"] counts as a metadata
|
|
55
|
+
// edit (a new row, the old one intact) — a set comparison would silently
|
|
56
|
+
// collapse an edit whose ordering the caller changed deliberately, and the
|
|
57
|
+
// conservative direction for a truth-claim is the one that writes more.
|
|
58
|
+
export const sameStrList = (a?: string[], c?: string[]) =>
|
|
59
|
+
(a?.length ?? 0) === (c?.length ?? 0) && (a ?? []).every((x, i) => (c ?? [])[i] === x);
|
|
60
|
+
|
|
61
|
+
// The sentence every success reply owes the reader when the gate promoted a
|
|
62
|
+
// row but its write_promoted audit line failed to land (#155 review): the
|
|
63
|
+
// row IS durable — and memory_evidence, where every other verdict points
|
|
64
|
+
// the curious reader, will show NOTHING for it. Only silence was optional.
|
|
65
|
+
export const auditCaveat = (outcome: GateOutcome): string =>
|
|
66
|
+
outcome.evidenceError !== undefined
|
|
67
|
+
? ` (its audit line was not recorded: ${outcome.evidenceError})`
|
|
68
|
+
: "";
|
|
69
|
+
|
|
50
70
|
export interface GateContext {
|
|
51
71
|
liveRoot: string;
|
|
52
72
|
evidenceCalls: string[];
|
|
@@ -68,6 +88,12 @@ export interface GateContext {
|
|
|
68
88
|
// excludes it from rivalry: the update IS the sanctioned supersession, so it
|
|
69
89
|
// must never be blocked as a conflict with the row it is about to supersede.
|
|
70
90
|
supersedesTs?: string;
|
|
91
|
+
// Optional caller-owned ledger (#158 round 3): GATE-2's drift/canonical
|
|
92
|
+
// supersessions append the ts values they made durable HERE, immediately
|
|
93
|
+
// after the batch publish and BEFORE their audit lines — so a failed audit
|
|
94
|
+
// line can no longer hide a persisted retirement from the caller's catch.
|
|
95
|
+
// "Nothing was written" is only writable when this stays empty.
|
|
96
|
+
durable?: string[];
|
|
71
97
|
}
|
|
72
98
|
|
|
73
99
|
export interface GateOutcome {
|
|
@@ -76,6 +102,18 @@ export interface GateOutcome {
|
|
|
76
102
|
ts?: string;
|
|
77
103
|
chain: string;
|
|
78
104
|
hint?: string;
|
|
105
|
+
// Promoted with the row DURABLE but its post-append write_promoted audit
|
|
106
|
+
// line failed (#155). Entry points with a further post-mutation step
|
|
107
|
+
// (memory_update's supersede) must still run it and report a partial
|
|
108
|
+
// result. Throwing was the old shape of this signal and it lied: callers
|
|
109
|
+
// read it as "nothing happened" while the row sat on disk. Pre-append
|
|
110
|
+
// faults keep throwing — there, nothing was in fact written.
|
|
111
|
+
evidenceError?: string;
|
|
112
|
+
// On a collapsed (un-stored) write: the ts of the ACTIVE row whose content
|
|
113
|
+
// already IS the candidate. An update completing its supersession needs the
|
|
114
|
+
// survivor's id to retire its own target in the survivor's favor (#155
|
|
115
|
+
// convergence: a retry must be able to end with one active row).
|
|
116
|
+
collapsedWith?: string;
|
|
79
117
|
}
|
|
80
118
|
|
|
81
119
|
const STOPWORDS = new Set([
|
|
@@ -413,6 +451,14 @@ export async function runWriteGate(
|
|
|
413
451
|
// and the pass is skipped by the batch (it re-reads under the lock).
|
|
414
452
|
const target = g1.candidateStale ? "<-" : chain;
|
|
415
453
|
if (typeof s.memory.superseded_by === "string") continue;
|
|
454
|
+
// The row an UPDATE replaces is retired by the update itself, with its
|
|
455
|
+
// own pointer. A drift stamp here wins first-call-wins against the
|
|
456
|
+
// caller's markSuperseded and leaves a chain id the caller's retry can
|
|
457
|
+
// never walk — so the tool would print "(superseded X)" naming a
|
|
458
|
+
// retirement it did not perform. Same principle GATE-3 applies to
|
|
459
|
+
// rivalry (the target is never a contender): the update IS the sanctioned
|
|
460
|
+
// supersession for that row.
|
|
461
|
+
if (s.memory.ts === ctx.supersedesTs) continue;
|
|
416
462
|
driftPlan.push({
|
|
417
463
|
s,
|
|
418
464
|
target,
|
|
@@ -420,8 +466,11 @@ export async function runWriteGate(
|
|
|
420
466
|
});
|
|
421
467
|
}
|
|
422
468
|
if (driftPlan.length > 0) {
|
|
423
|
-
const
|
|
424
|
-
if (
|
|
469
|
+
const { marked } = await markManySupersededReport(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })));
|
|
470
|
+
if (marked.length > 0) {
|
|
471
|
+
// Ledger BEFORE the audit lines: what is on disk now stays on disk no
|
|
472
|
+
// matter what the record loop below does (round-3 probe 3).
|
|
473
|
+
ctx.durable?.push(...marked);
|
|
425
474
|
for (const p of driftPlan) {
|
|
426
475
|
supersededTs = p.s.memory.ts;
|
|
427
476
|
await rec("superseded_by", {
|
|
@@ -454,6 +503,9 @@ export async function runWriteGate(
|
|
|
454
503
|
const canonPlan: { ts: string; from: string | undefined }[] = [];
|
|
455
504
|
for (const m of scopeMems) {
|
|
456
505
|
if (m.superseded_by) continue;
|
|
506
|
+
// The update's own target retires in the update's hand, not the
|
|
507
|
+
// canonical registry's (see the GATE-2 drift skip above).
|
|
508
|
+
if (m.ts === ctx.supersedesTs) continue;
|
|
457
509
|
if (tokens(m.content).some((t) => valueSet.has(t))) continue;
|
|
458
510
|
const from = rawTokens(m.content).find(
|
|
459
511
|
(t) => !STOPWORDS.has(t.toLowerCase()) && !entitySet.has(t.toLowerCase()) && !valueSet.has(t.toLowerCase()),
|
|
@@ -462,10 +514,15 @@ export async function runWriteGate(
|
|
|
462
514
|
}
|
|
463
515
|
// One batch publish for the whole neutralization set (#61); rows marked
|
|
464
516
|
// out-of-band since the scan are skipped by the batch (re-read under lock).
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
517
|
+
const { marked: canonMarked } = await markManySupersededReport(
|
|
518
|
+
canonPlan.map((p) => ({
|
|
519
|
+
ts: p.ts,
|
|
520
|
+
fields: { superseded_by: target, reason: "canonical", entity: canon.entry.entity, from: p.from, to: canon.entry.value },
|
|
521
|
+
})),
|
|
522
|
+
);
|
|
523
|
+
if (canonMarked.length > 0) {
|
|
524
|
+
// Same ledger discipline as the drift batch above.
|
|
525
|
+
ctx.durable?.push(...canonMarked);
|
|
469
526
|
for (const p of canonPlan) {
|
|
470
527
|
if (!supersededTs) supersededTs = p.ts;
|
|
471
528
|
await rec("superseded_by", {
|
|
@@ -490,8 +547,21 @@ export async function runWriteGate(
|
|
|
490
547
|
const exactPoll = scopeMems.filter(
|
|
491
548
|
(m) => m.superseded_by === undefined || m.reason === "drift",
|
|
492
549
|
);
|
|
550
|
+
// Byte-exact duplicate prose collapses (Principle 2) — with one UPDATE-only
|
|
551
|
+
// carve-out: the row being replaced counts as a duplicate of the candidate
|
|
552
|
+
// only if the update also restates its metadata. Same prose plus different
|
|
553
|
+
// retrieval keywords or status is a metadata EDIT on that row (GATE-3
|
|
554
|
+
// already refuses to see it as a rival), and collapsing it would silently
|
|
555
|
+
// drop the edit — the tool could then never edit kw or status at all.
|
|
493
556
|
const exact = exactPoll.find(
|
|
494
|
-
(m) =>
|
|
557
|
+
(m) =>
|
|
558
|
+
m.type === candidate.type &&
|
|
559
|
+
m.content === candidate.content &&
|
|
560
|
+
(m.ts !== ctx.supersedesTs ||
|
|
561
|
+
(sameStrList(m.kw, candidate.kw) &&
|
|
562
|
+
sameStrList(m.tags, candidate.tags) &&
|
|
563
|
+
m.issue === candidate.issue &&
|
|
564
|
+
(m.status ?? "settled") === (candidate.status ?? "settled"))),
|
|
495
565
|
);
|
|
496
566
|
// Same-type live rows that could compete with the incoming statement; the
|
|
497
567
|
// row an update replaces is never a contender.
|
|
@@ -645,7 +715,7 @@ export async function runWriteGate(
|
|
|
645
715
|
}
|
|
646
716
|
|
|
647
717
|
if (collapseMatch) {
|
|
648
|
-
return { action: "collapsed", chain };
|
|
718
|
+
return { action: "collapsed", chain, collapsedWith: collapseMatch.ts };
|
|
649
719
|
}
|
|
650
720
|
|
|
651
721
|
// The write is specifically promoted on engagement (no refs, no gate check,
|
|
@@ -662,21 +732,38 @@ export async function runWriteGate(
|
|
|
662
732
|
// The write carries the CALLER's session, not whatever current says after
|
|
663
733
|
// the gate's own awaits - capture's stamp must follow the captured session.
|
|
664
734
|
const ts = await appendMemory({ ...candidate, sessionID: ctx.sessionID });
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
735
|
+
// #165: remember who made this row, so the writing session is not billed a
|
|
736
|
+
// prompt-cache bust to be shown its own thought. Only promoted writes are
|
|
737
|
+
// attributed — a blocked candidate created nothing.
|
|
738
|
+
noteAuthored(ctx.sessionID, ts);
|
|
739
|
+
// Everything past the append is durable state: an audit failure from here
|
|
740
|
+
// must not escape as a throw, or the caller reports a write that happened
|
|
741
|
+
// as if it had not (#155 — memory_update told the model "Nothing was
|
|
742
|
+
// written" while the replacement row sat un-superseded on disk). The
|
|
743
|
+
// outcome carries the error instead.
|
|
744
|
+
let evidenceError: string | undefined;
|
|
745
|
+
try {
|
|
746
|
+
await rec("write_promoted", {
|
|
747
|
+
gate: 4,
|
|
748
|
+
op: "write",
|
|
749
|
+
mem: ts,
|
|
750
|
+
scope: candidate.scope,
|
|
751
|
+
type: candidate.type,
|
|
752
|
+
status: candidate.status ?? "settled",
|
|
753
|
+
ch,
|
|
754
|
+
supersedes: supersededTs ?? "-",
|
|
755
|
+
canonical: canon ? `canonical.logfmt:${canon.entry.ts}` : "-",
|
|
756
|
+
evidence_refs: bracketList(ctx.evidenceCalls),
|
|
757
|
+
snapshot: snapshot[0] ?? "-",
|
|
758
|
+
trusted: ctx.trusted ? true : undefined,
|
|
759
|
+
grounded_by: groundedByEngagement ? "engagement" : undefined,
|
|
760
|
+
chain,
|
|
761
|
+
});
|
|
762
|
+
} catch (err) {
|
|
763
|
+
// NOT `(err as Error).message`: a messageless Error (or a non-Error
|
|
764
|
+
// rejection) would make the field FALSY, and callers test it for truth —
|
|
765
|
+
// the lie this field exists to kill would return as a clean success.
|
|
766
|
+
evidenceError = err instanceof Error && err.message ? err.message : String(err);
|
|
767
|
+
}
|
|
768
|
+
return { action: "promoted", ts, chain, evidenceError };
|
|
682
769
|
}
|
package/src/index.ts
CHANGED
|
@@ -31,7 +31,7 @@ import {
|
|
|
31
31
|
visibleTo,
|
|
32
32
|
type Memory,
|
|
33
33
|
} from "./memory.ts";
|
|
34
|
-
import { runWriteGate, type GateContext, type WriteCandidate } from "./gates.ts";
|
|
34
|
+
import { auditCaveat, runWriteGate, sameStrList, type GateContext, type WriteCandidate } from "./gates.ts";
|
|
35
35
|
import { withStoreLock } from "./lock.ts";
|
|
36
36
|
import { pruneMemory } from "./prune.ts";
|
|
37
37
|
import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
|
|
@@ -81,7 +81,7 @@ import {
|
|
|
81
81
|
markTurn,
|
|
82
82
|
onCompacting,
|
|
83
83
|
} from "./triggers.ts";
|
|
84
|
-
import { getCurrent, setCurrent } from "./state.ts";
|
|
84
|
+
import { authoredFor, getCurrent, setCurrent } from "./state.ts";
|
|
85
85
|
import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional, writeTarget } from "./repokey.ts";
|
|
86
86
|
import { parseLine, readLines } from "./logfmt.ts";
|
|
87
87
|
import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
|
|
@@ -483,7 +483,11 @@ const impl = {
|
|
|
483
483
|
if (ownerless) return await refuseOwnerlessWrite(ownerless, "remember");
|
|
484
484
|
}
|
|
485
485
|
const outcome = await runWriteGate(candidate, gateContext(sid));
|
|
486
|
-
|
|
486
|
+
// A durable row whose audit line fell is NOT a clean success
|
|
487
|
+
// (#155 review): the reply says what is missing where it is
|
|
488
|
+
// missing, and the row itself stands.
|
|
489
|
+
if (outcome.action === "promoted")
|
|
490
|
+
return { content: `Remembered: ${args.type} in ${args.scope}${auditCaveat(outcome)}` };
|
|
487
491
|
if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
|
|
488
492
|
return {
|
|
489
493
|
content: `Write blocked at GATE (${outcome.reason}). ${
|
|
@@ -585,7 +589,7 @@ const impl = {
|
|
|
585
589
|
editor.add(validated(UpdateArgs, {
|
|
586
590
|
name: "memory_update",
|
|
587
591
|
description:
|
|
588
|
-
"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.",
|
|
592
|
+
"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. A prose edit carries over everything the call does not name — tags, issue, keywords, status, and the row's repository. Naming a row that was already updated to exactly this content (metadata included) reports the duplicate; if its live successor holds the prose and only the metadata you name differs, the successor is updated. A failure after the write is reported as PARTIAL: the replacement is durable and memory_undo merge/force restores the old row.",
|
|
589
593
|
options: direct,
|
|
590
594
|
async execute(args, context): Promise<{ content: string }> {
|
|
591
595
|
const { sid } = toolIds(context);
|
|
@@ -606,6 +610,14 @@ const impl = {
|
|
|
606
610
|
// is exactly the race this lock exists to close. The loser then
|
|
607
611
|
// re-resolves under the lock, finds its target already retired,
|
|
608
612
|
// and writes nothing — the documented fail-closed contract.
|
|
613
|
+
// Flips once a replacement row is durable, so the catch below can
|
|
614
|
+
// never claim "Nothing was written" about a write that happened
|
|
615
|
+
// (#155's lie).
|
|
616
|
+
let mutated = false;
|
|
617
|
+
// The gate's durable steps: rows GATE-2 retired before a later
|
|
618
|
+
// failure (round-3 probe 3). Non-empty means "Nothing was written"
|
|
619
|
+
// is no longer writable.
|
|
620
|
+
const gateDurable: string[] = [];
|
|
609
621
|
try {
|
|
610
622
|
return await withStoreLock(
|
|
611
623
|
join(memoryRoot(), "update-order"),
|
|
@@ -616,12 +628,65 @@ const impl = {
|
|
|
616
628
|
// Resolve the row BEFORE the gate: an update that cannot identify its
|
|
617
629
|
// target must write nothing, rather than silently superseding whichever
|
|
618
630
|
// row happened to be newest in this scope+type.
|
|
619
|
-
|
|
631
|
+
let resolved = resolveMemoryTarget(prior, args.query);
|
|
620
632
|
if (resolved.status === "not_found") {
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
633
|
+
// Naming a SUPERSEDED row is not a miss (#155): the retry
|
|
634
|
+
// after a partial update lands here, and when that row's
|
|
635
|
+
// active successor already carries exactly this content the
|
|
636
|
+
// honest verdict is the duplicate one, not a dead end. Two
|
|
637
|
+
// subtleties the first cut missed: the successor's prose was
|
|
638
|
+
// stored REDACTED while a retry re-carries the raw input
|
|
639
|
+
// (the comparison must scrub), and "exactly this content"
|
|
640
|
+
// must mean the metadata too — a retry that also names new
|
|
641
|
+
// keywords still has work to do, and that work belongs on
|
|
642
|
+
// the chain head, so the update CONTINUES against the
|
|
643
|
+
// successor instead of collapsing here.
|
|
644
|
+
let chainHead: Memory | undefined;
|
|
645
|
+
if (args.query) {
|
|
646
|
+
const rows = (await loadAll()).filter(
|
|
647
|
+
(m) => m.scope === args.scope && m.type === args.type && isVisibleTo(m, reader),
|
|
648
|
+
);
|
|
649
|
+
const stale = resolveMemoryTarget(rows, args.query);
|
|
650
|
+
if (stale.status === "ok" && stale.target && !isActive(stale.target)) {
|
|
651
|
+
let latest = stale.target;
|
|
652
|
+
const walked = new Set<string>([latest.ts]);
|
|
653
|
+
while (latest.superseded_by) {
|
|
654
|
+
const next = rows.find((m) => m.ts === latest.superseded_by);
|
|
655
|
+
if (!next || walked.has(next.ts)) break;
|
|
656
|
+
walked.add(next.ts);
|
|
657
|
+
latest = next;
|
|
658
|
+
}
|
|
659
|
+
if (isActive(latest) && latest.content.trim() === redactSecrets(args.content).trim()) {
|
|
660
|
+
const restated =
|
|
661
|
+
(args.kw === undefined || sameStrList(args.kw, latest.kw)) &&
|
|
662
|
+
(args.status === undefined || args.status === (latest.status ?? "settled"));
|
|
663
|
+
if (restated) {
|
|
664
|
+
// Every other verdict is auditable; this one must
|
|
665
|
+
// be too — the message tells the model to consult
|
|
666
|
+
// memory_evidence.
|
|
667
|
+
await record(
|
|
668
|
+
"dedup_collapse",
|
|
669
|
+
{ op: "update", named: stale.target.ts, match: latest.ts, action: "exact_successor", incoming_ignored: true },
|
|
670
|
+
true,
|
|
671
|
+
sid,
|
|
672
|
+
);
|
|
673
|
+
return {
|
|
674
|
+
content:
|
|
675
|
+
`Duplicate ignored: ${args.type}/${args.scope} — ${JSON.stringify(args.query)} was already ` +
|
|
676
|
+
`updated to exactly this content (${latest.ts}). Nothing was written.`,
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
chainHead = latest;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
if (!chainHead) {
|
|
684
|
+
const where = args.query ? ` matches ${JSON.stringify(args.query)}` : "";
|
|
685
|
+
return {
|
|
686
|
+
content: `memory_update blocked: no active ${args.type} row in ${args.scope}${where}. Nothing was written.`,
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
resolved = { status: "ok", target: chainHead };
|
|
625
690
|
}
|
|
626
691
|
if (resolved.status === "ambiguous") {
|
|
627
692
|
return {
|
|
@@ -632,22 +697,165 @@ const impl = {
|
|
|
632
697
|
};
|
|
633
698
|
}
|
|
634
699
|
const target = resolved.target;
|
|
700
|
+
// A prose edit is not a metadata reset (#154): fields the
|
|
701
|
+
// call does not name carry over from the row being
|
|
702
|
+
// replaced, so updating an imported row can no longer
|
|
703
|
+
// launder away its provenance or issue link. kw follows
|
|
704
|
+
// the same rule with an override: omitted keeps the
|
|
705
|
+
// target's, provided replaces. The carry completes to the
|
|
706
|
+
// five fields of the #129 viewer precedent: STATUS (an
|
|
707
|
+
// open frontier row stays open) and REPO (updating a
|
|
708
|
+
// global row from one repository must not re-house it out
|
|
709
|
+
// of every other repository's view — "an edit must never
|
|
710
|
+
// widen visibility", and it must never narrow it either).
|
|
711
|
+
// These are also the fields the collapse-completion judges
|
|
712
|
+
// (review round 3): the fold asks whether the survivor
|
|
713
|
+
// already carries the REQUESTED state — not the pre-edit
|
|
714
|
+
// target's. An update naming kw:["new-alias"] is not
|
|
715
|
+
// "already standing" on a row holding ["old-alias"].
|
|
716
|
+
const requested = {
|
|
717
|
+
kw: args.kw ?? target.kw,
|
|
718
|
+
tags: target.tags,
|
|
719
|
+
issue: target.issue,
|
|
720
|
+
status: (args.status ?? target.status) ?? "settled",
|
|
721
|
+
repo: target.repo ?? "global",
|
|
722
|
+
};
|
|
635
723
|
const outcome = await runWriteGate(
|
|
636
|
-
{
|
|
637
|
-
|
|
724
|
+
{
|
|
725
|
+
type: args.type,
|
|
726
|
+
scope: args.scope,
|
|
727
|
+
content: args.content,
|
|
728
|
+
kw: requested.kw,
|
|
729
|
+
tags: requested.tags,
|
|
730
|
+
issue: requested.issue,
|
|
731
|
+
status: requested.status,
|
|
732
|
+
repo: requested.repo,
|
|
733
|
+
repoPath: target.repo ? target.repoPath : undefined,
|
|
734
|
+
},
|
|
735
|
+
{ ...gateContext(sid), supersedesTs: target.ts, durable: gateDurable },
|
|
638
736
|
);
|
|
639
737
|
if (outcome.action === "promoted" && outcome.ts && target) {
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
738
|
+
mutated = true;
|
|
739
|
+
const replacement = outcome.ts;
|
|
740
|
+
const retired = target.ts;
|
|
741
|
+
// The merge_review PARTIAL shape (156e887) applied to
|
|
742
|
+
// update: the replacement IS durable, so the message says
|
|
743
|
+
// exactly which follow-up step failed and what a retry does
|
|
744
|
+
// (#155 — never claim "Nothing was written" from here).
|
|
745
|
+
const partial = (why: string) => ({
|
|
746
|
+
content:
|
|
747
|
+
`memory_update PARTIAL: replacement ${replacement} IS on disk (memory_undo merge or force ` +
|
|
748
|
+
`restores ${retired}), but ${why}. Re-running this update reports the duplicate.`,
|
|
646
749
|
});
|
|
647
|
-
|
|
750
|
+
let retiredNow = false;
|
|
751
|
+
try {
|
|
752
|
+
retiredNow = await markSuperseded(retired, {
|
|
753
|
+
superseded_by: replacement,
|
|
754
|
+
reason: "update",
|
|
755
|
+
symbol: retired,
|
|
756
|
+
from: retired,
|
|
757
|
+
to: replacement,
|
|
758
|
+
});
|
|
759
|
+
} catch (err) {
|
|
760
|
+
return partial(
|
|
761
|
+
`retiring ${retired} failed: ${err instanceof Error && err.message ? err.message : String(err)}`,
|
|
762
|
+
);
|
|
763
|
+
}
|
|
764
|
+
if (!retiredNow) {
|
|
765
|
+
// merge_review checks exactly this boolean (156e887);
|
|
766
|
+
// "Updated (superseded X)" cannot be printed over a
|
|
767
|
+
// retirement a parallel supersession performed — that
|
|
768
|
+
// pointer names a DIFFERENT successor, and the confident
|
|
769
|
+
// line would hide a second active row.
|
|
770
|
+
return partial(
|
|
771
|
+
`${retired} had ALREADY been retired by another supersession while this call ran — ` +
|
|
772
|
+
`it points at that successor, not at ${replacement}; check memory_evidence`,
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
if (outcome.evidenceError !== undefined) {
|
|
776
|
+
return partial(`its write_promoted audit line was not recorded (${outcome.evidenceError})`);
|
|
777
|
+
}
|
|
778
|
+
return { content: `Updated ${args.type} in ${args.scope} (superseded ${retired})` };
|
|
779
|
+
}
|
|
780
|
+
if (outcome.action === "promoted")
|
|
781
|
+
return { content: `Remembered: ${args.type} in ${args.scope}${auditCaveat(outcome)}` };
|
|
782
|
+
if (outcome.action === "collapsed") {
|
|
783
|
+
// Completion (#155 convergence): when a retry collapses
|
|
784
|
+
// because an ACTIVE row already holds exactly this content
|
|
785
|
+
// while the row it NAMES is still active (the supersede
|
|
786
|
+
// step of an earlier PARTIAL attempt never landed), the
|
|
787
|
+
// idempotent close is to retire the named row in the
|
|
788
|
+
// survivor's favor — a bare "Duplicate ignored" would leave
|
|
789
|
+
// two active rows forever and a retry that never converges.
|
|
790
|
+
// first-call-wins makes this safe to attempt on any path.
|
|
791
|
+
// But the fold must not INVERT #154 (review): retiring the
|
|
792
|
+
// named row is loss-free only when the survivor already
|
|
793
|
+
// carries what the named row carries — the SAME predicate
|
|
794
|
+
// GATE-3 uses to call same-prose-different-metadata an
|
|
795
|
+
// edit rather than a duplicate. Otherwise the survivor
|
|
796
|
+
// would stand stripped of the named row's issue link,
|
|
797
|
+
// keywords, tags or OPEN frontier standing, and a "clean
|
|
798
|
+
// no-op" message would paper over a metadata destruction.
|
|
799
|
+
// On disagreement nothing retires: both ids are named and
|
|
800
|
+
// a human (or an update on the survivor) decides.
|
|
801
|
+
const survivorTs = outcome.collapsedWith;
|
|
802
|
+
if (target && survivorTs && survivorTs !== target.ts) {
|
|
803
|
+
const survivor = (await loadAll()).find((m) => m.ts === survivorTs && !m.superseded_by);
|
|
804
|
+
if (survivor) {
|
|
805
|
+
// The predicate is the REQUESTED state vs the survivor
|
|
806
|
+
// (round 3): content equality is already proven by the
|
|
807
|
+
// collapse, so the fold is loss-free only when the
|
|
808
|
+
// survivor also carries the metadata THIS call asked
|
|
809
|
+
// for — and stands where the target stands for readers
|
|
810
|
+
// of other repositories (repo visibility: folding a
|
|
811
|
+
// global row into a repo-private survivor would
|
|
812
|
+
// narrow a visibility the promotion path exists to
|
|
813
|
+
// preserve, and the reverse would leak).
|
|
814
|
+
if (
|
|
815
|
+
sameStrList(requested.kw, survivor.kw) &&
|
|
816
|
+
sameStrList(requested.tags, survivor.tags) &&
|
|
817
|
+
requested.issue === survivor.issue &&
|
|
818
|
+
requested.status === (survivor.status ?? "settled") &&
|
|
819
|
+
requested.repo === (survivor.repo ?? "global")
|
|
820
|
+
) {
|
|
821
|
+
const done = await markSuperseded(target.ts, {
|
|
822
|
+
superseded_by: survivorTs,
|
|
823
|
+
reason: "update",
|
|
824
|
+
symbol: target.ts,
|
|
825
|
+
from: target.ts,
|
|
826
|
+
to: survivorTs,
|
|
827
|
+
});
|
|
828
|
+
if (done) {
|
|
829
|
+
return {
|
|
830
|
+
content:
|
|
831
|
+
`Duplicate: ${args.type}/${args.scope} already stands active as ${survivorTs}; ` +
|
|
832
|
+
`${target.ts} was retired in its favor. Nothing new was written.`,
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
} else {
|
|
836
|
+
const differs: string[] = [];
|
|
837
|
+
if (requested.status !== (survivor.status ?? "settled"))
|
|
838
|
+
differs.push(`status ${requested.status} vs ${survivor.status ?? "settled"}`);
|
|
839
|
+
if (requested.issue !== survivor.issue)
|
|
840
|
+
differs.push(`issue ${requested.issue ?? "-"} vs ${survivor.issue ?? "-"}`);
|
|
841
|
+
if (!sameStrList(requested.kw, survivor.kw))
|
|
842
|
+
differs.push(`kw [${(requested.kw ?? []).join(", ") || "-"}] vs [${(survivor.kw ?? []).join(", ") || "-"}]`);
|
|
843
|
+
if (!sameStrList(requested.tags, survivor.tags))
|
|
844
|
+
differs.push(`tags [${(requested.tags ?? []).join(", ") || "-"}] vs [${(survivor.tags ?? []).join(", ") || "-"}]`);
|
|
845
|
+
if (requested.repo !== (survivor.repo ?? "global"))
|
|
846
|
+
differs.push(`visibility ${requested.repo} vs ${survivor.repo ?? "global"}`);
|
|
847
|
+
return {
|
|
848
|
+
content:
|
|
849
|
+
`Duplicate: ${args.type}/${args.scope} stands active as ${survivorTs}, but ${target.ts} ` +
|
|
850
|
+
`was NOT retired — the survivor does not carry what this update asked for ` +
|
|
851
|
+
`(${differs.join("; ")}), and the fold would drop it. Both stay active: restate them ` +
|
|
852
|
+
`onto ${survivorTs} with a memory_update, or memory_forget the row that should lose.`,
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
|
|
648
858
|
}
|
|
649
|
-
if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
|
|
650
|
-
if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
|
|
651
859
|
return { content: `Write blocked at GATE (${outcome.reason}). ${outcome.hint ?? ""}`.trimEnd() };
|
|
652
860
|
},
|
|
653
861
|
{
|
|
@@ -658,10 +866,27 @@ const impl = {
|
|
|
658
866
|
},
|
|
659
867
|
);
|
|
660
868
|
} catch (err) {
|
|
661
|
-
//
|
|
662
|
-
//
|
|
869
|
+
// Everything that still throws here was PRE-WRITE for THIS call's
|
|
870
|
+
// replacement: the fail-closed lock timeout, the #152 choke-point
|
|
871
|
+
// refusal, an evidence fault BEFORE the append. Post-append audit
|
|
872
|
+
// failures no longer reach this catch — the gate reports them on
|
|
873
|
+
// the promoted outcome (#155). mutated is the belt-and-braces
|
|
874
|
+
// truth check: a future post-write throw must report a partial,
|
|
875
|
+
// never a clean nothing. And gateDurable closes the last gap
|
|
876
|
+
// (round 3): the gate may have RETIRED OTHER rows at GATE-2
|
|
877
|
+
// before the fault that got here — those tombstones are on disk,
|
|
878
|
+
// and naming them beats the "Nothing was written" premise.
|
|
879
|
+
const msg = err instanceof Error && err.message ? err.message : String(err);
|
|
663
880
|
return {
|
|
664
|
-
content:
|
|
881
|
+
content: mutated
|
|
882
|
+
? `memory_update PARTIAL: a step after the durable write failed: ${msg}. ` +
|
|
883
|
+
"Re-running this update reports the duplicate; inspect with memory_evidence."
|
|
884
|
+
: gateDurable.length > 0
|
|
885
|
+
? `memory_update blocked: ${msg} No replacement was written, but the gate had ALREADY retired ` +
|
|
886
|
+
`${gateDurable.length} other row(s) (${gateDurable.join(", ")}): those retirements ARE on ` +
|
|
887
|
+
"disk and their audit lines may not all have landed. Re-running this update will not undo " +
|
|
888
|
+
"them — reconcile with memory_evidence / memory_undo before retrying."
|
|
889
|
+
: `memory_update blocked: ${msg} Nothing was written.`,
|
|
665
890
|
};
|
|
666
891
|
}
|
|
667
892
|
},
|
|
@@ -958,6 +1183,12 @@ const impl = {
|
|
|
958
1183
|
`${t.blocked} blocked by the gate, ${t.skipped} malformed lines skipped.` +
|
|
959
1184
|
(t.downgraded
|
|
960
1185
|
? ` ${t.downgraded} open rows downgraded to settled (missing eligible memory_export header or verifiable repo scope).`
|
|
1186
|
+
: "") +
|
|
1187
|
+
// Rows that landed without their write_promoted line are
|
|
1188
|
+
// durable but invisible to memory_evidence (#155 review) —
|
|
1189
|
+
// the tally owes the reader the count, not silence.
|
|
1190
|
+
(t.unaudited
|
|
1191
|
+
? ` ${t.unaudited} promoted rows landed without their write_promoted audit line (${t.auditError}); memory_evidence will miss them.`
|
|
961
1192
|
: ""),
|
|
962
1193
|
};
|
|
963
1194
|
} catch (err) {
|
|
@@ -1072,8 +1303,10 @@ const impl = {
|
|
|
1072
1303
|
// change, or after a compaction (see the prompt/context/compaction hooks).
|
|
1073
1304
|
// The RENDERED BYTES, not the fingerprint, decide whether the epoch moved
|
|
1074
1305
|
// (issue #162): a write that changes nothing the model is shown must not
|
|
1075
|
-
// cost the next request a full re-prefill.
|
|
1076
|
-
//
|
|
1306
|
+
// cost the next request a full re-prefill. And a pure addition the session
|
|
1307
|
+
// wrote itself does not move them either (#165) — see refreshEpoch. The
|
|
1308
|
+
// shared LRU below may evict the whole session state; a later prompt starts
|
|
1309
|
+
// it fresh.
|
|
1077
1310
|
const epoch = new Map<
|
|
1078
1311
|
string,
|
|
1079
1312
|
{
|
|
@@ -1084,6 +1317,20 @@ const impl = {
|
|
|
1084
1317
|
block: string;
|
|
1085
1318
|
/** Comparison key: every byte of the memory section, joined. */
|
|
1086
1319
|
prefix: string;
|
|
1320
|
+
/**
|
|
1321
|
+
* Rows THIS session had already authored when these bytes were rendered
|
|
1322
|
+
* (#165). The riding-bytes test subtracts everything authored after this
|
|
1323
|
+
* snapshot; if what remains renders identically, the whole difference is
|
|
1324
|
+
* the session's own additions and the bytes keep riding.
|
|
1325
|
+
*/
|
|
1326
|
+
ownRows: Set<string>;
|
|
1327
|
+
/**
|
|
1328
|
+
* The prompt these bytes were scored against. The counterfactual below
|
|
1329
|
+
* has to re-score the SAME inputs, or a topic change between the freeze
|
|
1330
|
+
* and the next write would look like a content change — and the epoch
|
|
1331
|
+
* would pay for a refresh it deliberately refuses to do on a prompt.
|
|
1332
|
+
*/
|
|
1333
|
+
prompt: string;
|
|
1087
1334
|
at: string;
|
|
1088
1335
|
reason: "first" | "store_changed";
|
|
1089
1336
|
refs: MemoryRefs;
|
|
@@ -1184,6 +1431,7 @@ const impl = {
|
|
|
1184
1431
|
const buildMemorySection = async (
|
|
1185
1432
|
sid: string | undefined,
|
|
1186
1433
|
mems: Memory[],
|
|
1434
|
+
promptOverride?: string,
|
|
1187
1435
|
): Promise<{ parts: string[]; block: string; prefix: string; rode: Memory[]; refs: MemoryRefs }> => {
|
|
1188
1436
|
const parts: string[] = [];
|
|
1189
1437
|
await systemDigest(
|
|
@@ -1191,7 +1439,7 @@ const impl = {
|
|
|
1191
1439
|
{ system: parts },
|
|
1192
1440
|
{ rows: mems, frontierBudget: openBudget },
|
|
1193
1441
|
);
|
|
1194
|
-
const prompt = sid === undefined ? "" : latestPrompt.get(sid) ?? "";
|
|
1442
|
+
const prompt = promptOverride ?? (sid === undefined ? "" : latestPrompt.get(sid) ?? "");
|
|
1195
1443
|
// Widen the candidate pool, then cap: the budget decides what rides.
|
|
1196
1444
|
const sel = await selectRelevant(prompt, 5, mems, await useSignals());
|
|
1197
1445
|
const block = sel.block ? capToBudget(sel.block, budget) : "";
|
|
@@ -1220,6 +1468,30 @@ const impl = {
|
|
|
1220
1468
|
epoch.set(sid, { ...cached, version });
|
|
1221
1469
|
return;
|
|
1222
1470
|
}
|
|
1471
|
+
// Riding bytes (#165): a pure addition this session wrote itself is
|
|
1472
|
+
// information it already has — the model produced it, it is in the
|
|
1473
|
+
// transcript. Re-render the section with every row authored SINCE these
|
|
1474
|
+
// bytes were frozen taken back out: if it comes back byte-identical, the
|
|
1475
|
+
// entire difference is attributable to the session's own additions and
|
|
1476
|
+
// the frozen bytes keep riding. Everything else survives into that render
|
|
1477
|
+
// and still busts — a riding row removed or rewritten (blocklist,
|
|
1478
|
+
// hand-redaction, forget, supersession, decay), another session's row, a
|
|
1479
|
+
// viewer edit, an import, a moved convergence line.
|
|
1480
|
+
if (cached) {
|
|
1481
|
+
const mine = authoredFor(sid);
|
|
1482
|
+
const extra = mems.filter((m) => mine.has(m.ts) && !cached.ownRows.has(m.ts));
|
|
1483
|
+
if (extra.length) {
|
|
1484
|
+
const back = await buildMemorySection(
|
|
1485
|
+
sid,
|
|
1486
|
+
mems.filter((m) => !extra.some((e) => e.ts === m.ts)),
|
|
1487
|
+
cached.prompt,
|
|
1488
|
+
);
|
|
1489
|
+
if (back.prefix === cached.prefix) {
|
|
1490
|
+
epoch.set(sid, { ...cached, version });
|
|
1491
|
+
return;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1223
1495
|
const prompt = latestPrompt.get(sid) ?? "";
|
|
1224
1496
|
// Use ledger (#42): the rows that actually rode the block, credited with
|
|
1225
1497
|
// the terms the prompt and those rows shared (never the prompt itself).
|
|
@@ -1233,6 +1505,8 @@ const impl = {
|
|
|
1233
1505
|
parts: built.parts,
|
|
1234
1506
|
block: built.block,
|
|
1235
1507
|
prefix: built.prefix,
|
|
1508
|
+
ownRows: new Set(mems.filter((m) => authoredFor(sid).has(m.ts)).map((m) => m.ts)),
|
|
1509
|
+
prompt,
|
|
1236
1510
|
at,
|
|
1237
1511
|
reason,
|
|
1238
1512
|
refs: built.refs,
|
|
@@ -1599,7 +1873,17 @@ const impl = {
|
|
|
1599
1873
|
? `auto_capture_compaction_${outcome.action}`
|
|
1600
1874
|
: `auto_capture_${outcome.action}`,
|
|
1601
1875
|
// A blocked credential-shaped scope must not reach the evidence log either.
|
|
1602
|
-
|
|
1876
|
+
// The promoted line also carries the audit fault when the
|
|
1877
|
+
// write_promoted line fell (#155 review — capture has no
|
|
1878
|
+
// reply to caveat, so this line is the trail's only note).
|
|
1879
|
+
{
|
|
1880
|
+
session: sid,
|
|
1881
|
+
trigger,
|
|
1882
|
+
type: c.type,
|
|
1883
|
+
scope: redactSecrets(c.scope),
|
|
1884
|
+
reason: outcome.reason ?? "",
|
|
1885
|
+
audit_error: outcome.evidenceError,
|
|
1886
|
+
},
|
|
1603
1887
|
false,
|
|
1604
1888
|
);
|
|
1605
1889
|
}
|
package/src/init.ts
CHANGED
|
@@ -47,6 +47,8 @@ export interface InitSummary {
|
|
|
47
47
|
written: number;
|
|
48
48
|
collapsed: number;
|
|
49
49
|
blocked: number;
|
|
50
|
+
/** Written rows whose write_promoted audit line fell (#155 review). */
|
|
51
|
+
unaudited?: number;
|
|
50
52
|
}
|
|
51
53
|
|
|
52
54
|
const NOTABLE_KEYS = ["test", "e2e", "lint", "typecheck", "check", "build", "format"];
|
|
@@ -247,14 +249,19 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
|
|
|
247
249
|
let written = 0;
|
|
248
250
|
let collapsed = 0;
|
|
249
251
|
let blocked = 0;
|
|
252
|
+
// Promoted rows whose write_promoted audit line fell (#155 review: the
|
|
253
|
+
// fault must be visible to every writer, bookkeeping included).
|
|
254
|
+
let unaudited = 0;
|
|
250
255
|
for (const s of scripts) {
|
|
251
256
|
const content = `${scope} ${s.key} command: run "${s.cmd}" from the repo root (${s.source}).`;
|
|
252
257
|
const outcome = await runWriteGate(
|
|
253
258
|
{ type: "pattern", scope, content, tags: ["init", s.source] },
|
|
254
259
|
gateCtx,
|
|
255
260
|
);
|
|
256
|
-
if (outcome.action === "promoted")
|
|
257
|
-
|
|
261
|
+
if (outcome.action === "promoted") {
|
|
262
|
+
written++;
|
|
263
|
+
if (outcome.evidenceError !== undefined) unaudited++;
|
|
264
|
+
} else if (outcome.action === "collapsed") collapsed++;
|
|
258
265
|
else blocked++;
|
|
259
266
|
}
|
|
260
267
|
|
|
@@ -267,6 +274,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
|
|
|
267
274
|
if (stampOutcome.action === "promoted" && prior && stampOutcome.ts) {
|
|
268
275
|
await markSuperseded(prior.ts, { superseded_by: stampOutcome.ts, reason: "init" });
|
|
269
276
|
}
|
|
277
|
+
if (stampOutcome.action === "promoted" && stampOutcome.evidenceError !== undefined) unaudited++;
|
|
270
278
|
|
|
271
279
|
await record(
|
|
272
280
|
"init_complete",
|
|
@@ -280,6 +288,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
|
|
|
280
288
|
written,
|
|
281
289
|
collapsed,
|
|
282
290
|
blocked,
|
|
291
|
+
unaudited,
|
|
283
292
|
stamp: stampTs ?? "-",
|
|
284
293
|
},
|
|
285
294
|
false,
|
|
@@ -296,6 +305,7 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
|
|
|
296
305
|
written,
|
|
297
306
|
collapsed,
|
|
298
307
|
blocked,
|
|
308
|
+
unaudited,
|
|
299
309
|
};
|
|
300
310
|
}
|
|
301
311
|
|
|
@@ -308,6 +318,8 @@ export function formatInit(s: InitSummary): string {
|
|
|
308
318
|
`Initialized ${s.scope} (root ${s.root}, head ${s.head}).`,
|
|
309
319
|
`Graph: ${s.graph.action}${s.graph.name ? ` (${s.graph.name})` : ""} [mode=${s.graph.mode}]`,
|
|
310
320
|
scr ? `Scripts (${s.scripts.length}):\n${scr}` : "Scripts: none detected",
|
|
311
|
-
`Memories: written=${s.written}, collapsed=${s.collapsed}, blocked=${s.blocked}
|
|
321
|
+
`Memories: written=${s.written}, collapsed=${s.collapsed}, blocked=${s.blocked}` +
|
|
322
|
+
(s.unaudited ? `, ${s.unaudited} without an audit line` : "") +
|
|
323
|
+
`; stamp=${s.stampTs ?? "-"}`,
|
|
312
324
|
].join("\n");
|
|
313
325
|
}
|
package/src/memory.ts
CHANGED
|
@@ -396,7 +396,7 @@ async function stampRow(
|
|
|
396
396
|
// Mark an existing memory as superseded IN PLACE (entry retained, recoverable).
|
|
397
397
|
// Idempotent: a second call is a no-op, so no double `superseded_by`.
|
|
398
398
|
export async function markSuperseded(ts: string, fields: SupersedeFields): Promise<boolean> {
|
|
399
|
-
return (await
|
|
399
|
+
return (await markManySupersededReport([{ ts, fields }])).marked.length > 0;
|
|
400
400
|
}
|
|
401
401
|
|
|
402
402
|
// Batch supersession (#61): one lock acquisition, one read, one snapshot and
|
|
@@ -408,56 +408,68 @@ export async function markSuperseded(ts: string, fields: SupersedeFields): Promi
|
|
|
408
408
|
// so a repeat run marks nothing and writes nothing. Duplicate ts entries in
|
|
409
409
|
// one batch: the FIRST entry's fields win (mirrors row-by-row first-call-wins).
|
|
410
410
|
// Returns the number of rows actually marked.
|
|
411
|
-
export async function markManySuperseded(
|
|
411
|
+
export async function markManySuperseded(entries: { ts: string; fields: SupersedeFields }[]): Promise<number> {
|
|
412
|
+
return (await markManySupersededReport(entries)).marked.length;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// Same operation, reporting WHICH rows retired rather than how many (#158
|
|
416
|
+
// round 3): the write gate needs the ids to keep a durable-mutation ledger,
|
|
417
|
+
// because a failed audit line after a persisted retirement must still be able
|
|
418
|
+
// to name what actually landed. Skipped-by-the-batch rows (already retired
|
|
419
|
+
// out of band) are absent from `marked` — the ledger never claims a retirement
|
|
420
|
+
// this call did not perform.
|
|
421
|
+
export async function markManySupersededReport(
|
|
412
422
|
entries: { ts: string; fields: SupersedeFields }[],
|
|
413
|
-
): Promise<
|
|
414
|
-
if (entries.length === 0) return
|
|
423
|
+
): Promise<{ marked: string[] }> {
|
|
424
|
+
if (entries.length === 0) return { marked: [] };
|
|
415
425
|
const wanted = new Map<string, SupersedeFields>();
|
|
416
426
|
for (const e of entries) if (!wanted.has(e.ts)) wanted.set(e.ts, e.fields);
|
|
417
|
-
|
|
427
|
+
const marked: string[] = [];
|
|
418
428
|
for (const file of await memoryFiles()) {
|
|
419
|
-
marked
|
|
420
|
-
|
|
421
|
-
|
|
429
|
+
marked.push(
|
|
430
|
+
...(await withStoreLock(
|
|
431
|
+
file,
|
|
432
|
+
async () => {
|
|
422
433
|
// #106: identity BEFORE the read, like every other whole-file
|
|
423
434
|
// read-modify-write (#89's contract) - the publish below may retry a
|
|
424
435
|
// Windows handover only while the destination still matches this.
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
436
|
+
const since = await fileIdentity(file);
|
|
437
|
+
const lines = await readLines(file);
|
|
438
|
+
const ids: string[] = [];
|
|
439
|
+
for (let i = 0; i < lines.length; i++) {
|
|
440
|
+
const parsed = parseLine(lines[i]);
|
|
441
|
+
if (!parsed || typeof parsed.superseded_by === "string") continue;
|
|
442
|
+
const fields = typeof parsed.ts === "string" ? wanted.get(parsed.ts) : undefined;
|
|
443
|
+
if (!fields) continue;
|
|
444
|
+
// Whole line rewritten, not extended: an old-format line comes out in
|
|
445
|
+
// the current format with its values unchanged (as markSuperseded did).
|
|
446
|
+
// The one exception is SECRET SCRUB (#128, review probe 4): the
|
|
447
|
+
// fields a merge/decay/update copies into the loser's row carry
|
|
448
|
+
// caller-authored prose (the rotation note "key ghp_... rotated"),
|
|
449
|
+
// and content already scrubs at this same boundary (line 260). The
|
|
450
|
+
// durable row must not be the one place a credential survives when
|
|
451
|
+
// the evidence line beside it was cleaned.
|
|
452
|
+
const clean: SupersedeFields = { ...fields };
|
|
453
|
+
for (const k of Object.keys(clean)) {
|
|
454
|
+
const v = (clean as unknown as Record<string, unknown>)[k];
|
|
455
|
+
if (typeof v === "string") (clean as unknown as Record<string, unknown>)[k] = redactSecrets(v);
|
|
456
|
+
}
|
|
457
|
+
lines[i] = formatLine({ ...parsed, ...clean });
|
|
458
|
+
ids.push(parsed.ts as string);
|
|
445
459
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
},
|
|
454
|
-
LOCK_WRITE,
|
|
460
|
+
if (ids.length === 0) return [];
|
|
461
|
+
await snapshotBefore(file);
|
|
462
|
+
await writeAtomic(file, lines.join("\n") + "\n", since);
|
|
463
|
+
return ids;
|
|
464
|
+
},
|
|
465
|
+
LOCK_WRITE,
|
|
466
|
+
))
|
|
455
467
|
);
|
|
456
468
|
}
|
|
457
469
|
// A ts that appears in several files (should not exist - append mints unique
|
|
458
470
|
// ts) retires in EVERY file here, where the row-by-row loop retired only the
|
|
459
471
|
// first; both are conservation-safe, this one is the more honest tombstone.
|
|
460
|
-
return marked;
|
|
472
|
+
return { marked };
|
|
461
473
|
}
|
|
462
474
|
|
|
463
475
|
// Drop a row's supersession markers IN PLACE (snapshot-first), making it active
|
package/src/portable.ts
CHANGED
|
@@ -194,6 +194,10 @@ export interface ImportTally {
|
|
|
194
194
|
skipped: number;
|
|
195
195
|
/** Open rows downgraded because the file cannot grant that frontier scope. */
|
|
196
196
|
downgraded: number;
|
|
197
|
+
/** Promoted rows whose write_promoted audit line failed to land (#155 review). */
|
|
198
|
+
unaudited: number;
|
|
199
|
+
/** First audit-fault message, so the reply can name what went wrong. */
|
|
200
|
+
auditError?: string;
|
|
197
201
|
}
|
|
198
202
|
|
|
199
203
|
// Recognize the export header line (see EXPORT_HEADER). A version NEWER than
|
|
@@ -277,7 +281,7 @@ function parseRow(line: string): WriteCandidate | null {
|
|
|
277
281
|
// day files, snapshots and the blocklist, none of which are import formats.
|
|
278
282
|
export async function importMemories(
|
|
279
283
|
path: string,
|
|
280
|
-
gate: (c: WriteCandidate) => Promise<{ action: string }>,
|
|
284
|
+
gate: (c: WriteCandidate) => Promise<{ action: string; evidenceError?: string }>,
|
|
281
285
|
// The importing session, captured at tool entry (#127): "the importing
|
|
282
286
|
// session's current repo" must be the CALLER's repo even though this loop
|
|
283
287
|
// awaits the gate on every row, during which a concurrent session can move
|
|
@@ -297,7 +301,7 @@ export async function importMemories(
|
|
|
297
301
|
}
|
|
298
302
|
const file = Bun.file(target);
|
|
299
303
|
if (!(await file.exists())) throw new Error(`import file not found: ${target}`);
|
|
300
|
-
const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0 };
|
|
304
|
+
const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0, unaudited: 0 };
|
|
301
305
|
// #152: the importing session's repository is resolved BEFORE the first row,
|
|
302
306
|
// through the writer rule rather than the ambient one. An unresolved named
|
|
303
307
|
// session has no write target, and half a file re-stamped into whatever
|
|
@@ -339,8 +343,13 @@ export async function importMemories(
|
|
|
339
343
|
tally.downgraded++;
|
|
340
344
|
}
|
|
341
345
|
const outcome = await gate(c);
|
|
342
|
-
if (outcome.action === "promoted")
|
|
343
|
-
|
|
346
|
+
if (outcome.action === "promoted") {
|
|
347
|
+
tally.promoted++;
|
|
348
|
+
if (outcome.evidenceError !== undefined) {
|
|
349
|
+
tally.unaudited++;
|
|
350
|
+
tally.auditError ??= outcome.evidenceError;
|
|
351
|
+
}
|
|
352
|
+
} else if (outcome.action === "collapsed") tally.collapsed++;
|
|
344
353
|
else tally.blocked++;
|
|
345
354
|
}
|
|
346
355
|
return tally;
|
package/src/schema.ts
CHANGED
|
@@ -93,7 +93,10 @@ export const UpdateArgs = z.object({
|
|
|
93
93
|
"Row selector: id (ts), clock fragment, or unique content substring. Omit to target the newest active row of scope+type.",
|
|
94
94
|
)
|
|
95
95
|
.optional(),
|
|
96
|
-
status: z
|
|
96
|
+
status: z
|
|
97
|
+
.enum(STATUSES)
|
|
98
|
+
.describe("Settled or open; omitted keeps the target row's standing (an open frontier row stays open)")
|
|
99
|
+
.optional(),
|
|
97
100
|
});
|
|
98
101
|
|
|
99
102
|
export const ForgetArgs = z.object({
|
package/src/state.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Per-session in-memory state shared by the hooks and the gate pipeline.
|
|
2
2
|
// Deterministic: only tool results and tool invocations mutate it, never the
|
|
3
3
|
// model. Reset between scenario runs with resetState().
|
|
4
|
+
import { SESSION_CAP, SessionLru } from "./sessions.ts";
|
|
4
5
|
|
|
5
6
|
export interface ToolResult {
|
|
6
7
|
call: string;
|
|
@@ -43,6 +44,39 @@ export interface SessionState {
|
|
|
43
44
|
finalized: boolean;
|
|
44
45
|
}
|
|
45
46
|
|
|
47
|
+
// Rows this session promoted, for the riding-bytes rule (#165): a session must
|
|
48
|
+
// not pay a prompt-cache bust to be shown a fact it wrote itself, because that
|
|
49
|
+
// fact is already in its transcript. Filled where a write is promoted (the one
|
|
50
|
+
// place a row is created ON behalf of a named session — the viewer's own writes
|
|
51
|
+
// are deliberately not attributed), read by the epoch refresh.
|
|
52
|
+
//
|
|
53
|
+
// In-process on purpose. Persisting an author field would need a store
|
|
54
|
+
// migration and a privacy review (it records which session wrote what) to cover
|
|
55
|
+
// only the server-restart edge case, and a lost entry degrades to today's
|
|
56
|
+
// behavior — one bust — never to a wrong freeze. Bounded by the same cap as
|
|
57
|
+
// every other session-keyed ledger, so a resident server cannot grow it.
|
|
58
|
+
const authoredRows = new Map<string, Set<string>>();
|
|
59
|
+
const authoredOrder = new SessionLru(SESSION_CAP, (sid) => {
|
|
60
|
+
authoredRows.delete(sid);
|
|
61
|
+
});
|
|
62
|
+
const NO_ROWS: ReadonlySet<string> = new Set();
|
|
63
|
+
|
|
64
|
+
export function noteAuthored(sid: string | undefined, ts: string): void {
|
|
65
|
+
if (!sid || sid === "?") return;
|
|
66
|
+
let rows = authoredRows.get(sid);
|
|
67
|
+
if (!rows) {
|
|
68
|
+
rows = new Set();
|
|
69
|
+
authoredRows.set(sid, rows);
|
|
70
|
+
}
|
|
71
|
+
rows.add(ts);
|
|
72
|
+
authoredOrder.touch(sid);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function authoredFor(sid: string | undefined): ReadonlySet<string> {
|
|
76
|
+
if (!sid) return NO_ROWS;
|
|
77
|
+
return authoredRows.get(sid) ?? NO_ROWS;
|
|
78
|
+
}
|
|
79
|
+
|
|
46
80
|
// Newest message-bearing session seen this process. Opening a session finalizes
|
|
47
81
|
// the previous one (there is no session-end hook on the host surface).
|
|
48
82
|
let lastSeenSidVar: string | null = null;
|
|
@@ -88,6 +122,7 @@ export function getCurrent(): { sid: string; call: string; tool: string } {
|
|
|
88
122
|
|
|
89
123
|
export function resetState(): void {
|
|
90
124
|
sessions.clear();
|
|
125
|
+
authoredRows.clear();
|
|
91
126
|
current = { sid: "?", call: "?", tool: "?" };
|
|
92
127
|
lastSeenSidVar = null;
|
|
93
128
|
}
|
package/src/status.ts
CHANGED
|
@@ -382,9 +382,10 @@ export function cacheLines(p: StatusPayload): string[] {
|
|
|
382
382
|
` cache busts ${st.invalidations} this session · last ${
|
|
383
383
|
st.lastInvalidation ? `${st.lastInvalidation.at.slice(11, 19)} (${st.lastInvalidation.reason})` : "-"
|
|
384
384
|
}`,
|
|
385
|
-
"
|
|
386
|
-
"
|
|
387
|
-
"
|
|
385
|
+
" a memory YOU saved in this session never costs one — you",
|
|
386
|
+
" already said it (#165). A correction, a removal, or a row",
|
|
387
|
+
" another session wrote costs exactly one, and the prefix",
|
|
388
|
+
" re-warms on the following turn",
|
|
388
389
|
];
|
|
389
390
|
const rate = cacheRate(p.measured);
|
|
390
391
|
const receipts = rate
|