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
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.15.
|
|
3
|
+
"version": "0.15.5",
|
|
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": {
|
|
7
7
|
".": "./index.ts",
|
|
8
|
-
"./tui": "./src/tui.tsx"
|
|
8
|
+
"./tui": "./src/tui/panel.tsx"
|
|
9
9
|
},
|
|
10
10
|
"module": "index.ts",
|
|
11
11
|
"type": "module",
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// candidates — split from src/capture.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
// Opt-in auto-capture parsing, prompt, and lag helpers. Host access and model
|
|
3
|
+
// calls live in src/index.ts. Every candidate that leaves this module flows
|
|
4
|
+
// through runWriteGate in index.ts: capture NEVER writes memories directly,
|
|
5
|
+
// so dupes/stale/canonical rules keep the moat (same as model-authored writes).
|
|
6
|
+
// All parsing functions are TOTAL: any malformed input yields [] / "" / null,
|
|
7
|
+
// never a throw.
|
|
8
|
+
import { TYPES } from "../core/types.ts";
|
|
9
|
+
import { flattenMemoryText } from "../store/sanitize.ts";
|
|
10
|
+
import { CAPTURE_KEYWORD_CAP, CAPTURE_KEYWORD_CHARS, type CaptureCandidate } from "./prompt.ts";
|
|
11
|
+
|
|
12
|
+
function cleanKeywords(value: unknown): string[] | undefined {
|
|
13
|
+
if (!Array.isArray(value)) return undefined;
|
|
14
|
+
const out: string[] = [];
|
|
15
|
+
for (const item of value) {
|
|
16
|
+
if (typeof item !== "string") continue;
|
|
17
|
+
const k = item.trim().toLowerCase();
|
|
18
|
+
if (!k || k.length > CAPTURE_KEYWORD_CHARS || flattenMemoryText(k) !== k) continue;
|
|
19
|
+
if (!out.includes(k)) out.push(k);
|
|
20
|
+
if (out.length === CAPTURE_KEYWORD_CAP) break;
|
|
21
|
+
}
|
|
22
|
+
return out.length ? out : undefined;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const VALID_TYPES = new Set<string>(TYPES);
|
|
26
|
+
|
|
27
|
+
// Remove markdown code-fence marker lines, keeping the fenced payload.
|
|
28
|
+
function stripFences(text: string): string {
|
|
29
|
+
return text.replace(/^[ \t]*```[^\n]*$/gm, "");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// First balanced [...] span, string-literal aware. null when absent or
|
|
33
|
+
// unbalanced (a model that truncates mid-array yields nothing, not garbage).
|
|
34
|
+
function firstJsonArray(text: string): string | null {
|
|
35
|
+
const start = text.indexOf("[");
|
|
36
|
+
if (start === -1) return null;
|
|
37
|
+
let depth = 0;
|
|
38
|
+
let inString = false;
|
|
39
|
+
let escaped = false;
|
|
40
|
+
for (let i = start; i < text.length; i++) {
|
|
41
|
+
const ch = text[i];
|
|
42
|
+
if (inString) {
|
|
43
|
+
if (escaped) escaped = false;
|
|
44
|
+
else if (ch === "\\") escaped = true;
|
|
45
|
+
else if (ch === '"') inString = false;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (ch === '"') inString = true;
|
|
49
|
+
else if (ch === "[") depth++;
|
|
50
|
+
else if (ch === "]") {
|
|
51
|
+
depth--;
|
|
52
|
+
if (depth === 0) return text.slice(start, i + 1);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Extract memory candidates from a model reply. Never throws: any malformed
|
|
59
|
+
// input yields []. Items missing fields, with unknown types, or with content
|
|
60
|
+
// outside 20-600 chars are dropped; the result is clamped to `max`.
|
|
61
|
+
export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
|
|
62
|
+
try {
|
|
63
|
+
if (typeof raw !== "string" || !raw.trim() || !(max > 0)) return [];
|
|
64
|
+
const span = firstJsonArray(stripFences(raw));
|
|
65
|
+
if (!span) return [];
|
|
66
|
+
const parsed = JSON.parse(span);
|
|
67
|
+
if (!Array.isArray(parsed)) return [];
|
|
68
|
+
const out: CaptureCandidate[] = [];
|
|
69
|
+
for (const item of parsed) {
|
|
70
|
+
if (out.length >= max) break;
|
|
71
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
|
|
72
|
+
const o = item as Record<string, unknown>;
|
|
73
|
+
const rawType = typeof o.type === "string" ? o.type : "";
|
|
74
|
+
const rawScope = typeof o.scope === "string" ? o.scope : "";
|
|
75
|
+
const type = rawType.trim();
|
|
76
|
+
const scope = rawScope.trim();
|
|
77
|
+
const content = typeof o.content === "string" ? o.content.trim() : "";
|
|
78
|
+
if (!type || !scope || !content) continue;
|
|
79
|
+
if (
|
|
80
|
+
flattenMemoryText(rawType) !== rawType ||
|
|
81
|
+
flattenMemoryText(rawScope) !== rawScope
|
|
82
|
+
) continue;
|
|
83
|
+
if (!VALID_TYPES.has(type)) continue;
|
|
84
|
+
if (content.length < 20 || content.length > 600) continue;
|
|
85
|
+
const status = o.status === "open" || o.status === "settled" ? o.status : undefined;
|
|
86
|
+
// A bad kw list costs the row its keywords, never the row itself.
|
|
87
|
+
const kw = cleanKeywords(o.kw);
|
|
88
|
+
out.push({
|
|
89
|
+
...(status ? { type, scope, content, status } : { type, scope, content }),
|
|
90
|
+
...(kw ? { kw } : {}),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
} catch {
|
|
95
|
+
return [];
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// "provider/id" -> { providerID, id }, splitting on the FIRST "/". Returns
|
|
100
|
+
// null when the string has no slash or either half is empty — the caller then
|
|
101
|
+
// skips capture entirely rather than guessing a model.
|
|
102
|
+
export function parseModelRef(ref: unknown): { providerID: string; id: string } | null {
|
|
103
|
+
if (typeof ref !== "string") return null;
|
|
104
|
+
const i = ref.indexOf("/");
|
|
105
|
+
if (i <= 0) return null;
|
|
106
|
+
const providerID = ref.slice(0, i).trim();
|
|
107
|
+
const id = ref.slice(i + 1).trim();
|
|
108
|
+
if (!providerID || !id) return null;
|
|
109
|
+
return { providerID, id };
|
|
110
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// lag — split from src/capture.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Age of the newest message in a session context, in ms, or null when no
|
|
6
|
+
* message carries a timestamp. Capture uses this to say how stale a transcript
|
|
7
|
+
* was at the moment the model was asked for candidates (#44).
|
|
8
|
+
*/
|
|
9
|
+
export function lagSince(messages: unknown, now = Date.now()): number | null {
|
|
10
|
+
let newest = 0;
|
|
11
|
+
for (const raw of Array.isArray(messages) ? messages : []) {
|
|
12
|
+
const m = raw as Record<string, any>;
|
|
13
|
+
const at = m?.time?.updated ?? m?.createdAt ?? m?.created ?? m?.timestamp;
|
|
14
|
+
const ms = typeof at === "number" ? at : typeof at === "string" ? Date.parse(at) : Number.NaN;
|
|
15
|
+
if (Number.isFinite(ms) && ms > newest) newest = ms;
|
|
16
|
+
}
|
|
17
|
+
return newest ? now - newest : null;
|
|
18
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// prompt — split from src/capture.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
// Opt-in auto-capture parsing, prompt, and lag helpers. Host access and model
|
|
3
|
+
// calls live in src/index.ts. Every candidate that leaves this module flows
|
|
4
|
+
// through runWriteGate in index.ts: capture NEVER writes memories directly,
|
|
5
|
+
// so dupes/stale/canonical rules keep the moat (same as model-authored writes).
|
|
6
|
+
// All parsing functions are TOTAL: any malformed input yields [] / "" / null,
|
|
7
|
+
// never a throw.
|
|
8
|
+
import { TYPES } from "../core/types.ts";
|
|
9
|
+
import { redactSecrets } from "../store/secrets.ts";
|
|
10
|
+
|
|
11
|
+
export interface CaptureCandidate {
|
|
12
|
+
type: string;
|
|
13
|
+
scope: string;
|
|
14
|
+
content: string;
|
|
15
|
+
status?: "open" | "settled";
|
|
16
|
+
/** Retrieval keywords (#40): indexed by the store, never rendered. */
|
|
17
|
+
kw?: string[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Keywords are the vocabulary bridge for the strict-paraphrase wall, mined from
|
|
21
|
+
// the transcript the model just saw. Cap and shape mirror the store's own
|
|
22
|
+
// limits; the store normalises again at write, so this only has to stay
|
|
23
|
+
// junk-proof (capture.ts never imports the store — it stays dependency-free).
|
|
24
|
+
export const CAPTURE_KEYWORD_CAP = 8;
|
|
25
|
+
|
|
26
|
+
export const CAPTURE_KEYWORD_CHARS = 48;
|
|
27
|
+
|
|
28
|
+
// Prompt for the cheap capture model. The output contract is a bare JSON
|
|
29
|
+
// array so parseCandidates can trust it; anything else parses to [].
|
|
30
|
+
export function buildCapturePrompt(transcript: string, max = 3): string {
|
|
31
|
+
return [
|
|
32
|
+
"You mine one coding-agent session transcript for durable memories worth keeping across future sessions.",
|
|
33
|
+
"",
|
|
34
|
+
`Output ONLY a JSON array of at most ${max} objects (a fenced json block is fine), each:`,
|
|
35
|
+
'{"type": "...", "scope": "...", "content": "...", "status": "...", "kw": ["...", "..."]}',
|
|
36
|
+
"",
|
|
37
|
+
"Rules:",
|
|
38
|
+
`- type: one of ${TYPES.join(", ")}.`,
|
|
39
|
+
"- scope: short area name (e.g. auth, api, build).",
|
|
40
|
+
'- status: "open" for a live planning thread; otherwise "settled".',
|
|
41
|
+
"- content: one self-contained fact, 20-600 characters, useful in a NEW session.",
|
|
42
|
+
'- kw: 3-5 search keywords for how a DIFFERENT session would ask for this — synonyms and alternate names, other verb forms, the literal command or file name. They are indexed for retrieval and never shown to a model. Omit (or []) when the content already uses those words.',
|
|
43
|
+
"- Keep: decisions made, working commands, user preferences, blockers hit, durable context, conventions.",
|
|
44
|
+
"- Skip: anything derivable from the code or git history, small talk, and details that only mattered inside this conversation.",
|
|
45
|
+
"- If nothing is worth remembering, output [ ].",
|
|
46
|
+
"",
|
|
47
|
+
"Transcript:",
|
|
48
|
+
redactSecrets(transcript),
|
|
49
|
+
].join("\n");
|
|
50
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// transcript — split from src/capture.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
// Render an array of session-context messages of unknown shape into
|
|
5
|
+
// "role: text" lines. Defensive by construction (the API shape varies and is
|
|
6
|
+
// not ours to trust): non-arrays and junk entries are skipped; role comes
|
|
7
|
+
// from info.role | role, text from parts[].text | text | content (strings
|
|
8
|
+
// only); capped at 40 user turns. Never throws.
|
|
9
|
+
const TRANSCRIPT_USER_TURN_CAP = 40;
|
|
10
|
+
|
|
11
|
+
export function flattenTranscript(msgs: unknown): string {
|
|
12
|
+
try {
|
|
13
|
+
if (!Array.isArray(msgs)) return "";
|
|
14
|
+
const lines: string[] = [];
|
|
15
|
+
let userTurns = 0;
|
|
16
|
+
for (const msg of msgs) {
|
|
17
|
+
if (!msg || typeof msg !== "object") continue;
|
|
18
|
+
const m = msg as Record<string, unknown>;
|
|
19
|
+
const info =
|
|
20
|
+
m.info && typeof m.info === "object" ? (m.info as Record<string, unknown>) : undefined;
|
|
21
|
+
const role =
|
|
22
|
+
typeof info?.role === "string" ? info.role : typeof m.role === "string" ? m.role : "";
|
|
23
|
+
let text = "";
|
|
24
|
+
let hadPrivatePart = false;
|
|
25
|
+
if (Array.isArray(m.parts)) {
|
|
26
|
+
text = m.parts
|
|
27
|
+
.map((p) => {
|
|
28
|
+
if (!p || typeof p !== "object") return undefined;
|
|
29
|
+
const part = p as Record<string, unknown>;
|
|
30
|
+
const partType = typeof part.type === "string" ? part.type.toLowerCase() : "";
|
|
31
|
+
if (partType === "reasoning" || partType === "thinking") {
|
|
32
|
+
hadPrivatePart = true;
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
return part.text;
|
|
36
|
+
})
|
|
37
|
+
.filter((t): t is string => typeof t === "string" && t.length > 0)
|
|
38
|
+
.join(" ");
|
|
39
|
+
}
|
|
40
|
+
if (!text && !hadPrivatePart) {
|
|
41
|
+
for (const k of ["text", "content"]) {
|
|
42
|
+
if (typeof m[k] === "string") {
|
|
43
|
+
text = m[k] as string;
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (!role || !text.trim()) continue;
|
|
49
|
+
if (role === "user") {
|
|
50
|
+
userTurns++;
|
|
51
|
+
if (userTurns > TRANSCRIPT_USER_TURN_CAP) break;
|
|
52
|
+
}
|
|
53
|
+
lines.push(`${role}: ${text.trim()}`);
|
|
54
|
+
}
|
|
55
|
+
return lines.join("\n");
|
|
56
|
+
} catch {
|
|
57
|
+
return "";
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -2,17 +2,18 @@
|
|
|
2
2
|
// tool results, never by a model decision. Nothing here injects into chat.
|
|
3
3
|
import { existsSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
|
-
import { record } from "
|
|
6
|
-
import { evidenceDir } from "
|
|
7
|
-
import { parseLine
|
|
8
|
-
import {
|
|
5
|
+
import { record } from "../evidence/record.ts";
|
|
6
|
+
import { evidenceDir } from "../core/config/paths.ts";
|
|
7
|
+
import { parseLine } from "../core/logfmt/format.ts"
|
|
8
|
+
import { readLines } from "../core/logfmt/read.ts";
|
|
9
|
+
import { redactSecrets } from "../store/secrets.ts";
|
|
9
10
|
import {
|
|
10
11
|
session,
|
|
11
12
|
setLastSeenSid,
|
|
12
13
|
lastSeenSid,
|
|
13
14
|
type SessionState,
|
|
14
15
|
type ToolResult,
|
|
15
|
-
} from "
|
|
16
|
+
} from "../core/state.ts";
|
|
16
17
|
|
|
17
18
|
export interface AfterInput {
|
|
18
19
|
tool?: unknown;
|
|
@@ -7,9 +7,9 @@ import { existsSync } from "node:fs";
|
|
|
7
7
|
import { mkdir } from "node:fs/promises";
|
|
8
8
|
import { dirname, join } from "node:path";
|
|
9
9
|
import { fileURLToPath } from "node:url";
|
|
10
|
-
import { commandsDir } from "
|
|
10
|
+
import { commandsDir } from "../core/config/paths.ts";
|
|
11
11
|
|
|
12
|
-
const PKG_COMMANDS = join(dirname(fileURLToPath(import.meta.url)), "..", "command");
|
|
12
|
+
const PKG_COMMANDS = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "command");
|
|
13
13
|
|
|
14
14
|
export async function ensureCommand(name: string): Promise<string | null> {
|
|
15
15
|
try {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// propose — split from src/consolidate.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
1
2
|
// Consolidation proposals (#45): episodic rows → one canonical row, proposed and
|
|
2
3
|
// measured, never silently applied.
|
|
3
4
|
//
|
|
@@ -25,12 +26,15 @@
|
|
|
25
26
|
// 3. PROPOSALS, not writes. Nothing here mutates the store. A human resolves a
|
|
26
27
|
// proposal through memory_merge_review (supersede-not-delete, recoverable).
|
|
27
28
|
// 4. The most recently used member is never a loser (#42's rule, inherited).
|
|
28
|
-
import type { Memory } from "
|
|
29
|
-
import type { UseSignal } from "
|
|
30
|
-
import { cmpTs
|
|
29
|
+
import type { Memory } from "../store/model/memory.ts";
|
|
30
|
+
import type { UseSignal } from "../hits/ledger.ts";
|
|
31
|
+
import { cmpTs } from "../core/cmp-ts.ts"
|
|
32
|
+
import { formatMemory } from "../inject/format.ts"
|
|
33
|
+
import { scoreMemories, words } from "../recall/score.ts";
|
|
31
34
|
|
|
32
35
|
/** Default jaccard floor for "these two rows are the same statement". */
|
|
33
36
|
export const DEFAULT_JACCARD = 0.55;
|
|
37
|
+
|
|
34
38
|
/** Aliases are useful up to a point; a merged row that hoards 60 words is noise. */
|
|
35
39
|
export const MAX_MERGED_KW = 12;
|
|
36
40
|
|
|
@@ -292,30 +296,3 @@ export function proposeConsolidations(
|
|
|
292
296
|
injectedAfter: injected(rows.filter((m) => !absorbed.has(m))),
|
|
293
297
|
};
|
|
294
298
|
}
|
|
295
|
-
|
|
296
|
-
/** Human-readable proposal list. Ends with the exact command to resolve one. */
|
|
297
|
-
export function renderProposals(report: ProposalReport): string {
|
|
298
|
-
const out: string[] = ["CONSOLIDATION PROPOSALS — nothing was written", ""];
|
|
299
|
-
if (!report.plans.length) {
|
|
300
|
-
out.push(" none — no cluster proved it could hold its reads.");
|
|
301
|
-
return out.join("\n");
|
|
302
|
-
}
|
|
303
|
-
for (const p of report.plans) {
|
|
304
|
-
out.push(
|
|
305
|
-
`${p.id} ${p.type}/${p.scope} ${p.losers.length + 1} rows → 1`,
|
|
306
|
-
` keep ${p.survivor.ts}`,
|
|
307
|
-
` ${p.survivor.content.slice(0, 160)}`,
|
|
308
|
-
...p.losers.map((l) => ` absorb ${l.ts} ${l.content.slice(0, 120)}`),
|
|
309
|
-
` reads ${p.reads.length} logged · best member alone ${p.bestMemberBefore} · merged ${p.readsAfter}`,
|
|
310
|
-
` budget ${p.bytesBefore}c → ${p.bytesAfter}c for this cluster`,
|
|
311
|
-
` resolve: memory_merge_review(loser="${p.losers[0]!.ts}", survivor="${p.survivor.ts}", reason="consolidate ${p.id}")`,
|
|
312
|
-
"",
|
|
313
|
-
);
|
|
314
|
-
}
|
|
315
|
-
out.push(
|
|
316
|
-
`STORE ${report.rowsBefore} rows → ${report.rowsAfter} if every proposal is resolved · ` +
|
|
317
|
-
`injected ${report.injectedBefore}c → ${report.injectedAfter}c`,
|
|
318
|
-
);
|
|
319
|
-
out.push("Resolving is supersede-not-delete: absorbed rows stay recoverable via memory_undo.");
|
|
320
|
-
return out.join("\n");
|
|
321
|
-
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// render — split from src/consolidate.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
|
|
3
|
+
import { type ProposalReport } from "./propose.ts";
|
|
4
|
+
|
|
5
|
+
/** Human-readable proposal list. Ends with the exact command to resolve one. */
|
|
6
|
+
export function renderProposals(report: ProposalReport): string {
|
|
7
|
+
const out: string[] = ["CONSOLIDATION PROPOSALS — nothing was written", ""];
|
|
8
|
+
if (!report.plans.length) {
|
|
9
|
+
out.push(" none — no cluster proved it could hold its reads.");
|
|
10
|
+
return out.join("\n");
|
|
11
|
+
}
|
|
12
|
+
for (const p of report.plans) {
|
|
13
|
+
out.push(
|
|
14
|
+
`${p.id} ${p.type}/${p.scope} ${p.losers.length + 1} rows → 1`,
|
|
15
|
+
` keep ${p.survivor.ts}`,
|
|
16
|
+
` ${p.survivor.content.slice(0, 160)}`,
|
|
17
|
+
...p.losers.map((l) => ` absorb ${l.ts} ${l.content.slice(0, 120)}`),
|
|
18
|
+
` reads ${p.reads.length} logged · best member alone ${p.bestMemberBefore} · merged ${p.readsAfter}`,
|
|
19
|
+
` budget ${p.bytesBefore}c → ${p.bytesAfter}c for this cluster`,
|
|
20
|
+
` resolve: memory_merge_review(loser="${p.losers[0]!.ts}", survivor="${p.survivor.ts}", reason="consolidate ${p.id}")`,
|
|
21
|
+
"",
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
out.push(
|
|
25
|
+
`STORE ${report.rowsBefore} rows → ${report.rowsAfter} if every proposal is resolved · ` +
|
|
26
|
+
`injected ${report.injectedBefore}c → ${report.injectedAfter}c`,
|
|
27
|
+
);
|
|
28
|
+
out.push("Resolving is supersede-not-delete: absorbed rows stay recoverable via memory_undo.");
|
|
29
|
+
return out.join("\n");
|
|
30
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// cmp-ts — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
// Numeric compare, with the string compare kept as fallback for non-dates
|
|
5
|
+
// (the ledger hands "" when a row was never used). ISO strings agree with
|
|
6
|
+
// Date.parse only while the FORMAT agrees: a legacy second-precision stamp
|
|
7
|
+
// ("…:01Z") and a millisecond stamp ("…:01.000Z") for the same instant order
|
|
8
|
+
// wrong as strings, which would silently mis-rank the recency tie-break.
|
|
9
|
+
// Exported for consolidate.ts — cluster ordering must not disagree with the
|
|
10
|
+
// ranking it is merging.
|
|
11
|
+
export function cmpTs(a: string, b: string): number {
|
|
12
|
+
const na = Date.parse(a);
|
|
13
|
+
const nb = Date.parse(b);
|
|
14
|
+
if (!Number.isNaN(na) && !Number.isNaN(nb)) return na < nb ? -1 : na > nb ? 1 : 0;
|
|
15
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
16
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// budgets — split from src/config.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
// Character budget for the injected "Relevant durable memory" block (the
|
|
5
|
+
// cache-safe epoch injection). Overridable via OPENCODE_MEMORY_INJECT_BUDGET
|
|
6
|
+
// (plugin options take precedence — see src/index.ts); falls back to 1200 on
|
|
7
|
+
// missing or invalid values.
|
|
8
|
+
export function injectBudget(): number {
|
|
9
|
+
const raw = process.env.OPENCODE_MEMORY_INJECT_BUDGET;
|
|
10
|
+
if (raw) {
|
|
11
|
+
const n = Number.parseInt(raw, 10);
|
|
12
|
+
if (Number.isFinite(n) && n > 0) return n;
|
|
13
|
+
}
|
|
14
|
+
return 1200;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Character budget for the session-start open-thread frontier. Kept separate
|
|
18
|
+
// from relevance injection and contextual pulls: planning rows are often much
|
|
19
|
+
// longer, and raising this cap must not raise those per-request surfaces too.
|
|
20
|
+
// Defaults to 3x the effective injection budget.
|
|
21
|
+
export function frontierBudget(baseBudget = injectBudget()): number {
|
|
22
|
+
const raw = process.env.OPENCODE_MEMORY_FRONTIER_BUDGET;
|
|
23
|
+
if (raw) {
|
|
24
|
+
const n = Number.parseInt(raw, 10);
|
|
25
|
+
if (Number.isFinite(n) && n > 0) return n;
|
|
26
|
+
}
|
|
27
|
+
return baseBudget * 3;
|
|
28
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// paths — split from src/config.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
1
2
|
// Store paths for the self-improvement harness. Everything lives OUTSIDE any
|
|
2
3
|
// repository: under ~/.config/opencode/memory by default, or
|
|
3
4
|
// under $OPENCODE_MEMORY_DIR when set (tests use this for hermetic runs).
|
|
@@ -58,36 +59,6 @@ export function deletionsFile(): string {
|
|
|
58
59
|
return join(memoryRoot(), "deletions.logfmt");
|
|
59
60
|
}
|
|
60
61
|
|
|
61
|
-
export function dateStr(d: Date = new Date()): string {
|
|
62
|
-
return d.toISOString().split("T")[0];
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
// Character budget for the injected "Relevant durable memory" block (the
|
|
66
|
-
// cache-safe epoch injection). Overridable via OPENCODE_MEMORY_INJECT_BUDGET
|
|
67
|
-
// (plugin options take precedence — see src/index.ts); falls back to 1200 on
|
|
68
|
-
// missing or invalid values.
|
|
69
|
-
export function injectBudget(): number {
|
|
70
|
-
const raw = process.env.OPENCODE_MEMORY_INJECT_BUDGET;
|
|
71
|
-
if (raw) {
|
|
72
|
-
const n = Number.parseInt(raw, 10);
|
|
73
|
-
if (Number.isFinite(n) && n > 0) return n;
|
|
74
|
-
}
|
|
75
|
-
return 1200;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
// Character budget for the session-start open-thread frontier. Kept separate
|
|
79
|
-
// from relevance injection and contextual pulls: planning rows are often much
|
|
80
|
-
// longer, and raising this cap must not raise those per-request surfaces too.
|
|
81
|
-
// Defaults to 3x the effective injection budget.
|
|
82
|
-
export function frontierBudget(baseBudget = injectBudget()): number {
|
|
83
|
-
const raw = process.env.OPENCODE_MEMORY_FRONTIER_BUDGET;
|
|
84
|
-
if (raw) {
|
|
85
|
-
const n = Number.parseInt(raw, 10);
|
|
86
|
-
if (Number.isFinite(n) && n > 0) return n;
|
|
87
|
-
}
|
|
88
|
-
return baseBudget * 3;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
62
|
// Optional live-graph binary. When present the resolver cross-checks the local
|
|
92
63
|
// source scan against the codebase-memory-mcp file graph; when absent the local
|
|
93
64
|
// scan alone is authoritative (install-from-scratch requirement).
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// format — split from src/logfmt.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
export const IS_WINDOWS = process.platform === "win32";
|
|
5
|
+
|
|
6
|
+
export type Fields = Record<string, unknown>;
|
|
7
|
+
|
|
8
|
+
// Escapes for quoted values. One record is one line, so a raw newline inside a
|
|
9
|
+
// value would end the record early and the rest of the value would be read
|
|
10
|
+
// back as a separate line of fields. Backslash is escaped too, so a value
|
|
11
|
+
// ending in `\` cannot swallow its closing quote.
|
|
12
|
+
const ESCAPE: Record<string, string> = { "\\": "\\\\", '"': '\\"', "\n": "\\n", "\r": "\\r", "\t": "\\t" };
|
|
13
|
+
|
|
14
|
+
const UNESCAPE: Record<string, string> = { "\\": "\\", '"': '"', n: "\n", r: "\r", t: "\t" };
|
|
15
|
+
|
|
16
|
+
// Lines written before these escapes existed stored backslashes raw, so in an
|
|
17
|
+
// old line `C:\new` is a backslash and an `n`, not a newline. A line whose
|
|
18
|
+
// values use the escapes ends with this marker, and only fields before it are
|
|
19
|
+
// unescaped; everything else is read the old way, where only `\"` is an escape.
|
|
20
|
+
// Fields after the marker were appended by an older version (supersede adds
|
|
21
|
+
// fields to the end of an existing line). Lines without backslashes, newlines
|
|
22
|
+
// or tabs read the same either way, so they don't carry the marker.
|
|
23
|
+
const MARKER = "esc";
|
|
24
|
+
|
|
25
|
+
const MARKER_VALUE = "1";
|
|
26
|
+
|
|
27
|
+
export function quote(value: unknown): string {
|
|
28
|
+
const s = String(value);
|
|
29
|
+
if (s === "") return '""';
|
|
30
|
+
return /[\s"=]/.test(s) ? `"${s.replace(/[\\"\n\r\t]/g, (c) => ESCAPE[c])}"` : s;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function formatLine(fields: Fields): string {
|
|
34
|
+
const parts: string[] = [];
|
|
35
|
+
let escaped = false;
|
|
36
|
+
for (const [k, v] of Object.entries(fields)) {
|
|
37
|
+
if (v === undefined || v === null || k === MARKER) continue;
|
|
38
|
+
const q = quote(v);
|
|
39
|
+
if (q.startsWith('"') && /[\\\n\r\t]/.test(String(v))) escaped = true;
|
|
40
|
+
parts.push(`${k}=${q}`);
|
|
41
|
+
}
|
|
42
|
+
if (escaped) parts.push(`${MARKER}=${MARKER_VALUE}`);
|
|
43
|
+
return parts.join(" ");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Unescape a quoted logfmt value and read it back. Unknown sequences are kept
|
|
47
|
+
// as written.
|
|
48
|
+
function unquote(s: string): string {
|
|
49
|
+
return s.replace(/\\(.)/g, (seq, c: string) => UNESCAPE[c] ?? seq);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function unquoteLegacy(s: string): string {
|
|
53
|
+
return s.replace(/\\"/g, '"');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function parseLine(line: string): Fields | null {
|
|
57
|
+
const trimmed = line.trim();
|
|
58
|
+
if (!trimmed || !trimmed.includes("=")) return null;
|
|
59
|
+
const tokens: [string, string][] = [];
|
|
60
|
+
const re = /([A-Za-z0-9_.-]+)=("(?:[^"\\]|\\.)*"|[^\s]*)/g;
|
|
61
|
+
for (;;) {
|
|
62
|
+
const m = re.exec(trimmed);
|
|
63
|
+
if (!m) break;
|
|
64
|
+
tokens.push([m[1], m[2]]);
|
|
65
|
+
}
|
|
66
|
+
const marker = tokens.findIndex(([k, v]) => k === MARKER && v === MARKER_VALUE);
|
|
67
|
+
const fields: Fields = {};
|
|
68
|
+
tokens.forEach(([key, value], i) => {
|
|
69
|
+
if (key === MARKER) return;
|
|
70
|
+
let raw = value;
|
|
71
|
+
if (raw.startsWith('"') && raw.endsWith('"')) {
|
|
72
|
+
raw = (i < marker ? unquote : unquoteLegacy)(raw.slice(1, -1));
|
|
73
|
+
}
|
|
74
|
+
fields[key] = raw;
|
|
75
|
+
});
|
|
76
|
+
// parse booleans/numbers as strings is fine; callers coerce.
|
|
77
|
+
return fields;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function bracketList(items: string[]): string {
|
|
81
|
+
return `[${items.join(",")}]`;
|
|
82
|
+
}
|
|
@@ -1,81 +1,9 @@
|
|
|
1
|
+
// publish — split from src/logfmt.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
1
2
|
// Minimal logfmt reader/writer shared by the durable store and the evidence
|
|
2
3
|
// log. Field order is preserved on write so chains are diffable.
|
|
3
4
|
import { dirname } from "node:path";
|
|
4
|
-
import { appendFile, mkdir,
|
|
5
|
-
|
|
6
|
-
const IS_WINDOWS = process.platform === "win32";
|
|
7
|
-
|
|
8
|
-
export type Fields = Record<string, unknown>;
|
|
9
|
-
|
|
10
|
-
// Escapes for quoted values. One record is one line, so a raw newline inside a
|
|
11
|
-
// value would end the record early and the rest of the value would be read
|
|
12
|
-
// back as a separate line of fields. Backslash is escaped too, so a value
|
|
13
|
-
// ending in `\` cannot swallow its closing quote.
|
|
14
|
-
const ESCAPE: Record<string, string> = { "\\": "\\\\", '"': '\\"', "\n": "\\n", "\r": "\\r", "\t": "\\t" };
|
|
15
|
-
const UNESCAPE: Record<string, string> = { "\\": "\\", '"': '"', n: "\n", r: "\r", t: "\t" };
|
|
16
|
-
|
|
17
|
-
// Lines written before these escapes existed stored backslashes raw, so in an
|
|
18
|
-
// old line `C:\new` is a backslash and an `n`, not a newline. A line whose
|
|
19
|
-
// values use the escapes ends with this marker, and only fields before it are
|
|
20
|
-
// unescaped; everything else is read the old way, where only `\"` is an escape.
|
|
21
|
-
// Fields after the marker were appended by an older version (supersede adds
|
|
22
|
-
// fields to the end of an existing line). Lines without backslashes, newlines
|
|
23
|
-
// or tabs read the same either way, so they don't carry the marker.
|
|
24
|
-
const MARKER = "esc";
|
|
25
|
-
const MARKER_VALUE = "1";
|
|
26
|
-
|
|
27
|
-
export function quote(value: unknown): string {
|
|
28
|
-
const s = String(value);
|
|
29
|
-
if (s === "") return '""';
|
|
30
|
-
return /[\s"=]/.test(s) ? `"${s.replace(/[\\"\n\r\t]/g, (c) => ESCAPE[c])}"` : s;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export function formatLine(fields: Fields): string {
|
|
34
|
-
const parts: string[] = [];
|
|
35
|
-
let escaped = false;
|
|
36
|
-
for (const [k, v] of Object.entries(fields)) {
|
|
37
|
-
if (v === undefined || v === null || k === MARKER) continue;
|
|
38
|
-
const q = quote(v);
|
|
39
|
-
if (q.startsWith('"') && /[\\\n\r\t]/.test(String(v))) escaped = true;
|
|
40
|
-
parts.push(`${k}=${q}`);
|
|
41
|
-
}
|
|
42
|
-
if (escaped) parts.push(`${MARKER}=${MARKER_VALUE}`);
|
|
43
|
-
return parts.join(" ");
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// Unescape a quoted logfmt value and read it back. Unknown sequences are kept
|
|
47
|
-
// as written.
|
|
48
|
-
function unquote(s: string): string {
|
|
49
|
-
return s.replace(/\\(.)/g, (seq, c: string) => UNESCAPE[c] ?? seq);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function unquoteLegacy(s: string): string {
|
|
53
|
-
return s.replace(/\\"/g, '"');
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export function parseLine(line: string): Fields | null {
|
|
57
|
-
const trimmed = line.trim();
|
|
58
|
-
if (!trimmed || !trimmed.includes("=")) return null;
|
|
59
|
-
const tokens: [string, string][] = [];
|
|
60
|
-
const re = /([A-Za-z0-9_.-]+)=("(?:[^"\\]|\\.)*"|[^\s]*)/g;
|
|
61
|
-
for (;;) {
|
|
62
|
-
const m = re.exec(trimmed);
|
|
63
|
-
if (!m) break;
|
|
64
|
-
tokens.push([m[1], m[2]]);
|
|
65
|
-
}
|
|
66
|
-
const marker = tokens.findIndex(([k, v]) => k === MARKER && v === MARKER_VALUE);
|
|
67
|
-
const fields: Fields = {};
|
|
68
|
-
tokens.forEach(([key, value], i) => {
|
|
69
|
-
if (key === MARKER) return;
|
|
70
|
-
let raw = value;
|
|
71
|
-
if (raw.startsWith('"') && raw.endsWith('"')) {
|
|
72
|
-
raw = (i < marker ? unquote : unquoteLegacy)(raw.slice(1, -1));
|
|
73
|
-
}
|
|
74
|
-
fields[key] = raw;
|
|
75
|
-
});
|
|
76
|
-
// parse booleans/numbers as strings is fine; callers coerce.
|
|
77
|
-
return fields;
|
|
78
|
-
}
|
|
5
|
+
import { appendFile, mkdir, rename, stat, unlink } from "node:fs/promises";
|
|
6
|
+
import { IS_WINDOWS } from "./format.ts";
|
|
79
7
|
|
|
80
8
|
export async function ensureDir(path: string): Promise<void> {
|
|
81
9
|
await mkdir(path, { recursive: true });
|
|
@@ -177,20 +105,3 @@ async function handoverRename(tmp: string, file: string, since?: string): Promis
|
|
|
177
105
|
}
|
|
178
106
|
}
|
|
179
107
|
}
|
|
180
|
-
|
|
181
|
-
export async function readLines(file: string): Promise<string[]> {
|
|
182
|
-
// BunFile.exists() and .size cache the size; a later text() can crop a larger
|
|
183
|
-
// atomic replacement. Read metadata and bytes through one handle instead.
|
|
184
|
-
let text: string;
|
|
185
|
-
try {
|
|
186
|
-
text = await readFile(file, "utf8");
|
|
187
|
-
} catch (err) {
|
|
188
|
-
if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
189
|
-
throw err;
|
|
190
|
-
}
|
|
191
|
-
return text.split("\n").filter((l) => l.trim().length > 0);
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
export function bracketList(items: string[]): string {
|
|
195
|
-
return `[${items.join(",")}]`;
|
|
196
|
-
}
|