opencode-self-improvement 0.15.3 → 0.15.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/capture/candidates.ts +110 -0
- package/src/capture/lag.ts +18 -0
- package/src/capture/prompt.ts +50 -0
- package/src/capture/transcript.ts +59 -0
- package/src/{triggers.ts → capture/triggers.ts} +6 -5
- package/src/{command.ts → command/ensure.ts} +2 -2
- package/src/{consolidate.ts → consolidate/propose.ts} +7 -30
- package/src/consolidate/render.ts +30 -0
- package/src/core/cmp-ts.ts +16 -0
- package/src/core/config/budgets.ts +28 -0
- package/src/{config.ts → core/config/paths.ts} +1 -30
- package/src/core/logfmt/format.ts +82 -0
- package/src/{logfmt.ts → core/logfmt/publish.ts} +3 -92
- package/src/core/logfmt/read.ts +15 -0
- package/src/{state.ts → core/state.ts} +1 -1
- package/src/core/time.ts +6 -0
- package/src/{evidence.ts → evidence/record.ts} +7 -5
- package/src/{gates.ts → gate/gate.ts} +19 -21
- package/src/{resolver.ts → gate/resolver.ts} +1 -1
- package/src/{hits.ts → hits/ledger.ts} +8 -6
- package/src/index.ts +64 -943
- package/src/init/detect.ts +144 -0
- package/src/init/format.ts +25 -0
- package/src/init/run.ts +188 -0
- package/src/inject/anchor.ts +43 -0
- package/src/{attribution.ts → inject/attribution.ts} +2 -2
- package/src/inject/budget.ts +78 -0
- package/src/inject/digest.ts +89 -0
- package/src/{injection-epochs.ts → inject/epochs.ts} +15 -14
- package/src/inject/format.ts +32 -0
- package/src/inject/pull.ts +52 -0
- package/src/inject/version.ts +31 -0
- package/src/portable/decay.ts +20 -0
- package/src/portable/export.ts +194 -0
- package/src/portable/import.ts +173 -0
- package/src/recall/relevant.ts +72 -0
- package/src/recall/score.ts +106 -0
- package/src/recall/shared-terms.ts +15 -0
- package/src/status/format.ts +58 -0
- package/src/status/metrics.ts +65 -0
- package/src/status/payload.ts +143 -0
- package/src/status/report.ts +202 -0
- package/src/status/write.ts +102 -0
- package/src/{blocklist.ts → store/blocklist.ts} +4 -2
- package/src/store/files/append.ts +176 -0
- package/src/store/files/deletions.ts +31 -0
- package/src/store/files/load.ts +106 -0
- package/src/store/files/prune.ts +81 -0
- package/src/store/files/snapshots.ts +88 -0
- package/src/store/files/supersede.ts +123 -0
- package/src/store/files/target.ts +36 -0
- package/src/{lock.ts → store/lock.ts} +1 -1
- package/src/store/model/memory.ts +91 -0
- package/src/store/model/predicates.ts +12 -0
- package/src/store/model/visibility.ts +140 -0
- package/src/{prune.ts → store/prune.ts} +4 -3
- package/src/store/quarantine/release.ts +24 -0
- package/src/store/tombstones/rejection.ts +93 -0
- package/src/{tombstones.ts → store/tombstones/tombstone.ts} +12 -97
- package/src/{undo.ts → store/undo.ts} +6 -3
- package/src/tools/consolidate.ts +42 -0
- package/src/tools/decay.ts +83 -0
- package/src/tools/deps.ts +27 -0
- package/src/tools/evidence.ts +48 -0
- package/src/tools/export.ts +27 -0
- package/src/tools/forget.ts +23 -0
- package/src/tools/import.ts +57 -0
- package/src/tools/init.ts +30 -0
- package/src/tools/list.ts +36 -0
- package/src/tools/merge-review.ts +138 -0
- package/src/tools/recall.ts +72 -0
- package/src/tools/registry.ts +40 -0
- package/src/tools/remember.ts +49 -0
- package/src/{schema.ts → tools/schema.ts} +3 -3
- package/src/tools/status-tool.ts +59 -0
- package/src/tools/undo.ts +57 -0
- package/src/tools/update.ts +342 -0
- package/src/{tui.tsx → tui/panel.tsx} +7 -17
- package/src/viewer/mutate.ts +15 -15
- package/src/viewer/server.ts +10 -8
- package/tsconfig.json +2 -2
- package/tui.ts +1 -1
- package/src/capture.ts +0 -222
- package/src/init.ts +0 -333
- package/src/inject.ts +0 -471
- package/src/memory.ts +0 -851
- package/src/portable.ts +0 -379
- package/src/status.ts +0 -536
- /package/src/{sessions.ts → core/lru.ts} +0 -0
- /package/src/{runtime.ts → core/runtime.ts} +0 -0
- /package/src/{tokenize.ts → core/tokenize.ts} +0 -0
- /package/src/{types.ts → core/types.ts} +0 -0
- /package/src/{host.ts → identity/host-events.ts} +0 -0
- /package/src/{repokey.ts → identity/repokey.ts} +0 -0
- /package/src/{containment.ts → store/containment.ts} +0 -0
- /package/src/{quarantine.ts → store/quarantine/quarantine.ts} +0 -0
- /package/src/{sanitize.ts → store/sanitize.ts} +0 -0
- /package/src/{secrets.ts → store/secrets.ts} +0 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// memory — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
|
|
3
|
+
export type MemoryStatus = "open" | "settled";
|
|
4
|
+
|
|
5
|
+
// Hard ceiling on stored content. No entry point may persist a line longer
|
|
6
|
+
// than this: injection ever shows ~1200 chars, the gate runs on the shared
|
|
7
|
+
// service event loop, and regex scanning over megabyte-scale strings froze
|
|
8
|
+
// sessions (100KB write = 6s, 2MB = hang).
|
|
9
|
+
// Enforced twice — politely in runWriteGate (blocked outcome + evidence),
|
|
10
|
+
// absolutely in appendMemory (throws, covering gate-bypassing callers).
|
|
11
|
+
export const MAX_CONTENT_CHARS = 4000;
|
|
12
|
+
|
|
13
|
+
/** How many retrieval keywords a row may carry, and how long each one may be. */
|
|
14
|
+
export const MAX_KEYWORDS = 8;
|
|
15
|
+
|
|
16
|
+
export const MAX_KEYWORD_CHARS = 48;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Normalise author-supplied retrieval keywords: trim, lowercase, split on the
|
|
20
|
+
* storage delimiter, de-duplicate, drop empties and over-long entries, cap the
|
|
21
|
+
* count. TOTAL on purpose — junk yields a shorter list rather than a throw,
|
|
22
|
+
* because keywords only ever widen recall and must never be able to fail a
|
|
23
|
+
* write the prose alone deserved.
|
|
24
|
+
*/
|
|
25
|
+
export function normalizeKeywords(kw: unknown): string[] | undefined {
|
|
26
|
+
if (!Array.isArray(kw)) return undefined;
|
|
27
|
+
const out: string[] = [];
|
|
28
|
+
for (const item of kw) {
|
|
29
|
+
if (typeof item !== "string") continue;
|
|
30
|
+
// Commas are the storage delimiter (kw serialises as one comma-joined
|
|
31
|
+
// scalar), so an item carrying one would read back fragmented. Treat them
|
|
32
|
+
// as separators: "build, test" becomes two aliases, never a " test".
|
|
33
|
+
for (const part of item.split(",")) {
|
|
34
|
+
const k = part.trim().toLowerCase();
|
|
35
|
+
if (!k || k.length > MAX_KEYWORD_CHARS) continue;
|
|
36
|
+
if (!out.includes(k)) out.push(k);
|
|
37
|
+
if (out.length === MAX_KEYWORDS) break;
|
|
38
|
+
}
|
|
39
|
+
if (out.length === MAX_KEYWORDS) break;
|
|
40
|
+
}
|
|
41
|
+
return out.length ? out : undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface Memory {
|
|
45
|
+
ts: string;
|
|
46
|
+
type: string;
|
|
47
|
+
scope: string;
|
|
48
|
+
content: string;
|
|
49
|
+
issue?: string;
|
|
50
|
+
tags?: string[];
|
|
51
|
+
// Retrieval keywords (#40): author-supplied aliases, verb forms and synonyms
|
|
52
|
+
// for this row, written at capture time. They widen the scoring haystack
|
|
53
|
+
// ONLY — a row is never rendered through them, so injection bytes and the
|
|
54
|
+
// content cap stay exactly what the prose says. This is the zero-embedding
|
|
55
|
+
// answer to the bench's strict-paraphrase wall (0% R@1: the user's words are
|
|
56
|
+
// not the memory's words).
|
|
57
|
+
kw?: string[];
|
|
58
|
+
superseded_by?: string;
|
|
59
|
+
reason?: string;
|
|
60
|
+
status?: MemoryStatus;
|
|
61
|
+
// Origin repo: sha1 of the normalized origin URL, the toplevel
|
|
62
|
+
// path when the repo had no remote, the literal "global" for cross-project
|
|
63
|
+
// writes, or absent for legacy/viewer rows — all three read as described
|
|
64
|
+
// in isVisibleHere().
|
|
65
|
+
repo?: string;
|
|
66
|
+
repoPath?: string;
|
|
67
|
+
file: string;
|
|
68
|
+
index: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Row identity is `ts`: supersede chains, the blocklist, undo matching, and
|
|
72
|
+
// the viewer's action buttons all key off it. A row whose ts is
|
|
73
|
+
// not an ISO instant must never become an addressable live row — readers
|
|
74
|
+
// treat it as malformed: skipped, counted, warned once per file. The shape
|
|
75
|
+
// check lives here (the store knows its schema); logfmt stays a dumb parser.
|
|
76
|
+
export const ISO_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
|
|
77
|
+
|
|
78
|
+
export const malformedWarnedFiles = new Set<string>();
|
|
79
|
+
|
|
80
|
+
// Score one row against a query: exact row id first, then content.
|
|
81
|
+
export function targetScore(m: Memory, query: string): number {
|
|
82
|
+
const ts = m.ts.toLowerCase();
|
|
83
|
+
if (ts === query) return 100;
|
|
84
|
+
// A clock fragment ("00:11:25.867") is unique enough to identify a row.
|
|
85
|
+
if (query.length >= 8 && ts.includes(query)) return 95;
|
|
86
|
+
const content = m.content.toLowerCase();
|
|
87
|
+
if (content === query) return 90;
|
|
88
|
+
if (content.includes(query)) return 80;
|
|
89
|
+
if (query.includes(content)) return 70;
|
|
90
|
+
return 0;
|
|
91
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// predicates — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { isQuarantined } from "../quarantine/quarantine.ts";
|
|
3
|
+
import { type Memory } from "./memory.ts";
|
|
4
|
+
|
|
5
|
+
export function isActive(m: Memory): boolean {
|
|
6
|
+
return !m.superseded_by;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// Quarantine remains durable and reviewable; only model-facing reads withhold it.
|
|
10
|
+
export function isInjectable(m: Memory): boolean {
|
|
11
|
+
return isActive(m) && !isQuarantined(m);
|
|
12
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// visibility — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { repoScopeFor, sessionScope, type RepoScope } from "../../identity/repokey.ts";
|
|
3
|
+
import { getCurrent } from "../../core/state.ts";
|
|
4
|
+
import { parseLine } from "../../core/logfmt/format.ts";
|
|
5
|
+
import { prune } from "../files/prune.ts";
|
|
6
|
+
import { type Memory } from "./memory.ts";
|
|
7
|
+
|
|
8
|
+
// --- repo visibility ---------------------------------------------------------
|
|
9
|
+
// A READER is an immutable caller identity, resolved once at the entry of a
|
|
10
|
+
// flow (a hook, a tool call, a viewer route) and carried through every await
|
|
11
|
+
// in that flow. Resolution must NOT be deferred to filter time: the module
|
|
12
|
+
// global current moves whenever another session's hook or tool dispatches, and
|
|
13
|
+
// a store read awaits filesystem I/O — filtering after the await with the
|
|
14
|
+
// ambient identity injects the OTHER session's repo (#127).
|
|
15
|
+
//
|
|
16
|
+
// repo — the caller's session resolved a repository (its own when
|
|
17
|
+
// bound; the setup location for an unbound session in a
|
|
18
|
+
// single-workspace plugin, exactly the historical semantics).
|
|
19
|
+
// global-only — a plugin flow whose caller identity names no repository:
|
|
20
|
+
// explicit/legacy global rows ONLY. This is the fail-closed
|
|
21
|
+
// answer for an unbound session on a serve host; "unknown"
|
|
22
|
+
// is never "everything".
|
|
23
|
+
// admin — explicit all-repositories access: the standalone viewer and
|
|
24
|
+
// out-of-plugin maintenance callers. Administrative breadth is
|
|
25
|
+
// a property of the entry point, never of a missing session.
|
|
26
|
+
export type Reader =
|
|
27
|
+
| { kind: "repo"; scope: RepoScope }
|
|
28
|
+
| { kind: "global-only" }
|
|
29
|
+
| { kind: "admin" };
|
|
30
|
+
|
|
31
|
+
/** Explicit all-repositories identity (viewer routes, CLI maintenance). */
|
|
32
|
+
export const ADMIN_READER: Reader = { kind: "admin" };
|
|
33
|
+
|
|
34
|
+
// Reader for a plugin-session flow, resolved from the caller's OWN session id
|
|
35
|
+
// captured synchronously at flow entry. Bound session → its repo; unbound →
|
|
36
|
+
// global-only. The module scope is NOT a fallback here: in a process that
|
|
37
|
+
// loaded more than one plugin instance it belongs to whoever set up LAST,
|
|
38
|
+
// which is another workspace (#127's multi-setup gap). Plugin flows bind an
|
|
39
|
+
// unbound caller to their OWN setup location at entry (index.ts), so ordinary
|
|
40
|
+
// single-workspace sessions resolve through the session map, never here.
|
|
41
|
+
export function readerForSession(sid?: unknown): Reader {
|
|
42
|
+
const scope = sessionScope(sid);
|
|
43
|
+
return scope ? { kind: "repo", scope } : { kind: "global-only" };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// The historical AMBIENT reader: live session, then module scope, and no
|
|
47
|
+
// scope at all reads as unpartitioned. Correct only for out-of-plugin callers
|
|
48
|
+
// (viewer, scripts, unit tests) with no concurrent sessions; model-facing
|
|
49
|
+
// plugin paths carry a Reader instead of using this.
|
|
50
|
+
export function readerForAmbient(): Reader {
|
|
51
|
+
const scope = repoScopeFor(getCurrent().sid);
|
|
52
|
+
return scope ? { kind: "repo", scope } : { kind: "admin" };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Ambient-style entry points take an optional sid: a real session id resolves
|
|
56
|
+
// fail-closed through readerForSession; "?" or absent keeps legacy semantics.
|
|
57
|
+
export function readerFromSid(sid?: unknown): Reader {
|
|
58
|
+
return typeof sid === "string" && sid !== "" && sid !== "?"
|
|
59
|
+
? readerForSession(sid)
|
|
60
|
+
: readerForAmbient();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// The ONLY repo filter every read path uses (injection sinks, recall, list,
|
|
64
|
+
// update targeting, prune, decay, gate scope reads). A row is visible when it
|
|
65
|
+
// is global (explicit marker OR no stamp — legacy rows and writes by
|
|
66
|
+
// processes with no scope, e.g. the viewer), or was written in the reader's
|
|
67
|
+
// repo. Keeping it one predicate is what stops the filtering from drifting
|
|
68
|
+
// between entry points.
|
|
69
|
+
export function isVisibleTo(m: Pick<Memory, "repo" | "repoPath">, reader: Reader): boolean {
|
|
70
|
+
if (reader.kind === "admin") return true;
|
|
71
|
+
if (!m.repo || m.repo === "global") return true;
|
|
72
|
+
if (reader.kind === "global-only") return false;
|
|
73
|
+
return m.repo === reader.scope.key || (!!m.repoPath && m.repoPath === reader.scope.path);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function visibleTo(mems: Memory[], reader: Reader): Memory[] {
|
|
77
|
+
return mems.filter((m) => isVisibleTo(m, reader));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// The day-file twin of isVisibleTo for whole-file paths (undo/restore) that
|
|
81
|
+
// work on raw logfmt lines instead of parsed rows: the SAME predicate, with the
|
|
82
|
+
// rows' rule that a line with no stamp is a legacy row, not a private one —
|
|
83
|
+
// which is exactly the rule the evidence lines do NOT share, and the reason
|
|
84
|
+
// these are not one function. An unparseable line has no stamp, so it reads
|
|
85
|
+
// legacy-global rather than silently vanishing under a restore.
|
|
86
|
+
export function lineVisibleTo(line: string, reader: Reader): boolean {
|
|
87
|
+
if (reader.kind === "admin") return true;
|
|
88
|
+
const fields = parseLine(line);
|
|
89
|
+
return isVisibleTo(
|
|
90
|
+
{
|
|
91
|
+
repo: typeof fields?.repo === "string" ? fields.repo : undefined,
|
|
92
|
+
repoPath: typeof fields?.repoPath === "string" ? fields.repoPath : undefined,
|
|
93
|
+
},
|
|
94
|
+
reader,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// The evidence-line twin of isVisibleTo, plus the one rule rows do not need:
|
|
99
|
+
// a missing stamp is NOT the same as a global marker. An explicitly
|
|
100
|
+
// `repo=global` line is global, and a line with no stamp AND no named
|
|
101
|
+
// session (legacy, or an out-of-plugin maintenance write) keeps its
|
|
102
|
+
// historical global reading. But a line a NAMED session wrote while its
|
|
103
|
+
// repository was unresolvable (evidence.ts) belongs to that session alone —
|
|
104
|
+
// visible back to the same session and to the admin surface, never to a
|
|
105
|
+
// stranger's memory_evidence. `callerSid` is the reading session's own id
|
|
106
|
+
// captured at flow entry; without it the private branch can only fail
|
|
107
|
+
// closed (admin sees all, everyone else does not).
|
|
108
|
+
export function evidenceVisibleTo(
|
|
109
|
+
fields: Record<string, unknown>,
|
|
110
|
+
reader: Reader,
|
|
111
|
+
callerSid?: unknown,
|
|
112
|
+
): boolean {
|
|
113
|
+
if (reader.kind === "admin") return true;
|
|
114
|
+
const repo = fields.repo;
|
|
115
|
+
if (typeof repo === "string" && repo !== "") {
|
|
116
|
+
if (repo === "global") return true;
|
|
117
|
+
if (reader.kind === "global-only") return false;
|
|
118
|
+
const repoPath = fields.repoPath;
|
|
119
|
+
return (
|
|
120
|
+
repo === reader.scope.key ||
|
|
121
|
+
(typeof repoPath === "string" && !!repoPath && repoPath === reader.scope.path)
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
const sid = fields.sid;
|
|
125
|
+
if (typeof sid === "string" && sid !== "" && sid !== "?") {
|
|
126
|
+
return typeof callerSid === "string" && callerSid === sid;
|
|
127
|
+
}
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Ambient (out-of-plugin) convenience: resolves the reader at CALL time.
|
|
132
|
+
// Plugin paths must pass an explicit Reader/sid instead of relying on this.
|
|
133
|
+
export function isVisibleHere(m: Memory): boolean {
|
|
134
|
+
return isVisibleTo(m, readerForAmbient());
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Rows visible to the current process (active filtering stays with callers).
|
|
138
|
+
export function visibleHere(mems: Memory[]): Memory[] {
|
|
139
|
+
return mems.filter(isVisibleHere);
|
|
140
|
+
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// Principle 3: a human can prune a bad memory. Deletion is auditable (reason),
|
|
2
2
|
// reversible (snapshot) and never touches a repo. The `prune` evidence line is
|
|
3
3
|
// emitted before/around the mutation so S5 can assert the reason and snapshot.
|
|
4
|
-
import { deletionsFile } from "
|
|
5
|
-
import { prune,
|
|
6
|
-
import {
|
|
4
|
+
import { deletionsFile } from "../core/config/paths.ts";
|
|
5
|
+
import { prune, type PruneResult } from "./files/prune.ts"
|
|
6
|
+
import { readerFromSid } from "./model/visibility.ts";
|
|
7
|
+
import { record } from "../evidence/record.ts";
|
|
7
8
|
|
|
8
9
|
export async function pruneMemory(
|
|
9
10
|
scope: string,
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// release — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { formatLine } from "../../core/logfmt/format.ts";
|
|
4
|
+
import { QUARANTINE_TAG, quarantineReasons } from "./quarantine.ts";
|
|
5
|
+
import { memoryFiles } from "../files/load.ts";
|
|
6
|
+
import { stampRow } from "../files/snapshots.ts";
|
|
7
|
+
|
|
8
|
+
// Human viewer action only. Preserve identity, origin, and all non-quarantine
|
|
9
|
+
// metadata; stampRow snapshots and atomically publishes under the store lock.
|
|
10
|
+
export async function releaseQuarantine(ts: string): Promise<"released" | "not_found" | "not_quarantined"> {
|
|
11
|
+
for (const file of await memoryFiles()) {
|
|
12
|
+
const result = await stampRow(file, ts, (fields) => {
|
|
13
|
+
const tags = typeof fields.tags === "string" ? fields.tags.split(",") : [];
|
|
14
|
+
if (!tags.includes(QUARANTINE_TAG)) return null;
|
|
15
|
+
const scanTags = new Set([QUARANTINE_TAG, ...quarantineReasons({ tags }).map((id) => `quarantine:${id}`)]);
|
|
16
|
+
const kept = tags.filter((tag) => !scanTags.has(tag));
|
|
17
|
+
if (kept.length) fields.tags = kept.join(",");
|
|
18
|
+
else delete fields.tags;
|
|
19
|
+
return formatLine(fields);
|
|
20
|
+
});
|
|
21
|
+
if (result !== null) return result ? "released" : "not_quarantined";
|
|
22
|
+
}
|
|
23
|
+
return "not_found";
|
|
24
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// rejection — split from src/tombstones.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { contentHash } from "../../evidence/record.ts";
|
|
4
|
+
import { memoryRoot } from "../../core/config/paths.ts";
|
|
5
|
+
import { NEAR_FLOOR, NEAR_MIN_SHARED, type Tombstone, differsIn, sketchOf, tombstone, tombstones, valueSigOf } from "./tombstone.ts";
|
|
6
|
+
|
|
7
|
+
const REJECTED_FILENAME = "rejected.logfmt";
|
|
8
|
+
|
|
9
|
+
export type Rejection =
|
|
10
|
+
| { kind: "exact"; tombstone: Tombstone }
|
|
11
|
+
| { kind: "near"; tombstone: Tombstone; score: number; shared: number };
|
|
12
|
+
|
|
13
|
+
/** The dimension on which a strong sketch match is nonetheless a different fact. */
|
|
14
|
+
export type ValueDifference = "numeric_value" | "polarity";
|
|
15
|
+
|
|
16
|
+
/** A sketch match over the floor that was NOT treated as the rejected value. */
|
|
17
|
+
export interface VetoedMatch {
|
|
18
|
+
tombstone: Tombstone;
|
|
19
|
+
score: number;
|
|
20
|
+
shared: number;
|
|
21
|
+
differs: ValueDifference;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface RejectionProbe {
|
|
25
|
+
rejection?: Rejection;
|
|
26
|
+
/** Set only when there is no rejection AND something over the floor was
|
|
27
|
+
* declined. Nothing is enforced from it — it exists so the guard is visible
|
|
28
|
+
* in the field, where "the mechanism never over-blocks" would otherwise be a
|
|
29
|
+
* claim with no evidence either way. */
|
|
30
|
+
vetoed?: VetoedMatch;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function rejectedFile(): string {
|
|
34
|
+
return join(memoryRoot(), REJECTED_FILENAME);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Is this content refused because a human already rejected it?
|
|
39
|
+
*
|
|
40
|
+
* Exact hash first: it is cheap, unambiguous, and the answer a rejection owes.
|
|
41
|
+
* Near-match second, over the whole tombstone set, returning the STRONGEST
|
|
42
|
+
* match rather than the first — the hint names a specific prior rejection, so
|
|
43
|
+
* pointing at a weak one while a better one exists would misreport why the
|
|
44
|
+
* write was refused.
|
|
45
|
+
*
|
|
46
|
+
* A match that {@link differsIn} calls a changed value is skipped, not scored:
|
|
47
|
+
* the guard runs per candidate, so the strongest NON-vetoed match still wins
|
|
48
|
+
* even when a vetoed one scores higher. That case is real — "the service must not
|
|
49
|
+
* enable anonymous access…" scores 0.79 against a rejection of the ENABLE
|
|
50
|
+
* statement (a polarity flip, so correctly not the rejected fact) and 0.70
|
|
51
|
+
* against the rejection of DISABLE, which is what it actually restates.
|
|
52
|
+
*/
|
|
53
|
+
export async function probeRejection(content: string): Promise<RejectionProbe> {
|
|
54
|
+
const all = await tombstones();
|
|
55
|
+
if (all.length === 0) return {};
|
|
56
|
+
const ch = contentHash(content);
|
|
57
|
+
const exact = all.find((t) => t.ch === ch);
|
|
58
|
+
if (exact) return { rejection: { kind: "exact", tombstone: exact } };
|
|
59
|
+
|
|
60
|
+
const sig = sketchOf(content);
|
|
61
|
+
// Below the shared-token floor a near-match cannot fire at all, so short
|
|
62
|
+
// content is refused only ever on an exact match.
|
|
63
|
+
if (sig.length < NEAR_MIN_SHARED) return {};
|
|
64
|
+
const values = valueSigOf(content);
|
|
65
|
+
let best: Extract<Rejection, { kind: "near" }> | undefined;
|
|
66
|
+
let vetoed: VetoedMatch | undefined;
|
|
67
|
+
for (const t of all) {
|
|
68
|
+
if (t.sig.length < NEAR_MIN_SHARED) continue;
|
|
69
|
+
const { score, shared } = jaccardShared(sig, t.sig);
|
|
70
|
+
if (shared < NEAR_MIN_SHARED || score < NEAR_FLOOR) continue;
|
|
71
|
+
const differs = differsIn(values, { num: t.num ?? [], pol: t.pol ?? [] });
|
|
72
|
+
if (differs) {
|
|
73
|
+
if (!vetoed || score > vetoed.score) vetoed = { tombstone: t, score, shared, differs };
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (!best || score > best.score) best = { kind: "near", tombstone: t, score, shared };
|
|
77
|
+
}
|
|
78
|
+
if (best) return { rejection: best };
|
|
79
|
+
return vetoed ? { vetoed } : {};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The verdict without the veto telemetry — see {@link probeRejection}. */
|
|
83
|
+
export async function findRejection(content: string): Promise<Rejection | undefined> {
|
|
84
|
+
return (await probeRejection(content)).rejection;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function jaccardShared(a: string[], b: string[]): { score: number; shared: number } {
|
|
88
|
+
const setB = new Set(b);
|
|
89
|
+
let shared = 0;
|
|
90
|
+
for (const h of a) if (setB.has(h)) shared++;
|
|
91
|
+
const union = a.length + b.length - shared;
|
|
92
|
+
return { score: union === 0 ? 0 : shared / union, shared };
|
|
93
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// tombstone — split from src/tombstones.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
1
2
|
// Value-keyed rejection tombstones (#35).
|
|
2
3
|
//
|
|
3
4
|
// The blocklist keys on `ts` — ROW identity. memory_forget/prune deletes the
|
|
@@ -44,14 +45,14 @@
|
|
|
44
45
|
import { readFile } from "node:fs/promises";
|
|
45
46
|
import { createHash } from "node:crypto";
|
|
46
47
|
import { join } from "node:path";
|
|
47
|
-
import { contentHash } from "
|
|
48
|
-
import {
|
|
49
|
-
import { appendLog, fileIdentity,
|
|
50
|
-
import {
|
|
51
|
-
import {
|
|
52
|
-
import {
|
|
53
|
-
|
|
54
|
-
|
|
48
|
+
import { contentHash } from "../../evidence/record.ts";
|
|
49
|
+
import { formatLine, parseLine } from "../../core/logfmt/format.ts"
|
|
50
|
+
import { appendLog, fileIdentity, writeAtomic } from "../../core/logfmt/publish.ts"
|
|
51
|
+
import { readLines } from "../../core/logfmt/read.ts";
|
|
52
|
+
import { withStoreLock, LOCK_WRITE } from "../lock.ts";
|
|
53
|
+
import { redactSecrets } from "../secrets.ts";
|
|
54
|
+
import { STOPWORDS, tokens, numericTokens, polaritySigns } from "../../core/tokenize.ts";
|
|
55
|
+
import { type Rejection, type ValueDifference, findRejection, rejectedFile } from "./rejection.ts";
|
|
55
56
|
|
|
56
57
|
/** How many lowest token-hashes the sketch keeps. */
|
|
57
58
|
const SKETCH_SIZE = 64;
|
|
@@ -91,7 +92,8 @@ const TOKEN_HASH_CHARS = 8;
|
|
|
91
92
|
* an exact match.
|
|
92
93
|
*/
|
|
93
94
|
export const NEAR_FLOOR = 0.4;
|
|
94
|
-
|
|
95
|
+
|
|
96
|
+
export const NEAR_MIN_SHARED = 6;
|
|
95
97
|
|
|
96
98
|
export interface Tombstone {
|
|
97
99
|
ch: string;
|
|
@@ -115,34 +117,6 @@ export interface Tombstone {
|
|
|
115
117
|
pol?: string[];
|
|
116
118
|
}
|
|
117
119
|
|
|
118
|
-
export type Rejection =
|
|
119
|
-
| { kind: "exact"; tombstone: Tombstone }
|
|
120
|
-
| { kind: "near"; tombstone: Tombstone; score: number; shared: number };
|
|
121
|
-
|
|
122
|
-
/** The dimension on which a strong sketch match is nonetheless a different fact. */
|
|
123
|
-
export type ValueDifference = "numeric_value" | "polarity";
|
|
124
|
-
|
|
125
|
-
/** A sketch match over the floor that was NOT treated as the rejected value. */
|
|
126
|
-
export interface VetoedMatch {
|
|
127
|
-
tombstone: Tombstone;
|
|
128
|
-
score: number;
|
|
129
|
-
shared: number;
|
|
130
|
-
differs: ValueDifference;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
export interface RejectionProbe {
|
|
134
|
-
rejection?: Rejection;
|
|
135
|
-
/** Set only when there is no rejection AND something over the floor was
|
|
136
|
-
* declined. Nothing is enforced from it — it exists so the guard is visible
|
|
137
|
-
* in the field, where "the mechanism never over-blocks" would otherwise be a
|
|
138
|
-
* claim with no evidence either way. */
|
|
139
|
-
vetoed?: VetoedMatch;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
export function rejectedFile(): string {
|
|
143
|
-
return join(memoryRoot(), REJECTED_FILENAME);
|
|
144
|
-
}
|
|
145
|
-
|
|
146
120
|
function tokenHash(token: string): string {
|
|
147
121
|
return createHash("sha1").update(token).digest("hex").slice(0, TOKEN_HASH_CHARS);
|
|
148
122
|
}
|
|
@@ -219,7 +193,7 @@ export function valueSigOf(content: string): ValueSig {
|
|
|
219
193
|
* near-match decides exactly as it shipped (every row from here on carries
|
|
220
194
|
* both signatures, so that degradation does not grow).
|
|
221
195
|
*/
|
|
222
|
-
function differsIn(a: ValueSig, b: ValueSig): ValueDifference | undefined {
|
|
196
|
+
export function differsIn(a: ValueSig, b: ValueSig): ValueDifference | undefined {
|
|
223
197
|
if (moved(a.num, b.num)) return "numeric_value";
|
|
224
198
|
if (moved(a.pol, b.pol)) return "polarity";
|
|
225
199
|
return undefined;
|
|
@@ -233,7 +207,6 @@ function moved(a: string[], b: string[]): boolean {
|
|
|
233
207
|
return a.some((x) => !sb.has(x)) && b.some((y) => !sa.has(y));
|
|
234
208
|
}
|
|
235
209
|
|
|
236
|
-
|
|
237
210
|
/**
|
|
238
211
|
* The tombstone set, cached against the file's change token.
|
|
239
212
|
*
|
|
@@ -363,64 +336,6 @@ export async function tombstone(
|
|
|
363
336
|
return { ch: chs[0], recorded: recorded > 0 };
|
|
364
337
|
}
|
|
365
338
|
|
|
366
|
-
/**
|
|
367
|
-
* Is this content refused because a human already rejected it?
|
|
368
|
-
*
|
|
369
|
-
* Exact hash first: it is cheap, unambiguous, and the answer a rejection owes.
|
|
370
|
-
* Near-match second, over the whole tombstone set, returning the STRONGEST
|
|
371
|
-
* match rather than the first — the hint names a specific prior rejection, so
|
|
372
|
-
* pointing at a weak one while a better one exists would misreport why the
|
|
373
|
-
* write was refused.
|
|
374
|
-
*
|
|
375
|
-
* A match that {@link differsIn} calls a changed value is skipped, not scored:
|
|
376
|
-
* the guard runs per candidate, so the strongest NON-vetoed match still wins
|
|
377
|
-
* even when a vetoed one scores higher. That case is real — "the service must not
|
|
378
|
-
* enable anonymous access…" scores 0.79 against a rejection of the ENABLE
|
|
379
|
-
* statement (a polarity flip, so correctly not the rejected fact) and 0.70
|
|
380
|
-
* against the rejection of DISABLE, which is what it actually restates.
|
|
381
|
-
*/
|
|
382
|
-
export async function probeRejection(content: string): Promise<RejectionProbe> {
|
|
383
|
-
const all = await tombstones();
|
|
384
|
-
if (all.length === 0) return {};
|
|
385
|
-
const ch = contentHash(content);
|
|
386
|
-
const exact = all.find((t) => t.ch === ch);
|
|
387
|
-
if (exact) return { rejection: { kind: "exact", tombstone: exact } };
|
|
388
|
-
|
|
389
|
-
const sig = sketchOf(content);
|
|
390
|
-
// Below the shared-token floor a near-match cannot fire at all, so short
|
|
391
|
-
// content is refused only ever on an exact match.
|
|
392
|
-
if (sig.length < NEAR_MIN_SHARED) return {};
|
|
393
|
-
const values = valueSigOf(content);
|
|
394
|
-
let best: Extract<Rejection, { kind: "near" }> | undefined;
|
|
395
|
-
let vetoed: VetoedMatch | undefined;
|
|
396
|
-
for (const t of all) {
|
|
397
|
-
if (t.sig.length < NEAR_MIN_SHARED) continue;
|
|
398
|
-
const { score, shared } = jaccardShared(sig, t.sig);
|
|
399
|
-
if (shared < NEAR_MIN_SHARED || score < NEAR_FLOOR) continue;
|
|
400
|
-
const differs = differsIn(values, { num: t.num ?? [], pol: t.pol ?? [] });
|
|
401
|
-
if (differs) {
|
|
402
|
-
if (!vetoed || score > vetoed.score) vetoed = { tombstone: t, score, shared, differs };
|
|
403
|
-
continue;
|
|
404
|
-
}
|
|
405
|
-
if (!best || score > best.score) best = { kind: "near", tombstone: t, score, shared };
|
|
406
|
-
}
|
|
407
|
-
if (best) return { rejection: best };
|
|
408
|
-
return vetoed ? { vetoed } : {};
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
/** The verdict without the veto telemetry — see {@link probeRejection}. */
|
|
412
|
-
export async function findRejection(content: string): Promise<Rejection | undefined> {
|
|
413
|
-
return (await probeRejection(content)).rejection;
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
function jaccardShared(a: string[], b: string[]): { score: number; shared: number } {
|
|
417
|
-
const setB = new Set(b);
|
|
418
|
-
let shared = 0;
|
|
419
|
-
for (const h of a) if (setB.has(h)) shared++;
|
|
420
|
-
const union = a.length + b.length - shared;
|
|
421
|
-
return { score: union === 0 ? 0 : shared / union, shared };
|
|
422
|
-
}
|
|
423
|
-
|
|
424
339
|
/**
|
|
425
340
|
* Lift a tombstone. Human-only by construction: this is exported to the
|
|
426
341
|
* viewer's mutation layer and NEVER wired to a plugin tool. A blocked model
|
|
@@ -26,11 +26,14 @@
|
|
|
26
26
|
// restore exactly as it was.
|
|
27
27
|
import { lstat, readFile, realpath, stat } from "node:fs/promises";
|
|
28
28
|
import { basename, isAbsolute, join, relative, resolve } from "node:path";
|
|
29
|
-
import { deletionsFile, snapshotDir } from "
|
|
29
|
+
import { deletionsFile, snapshotDir } from "../core/config/paths.ts";
|
|
30
30
|
import { isWithin } from "./containment.ts";
|
|
31
|
-
import {
|
|
31
|
+
import { parseLine } from "../core/logfmt/format.ts"
|
|
32
|
+
import { ensureDir, fileIdentity, writeAtomic } from "../core/logfmt/publish.ts"
|
|
33
|
+
import { readLines } from "../core/logfmt/read.ts";
|
|
32
34
|
import { withStoreLock, LOCK_RESTORE } from "./lock.ts";
|
|
33
|
-
import {
|
|
35
|
+
import { snapshotFiles } from "./files/snapshots.ts"
|
|
36
|
+
import { ADMIN_READER, lineVisibleTo, type Reader } from "./model/visibility.ts";
|
|
34
37
|
|
|
35
38
|
const SNAPSHOT_NAME = /^(\d+)-(\d{4}-\d{2}-\d{2}\.logfmt)$/;
|
|
36
39
|
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// The memory_consolidate tool, extracted from index.ts (#168). Schema, description
|
|
2
|
+
// and handler are byte-identical to the pre-split source; closure access arrives
|
|
3
|
+
// through ToolDeps.
|
|
4
|
+
import type { ToolRegister } from "./deps.ts";
|
|
5
|
+
import { proposeConsolidations } from "../consolidate/propose.ts"
|
|
6
|
+
import { renderProposals } from "../consolidate/render.ts";
|
|
7
|
+
import { record } from "../evidence/record.ts";
|
|
8
|
+
import { readLedger, readReads } from "../hits/ledger.ts";
|
|
9
|
+
import { loadAll } from "../store/files/load.ts"
|
|
10
|
+
import { isInjectable } from "../store/model/predicates.ts"
|
|
11
|
+
import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
|
|
12
|
+
import { ConsolidateArgs, validated } from "./schema.ts";
|
|
13
|
+
|
|
14
|
+
export const register: ToolRegister = (editor, deps) => {
|
|
15
|
+
const { toolIds, direct } = deps;
|
|
16
|
+
editor.add(validated(ConsolidateArgs, {
|
|
17
|
+
name: "memory_consolidate",
|
|
18
|
+
description:
|
|
19
|
+
"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.",
|
|
20
|
+
options: direct,
|
|
21
|
+
async execute(args, context): Promise<{ content: string }> {
|
|
22
|
+
const { sid } = toolIds(context);
|
|
23
|
+
const reader = readerFromSid(sid);
|
|
24
|
+
const all = (await loadAll()).filter(isInjectable).filter((m) => isVisibleTo(m, reader));
|
|
25
|
+
const rows = args.scope ? all.filter((m) => m.scope === args.scope) : all;
|
|
26
|
+
const ledger = await readLedger();
|
|
27
|
+
const use = ledger.byRow;
|
|
28
|
+
const reads = await readReads();
|
|
29
|
+
const report = proposeConsolidations(rows, use, reads, {
|
|
30
|
+
...(args.jaccard !== undefined ? { jaccard: args.jaccard } : {}),
|
|
31
|
+
});
|
|
32
|
+
const shown = report.plans.slice(0, args.limit ?? 10);
|
|
33
|
+
const out = renderProposals({ ...report, plans: shown });
|
|
34
|
+
await record(
|
|
35
|
+
"consolidate_propose",
|
|
36
|
+
{ clusters: shown.length, rows: report.rowsBefore, would_drop: report.rowsBefore - report.rowsAfter },
|
|
37
|
+
false,
|
|
38
|
+
);
|
|
39
|
+
return { content: out };
|
|
40
|
+
},
|
|
41
|
+
}));
|
|
42
|
+
};
|