opencode-self-improvement 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -1
- package/package.json +2 -1
- package/src/capture/candidates.ts +37 -1
- package/src/capture/guided-rules.ts +198 -0
- package/src/capture/lag.ts +11 -1
- package/src/capture/prompt.ts +23 -0
- package/src/capture/runtime.ts +244 -23
- package/src/capture/transcript.ts +24 -0
- package/src/core/hooks.ts +18 -0
- package/src/gate/gate.ts +5 -0
- package/src/index.ts +8 -0
- package/src/inject/budget.ts +8 -2
- package/src/inject/epochs.ts +74 -5
- package/src/inject/format.ts +8 -1
- package/src/recall/conflicts.ts +247 -0
- package/src/recall/relevant.ts +47 -4
- package/src/store/blocklist.ts +1 -1
- package/src/store/files/append.ts +96 -55
- package/src/store/files/deletions.ts +1 -1
- package/src/store/files/load.ts +99 -2
- package/src/store/files/prune.ts +14 -7
- package/src/store/files/snapshots.ts +3 -3
- package/src/store/files/supersede.ts +125 -74
- package/src/store/lock.ts +17 -1
- package/src/store/model/memory.ts +62 -0
- package/src/store/model/predicates.ts +1 -1
- package/src/store/model/visibility.ts +4 -4
- package/src/store/prune.ts +2 -2
- package/src/store/quarantine/quarantine.ts +12 -3
- package/src/store/quarantine/release.ts +34 -17
- package/src/store/tombstones/rejection.ts +3 -3
- package/src/store/tombstones/tombstone.ts +9 -8
- package/src/store/undo.ts +4 -4
- package/src/tools/update.ts +19 -7
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
// Contradiction surface (POC, bench FINDINGS §4). A user-guided row may
|
|
2
|
+
// declare ref (the code symbol its value is about), claim (the user's value)
|
|
3
|
+
// and klass (who holds authority). At render time the plugin reads the code —
|
|
4
|
+
// bounded, deterministic, NO model call — and a collision renders ONE flagged
|
|
5
|
+
// CONFLICT line whose Action is fixed by the class: behavior class trusts the
|
|
6
|
+
// code, spec class fixes it. #345 measured the alternative twice: a wrong
|
|
7
|
+
// guided row made the agent rewrite a correct constant (raw row) and the
|
|
8
|
+
// framing-only fix stayed a coin flip (2 harms in 5). The class rule held 6/6.
|
|
9
|
+
import {
|
|
10
|
+
closeSync,
|
|
11
|
+
fstatSync,
|
|
12
|
+
lstatSync,
|
|
13
|
+
openSync,
|
|
14
|
+
readSync,
|
|
15
|
+
readdirSync,
|
|
16
|
+
type Dirent,
|
|
17
|
+
} from "node:fs";
|
|
18
|
+
import { createRequire } from "node:module";
|
|
19
|
+
import { extname, join, relative } from "node:path";
|
|
20
|
+
import type { Expression } from "@babel/types";
|
|
21
|
+
import { type Memory } from "../store/model/memory.ts";
|
|
22
|
+
|
|
23
|
+
export interface CodeFact {
|
|
24
|
+
/** Repo-relative path where the declaration was read. */
|
|
25
|
+
file: string;
|
|
26
|
+
/** The declared literal, verbatim (trimmed). */
|
|
27
|
+
value: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Bounded source scan: cap files, bytes per file, and directory depth. When
|
|
31
|
+
// a relevant source cannot be decided, keep the row's plain caveat.
|
|
32
|
+
const MAX_FILES = 300;
|
|
33
|
+
const MAX_FILE_BYTES = 256 * 1024;
|
|
34
|
+
const SCAN_DEPTH = 3;
|
|
35
|
+
const EXTENSIONS = new Set([".ts", ".tsx", ".js", ".mjs", ".cjs"]);
|
|
36
|
+
const SKIP_DIRS = new Set([
|
|
37
|
+
"node_modules",
|
|
38
|
+
".git",
|
|
39
|
+
"dist",
|
|
40
|
+
"build",
|
|
41
|
+
".opencode",
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
function walk(dir: string, depth: number, out: string[]): void {
|
|
45
|
+
if (depth > SCAN_DEPTH || out.length > MAX_FILES) return;
|
|
46
|
+
let entries: Dirent[];
|
|
47
|
+
try {
|
|
48
|
+
// Never turn a src/ link or a linked child into an out-of-repo code fact.
|
|
49
|
+
if (!lstatSync(dir).isDirectory()) return;
|
|
50
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
51
|
+
} catch {
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
for (const e of entries.sort((a, b) =>
|
|
55
|
+
a.name < b.name ? -1 : a.name > b.name ? 1 : 0,
|
|
56
|
+
)) {
|
|
57
|
+
if (out.length > MAX_FILES) return;
|
|
58
|
+
if (e.isDirectory()) {
|
|
59
|
+
if (!SKIP_DIRS.has(e.name) && !e.name.startsWith("."))
|
|
60
|
+
walk(join(dir, e.name), depth + 1, out);
|
|
61
|
+
} else if (e.isFile()) {
|
|
62
|
+
const dot = e.name.lastIndexOf(".");
|
|
63
|
+
if (dot >= 0 && EXTENSIONS.has(e.name.slice(dot)))
|
|
64
|
+
out.push(join(dir, e.name));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Load the parser only for an actual code check, never on the opt-out path.
|
|
70
|
+
const require = createRequire(import.meta.url);
|
|
71
|
+
let parser: typeof import("@babel/parser") | undefined;
|
|
72
|
+
const sourceParser = (): typeof import("@babel/parser") =>
|
|
73
|
+
(parser ??= require("@babel/parser"));
|
|
74
|
+
|
|
75
|
+
function literalValue(
|
|
76
|
+
node: Expression | null | undefined,
|
|
77
|
+
): string | number | boolean | null | undefined {
|
|
78
|
+
if (!node) return undefined;
|
|
79
|
+
switch (node.type) {
|
|
80
|
+
case "StringLiteral":
|
|
81
|
+
case "BooleanLiteral":
|
|
82
|
+
return node.value;
|
|
83
|
+
case "NullLiteral":
|
|
84
|
+
return null;
|
|
85
|
+
case "NumericLiteral":
|
|
86
|
+
return Number.isFinite(node.value) ? node.value : undefined;
|
|
87
|
+
case "UnaryExpression": {
|
|
88
|
+
if (
|
|
89
|
+
node.argument.type !== "NumericLiteral" ||
|
|
90
|
+
!["+", "-"].includes(node.operator)
|
|
91
|
+
)
|
|
92
|
+
return undefined;
|
|
93
|
+
const value = (node.operator === "-" ? -1 : 1) * node.argument.value;
|
|
94
|
+
return Number.isFinite(value) ? value : undefined;
|
|
95
|
+
}
|
|
96
|
+
default:
|
|
97
|
+
return undefined;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** null = target found but undecidable; undefined = no top-level declaration. */
|
|
102
|
+
function declaration(
|
|
103
|
+
text: string,
|
|
104
|
+
file: string,
|
|
105
|
+
ref: string,
|
|
106
|
+
): string | null | undefined {
|
|
107
|
+
const extension = extname(file);
|
|
108
|
+
const plugins: import("@babel/parser").ParserPlugin[] = [];
|
|
109
|
+
if (extension === ".ts" || extension === ".tsx") plugins.push("typescript");
|
|
110
|
+
if (extension === ".tsx") plugins.push("jsx");
|
|
111
|
+
const tree = sourceParser().parse(text, {
|
|
112
|
+
sourceType: "unambiguous",
|
|
113
|
+
plugins,
|
|
114
|
+
});
|
|
115
|
+
let found: string | undefined;
|
|
116
|
+
for (const statement of tree.program.body) {
|
|
117
|
+
const candidate =
|
|
118
|
+
statement.type === "ExportNamedDeclaration"
|
|
119
|
+
? statement.declaration
|
|
120
|
+
: statement;
|
|
121
|
+
if (candidate?.type !== "VariableDeclaration" || candidate.kind !== "const")
|
|
122
|
+
continue;
|
|
123
|
+
for (const binding of candidate.declarations) {
|
|
124
|
+
if (binding.id.type !== "Identifier" || binding.id.name !== ref) continue;
|
|
125
|
+
if (
|
|
126
|
+
found !== undefined ||
|
|
127
|
+
literalValue(binding.init) === undefined ||
|
|
128
|
+
binding.init?.start == null ||
|
|
129
|
+
binding.init.end == null
|
|
130
|
+
)
|
|
131
|
+
return null;
|
|
132
|
+
found = text.slice(binding.init.start, binding.init.end);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return found;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function readBounded(file: string): string | undefined {
|
|
139
|
+
const fd = openSync(file, "r");
|
|
140
|
+
try {
|
|
141
|
+
const stat = fstatSync(fd);
|
|
142
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return undefined;
|
|
143
|
+
// Bound the read too: a file growing after stat cannot make this path
|
|
144
|
+
// allocate/read an arbitrarily large source file.
|
|
145
|
+
const bytes = Buffer.alloc(MAX_FILE_BYTES + 1);
|
|
146
|
+
let length = 0;
|
|
147
|
+
while (length < bytes.length) {
|
|
148
|
+
const count = readSync(fd, bytes, length, bytes.length - length, length);
|
|
149
|
+
if (!count) break;
|
|
150
|
+
length += count;
|
|
151
|
+
}
|
|
152
|
+
return length > MAX_FILE_BYTES
|
|
153
|
+
? undefined
|
|
154
|
+
: bytes.toString("utf8", 0, length);
|
|
155
|
+
} finally {
|
|
156
|
+
closeSync(fd);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* A unique top-level `const REF = <literal>` in the bounded scan (src/
|
|
162
|
+
* preferred, whole repo fallback). Comments/strings are never declarations.
|
|
163
|
+
* Duplicate names, invalid source and computed initializers cannot decide —
|
|
164
|
+
* a behavior implemented as computed logic is deliberately not guessed: the
|
|
165
|
+
* caller keeps the plain row and its verify-against-code caveat instead.
|
|
166
|
+
*/
|
|
167
|
+
export function findConstant(dir: string, ref: string): CodeFact | null {
|
|
168
|
+
const files: string[] = [];
|
|
169
|
+
walk(join(dir, "src"), 0, files);
|
|
170
|
+
if (!files.length) walk(dir, 0, files);
|
|
171
|
+
if (files.length > MAX_FILES) return null;
|
|
172
|
+
let fact: CodeFact | null = null;
|
|
173
|
+
for (const f of files) {
|
|
174
|
+
try {
|
|
175
|
+
const text = readBounded(f);
|
|
176
|
+
if (text === undefined) return null;
|
|
177
|
+
if (!text.includes(ref) && !text.includes("\\u")) continue;
|
|
178
|
+
const value = declaration(text, f, ref);
|
|
179
|
+
if (value === null || (value !== undefined && fact)) return null;
|
|
180
|
+
if (value !== undefined) fact = { file: relative(dir, f), value };
|
|
181
|
+
} catch {
|
|
182
|
+
// A relevant unreadable/invalid source is not evidence of absence.
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return fact;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Numeric-aware agreement: "$50.00" == "50", "0.0825" == "0.0825", and a
|
|
191
|
+
* percent claim matches the fraction it names ("8.25%" == "0.0825"). String
|
|
192
|
+
* whitespace is significant. Undefined means the claim cannot decide the
|
|
193
|
+
* observed literal's value — the caller must keep plain guidance.
|
|
194
|
+
*/
|
|
195
|
+
export function valuesAgree(claim: string, code: string): boolean | undefined {
|
|
196
|
+
try {
|
|
197
|
+
const observed = literalValue(sourceParser().parseExpression(code));
|
|
198
|
+
if (observed === undefined) return undefined;
|
|
199
|
+
let stated = claim.trim();
|
|
200
|
+
if (stated.startsWith('"') || stated.startsWith("'")) {
|
|
201
|
+
const decoded = literalValue(sourceParser().parseExpression(stated));
|
|
202
|
+
if (typeof decoded !== "string") return undefined;
|
|
203
|
+
stated = decoded;
|
|
204
|
+
}
|
|
205
|
+
const numeric = (s: string): number | undefined => {
|
|
206
|
+
if (
|
|
207
|
+
!/^[+-]?\$?(?:(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?%?$/i.test(
|
|
208
|
+
s,
|
|
209
|
+
)
|
|
210
|
+
)
|
|
211
|
+
return undefined;
|
|
212
|
+
const [mantissa, exponent = "0"] = s.replace(/[$,%]/g, "").split(/e/i);
|
|
213
|
+
// Shift before converting: dividing an already-rounded float (8.2/100)
|
|
214
|
+
// invents a mismatch with the literal 0.082.
|
|
215
|
+
const n = Number(
|
|
216
|
+
`${mantissa}e${Number(exponent) - (s.endsWith("%") ? 2 : 0)}`,
|
|
217
|
+
);
|
|
218
|
+
return Number.isFinite(n) ? n : undefined;
|
|
219
|
+
};
|
|
220
|
+
const value = numeric(stated);
|
|
221
|
+
if (typeof observed === "number")
|
|
222
|
+
return value === undefined ? undefined : value === observed;
|
|
223
|
+
if (typeof observed === "string") {
|
|
224
|
+
const n = numeric(observed);
|
|
225
|
+
return n !== undefined && value !== undefined
|
|
226
|
+
? n === value
|
|
227
|
+
: stated === observed;
|
|
228
|
+
}
|
|
229
|
+
if (observed === null) return stated === "null" ? true : undefined;
|
|
230
|
+
return stated === "true" || stated === "false"
|
|
231
|
+
? (stated === "true") === observed
|
|
232
|
+
: undefined;
|
|
233
|
+
} catch {
|
|
234
|
+
return undefined;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** The one flagged object: both facts, the provenance, the FIXED verdict. */
|
|
239
|
+
export function conflictLine(m: Memory, fact: CodeFact): string {
|
|
240
|
+
return (
|
|
241
|
+
`CONFLICT (${m.ref}). Memory: ${m.claim} — user-stated, never verified. ` +
|
|
242
|
+
`Code today: ${m.ref} = ${fact.value} (observed in ${fact.file}). ` +
|
|
243
|
+
(m.klass === "spec"
|
|
244
|
+
? `Class: spec — the user is the authority on this value. Action: the code is the bug; fix ${m.ref} to ${m.claim}.`
|
|
245
|
+
: `Class: behavior — working code is the authority. Action: trust the code; do not edit ${m.ref}; if the remembered rule looks intentional, raise it with the user instead.`)
|
|
246
|
+
);
|
|
247
|
+
}
|
package/src/recall/relevant.ts
CHANGED
|
@@ -5,7 +5,8 @@ import { isInjectable } from "../store/model/predicates.ts";
|
|
|
5
5
|
import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
|
|
6
6
|
import { FRAME } from "../inject/budget.ts";
|
|
7
7
|
import { formatMemory } from "../inject/format.ts";
|
|
8
|
-
import {
|
|
8
|
+
import { conflictLine, findConstant, valuesAgree } from "./conflicts.ts";
|
|
9
|
+
import { USER_GUIDED_TAG } from "../core/tags.ts";
|
|
9
10
|
import { cmpTs } from "../core/cmp-ts.ts";
|
|
10
11
|
import { scoreMemories } from "./score.ts";
|
|
11
12
|
|
|
@@ -59,6 +60,18 @@ export interface SelectOptions {
|
|
|
59
60
|
* and pull leave this off and stay query-driven.
|
|
60
61
|
*/
|
|
61
62
|
guidedCap?: number;
|
|
63
|
+
/**
|
|
64
|
+
* Contradiction surface (POC): when true, a user-guided row that declares
|
|
65
|
+
* ref/claim/klass is code-checked at render time. A collision replaces the
|
|
66
|
+
* row's rendered text with one flagged CONFLICT line whose Action is fixed
|
|
67
|
+
* by the class. Detection is a bounded file scan — deterministic, no model.
|
|
68
|
+
*/
|
|
69
|
+
conflictCheck?: boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Repo directory the code check reads. Absent (or a non-repo reader) means
|
|
72
|
+
* no check: rows render plainly, exactly as before the feature.
|
|
73
|
+
*/
|
|
74
|
+
repoDir?: string;
|
|
62
75
|
}
|
|
63
76
|
|
|
64
77
|
/** Row carries the hint-channel tag (written by capture for user-stated facts). */
|
|
@@ -76,6 +89,15 @@ export function isUserGuided(m: Memory): boolean {
|
|
|
76
89
|
const GUIDED_CAVEAT =
|
|
77
90
|
"; user-stated guidance may be stale — verify against the current code before changing behavior it contradicts";
|
|
78
91
|
|
|
92
|
+
// Measured (arm F run 2.1): with a code-checked CONFLICT row riding, the
|
|
93
|
+
// plain caveat plus a captured "trust code over docs" row pushed the agent
|
|
94
|
+
// to file the CONFLICT row with the stale-doc decoys — the blanket rule beat
|
|
95
|
+
// the specific verdict. When a CONFLICT row rides, the header states the
|
|
96
|
+
// verification is ALREADY done and its Action governs; the staleness warning
|
|
97
|
+
// stays for everything else.
|
|
98
|
+
const CONFLICT_CAVEAT =
|
|
99
|
+
"; CONFLICT rows were code-checked against this repo's current source — follow their Action; other user-stated guidance may be stale, verify against the current code before changing behavior it contradicts";
|
|
100
|
+
|
|
79
101
|
export async function selectRelevant(
|
|
80
102
|
message: string,
|
|
81
103
|
limit = 3,
|
|
@@ -83,7 +105,11 @@ export async function selectRelevant(
|
|
|
83
105
|
use?: UseSignals,
|
|
84
106
|
sid?: string,
|
|
85
107
|
opts?: SelectOptions,
|
|
86
|
-
): Promise<{
|
|
108
|
+
): Promise<{
|
|
109
|
+
block: string;
|
|
110
|
+
selected: Memory[];
|
|
111
|
+
rendered: ReadonlyMap<Memory, Memory>;
|
|
112
|
+
}> {
|
|
87
113
|
// Repo-scoped: model-facing reads see the caller's repo + global rows
|
|
88
114
|
// (their session when one was threaded, #127).
|
|
89
115
|
const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(
|
|
@@ -96,13 +122,30 @@ export async function selectRelevant(
|
|
|
96
122
|
.sort((a, b) => cmpTs(b.ts, a.ts))
|
|
97
123
|
.slice(0, cap)
|
|
98
124
|
: [];
|
|
125
|
+
// Contradiction surface: code-check the guided rows that declared a ref.
|
|
126
|
+
// Only the RENDERED row changes (a shallow copy carries the CONFLICT text);
|
|
127
|
+
// `selected` keeps the originals, so the use ledger and attribution still
|
|
128
|
+
// key on stored rows. No collision (or no code found, or a computed value
|
|
129
|
+
// the parser cannot decide) leaves the row plain — fail-open to the row,
|
|
130
|
+
// never fail-shut on injection.
|
|
131
|
+
const rendered = new Map<Memory, Memory>();
|
|
132
|
+
if (opts?.conflictCheck && opts.repoDir && guided.length) {
|
|
133
|
+
for (const m of guided) {
|
|
134
|
+
if (!m.ref || !m.claim || !m.klass) continue;
|
|
135
|
+
const fact = findConstant(opts.repoDir!, m.ref);
|
|
136
|
+
if (!fact || valuesAgree(m.claim, fact.value) !== false) continue;
|
|
137
|
+
rendered.set(m, { ...m, content: conflictLine(m, fact) });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
99
140
|
const text = message.trim();
|
|
100
141
|
const top = text ? scoreMemories(text, mems, limit, use) : [];
|
|
101
142
|
const merged = [...guided, ...top.filter((m) => !guided.includes(m))];
|
|
102
|
-
if (!merged.length) return { block: "", selected: [] };
|
|
143
|
+
if (!merged.length) return { block: "", selected: [], rendered };
|
|
144
|
+
const hasConflict = rendered.size > 0;
|
|
103
145
|
return {
|
|
104
|
-
block: `## Relevant durable memory${FRAME}${guided.length ? GUIDED_CAVEAT : ""}\n${merged.map(formatMemory).join("\n")}`,
|
|
146
|
+
block: `## Relevant durable memory${FRAME}${guided.length ? (hasConflict ? CONFLICT_CAVEAT : GUIDED_CAVEAT) : ""}\n${merged.map((m) => formatMemory(rendered.get(m) ?? m)).join("\n")}`,
|
|
105
147
|
selected: merged,
|
|
148
|
+
rendered,
|
|
106
149
|
};
|
|
107
150
|
}
|
|
108
151
|
|
package/src/store/blocklist.ts
CHANGED
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
writeAtomic,
|
|
14
14
|
} from "../core/logfmt/publish.ts";
|
|
15
15
|
import { readLines } from "../core/logfmt/read.ts";
|
|
16
|
-
import {
|
|
16
|
+
import { LOCK_WRITE, withStoreLock } from "./lock.ts";
|
|
17
17
|
import { redactSecrets } from "./secrets.ts";
|
|
18
18
|
|
|
19
19
|
const BLOCKLIST_FILENAME = "blocklist.logfmt";
|
|
@@ -2,19 +2,21 @@
|
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { memoryRoot } from "../../core/config/paths.ts";
|
|
5
|
-
import { dateStr } from "../../core/time.ts";
|
|
6
|
-
import { writeTarget } from "../../identity/repokey.ts";
|
|
7
|
-
import { getCurrent } from "../../core/state.ts";
|
|
8
5
|
import { formatLine, parseLine } from "../../core/logfmt/format.ts";
|
|
9
6
|
import { fileIdentity, writeAtomic } from "../../core/logfmt/publish.ts";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
7
|
+
import { getCurrent } from "../../core/state.ts";
|
|
8
|
+
import { dateStr } from "../../core/time.ts";
|
|
9
|
+
import { writeTarget } from "../../identity/repokey.ts";
|
|
10
|
+
import { LOCK_WRITE, withStoreLock } from "../lock.ts";
|
|
13
11
|
import {
|
|
14
12
|
MAX_CONTENT_CHARS,
|
|
15
13
|
type MemoryStatus,
|
|
14
|
+
normalizeConflictFields,
|
|
16
15
|
normalizeKeywords,
|
|
16
|
+
normalizeOriginal,
|
|
17
17
|
} from "../model/memory.ts";
|
|
18
|
+
import { flattenMemoryText } from "../sanitize.ts";
|
|
19
|
+
import { containsSecret, redactSecrets } from "../secrets.ts";
|
|
18
20
|
|
|
19
21
|
export interface AppendMemoryInput {
|
|
20
22
|
type: string;
|
|
@@ -25,6 +27,18 @@ export interface AppendMemoryInput {
|
|
|
25
27
|
/** Retrieval keywords (#40); normalised and capped by appendMemory. */
|
|
26
28
|
kw?: string[];
|
|
27
29
|
status?: MemoryStatus;
|
|
30
|
+
/**
|
|
31
|
+
* Contradiction surface (POC): guided row's code symbol / user's value /
|
|
32
|
+
* authority class. Normalised by appendMemory; junk drops the fields only.
|
|
33
|
+
*/
|
|
34
|
+
ref?: string;
|
|
35
|
+
claim?: string;
|
|
36
|
+
klass?: "spec" | "behavior";
|
|
37
|
+
/**
|
|
38
|
+
* Verbatim user utterance behind a guided row (see model/memory.ts).
|
|
39
|
+
* Normalised by appendMemory; junk drops the field only.
|
|
40
|
+
*/
|
|
41
|
+
original?: string;
|
|
28
42
|
// "global" for explicit cross-project writes; imports may carry a validated
|
|
29
43
|
// same-repo origin stamp (see portable.ts). Any missing value is resolved by
|
|
30
44
|
// appendMemory against the live repo scope.
|
|
@@ -109,6 +123,8 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
|
|
|
109
123
|
input.tags?.some(containsSecret) ? "tags" : undefined,
|
|
110
124
|
input.kw?.some(containsSecret) ? "kw" : undefined,
|
|
111
125
|
containsSecret(input.issue) ? "issue" : undefined,
|
|
126
|
+
containsSecret(input.ref) ? "ref" : undefined,
|
|
127
|
+
containsSecret(input.claim) ? "claim" : undefined,
|
|
112
128
|
].filter((field): field is string => field !== undefined);
|
|
113
129
|
if (credentialMetadata.length) {
|
|
114
130
|
throw new Error(
|
|
@@ -144,53 +160,78 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
|
|
|
144
160
|
repoPath = target.scope.path;
|
|
145
161
|
}
|
|
146
162
|
}
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
//
|
|
150
|
-
|
|
151
|
-
//
|
|
152
|
-
//
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
163
|
+
// The day file is chosen before the lock because it IS the lock key. A
|
|
164
|
+
// colliding ts is bumped inside that lock, and the bump can cross UTC midnight
|
|
165
|
+
// — which #215 made more than cosmetic: a supersede addresses a row by the day
|
|
166
|
+
// its own ts names, so a row filed under another day is a second, unreachable
|
|
167
|
+
// address for the same identity (two files can then hold the same ts). So when
|
|
168
|
+
// the bumped ts leaves the day, hand the row to the file it names and take that
|
|
169
|
+
// file's lock instead. The loop releases before it re-acquires — never two
|
|
170
|
+
// locks at once — and is bounded only so a pathological store cannot spin.
|
|
171
|
+
let day = dateStr();
|
|
172
|
+
let carryTs: string | undefined;
|
|
173
|
+
for (let attempt = 0; ; attempt++) {
|
|
174
|
+
const file = join(memoryRoot(), `${day}.logfmt`);
|
|
175
|
+
// Locked end to end: seeding ts from a scan another process can race yields
|
|
176
|
+
// two rows with the same identity, and an append that lands inside someone
|
|
177
|
+
// else's whole-file rewrite is simply not there afterwards.
|
|
178
|
+
const outcome = await withStoreLock(
|
|
179
|
+
file,
|
|
180
|
+
async (): Promise<{
|
|
181
|
+
moved?: string;
|
|
182
|
+
bumped?: string;
|
|
183
|
+
ts?: string;
|
|
184
|
+
}> => {
|
|
185
|
+
const since = await fileIdentity(file);
|
|
186
|
+
let prior = "";
|
|
187
|
+
try {
|
|
188
|
+
prior = await readFile(file, "utf8");
|
|
189
|
+
} catch (err) {
|
|
190
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
|
191
|
+
}
|
|
192
|
+
const taken = existingTs(prior);
|
|
193
|
+
let ts = carryTs ?? new Date().toISOString();
|
|
194
|
+
let guard = 0;
|
|
195
|
+
while (taken.has(ts) && guard++ < 1000) {
|
|
196
|
+
ts = new Date(new Date(ts).getTime() + 1).toISOString();
|
|
197
|
+
}
|
|
198
|
+
const ownDay = ts.slice(0, 10);
|
|
199
|
+
// Carry the bumped identity with the move: re-reading the clock in the
|
|
200
|
+
// new file would hand back the PREVIOUS day's instant and file it under
|
|
201
|
+
// the next day — the same lie in the other direction.
|
|
202
|
+
if (ownDay !== day && attempt < 3) return { moved: ownDay, bumped: ts };
|
|
203
|
+
const kw = normalizeKeywords(input.kw);
|
|
204
|
+
const conflict = normalizeConflictFields(input);
|
|
205
|
+
const original = normalizeOriginal(input.original);
|
|
206
|
+
const line = formatLine({
|
|
207
|
+
ts,
|
|
208
|
+
type: input.type,
|
|
209
|
+
scope: input.scope,
|
|
210
|
+
content,
|
|
211
|
+
issue: input.issue,
|
|
212
|
+
tags: input.tags?.length ? input.tags.join(",") : undefined,
|
|
213
|
+
kw: kw?.join(","),
|
|
214
|
+
status: input.status,
|
|
215
|
+
...conflict,
|
|
216
|
+
...(original ? { original } : {}),
|
|
217
|
+
repo,
|
|
218
|
+
repoPath,
|
|
219
|
+
});
|
|
220
|
+
// A lock excludes writers, not readers: an O_APPEND read can end mid-row.
|
|
221
|
+
// Publish the complete day file using the read already needed for IDs.
|
|
222
|
+
// This costs a whole-file write and can refuse on Windows reader handles;
|
|
223
|
+
// the old destination remains intact if publication fails (#198).
|
|
224
|
+
await writeAtomic(
|
|
225
|
+
file,
|
|
226
|
+
prior + (prior && !prior.endsWith("\n") ? "\n" : "") + line + "\n",
|
|
227
|
+
since,
|
|
228
|
+
);
|
|
229
|
+
return { ts };
|
|
230
|
+
},
|
|
231
|
+
LOCK_WRITE,
|
|
232
|
+
);
|
|
233
|
+
if (outcome.ts !== undefined) return outcome.ts;
|
|
234
|
+
day = outcome.moved as string;
|
|
235
|
+
carryTs = outcome.bumped;
|
|
236
|
+
}
|
|
196
237
|
}
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
import { deletionsFile } from "../../core/config/paths.ts";
|
|
3
3
|
import { formatLine } from "../../core/logfmt/format.ts";
|
|
4
4
|
import { appendLog } from "../../core/logfmt/publish.ts";
|
|
5
|
+
import type { Memory } from "../model/memory.ts";
|
|
5
6
|
import { redactSecrets } from "../secrets.ts";
|
|
6
|
-
import { type Memory } from "../model/memory.ts";
|
|
7
7
|
|
|
8
8
|
export interface DeletedMemory {
|
|
9
9
|
memory: Memory;
|
package/src/store/files/load.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// needs: supersession markers, snapshots and audited deletion.
|
|
6
6
|
import { existsSync } from "node:fs";
|
|
7
7
|
import { open } from "node:fs/promises";
|
|
8
|
-
import { join } from "node:path";
|
|
8
|
+
import { basename, join } from "node:path";
|
|
9
9
|
import { HITS_FILENAME, memoryRoot } from "../../core/config/paths.ts";
|
|
10
10
|
import { parseLine } from "../../core/logfmt/format.ts";
|
|
11
11
|
import { readLines } from "../../core/logfmt/read.ts";
|
|
@@ -16,8 +16,8 @@ import {
|
|
|
16
16
|
malformedWarnedFiles,
|
|
17
17
|
} from "../model/memory.ts";
|
|
18
18
|
import {
|
|
19
|
-
type Reader,
|
|
20
19
|
isVisibleTo,
|
|
20
|
+
type Reader,
|
|
21
21
|
readerForAmbient,
|
|
22
22
|
} from "../model/visibility.ts";
|
|
23
23
|
|
|
@@ -79,6 +79,19 @@ export function toMemory(
|
|
|
79
79
|
typeof fields.superseded_by === "string"
|
|
80
80
|
? fields.superseded_by
|
|
81
81
|
: undefined,
|
|
82
|
+
ref: typeof fields.ref === "string" && fields.ref ? fields.ref : undefined,
|
|
83
|
+
claim:
|
|
84
|
+
typeof fields.claim === "string" && fields.claim
|
|
85
|
+
? fields.claim
|
|
86
|
+
: undefined,
|
|
87
|
+
klass:
|
|
88
|
+
fields.klass === "spec" || fields.klass === "behavior"
|
|
89
|
+
? fields.klass
|
|
90
|
+
: undefined,
|
|
91
|
+
original:
|
|
92
|
+
typeof fields.original === "string" && fields.original
|
|
93
|
+
? fields.original
|
|
94
|
+
: undefined,
|
|
82
95
|
reason: typeof fields.reason === "string" ? fields.reason : undefined,
|
|
83
96
|
status:
|
|
84
97
|
fields.status === "open" || fields.status === "settled"
|
|
@@ -105,6 +118,90 @@ export async function memoryFiles(): Promise<string[]> {
|
|
|
105
118
|
return files.sort();
|
|
106
119
|
}
|
|
107
120
|
|
|
121
|
+
/**
|
|
122
|
+
* The day file a row's own ts names, as a `YYYY-MM-DD.logfmt` basename, or null
|
|
123
|
+
* when the string is not an ISO instant. `appendMemory` mints ts at write time
|
|
124
|
+
* and appends to that same day file, so for every row the plugin wrote the ts
|
|
125
|
+
* date IS the file date (#215).
|
|
126
|
+
*/
|
|
127
|
+
export function dayFileName(ts: string): string | null {
|
|
128
|
+
const m = /^(\d{4}-\d{2}-\d{2})T/.exec(ts);
|
|
129
|
+
return m ? `${m[1]}.logfmt` : null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Day files ordered so the ones these ts values name come first (#215). A
|
|
134
|
+
* single-row mutation that stops as soon as it has SEEN the row then locks one
|
|
135
|
+
* file instead of one per day of store age — the cost that made supersing a row
|
|
136
|
+
* 25x a full read on a 30-day store.
|
|
137
|
+
*
|
|
138
|
+
* The mapping is a hint, never a proof: a store edited outside the plugin can
|
|
139
|
+
* hold a row in a file its ts does not name. Callers must keep walking the rest
|
|
140
|
+
* of the list until they find the row, which is the behaviour this replaced.
|
|
141
|
+
*/
|
|
142
|
+
export async function filesOrderedFor(tsValues: string[]): Promise<string[]> {
|
|
143
|
+
const all = await memoryFiles();
|
|
144
|
+
const names = new Set<string>();
|
|
145
|
+
for (const ts of tsValues) {
|
|
146
|
+
const name = dayFileName(ts);
|
|
147
|
+
if (name) names.add(name);
|
|
148
|
+
}
|
|
149
|
+
if (!names.size) return all;
|
|
150
|
+
const near: string[] = [];
|
|
151
|
+
const rest: string[] = [];
|
|
152
|
+
for (const file of all) {
|
|
153
|
+
(names.has(basename(file)) ? near : rest).push(file);
|
|
154
|
+
}
|
|
155
|
+
return [...near, ...rest];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The day BEFORE `YYYY-MM-DD`, UTC. Month and year boundaries included: the
|
|
160
|
+
* only caller uses it to name a file that may hold a row appended a millisecond
|
|
161
|
+
* before midnight.
|
|
162
|
+
*/
|
|
163
|
+
export function previousDayName(day: string): string {
|
|
164
|
+
return new Date(new Date(`${day}T12:00:00.000Z`).getTime() - 86_400_000)
|
|
165
|
+
.toISOString()
|
|
166
|
+
.slice(0, 10);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The day files that could hold a copy of `ts` — the addresses a single-row
|
|
171
|
+
* mutation must try before it may report success (#373 review).
|
|
172
|
+
*
|
|
173
|
+
* Two files, at most. The one the ts names, plus the previous day's file ONLY
|
|
174
|
+
* when a text scan finds the identity in it: `appendMemory` used to pick the
|
|
175
|
+
* file from the clock and bump a colliding ts inside the lock, so a row whose ts
|
|
176
|
+
* is one millisecond past midnight could be filed under the day before it. That
|
|
177
|
+
* is the only way the plugin can write a row outside its own day, so the
|
|
178
|
+
* neighbour scan is complete, and scanning (not locking) keeps the ordinary
|
|
179
|
+
* single-row mutation at ONE lock.
|
|
180
|
+
*
|
|
181
|
+
* Reading without a lock is sound because this only decides what to lock next:
|
|
182
|
+
* every mutation re-reads under the lock it takes.
|
|
183
|
+
*
|
|
184
|
+
* Empty for a ts that is not an ISO instant — the caller then sweeps, as before.
|
|
185
|
+
*/
|
|
186
|
+
export async function filesHoldingTs(
|
|
187
|
+
ts: string,
|
|
188
|
+
present?: Set<string>,
|
|
189
|
+
): Promise<string[]> {
|
|
190
|
+
const name = dayFileName(ts);
|
|
191
|
+
if (!name) return [];
|
|
192
|
+
const have =
|
|
193
|
+
present ?? new Set((await memoryFiles()).map((f) => basename(f)));
|
|
194
|
+
const out: string[] = [];
|
|
195
|
+
if (have.has(name)) out.push(join(memoryRoot(), name));
|
|
196
|
+
const prev = `${previousDayName(name.slice(0, 10))}.logfmt`;
|
|
197
|
+
if (have.has(prev)) {
|
|
198
|
+
const file = join(memoryRoot(), prev);
|
|
199
|
+
const text = await Bun.file(file).text();
|
|
200
|
+
if (text.includes(`ts=${ts}`)) out.push(file);
|
|
201
|
+
}
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
|
|
108
205
|
export async function loadAll(): Promise<Memory[]> {
|
|
109
206
|
malformedRows = 0; // per-load telemetry: the most recent read wins
|
|
110
207
|
const blocked = await blockedTs();
|