opencode-self-improvement 0.15.4 → 0.15.6
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 +2 -0
- 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} +6 -31
- package/src/core/logfmt/format.ts +82 -0
- package/src/{logfmt.ts → core/logfmt/publish.ts} +20 -96
- package/src/core/logfmt/read.ts +15 -0
- package/src/core/permissions.ts +47 -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 +145 -0
- package/src/status/report.ts +202 -0
- package/src/status/write.ts +114 -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} +5 -4
- 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/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,52 @@
|
|
|
1
|
+
// pull — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { loadAll } from "../store/files/load.ts"
|
|
3
|
+
import { type Memory } from "../store/model/memory.ts"
|
|
4
|
+
import { isInjectable } from "../store/model/predicates.ts"
|
|
5
|
+
import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
|
|
6
|
+
import { injectBudget } from "../core/config/budgets.ts";
|
|
7
|
+
import { FRAME, capToBudget, injectedRows } from "./budget.ts";
|
|
8
|
+
import { formatMemory } from "./format.ts";
|
|
9
|
+
import { type UseSignals, argText } from "../recall/relevant.ts";
|
|
10
|
+
import { scoreMemories } from "../recall/score.ts";
|
|
11
|
+
|
|
12
|
+
export interface TransformOutput {
|
|
13
|
+
system: string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface PullInput {
|
|
17
|
+
tool?: unknown;
|
|
18
|
+
args?: unknown;
|
|
19
|
+
// The session the pull runs FOR (#127): resolved to an immutable Reader at
|
|
20
|
+
// entry so the loadAll await below cannot drift into another session's repo.
|
|
21
|
+
sessionID?: unknown;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface PullOutput {
|
|
25
|
+
output?: unknown;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function contextualPull(
|
|
29
|
+
input: PullInput,
|
|
30
|
+
output: PullOutput,
|
|
31
|
+
budget = injectBudget(),
|
|
32
|
+
use?: UseSignals,
|
|
33
|
+
): Promise<Memory[]> {
|
|
34
|
+
const tool = typeof input.tool === "string" ? input.tool : "";
|
|
35
|
+
if (!["grep", "glob", "read"].includes(tool)) return [];
|
|
36
|
+
const term = argText(input.args);
|
|
37
|
+
if (!term) return [];
|
|
38
|
+
// Repo-scoped: model-facing reads see the CALLER's repo + global rows —
|
|
39
|
+
// the pull's own sessionID, resolved before the store read (#127).
|
|
40
|
+
const mems = visibleTo((await loadAll()).filter(isInjectable), readerFromSid(input.sessionID));
|
|
41
|
+
const top = scoreMemories(term, mems, 3, use);
|
|
42
|
+
if (!top.length) return [];
|
|
43
|
+
// Held to the injection budget too: three long rows were ~12 KB per call.
|
|
44
|
+
const block = capToBudget(`## Related durable memory (pull)${FRAME}\n${top.map(formatMemory).join("\n")}`, budget);
|
|
45
|
+
if (block && typeof output.output === "string") {
|
|
46
|
+
output.output += `\n${block}`;
|
|
47
|
+
// What the ledger counts is what actually rode the result — the budget can
|
|
48
|
+
// drop rows, and crediting a memory the model never saw would inflate it.
|
|
49
|
+
return injectedRows(block, top);
|
|
50
|
+
}
|
|
51
|
+
return [];
|
|
52
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// version — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
// Context surfaces: a small system digest, a capped open-thread frontier, and
|
|
3
|
+
// relevance-ranked memory frozen per epoch by src/index.ts. These ride the
|
|
4
|
+
// session context hook's system parts. Contextual pull appends relevant memory
|
|
5
|
+
// to grep/glob/read results. Evidence is never injected.
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { loadAll } from "../store/files/load.ts"
|
|
8
|
+
import { type Memory } from "../store/model/memory.ts"
|
|
9
|
+
import { isInjectable } from "../store/model/predicates.ts"
|
|
10
|
+
import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
|
|
11
|
+
import { cmpTs } from "../core/cmp-ts.ts";
|
|
12
|
+
import { formatMemory } from "./format.ts";
|
|
13
|
+
|
|
14
|
+
// Deterministic fingerprint of the rows that can affect injection. Hash the
|
|
15
|
+
// exact rendered row plus its full id, in load order: content edits, blocklist
|
|
16
|
+
// changes and supersession all invalidate an epoch, while evidence, hidden
|
|
17
|
+
// rows and non-rendered metadata do not. This is only a linear hash over rows
|
|
18
|
+
// loadAll() already had to read and parse for the request.
|
|
19
|
+
export async function storeVersion(rows?: Memory[], sid?: string): Promise<string> {
|
|
20
|
+
// Repo-scoped: model-facing reads see the caller's repo + global rows.
|
|
21
|
+
const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(isInjectable);
|
|
22
|
+
if (!mems.length) return "0:";
|
|
23
|
+
let max = "";
|
|
24
|
+
const hash = createHash("sha256");
|
|
25
|
+
for (const m of mems) {
|
|
26
|
+
if (cmpTs(m.ts, max) > 0) max = m.ts;
|
|
27
|
+
hash.update(JSON.stringify([m.ts, formatMemory(m)]));
|
|
28
|
+
hash.update("\n");
|
|
29
|
+
}
|
|
30
|
+
return `${mems.length}:${max}:${hash.digest("hex")}`;
|
|
31
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// decay — split from src/portable.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { open } from "node:fs/promises";
|
|
3
|
+
import { loadAll } from "../store/files/load.ts"
|
|
4
|
+
import { type Memory } from "../store/model/memory.ts"
|
|
5
|
+
import { isInjectable } from "../store/model/predicates.ts"
|
|
6
|
+
import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
|
|
7
|
+
|
|
8
|
+
// --- decay support --------------------------------------------------------------
|
|
9
|
+
|
|
10
|
+
// Active open threads with ts older than `days` days, oldest first (both sides
|
|
11
|
+
// are UTC-Z ISO strings, so plain lexicographic compare is correct).
|
|
12
|
+
export async function findStaleOpen(days: number, sid?: string): Promise<Memory[]> {
|
|
13
|
+
const cutoff = new Date(Date.now() - days * 86_400_000).toISOString();
|
|
14
|
+
const reader = readerFromSid(sid);
|
|
15
|
+
return (await loadAll())
|
|
16
|
+
// Decay is repo-scoped: running it here must not retire
|
|
17
|
+
// another repo's open threads.
|
|
18
|
+
.filter((m) => isInjectable(m) && isVisibleTo(m, reader) && m.status === "open" && m.ts < cutoff)
|
|
19
|
+
.sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0));
|
|
20
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
// export — split from src/portable.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
// Portability: JSONL export/import of the durable store, plus the
|
|
3
|
+
// stale-open-thread query that backs memory_decay. Import NEVER writes: every
|
|
4
|
+
// row flows through the caller-provided gate callback (index.ts wires it to
|
|
5
|
+
// runWriteGate), so moving memories between machines cannot bypass the 4-gate
|
|
6
|
+
// moat. Decay is supersede-not-delete and snapshot-first, mirroring prune.
|
|
7
|
+
import { constants } from "node:fs";
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import { mkdir, open } from "node:fs/promises";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
11
|
+
import { allowOutsideStorePaths, exportsDir, memoryRoot } from "../core/config/paths.ts";
|
|
12
|
+
import { resolveContained } from "../store/containment.ts";
|
|
13
|
+
import { loadAll } from "../store/files/load.ts"
|
|
14
|
+
import { isActive } from "../store/model/predicates.ts"
|
|
15
|
+
import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
|
|
16
|
+
|
|
17
|
+
// --- export -------------------------------------------------------------------
|
|
18
|
+
|
|
19
|
+
// Export header line: the first line of a v1 export identifies the file as
|
|
20
|
+
// machine-made by memory_export. It is what vouches for status="open" frontier
|
|
21
|
+
// rows on import — the open status exempts a row from ref grounding at the
|
|
22
|
+
// gate, so it must not be granted by an attacker-chosen field in a
|
|
23
|
+
// hand-written JSONL. The header is friction, not a boundary (anyone can
|
|
24
|
+
// paste one); the real defense against planted content is the injection
|
|
25
|
+
// framing + provenance in inject.ts and the write gates.
|
|
26
|
+
export const EXPORT_HEADER = "opencode-self-improvement";
|
|
27
|
+
|
|
28
|
+
export const EXPORT_VERSION = 1;
|
|
29
|
+
|
|
30
|
+
export interface ExportOptions {
|
|
31
|
+
/** Only export rows from this exact scope. */
|
|
32
|
+
scope?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Destination, confined to <memory-root>/exports/ (see containment.ts).
|
|
35
|
+
* Defaults to <memory-root>/exports/<stamp>-<unique>.jsonl: a UNIQUE name,
|
|
36
|
+
* created exclusively, so two exports in the same second can never replace
|
|
37
|
+
* each other's artifact (#143's review). An explicit `file` keeps the
|
|
38
|
+
* historical replace semantics backups rely on.
|
|
39
|
+
*/
|
|
40
|
+
file?: string;
|
|
41
|
+
/**
|
|
42
|
+
* The calling session's identity (#143): an export carries exactly the rows
|
|
43
|
+
* its reader can read — own repo plus global. "?" or absent resolves the
|
|
44
|
+
* AMBIENT reader: out-of-plugin callers (viewer, CLI maintenance) keep the
|
|
45
|
+
* full-store breadth; breadth stays a property of the entry point.
|
|
46
|
+
*/
|
|
47
|
+
sessionID?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface ExportResult {
|
|
51
|
+
path: string;
|
|
52
|
+
count: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Filesystem-safe YYYY-MM-DDTHHMMSS (no colons) plus a unique suffix for each
|
|
56
|
+
// default export. The timestamp alone was second-granular: two sessions
|
|
57
|
+
// exporting in the same second got the SAME path, and O_TRUNC let the later
|
|
58
|
+
// one destroy the earlier one's artifact AND its returned path (#143 review).
|
|
59
|
+
// Milliseconds would still collide; uniqueness comes from the name, not the
|
|
60
|
+
// clock.
|
|
61
|
+
export function stamp(d: Date = new Date()): string {
|
|
62
|
+
return `${d.toISOString().slice(0, 19).replace(/:/g, "")}-${randomUUID()}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// An export is a full copy of the live store, so it may only be written inside
|
|
66
|
+
// the store's own exports/ directory: ~/.gitconfig, a relative path landing in
|
|
67
|
+
// the host process's cwd, ../.., and links out of the root are all rejected.
|
|
68
|
+
// Only an absent `file` means the default — an empty or whitespace-only one is
|
|
69
|
+
// a caller bug and fails rather than silently redirecting.
|
|
70
|
+
async function resolveExportTarget(file: string | undefined): Promise<string> {
|
|
71
|
+
const allowOutside = allowOutsideStorePaths();
|
|
72
|
+
const opts = {
|
|
73
|
+
label: "memory_export file",
|
|
74
|
+
hint: `omit file for the default, or name a path under ${exportsDir()}`,
|
|
75
|
+
// An exports/ that is itself a symlink must not move the write out of the
|
|
76
|
+
// store either — same two-level check undo.ts's restore makes.
|
|
77
|
+
outerRoot: memoryRoot(),
|
|
78
|
+
allowOutside,
|
|
79
|
+
};
|
|
80
|
+
// A default destination is still a destination. Routing it through the same
|
|
81
|
+
// check is what stops an exports/ that is a link from writing the whole store
|
|
82
|
+
// copy outside the store on the argument-free call — the one a model reaches
|
|
83
|
+
// without knowing anything about the layout. Under the operator escape hatch
|
|
84
|
+
// there is nothing to check, so the plain join is what remains.
|
|
85
|
+
if (file === undefined && allowOutside) return join(exportsDir(), `${stamp()}.jsonl`);
|
|
86
|
+
return resolveContained(file ?? `${stamp()}.jsonl`, exportsDir(), opts);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// An export is a plaintext copy of the whole store, so it is written 0600 and
|
|
90
|
+
// opened O_NOFOLLOW. The flag matters: the containment check and this open are
|
|
91
|
+
// separate syscalls, and the gap is the entire store read — single-digit to tens
|
|
92
|
+
// of milliseconds on a 5 000-row store depending on the machine, which is long
|
|
93
|
+
// enough for anything that can create a link inside exports/.
|
|
94
|
+
//
|
|
95
|
+
// Both are POSIX guarantees. libuv does not implement O_NOFOLLOW on Windows
|
|
96
|
+
// (verified on the CI windows leg: the open follows the link) and Windows
|
|
97
|
+
// reports every writable file as 0666, so there the containment check that ran
|
|
98
|
+
// before this call is the only protection.
|
|
99
|
+
//
|
|
100
|
+
// Exported so the flag itself can be pinned: the containment layer refuses an
|
|
101
|
+
// existing link long before this runs, so the only way to test O_NOFOLLOW
|
|
102
|
+
// without racing is to call the writer directly.
|
|
103
|
+
export async function writeExport(path: string, text: string, exclusive = false): Promise<void> {
|
|
104
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
105
|
+
// exclusive = a default destination WE chose: create it or fail, never
|
|
106
|
+
// silently replace another export's file. An explicit caller-supplied
|
|
107
|
+
// `file` keeps the historical O_TRUNC replace (backup workflows rewrite
|
|
108
|
+
// the same path on purpose).
|
|
109
|
+
const flags =
|
|
110
|
+
constants.O_WRONLY |
|
|
111
|
+
constants.O_CREAT |
|
|
112
|
+
(exclusive ? constants.O_EXCL : constants.O_TRUNC) |
|
|
113
|
+
(constants.O_NOFOLLOW ?? 0);
|
|
114
|
+
const handle = await open(path, flags, 0o600);
|
|
115
|
+
try {
|
|
116
|
+
await handle.writeFile(text, "utf8");
|
|
117
|
+
// open()'s mode applies only when the file is created, so re-exporting over
|
|
118
|
+
// a file that already existed (a 0644 one, say) would otherwise leave it
|
|
119
|
+
// world-readable and make the 0600 above a claim rather than a guarantee.
|
|
120
|
+
await handle.chmod(0o600);
|
|
121
|
+
} finally {
|
|
122
|
+
await handle.close();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Write the ACTIVE store as JSONL — a header line followed by one JSON object
|
|
127
|
+
// per line carrying {ts,type,scope,content,status,tags,issue}. Superseded rows
|
|
128
|
+
// are not exported: the export is the live store, and history stays auditable
|
|
129
|
+
// where it lives (the original logfmt files + snapshots). The header is always
|
|
130
|
+
// written, even for an empty store, so "has header" is a format invariant.
|
|
131
|
+
//
|
|
132
|
+
// "the live store" means the store AS THE CALLER CAN READ IT (#143): rows are
|
|
133
|
+
// filtered through the caller's Reader, exactly as recall and injection do.
|
|
134
|
+
// Full breadth remains the ambient/admin entry point's, never a missing
|
|
135
|
+
// session's.
|
|
136
|
+
//
|
|
137
|
+
// The destination is model-supplied, so it is resolved and confined BEFORE the
|
|
138
|
+
// store is read: a rejected export must not leave a file behind, and must not
|
|
139
|
+
// be a way to learn how many rows matched either.
|
|
140
|
+
export async function exportMemories(opts: ExportOptions = {}): Promise<ExportResult> {
|
|
141
|
+
const path = await resolveExportTarget(opts.file);
|
|
142
|
+
const reader = readerFromSid(opts.sessionID);
|
|
143
|
+
let mems = (await loadAll()).filter(isActive).filter((m) => isVisibleTo(m, reader));
|
|
144
|
+
if (opts.scope) mems = mems.filter((m) => m.scope === opts.scope);
|
|
145
|
+
const header = JSON.stringify({
|
|
146
|
+
_export: EXPORT_HEADER,
|
|
147
|
+
version: EXPORT_VERSION,
|
|
148
|
+
exportedAt: new Date().toISOString(),
|
|
149
|
+
count: mems.length,
|
|
150
|
+
});
|
|
151
|
+
const lines = mems.map((m) =>
|
|
152
|
+
JSON.stringify({
|
|
153
|
+
ts: m.ts,
|
|
154
|
+
type: m.type,
|
|
155
|
+
scope: m.scope,
|
|
156
|
+
content: m.content,
|
|
157
|
+
status: m.status,
|
|
158
|
+
tags: m.tags,
|
|
159
|
+
kw: m.kw,
|
|
160
|
+
issue: m.issue,
|
|
161
|
+
// Origin stamps ride along so a same-repo machine hop can retain them.
|
|
162
|
+
// Import validates them against its current repo before promotion.
|
|
163
|
+
repo: m.repo,
|
|
164
|
+
repoPath: m.repoPath,
|
|
165
|
+
}),
|
|
166
|
+
);
|
|
167
|
+
try {
|
|
168
|
+
await writeExport(path, `${[header, ...lines].join("\n")}\n`, opts.file === undefined);
|
|
169
|
+
} catch (err) {
|
|
170
|
+
// Past containment, so this is not an existence oracle: `path` is one the
|
|
171
|
+
// plugin chose or already validated. The errno stays, because it is the
|
|
172
|
+
// operator's only diagnostic — but in our sentence rather than the runtime's,
|
|
173
|
+
// so a model-facing tool result never carries a raw stack-adjacent string.
|
|
174
|
+
const code = err instanceof Error && "code" in err ? String(err.code) : "unknown error";
|
|
175
|
+
throw new Error(`memory_export could not write ${path} (${code})`);
|
|
176
|
+
}
|
|
177
|
+
return { path, count: mems.length };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Recognize the export header line (see EXPORT_HEADER). A version NEWER than
|
|
181
|
+
// we understand does NOT grant the frontier exemption — we cannot know what
|
|
182
|
+
// its writer meant (fail closed).
|
|
183
|
+
export function exportHeader(line: string): { version: number } | null {
|
|
184
|
+
let row: unknown;
|
|
185
|
+
try {
|
|
186
|
+
row = JSON.parse(line);
|
|
187
|
+
} catch {
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) return null;
|
|
191
|
+
const r = row as Record<string, unknown>;
|
|
192
|
+
if (r._export !== EXPORT_HEADER) return null;
|
|
193
|
+
return { version: typeof r.version === "number" ? r.version : 1 };
|
|
194
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// import — split from src/portable.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { open, readFile } from "node:fs/promises";
|
|
3
|
+
import { allowOutsideStorePaths, memoryRoot } from "../core/config/paths.ts";
|
|
4
|
+
import { resolveContained } from "../store/containment.ts";
|
|
5
|
+
import { isQuarantined, quarantineCandidate } from "../store/quarantine/quarantine.ts";
|
|
6
|
+
import { UnresolvedWriterError } from "../store/files/append.ts";
|
|
7
|
+
import { writeTarget } from "../identity/repokey.ts";
|
|
8
|
+
import { getCurrent } from "../core/state.ts";
|
|
9
|
+
import { TYPES } from "../core/types.ts";
|
|
10
|
+
import type { WriteCandidate } from "../gate/gate.ts";
|
|
11
|
+
import { flattenMemoryText } from "../store/sanitize.ts";
|
|
12
|
+
import { EXPORT_VERSION, exportHeader, stamp } from "./export.ts";
|
|
13
|
+
|
|
14
|
+
// --- import -------------------------------------------------------------------
|
|
15
|
+
|
|
16
|
+
export interface ImportTally {
|
|
17
|
+
promoted: number;
|
|
18
|
+
quarantined?: number;
|
|
19
|
+
collapsed: number;
|
|
20
|
+
blocked: number;
|
|
21
|
+
skipped: number;
|
|
22
|
+
/** Open rows downgraded because the file cannot grant that frontier scope. */
|
|
23
|
+
downgraded: number;
|
|
24
|
+
/** Promoted rows whose write_promoted audit line failed to land (#155 review). */
|
|
25
|
+
unaudited: number;
|
|
26
|
+
/** First audit-fault message, so the reply can name what went wrong. */
|
|
27
|
+
auditError?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// A line is malformed (skipped, never gated) unless it is a JSON object with a
|
|
31
|
+
// known type, a non-empty scope, and non-empty content. Optional fields are
|
|
32
|
+
// sanitized rather than fatal where noted. Control characters in structured
|
|
33
|
+
// metadata make the row malformed; content alone may remain multiline.
|
|
34
|
+
function parseRow(line: string): WriteCandidate | null {
|
|
35
|
+
let row: unknown;
|
|
36
|
+
try {
|
|
37
|
+
row = JSON.parse(line);
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) return null;
|
|
42
|
+
const r = row as Record<string, unknown>;
|
|
43
|
+
if (typeof r.type !== "string" || !(TYPES as readonly string[]).includes(r.type)) return null;
|
|
44
|
+
if (typeof r.scope !== "string" || !r.scope.trim()) return null;
|
|
45
|
+
if (flattenMemoryText(r.scope) !== r.scope) return null;
|
|
46
|
+
if (typeof r.content !== "string" || !r.content.trim()) return null;
|
|
47
|
+
if (
|
|
48
|
+
Array.isArray(r.tags) &&
|
|
49
|
+
r.tags.some((t) => typeof t === "string" && flattenMemoryText(t) !== t)
|
|
50
|
+
) return null;
|
|
51
|
+
if (typeof r.issue === "string" && flattenMemoryText(r.issue) !== r.issue) return null;
|
|
52
|
+
// Keywords widen recall only, so a malformed entry costs them, never the row
|
|
53
|
+
// (contrast scope/content, where a bad value makes the line malformed).
|
|
54
|
+
const kw = Array.isArray(r.kw)
|
|
55
|
+
? r.kw.filter(
|
|
56
|
+
(k): k is string =>
|
|
57
|
+
typeof k === "string" && !!k.trim() && flattenMemoryText(k.trim()) === k.trim(),
|
|
58
|
+
)
|
|
59
|
+
: undefined;
|
|
60
|
+
const c: WriteCandidate = { type: r.type, scope: r.scope, content: r.content };
|
|
61
|
+
if (r.status === "open" || r.status === "settled") c.status = r.status;
|
|
62
|
+
if (Array.isArray(r.tags) && r.tags.every((t) => typeof t === "string")) c.tags = r.tags;
|
|
63
|
+
if (kw?.length) c.kw = kw;
|
|
64
|
+
if (typeof r.issue === "string" && r.issue) c.issue = r.issue;
|
|
65
|
+
// Origin stamps survive an export/import hop (repokey.ts): a row written
|
|
66
|
+
// for repo X stays visible only where repo X is opened, even on a new
|
|
67
|
+
// machine. Unstamped rows stay global.
|
|
68
|
+
if (typeof r.repo === "string" && r.repo) c.repo = r.repo;
|
|
69
|
+
if (typeof r.repoPath === "string" && r.repoPath) c.repoPath = r.repoPath;
|
|
70
|
+
return quarantineCandidate(c);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Read a JSONL export and run every valid row through `gate`. The CALLER owns
|
|
74
|
+
// promotion (index.ts passes runWriteGate with the "import" tag), so imported
|
|
75
|
+
// rows face the same canonical/stale/dedup/ambiguity gates as any other write.
|
|
76
|
+
// Blocked and collapsed rows are normal outcomes, tallied rather than raised.
|
|
77
|
+
// Frontier policy: status="open" exempts a row from ref grounding
|
|
78
|
+
// at the gate, so it is honored ONLY when the file opens with our export
|
|
79
|
+
// header (version <= ours); otherwise every open row is downgraded to settled
|
|
80
|
+
// and tallied. Imported origin stamps are honored only when they match the
|
|
81
|
+
// importing session's current repo (or are an explicit "global"); foreign
|
|
82
|
+
// stamps are removed so the write choke point stamps the importing repo
|
|
83
|
+
// instead. With no current scope, stamps are kept (removing them would widen
|
|
84
|
+
// the row to global) and a stamped open row is downgraded, since its stamp
|
|
85
|
+
// cannot be verified. Only a missing file throws.
|
|
86
|
+
//
|
|
87
|
+
// The path is a model-supplied READ primitive, so it is confined to the memory
|
|
88
|
+
// root BEFORE the filesystem is touched, and containment's error never says
|
|
89
|
+
// whether the path exists — otherwise a rejection is an existence oracle for
|
|
90
|
+
// files outside the store. The .jsonl requirement closes the rest of that door:
|
|
91
|
+
// without it, the tally ("N malformed lines skipped") would leak line counts of
|
|
92
|
+
// day files, snapshots and the blocklist, none of which are import formats.
|
|
93
|
+
export async function importMemories(
|
|
94
|
+
path: string,
|
|
95
|
+
gate: (c: WriteCandidate) => Promise<{ action: string; evidenceError?: string }>,
|
|
96
|
+
// The importing session, captured at tool entry (#127): "the importing
|
|
97
|
+
// session's current repo" must be the CALLER's repo even though this loop
|
|
98
|
+
// awaits the gate on every row, during which a concurrent session can move
|
|
99
|
+
// the ambient current.
|
|
100
|
+
sessionID?: string,
|
|
101
|
+
): Promise<ImportTally> {
|
|
102
|
+
// Capture the importing owner before file I/O: later session moves must not
|
|
103
|
+
// re-home rows partway through the import (#183). Resolve with the writer
|
|
104
|
+
// rule so an unresolved named session never borrows the ambient repo (#152).
|
|
105
|
+
const writeAt = writeTarget(sessionID ?? getCurrent().sid);
|
|
106
|
+
const target = await resolveContained(path, memoryRoot(), {
|
|
107
|
+
label: "memory_import file",
|
|
108
|
+
// Deliberately no mention of the operator escape hatch: this string goes
|
|
109
|
+
// back to the model, and naming the variable there is an instruction it can
|
|
110
|
+
// relay. The hatch lives in the README.
|
|
111
|
+
hint: `copy the export under ${memoryRoot()} first`,
|
|
112
|
+
allowOutside: allowOutsideStorePaths(),
|
|
113
|
+
});
|
|
114
|
+
if (!target.toLowerCase().endsWith(".jsonl")) {
|
|
115
|
+
throw new Error(`memory_import file must be a .jsonl export (got "${path}")`);
|
|
116
|
+
}
|
|
117
|
+
let text: string;
|
|
118
|
+
try {
|
|
119
|
+
text = await readFile(target, "utf8");
|
|
120
|
+
} catch (err) {
|
|
121
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") throw new Error(`import file not found: ${target}`);
|
|
122
|
+
throw err;
|
|
123
|
+
}
|
|
124
|
+
const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0, unaudited: 0 };
|
|
125
|
+
// Preserve file-validation error precedence, but reject an unresolved owner
|
|
126
|
+
// before gating any row. Resolution happened at entry, not at this await.
|
|
127
|
+
if (!writeAt.ok) throw new UnresolvedWriterError(writeAt.sid);
|
|
128
|
+
const currentScope = writeAt.scope;
|
|
129
|
+
let allowFrontier = false;
|
|
130
|
+
let first = true;
|
|
131
|
+
for (const line of text.replace(/^\uFEFF/, "").split("\n")) {
|
|
132
|
+
if (!line.trim()) continue;
|
|
133
|
+
if (first) {
|
|
134
|
+
first = false;
|
|
135
|
+
const hdr = exportHeader(line);
|
|
136
|
+
if (hdr) {
|
|
137
|
+
allowFrontier = hdr.version <= EXPORT_VERSION;
|
|
138
|
+
continue; // metadata line: never a memory row, never a skipped one
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const c = parseRow(line);
|
|
142
|
+
if (!c) {
|
|
143
|
+
tally.skipped++;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const claimedGlobal = c.repo === "global";
|
|
147
|
+
const hadStamp = c.repo !== undefined || c.repoPath !== undefined;
|
|
148
|
+
// A foreign stamp is treated like no stamp, so appendMemory stamps the
|
|
149
|
+
// importing repo. Explicit "global" is not a foreign repo and is kept (open
|
|
150
|
+
// global rows are downgraded below). With no current scope there is nothing
|
|
151
|
+
// to re-stamp with: dropping the stamp would widen the row to global, so it
|
|
152
|
+
// is kept and only the open-row exemption is withdrawn.
|
|
153
|
+
if (currentScope && !claimedGlobal) {
|
|
154
|
+
if (c.repo !== currentScope.key) delete c.repo;
|
|
155
|
+
if (c.repoPath !== currentScope.path) delete c.repoPath;
|
|
156
|
+
}
|
|
157
|
+
if (c.status === "open" && (!allowFrontier || claimedGlobal || (hadStamp && !currentScope))) {
|
|
158
|
+
c.status = "settled";
|
|
159
|
+
tally.downgraded++;
|
|
160
|
+
}
|
|
161
|
+
const outcome = await gate(c);
|
|
162
|
+
if (outcome.action === "promoted") {
|
|
163
|
+
tally.promoted++;
|
|
164
|
+
if (isQuarantined(c)) tally.quarantined = (tally.quarantined ?? 0) + 1;
|
|
165
|
+
if (outcome.evidenceError !== undefined) {
|
|
166
|
+
tally.unaudited++;
|
|
167
|
+
tally.auditError ??= outcome.evidenceError;
|
|
168
|
+
}
|
|
169
|
+
} else if (outcome.action === "collapsed") tally.collapsed++;
|
|
170
|
+
else tally.blocked++;
|
|
171
|
+
}
|
|
172
|
+
return tally;
|
|
173
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// relevant — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { loadAll } from "../store/files/load.ts"
|
|
3
|
+
import { type Memory } from "../store/model/memory.ts"
|
|
4
|
+
import { isInjectable } from "../store/model/predicates.ts"
|
|
5
|
+
import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
|
|
6
|
+
import { FRAME } from "../inject/budget.ts";
|
|
7
|
+
import { formatMemory } from "../inject/format.ts";
|
|
8
|
+
import { scoreMemories } from "./score.ts";
|
|
9
|
+
|
|
10
|
+
export function argText(args: unknown): string {
|
|
11
|
+
if (!args || typeof args !== "object") return "";
|
|
12
|
+
const a = args as Record<string, unknown>;
|
|
13
|
+
for (const k of ["pattern", "query", "path", "filePath", "command"]) {
|
|
14
|
+
const v = a[k];
|
|
15
|
+
if (typeof v === "string" && v) return v;
|
|
16
|
+
}
|
|
17
|
+
return "";
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The content concepts a query and a row actually share (stopwords dropped,
|
|
22
|
+
* capped, `ts` never included). This is what the use ledger records (#42):
|
|
23
|
+
* every term in it already exists inside the row, so a hit line reveals
|
|
24
|
+
* nothing about the prompt beyond the memory it points at — and it is enough
|
|
25
|
+
* for #45 to replay a merge and prove the same reads would still land.
|
|
26
|
+
*/
|
|
27
|
+
/** The text a contextual pull actually searched with, for hit bookkeeping. */
|
|
28
|
+
export function pullQuery(args: unknown): string {
|
|
29
|
+
return argText(args);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Reinforcement (#42): a row the ledger has seen used breaks a tie over a row
|
|
33
|
+
// nobody ever read, and the more recently used one breaks it first. A TIE-BREAK
|
|
34
|
+
// only — the two-concept gate and IDF score still decide relevance, because
|
|
35
|
+
// popularity is not truth: reinforcement without evidence just amplifies
|
|
36
|
+
// whatever was retrieved first.
|
|
37
|
+
export interface UseSignals {
|
|
38
|
+
get(ts: string): { count: number; last: string } | undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function useBoost(a: Memory | undefined, use?: UseSignals): number {
|
|
42
|
+
if (!use || !a) return 0;
|
|
43
|
+
return use.get(a.ts) ? 1 : 0;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Select the rows relevant to a prompt and render the injection block, AND
|
|
47
|
+
// return the rows themselves so attribution (src/attribution.ts) can join the
|
|
48
|
+
// injected facts against the session's later tool calls. `relevantKnowledge`
|
|
49
|
+
// keeps its string contract for every existing caller; this is the richer seam.
|
|
50
|
+
export async function selectRelevant(
|
|
51
|
+
message: string,
|
|
52
|
+
limit = 3,
|
|
53
|
+
rows?: Memory[],
|
|
54
|
+
use?: UseSignals,
|
|
55
|
+
sid?: string,
|
|
56
|
+
): Promise<{ block: string; selected: Memory[] }> {
|
|
57
|
+
const text = message.trim();
|
|
58
|
+
if (!text) return { block: "", selected: [] };
|
|
59
|
+
// Repo-scoped: model-facing reads see the caller's repo + global rows
|
|
60
|
+
// (their session when one was threaded, #127).
|
|
61
|
+
const mems = (rows ?? visibleTo(await loadAll(), readerFromSid(sid))).filter(isInjectable);
|
|
62
|
+
const top = scoreMemories(text, mems, limit, use);
|
|
63
|
+
if (!top.length) return { block: "", selected: [] };
|
|
64
|
+
return {
|
|
65
|
+
block: `## Relevant durable memory${FRAME}\n${top.map(formatMemory).join("\n")}`,
|
|
66
|
+
selected: top,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function relevantKnowledge(message: string, limit = 3, rows?: Memory[]): Promise<string> {
|
|
71
|
+
return (await selectRelevant(message, limit, rows)).block;
|
|
72
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// score — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { loadAll } from "../store/files/load.ts"
|
|
3
|
+
import { type Memory } from "../store/model/memory.ts"
|
|
4
|
+
import { isInjectable } from "../store/model/predicates.ts";
|
|
5
|
+
import { cmpTs } from "../core/cmp-ts.ts";
|
|
6
|
+
import { type UseSignals, useBoost } from "./relevant.ts";
|
|
7
|
+
|
|
8
|
+
export function words(text: string): string[] {
|
|
9
|
+
return text
|
|
10
|
+
.toLowerCase()
|
|
11
|
+
.split(/[^a-z0-9_]+/)
|
|
12
|
+
.filter((t) => t.length > 2);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Query-side stopwords: bag-of-words scoring has no IDF, so "the/what/how"
|
|
16
|
+
// match a large share of every memory and let a query with ZERO content
|
|
17
|
+
// overlap rank. Dropping them makes the matcher abstain — inject nothing — when the vocabulary
|
|
18
|
+
// genuinely has nothing in common, instead of injecting confident noise.
|
|
19
|
+
// Memory-side tokens are never filtered: a memory stating "the" must not
|
|
20
|
+
// gain or lose rank from it, only queries drive matching.
|
|
21
|
+
export const QUERY_STOPWORDS = new Set(
|
|
22
|
+
"a an and are at be but by can did do does for from had has have how i in into is it its me my no not of on or our so than that the their them then there these they this to us was we were what when where which who why will with you your run runs getting want needs right back yet also just still ever should would could might may must shall ought nothing something anything everything thing things".split(" "),
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
// A free-text prompt long enough to carry >= this many content tokens must
|
|
26
|
+
// share >= 2 distinct concepts with a memory to inject: with a long query
|
|
27
|
+
// vocabulary, one shared token is near-certain coincidence (a live store hit
|
|
28
|
+
// injected a git memory on the word "should", df=1). A keyword-length query
|
|
29
|
+
// is a deliberate search — one shared concept suffices. memory_recall and the
|
|
30
|
+
// contextual pull keep single-overlap matches reachable; injection just stays
|
|
31
|
+
// quiet unless the vocabulary genuinely agrees twice.
|
|
32
|
+
const LONG_QUERY_TOKENS = 3;
|
|
33
|
+
|
|
34
|
+
// Production relevance ranking. Candidates must clear the concept-overlap
|
|
35
|
+
// gate, then rank by Robertson-IF of the shared tokens (rare concepts beat
|
|
36
|
+
// piles of common ones — the same idf form the bench's BM25 row uses).
|
|
37
|
+
// Ties break deliberately, in this order: open threads first (a pinned frontier
|
|
38
|
+
// row beats an equal-scoring settled one — that is what the frontier is for),
|
|
39
|
+
// then rows the use ledger has actually retrieved, most-recently-used first
|
|
40
|
+
// (#42 reinforcement), then the newer row (#40 item 2: between two equally
|
|
41
|
+
// relevant facts, the one stating what is true NOW is the better guess;
|
|
42
|
+
// epoch-freeze-safe because ts never changes for a given row).
|
|
43
|
+
// The haystack is `scope + type + content + kw`, where `kw` are the
|
|
44
|
+
// author-supplied aliases indexed at write time (#40 item 3, the vocabulary
|
|
45
|
+
// bridge for the bench's strict-paraphrase wall). Keywords are indexed, never
|
|
46
|
+
// rendered, so they cannot change what a block costs.
|
|
47
|
+
// Exported for bench/recall-quality.ts — the benchmark measures the shipped
|
|
48
|
+
// matcher.
|
|
49
|
+
//
|
|
50
|
+
// Superseded rows are dropped HERE, not only by the callers. Every model-facing
|
|
51
|
+
// sink already passes isInjectable() rows, but a scorer that can be handed a raw
|
|
52
|
+
// loadAll() result must not be the one place a retired memory leaks back into
|
|
53
|
+
// an injected block (#43 item 1: forbidden hits). The drop also keeps a
|
|
54
|
+
// retired row from diluting the document frequencies the ranking depends on.
|
|
55
|
+
export function scoreMemories(
|
|
56
|
+
term: string,
|
|
57
|
+
mems: Memory[],
|
|
58
|
+
limit: number,
|
|
59
|
+
use?: UseSignals,
|
|
60
|
+
): Memory[] {
|
|
61
|
+
const live = mems.filter(isInjectable);
|
|
62
|
+
const query = new Set(words(term).filter((t) => !QUERY_STOPWORDS.has(t)));
|
|
63
|
+
if (!query.size) return [];
|
|
64
|
+
const needShared = query.size >= LONG_QUERY_TOKENS ? 2 : 1;
|
|
65
|
+
const hays = live.map((m) => new Set(words(haystack(m))));
|
|
66
|
+
const df = new Map<string, number>();
|
|
67
|
+
for (const h of hays) for (const t of h) df.set(t, (df.get(t) ?? 0) + 1);
|
|
68
|
+
const n = live.length || 1;
|
|
69
|
+
return live
|
|
70
|
+
.map((m, i) => {
|
|
71
|
+
let shared = 0;
|
|
72
|
+
let score = 0;
|
|
73
|
+
for (const w of query)
|
|
74
|
+
if (hays[i]!.has(w)) {
|
|
75
|
+
shared++;
|
|
76
|
+
const d = df.get(w) ?? 0;
|
|
77
|
+
score += Math.log(1 + (n - d + 0.5) / (d + 0.5));
|
|
78
|
+
}
|
|
79
|
+
return { m, shared, score };
|
|
80
|
+
})
|
|
81
|
+
.filter((s) => s.shared >= needShared)
|
|
82
|
+
.sort(
|
|
83
|
+
(a, b) =>
|
|
84
|
+
b.score - a.score ||
|
|
85
|
+
openRank(b.m) - openRank(a.m) ||
|
|
86
|
+
useBoost(b.m, use) - useBoost(a.m, use) ||
|
|
87
|
+
cmpTs(use?.get(b.m.ts)?.last ?? "", use?.get(a.m.ts)?.last ?? "") ||
|
|
88
|
+
cmpTs(b.m.ts, a.m.ts),
|
|
89
|
+
)
|
|
90
|
+
.slice(0, limit)
|
|
91
|
+
.map((s) => s.m);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// What a row is matched against. Kept in one place so the bench's arms and
|
|
95
|
+
// production can never disagree about the indexed fields.
|
|
96
|
+
export function haystack(m: Memory): string {
|
|
97
|
+
return `${m.scope} ${m.type} ${m.content}${m.kw?.length ? ` ${m.kw.join(" ")}` : ""}`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function openRank(m: Memory): number {
|
|
101
|
+
return m.status === "open" ? 1 : 0;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function omittedLine(count: number): string {
|
|
105
|
+
return `+ ${count} open ${count === 1 ? "thread" : "threads"} omitted: over budget`;
|
|
106
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// shared-terms — split from src/inject.ts (#168 domain restructure). Declaration bodies are unchanged.
|
|
2
|
+
import { type Memory } from "../store/model/memory.ts";
|
|
3
|
+
import { QUERY_STOPWORDS, haystack, words } from "./score.ts";
|
|
4
|
+
|
|
5
|
+
export function sharedTerms(query: string, m: Memory, cap = 8): string[] {
|
|
6
|
+
const q = new Set(words(query).filter((t) => !QUERY_STOPWORDS.has(t)));
|
|
7
|
+
if (!q.size) return [];
|
|
8
|
+
const hay = new Set(words(haystack(m)));
|
|
9
|
+
const out: string[] = [];
|
|
10
|
+
for (const t of q) {
|
|
11
|
+
if (hay.has(t) && !out.includes(t)) out.push(t);
|
|
12
|
+
if (out.length === cap) break;
|
|
13
|
+
}
|
|
14
|
+
return out;
|
|
15
|
+
}
|