opencode-self-improvement 0.33.3 → 0.33.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/README.md +1 -1
- package/docs/internals/injection-cost.md +1 -0
- package/docs/internals/secret-redaction.md +5 -0
- package/docs/internals/use-ledger.md +9 -1
- package/docs/internals/write-gates.md +2 -0
- package/docs/reference/options.md +47 -0
- package/docs/reference/troubleshooting.md +1 -0
- package/package.json +2 -1
- package/src/events.ts +41 -14
- package/src/gate/gate.ts +1 -1
- package/src/gate/resolver.ts +114 -14
- package/src/index.ts +25 -0
- package/src/inject/pull.ts +239 -5
- package/src/recall/relevant.ts +16 -4
- package/src/store/lock.ts +38 -1
package/README.md
CHANGED
|
@@ -53,7 +53,7 @@ Zero configuration is the default. Two options change what the model sees:
|
|
|
53
53
|
| `injectBudget` | `1200` | Character cap on the injected relevance block and each contextual pull. |
|
|
54
54
|
| `frontierBudget` | `3 × injectBudget` | Character cap on the session-start open-threads block. A thread longer than the budget is not injected and is reported as omitted. |
|
|
55
55
|
|
|
56
|
-
Everything else goes in the object form of the plugin entry, and is documented once with its invalid-value rule: the capture options, `contradictionSurface`, `notifyBlocked`, and every environment variable in [docs/reference/options.md](docs/reference/options.md). Read [docs/reference/flags.md](docs/reference/flags.md) before flipping `OPENCODE_MEMORY_DEDUP`, `OPENCODE_MEMORY_SYMPTOM` or `OPENCODE_MEMORY_QUERY_GATE` — each switches off behaviour a measurement decided, and each has an invalid-value rule that surprises people.
|
|
56
|
+
Everything else goes in the object form of the plugin entry, and is documented once with its invalid-value rule: the capture options, `contradictionSurface`, `notifyBlocked`, the contextual pull's scope (`pullOutputChars`, `pullTools`, with the bench behind each default), and every environment variable in [docs/reference/options.md](docs/reference/options.md). Read [docs/reference/flags.md](docs/reference/flags.md) before flipping `OPENCODE_MEMORY_DEDUP`, `OPENCODE_MEMORY_SYMPTOM` or `OPENCODE_MEMORY_QUERY_GATE` — each switches off behaviour a measurement decided, and each has an invalid-value rule that surprises people.
|
|
57
57
|
|
|
58
58
|
## Auto-capture
|
|
59
59
|
|
|
@@ -17,6 +17,7 @@ claim, and a provider audit reported by its author.
|
|
|
17
17
|
- **User-stated guidance rides ahead of relevance.** A row auto-capture tagged `user-guided` — something you said outright, like "the correct sales tax rate is 8.25%" — rides the block ahead of the lexical picks: newest-first, at most three, and `injectBudget` still bounds the whole block (`test/inject/hint-channel.test.ts`). The channel exists because ranking cannot bridge vocabulary: a prompt about "the injected bug" shares no word with a row stating a tax rate, and the shipped matcher scored it zero ([#334](https://github.com/abogartz/opencode-self-improvement/issues/334)). `memory_recall` and the contextual pull stay query-driven — the channel changes only what rides the prompt. Because always-riding priority is a poisoning amplifier, the tag is minted by auto-capture alone: `memory_remember`, `memory_update` replacements and JSONL imports strip it, along with the contradiction fields ([#342](https://github.com/abogartz/opencode-self-improvement/issues/342), `test/gate/guidance-provenance.test.ts`).
|
|
18
18
|
- **The block re-scores at every user turn.** An epoch is not frozen at the first request: a later prompt re-scores, and the epoch MOVES only when the rendered bytes move — a prompt change that selects the same rows in the same order costs no cache bust ([#340](https://github.com/abogartz/opencode-self-improvement/issues/340), `test/inject/epoch.test.ts`). Order is part of those bytes on this build: the lexical picks render in score order, so a prompt that keeps the same rows and re-ranks them moves the bytes and pays the bust. Canonical render order, which removes that churn, is still open ([#388](https://github.com/abogartz/opencode-self-improvement/issues/388), [#396](https://github.com/abogartz/opencode-self-improvement/pull/396)).
|
|
19
19
|
- **Hard budgets.** Relevance block and each pull are capped at `injectBudget` characters, the frontier at `frontierBudget`, trimmed at whole-memory boundaries.
|
|
20
|
+
- **The pull is the un-cached channel.** The relevance block rides the frozen system prefix, so extra bytes there cost a cache bust; the contextual pull rides the tool result instead, which is free of the cache but also free of its discipline. That asymmetry is why its scope is measured per arm — `bench/runners/pull-precision.ts`, table and reasoning in [docs/reference/options.md](../reference/options.md) — and why widening it is a precision decision rather than a coverage one.
|
|
20
21
|
- **Nothing volatile on the cached prefix.** The standing digest carries no row count and no latest timestamp. Both used to ride the very front of the system prompt, so every saved memory rewrote the prefix and made the next request re-bill the whole conversation; the exact numbers now live where they are free — the footer badge, `/memory`, `memory_status`, the viewer.
|
|
21
22
|
- **Evidence is never injected**, and the standing system digest is two lines.
|
|
22
23
|
- **Measured, not claimed.** The plugin reads each turn's `tokens.cache` accounting and displays the actual hit rate next to the badge. The same receipts now carry what the session generated — `output` and `reasoning`, shown split, because on a reasoning-heavy seat the completion side is where the cost actually goes. A host that reports neither shows nothing, never a zero.
|
|
@@ -31,6 +31,11 @@ blocks, and high-entropy values assigned to names ending in `_KEY`, `_TOKEN`,
|
|
|
31
31
|
|
|
32
32
|
- It can miss hex-only secrets, low-diversity passwords, and credentials written
|
|
33
33
|
in prose without an assignment.
|
|
34
|
+
- The credential-shaped sweep needs 16 characters, so `password=hunter2` is
|
|
35
|
+
stored exactly as written. That floor is what keeps a short ordinary value —
|
|
36
|
+
a version string, an identifier carrying a digit — from being blanked wherever
|
|
37
|
+
it follows a name ending in `_KEY`, `_TOKEN`, `_SECRET` or `_PASSWORD`, which
|
|
38
|
+
is why it is a floor rather than a number to lower in passing.
|
|
34
39
|
- Credential-shaped `scope`, `tags` or `issue` metadata is rejected rather than
|
|
35
40
|
silently rewritten.
|
|
36
41
|
- `memory_remember` still replies `Remembered` when content was redacted, so the
|
|
@@ -29,7 +29,15 @@ harness offered" are different facts:
|
|
|
29
29
|
|
|
30
30
|
1. the row rode the injected block;
|
|
31
31
|
2. `memory_recall` returned it;
|
|
32
|
-
3. a grep/read
|
|
32
|
+
3. a pull appended it to a grep/glob/read result — searched against that call's
|
|
33
|
+
arguments plus the first 512 characters of what the tool printed, so a row can
|
|
34
|
+
be credited here for something the model had not asked about yet
|
|
35
|
+
(`pullOutputChars` in [docs/reference/options.md](../reference/options.md) dials it back).
|
|
36
|
+
|
|
37
|
+
Credit is recorded only when the bytes were actually placed on the result. When a
|
|
38
|
+
pull computed rows and found nowhere to write them, the evidence log gets a
|
|
39
|
+
`pull_undelivered` line instead — a host that changes its result shape should show
|
|
40
|
+
up as a failure, not as a quieter ledger.
|
|
33
41
|
|
|
34
42
|
The writer throttles identical sets of retrieved rows to one successful line
|
|
35
43
|
per session and source per hour. A row can appear in multiple sets.
|
|
@@ -14,6 +14,8 @@ Promotion evidence keeps a bounded sample of call IDs: the ten most recent code-
|
|
|
14
14
|
|
|
15
15
|
A settled claim about code must point at a file the repository has, so a write naming a missing path is refused with `ref_path_missing`. That check runs on writes only. A row that was correct when it was saved goes stale on its own the moment a later refactor moves the file, and nothing notices: recall keeps quoting a path the reader cannot open.
|
|
16
16
|
|
|
17
|
+
For a retired file, write the history lookup as a single backticked command, for example `git log -- bench/runners/append-cost-198.ts`. The gate verifies every such path against file names in the checkout’s available Git history from HEAD. A missing path or unavailable history refuses a settled write. Use the exact inline spelling shown above. A plain citation of the same path still needs a file in the current tree, and the repair report lists unverified pointers for a human. The command contributes no evidence that the file exists now. The usual grounding rules still apply.
|
|
18
|
+
|
|
17
19
|
`scripts/ref-fixer.ts` repairs the mechanical cases. The default is a dry run; `--apply` writes through the same gated update path as `memory_update`, so the old row is superseded rather than edited and `memory_undo` stays the recovery path. It repoints a path under two rules, and each is narrow for a specific reason:
|
|
18
20
|
|
|
19
21
|
1. **A scored rename.** Git records a rename scored at least `R90` whose chain ends at a file that exists today and whose basename is unchanged. The floor is measured rather than guessed: this repository's renames cluster at `R090`..`R100` — the domain restructure, where the only content change is the import lines inside the moved file — and the outliers below it (`R058`, `R072`, `R080`, `R086`, `R088`) are files git scored as renames after much of their content was rewritten. The basename matters because it is what a query matches on — `src/lock.ts` to `src/store/lock.ts` still says "lock", so the row stays findable by the words that found it before.
|
|
@@ -27,6 +27,53 @@ Set them in the object form of the plugin entry in `opencode.json(c)`:
|
|
|
27
27
|
| `captureMax` | `3` | Maximum candidates proposed per capture pass. |
|
|
28
28
|
| `captureOnCompact` | `true` | When auto-capture is armed, also mine the transcript at compaction, before the summarizer replaces it. Its 5-minute cooldown is separate from the turn-end one, so the two triggers' hit-rates stay measurable. Setting it while `autoCapture` is `false` does nothing and reports `switch_mismatch` on the `plugin_load` line. |
|
|
29
29
|
| `captureGuidedRules` | `false` | POC: deterministic guided-candidate pre-pass. The user's own lines decide which stated values or rules are guided (numbers, rates, currency, explicit rule assertions) and attach the verbatim quote; the capture model may phrase such a row but cannot clear the flag or the quote, and a guided quote the user never wrote is refused at the write boundary instead of silently stripped. Fires alongside the model pass only — no extra model calls. |
|
|
30
|
+
| `pullOutputChars` | `512` | How many characters of a tool's own **output** join the contextual pull's query, after its arguments. `0` searches the arguments only. This is how a fact keyed to something the model only just discovered — an error string, a symbol in a file body — can reach a seat that never calls `memory_recall`. A value that is not a non-negative number falls back to `512` and says so on the console. See the measurement below. |
|
|
31
|
+
| `pullTools` | `["grep", "glob", "read"]` | Which tool results may carry a pull at all. `[]` — an empty list, typed on purpose — turns the channel off: no tool result carries a pull. A value that is not a list, or a list holding no tool name, is read as a typo and falls back to the default rather than to no pull, with a console warning either way. |
|
|
32
|
+
|
|
33
|
+
### What the contextual pull searches, and what it costs
|
|
34
|
+
|
|
35
|
+
The pull is the one delivery channel that needs no cooperation from the model: it
|
|
36
|
+
appends a short block to a tool result the seat is about to read anyway. That makes
|
|
37
|
+
it the right channel for a model that never calls the plugin's tools, and the wrong
|
|
38
|
+
place to be careless — a wrong pull is paid for by every later turn, and unlike the
|
|
39
|
+
injected block it does not ride the prompt cache.
|
|
40
|
+
|
|
41
|
+
`bench/runners/pull-precision.ts` measures the scope on the committed recall dataset
|
|
42
|
+
(355 tool calls per store, stores of 52/200/800, plus random and store-order negative
|
|
43
|
+
controls). At store 200, `R@1`/`R@3` are split by whether the gold row was reachable
|
|
44
|
+
from the tool's arguments, and `noise%` is the share of no-gold calls that pulled
|
|
45
|
+
anything at all:
|
|
46
|
+
|
|
47
|
+
| Scope | R@1 args | R@3 args | R@1 output-only | noise% on ordinary traffic | bytes/call |
|
|
48
|
+
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
49
|
+
| arguments only | 98.6 | 100 | 0 | 65 | 122 |
|
|
50
|
+
| arguments + output, no merge | 92.9 | 94.3 | 18.8 | 0 | 216 |
|
|
51
|
+
| **shipped: arguments + output, argument matches take the slots first** | 98.6 | 100 | 18.8 | 65 | 252 |
|
|
52
|
+
| the same, with `shell` in scope | 98.6 | 100 | 37.6 | 100 | 389 |
|
|
53
|
+
|
|
54
|
+
Two things that doc comment would hide. The merge is load-bearing: a combined query is
|
|
55
|
+
longer, and a longer query raises the two-concept threshold, so searching
|
|
56
|
+
`table_manager.save grep results` on its own drops the row the model's own words matched
|
|
57
|
+
exactly. And `shell` doubles the reach while bolting a block onto every plain command —
|
|
58
|
+
it is excluded by measurement, not taste. Both arms stay in the bench so the next reader
|
|
59
|
+
has the numbers rather than a prohibition.
|
|
60
|
+
|
|
61
|
+
*First*, and not *last*, is the whole difference in the merge. Three rows is everything a
|
|
62
|
+
pull delivers, so merging the arguments-only search behind the combined one recovers a row
|
|
63
|
+
only when the output matches nothing: a grep for `table_manager.save` whose output names
|
|
64
|
+
three other memories leaves the exact match past the cap. The shipped scope's own bench
|
|
65
|
+
cannot see that — both orders score byte-identical at stores 200 and 800, because no
|
|
66
|
+
fixture call pairs a precise argument with three output-matching rows — so the case is
|
|
67
|
+
pinned by `test/inject/pull-scope.test.ts`. The `shell` row above is where the ordering
|
|
68
|
+
does show: taking slots first costs that arm 7.7 points of output-only R@1 (45.3 → 37.6),
|
|
69
|
+
because there the arguments usually fill all three slots. The trade is stated in
|
|
70
|
+
`src/inject/pull.ts`: intent outranks output, and the price is reach on the calls where
|
|
71
|
+
the arguments already match three rows.
|
|
72
|
+
|
|
73
|
+
Read the no-merge row's `noise% 0` carefully: it is not precision, it is silence. On
|
|
74
|
+
every arg-visible call it misses, it pulls nothing at all (the bench's `miss-abstain%`
|
|
75
|
+
column reads 100 for that arm), so it spends 5.7 points of recall the model was already
|
|
76
|
+
getting to buy reach it could have had for free.
|
|
30
77
|
|
|
31
78
|
## Environment variables
|
|
32
79
|
|
|
@@ -26,4 +26,5 @@ The seven cases a session actually hits.
|
|
|
26
26
|
| `memory store is busy` | A store write exhausted its 5s lock-wait budget, so the mutation is refused rather than run unlocked. Retry after contention clears. An operation spanning several files or steps may have completed earlier steps; refusal is not a rollback of those steps. If the reply reports `PARTIAL`, inspect the named rows and `memory_evidence` / `memory_undo` before retrying. A process that is killed releases the lock when it dies — there is no stale window to wait out. |
|
|
27
27
|
| Writes report a disk I/O error and the store is on a share | The lock's write-ahead log needs mmap'd shared memory, which SQLite does not support on network filesystems. SMB, NFS and OneDrive-mounted roots are unsupported — move `OPENCODE_MEMORY_DIR` to local disk. |
|
|
28
28
|
| Stale plugin after an update | `opencode plugin update opencode-self-improvement` (or bump the pinned `@version` in the `plugins` entry) and restart opencode. On desktop use `opencode service restart`: relaunching the app leaves the background service — and the plugin version and options it already parsed — alive. |
|
|
29
|
+
| Not sure which copy of the plugin is running | The `plugin_load` line in `memory_evidence` carries `entry=`, the directory the running plugin was loaded from. A published install names the npm cache; a checkout named in the `plugins` entry names that checkout. Version alone cannot tell them apart — a checkout and the published package built from it share a version, and the npm cache has been known to hold a stale one while the session ran against something else. |
|
|
29
30
|
| Auto-capture does nothing | `memory_evidence` says which case you are in from the `plugin_load` line: `capture=on` (the default), `capture=off` (you set `autoCapture: false`), `invalid_model`, `no_capabilities` or `switch_mismatch`. `capture=on` with no `auto_capture_*` line after a session means the pass did not complete, and is not your configuration — see [Auto-capture](../../README.md#auto-capture). On desktop, changing any of these options needs `opencode service restart`. The same `plugin_load` line carries `subscribed=[…]`, listing the event types that subscription really reacts to. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.33.
|
|
3
|
+
"version": "0.33.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": {
|
|
@@ -77,6 +77,7 @@
|
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
79
|
"@babel/parser": "7.29.9",
|
|
80
|
+
"@lezer/markdown": "1.8.1",
|
|
80
81
|
"zod": "4.6.7"
|
|
81
82
|
}
|
|
82
83
|
}
|
package/src/events.ts
CHANGED
|
@@ -24,8 +24,14 @@ import {
|
|
|
24
24
|
onCompacting,
|
|
25
25
|
} from "./capture/triggers.ts";
|
|
26
26
|
import { recordSessionModel } from "./capture/session-model.ts";
|
|
27
|
-
import {
|
|
28
|
-
|
|
27
|
+
import {
|
|
28
|
+
contextualPull,
|
|
29
|
+
PULL_SHIPPED,
|
|
30
|
+
type PullScope,
|
|
31
|
+
pullQueryFor,
|
|
32
|
+
writePullIntoResult,
|
|
33
|
+
} from "./inject/pull.ts";
|
|
34
|
+
import { record } from "./telemetry/record.ts";
|
|
29
35
|
import { compactionAnchor } from "./inject/anchor.ts";
|
|
30
36
|
|
|
31
37
|
interface HookDependencies {
|
|
@@ -43,6 +49,8 @@ interface HookDependencies {
|
|
|
43
49
|
bindSessionFromApi: (sid: string | undefined) => Promise<void>;
|
|
44
50
|
measuredTurns: Map<string, Measured>;
|
|
45
51
|
flushStatus: (sid: string) => Promise<void>;
|
|
52
|
+
/** Which tool results may carry a pull and what they search. */
|
|
53
|
+
pullScope: PullScope;
|
|
46
54
|
getCompactCapture: () =>
|
|
47
55
|
| ((sid: string, messages: unknown) => void)
|
|
48
56
|
| undefined;
|
|
@@ -86,6 +94,7 @@ export async function registerHooks(
|
|
|
86
94
|
bindSessionFromApi,
|
|
87
95
|
measuredTurns,
|
|
88
96
|
flushStatus,
|
|
97
|
+
pullScope = PULL_SHIPPED,
|
|
89
98
|
getCompactCapture,
|
|
90
99
|
}: HookDependencies,
|
|
91
100
|
) {
|
|
@@ -121,29 +130,47 @@ export async function registerHooks(
|
|
|
121
130
|
metadata: resultMeta(event?.result),
|
|
122
131
|
};
|
|
123
132
|
await afterTool(input, out);
|
|
133
|
+
// Capture the text BEFORE the pull appends to it, so the write-back can
|
|
134
|
+
// place just the appended block instead of duplicating the tool output.
|
|
135
|
+
const textBefore = typeof out.output === "string" ? out.output : "";
|
|
124
136
|
const pulled = await contextualPull(
|
|
125
137
|
input,
|
|
126
138
|
out as { output?: unknown },
|
|
127
139
|
budget,
|
|
128
140
|
await useSignals(),
|
|
141
|
+
pullScope,
|
|
129
142
|
);
|
|
130
|
-
|
|
143
|
+
// Deliver FIRST, credit AFTER: the ledger counts rows the model was shown.
|
|
144
|
+
// The old order credited every computed pull, so a result shape the host
|
|
145
|
+
// no longer hands back as a string (v2.3.0 sends a parts ARRAY) left 456
|
|
146
|
+
// `src=pull` credits against zero bytes delivered — the exact overclaim
|
|
147
|
+
// this ledger exists to avoid. `pull_undelivered` makes the failure
|
|
148
|
+
// readable instead of merely smaller.
|
|
149
|
+
const shown =
|
|
150
|
+
pulled.length > 0 && typeof out.output === "string"
|
|
151
|
+
? writePullIntoResult(event?.result, textBefore, out.output)
|
|
152
|
+
: false;
|
|
153
|
+
if (shown)
|
|
131
154
|
await noteHits(
|
|
132
155
|
"pull",
|
|
133
156
|
String(event?.sessionID ?? ""),
|
|
134
157
|
pulled,
|
|
135
|
-
|
|
158
|
+
// The query the pull ACTUALLY searched, so the ledger's shared terms
|
|
159
|
+
// describe the same match the model was shown — with the same scope,
|
|
160
|
+
// from the same function, so the two cannot drift apart.
|
|
161
|
+
pullQueryFor(
|
|
162
|
+
String(event?.tool ?? ""),
|
|
163
|
+
input.args,
|
|
164
|
+
textBefore,
|
|
165
|
+
pullScope,
|
|
166
|
+
),
|
|
167
|
+
);
|
|
168
|
+
else if (pulled.length)
|
|
169
|
+
await record(
|
|
170
|
+
"pull_undelivered",
|
|
171
|
+
{ tool: String(event?.tool ?? ""), rows: pulled.length },
|
|
172
|
+
false,
|
|
136
173
|
);
|
|
137
|
-
// Write a contextual-pull append back when the tool result is text we own.
|
|
138
|
-
if (
|
|
139
|
-
event?.result &&
|
|
140
|
-
typeof event.result === "object" &&
|
|
141
|
-
typeof event.result.content === "string"
|
|
142
|
-
) {
|
|
143
|
-
const text = resultText(event.result);
|
|
144
|
-
if (out.output && out.output !== text)
|
|
145
|
-
event.result.content = out.output;
|
|
146
|
-
}
|
|
147
174
|
}),
|
|
148
175
|
);
|
|
149
176
|
|
package/src/gate/gate.ts
CHANGED
|
@@ -907,7 +907,7 @@ export async function runWriteGate(
|
|
|
907
907
|
// created.
|
|
908
908
|
blockReason = "ref_path_missing";
|
|
909
909
|
blockFlags = [`missing=${g1.missingPaths.join(",")}`];
|
|
910
|
-
hint = `Path ref(s) not found in the repo: ${g1.missingPaths.join(", ")}.
|
|
910
|
+
hint = `Path ref(s) not found in the repo: ${g1.missingPaths.join(", ")}. Correct the live citation, or cite a committed retired file as a single inline command: \`git log -- <path>\`. Each history pointer must exist in this checkout's Git history; use status="open" if the file is planned, not existing.`;
|
|
911
911
|
} else if (canon && !canon.aligns) {
|
|
912
912
|
blockReason = "conflicts_with_canonical";
|
|
913
913
|
blockFlags = [
|
package/src/gate/resolver.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
// GATE-1 resolver. Extracts embedded path/symbol refs from a memory/evidence
|
|
2
2
|
// candidate and re-resolves them against the live source tree. Deterministic:
|
|
3
|
-
//
|
|
4
|
-
import {
|
|
3
|
+
// Markdown span boundaries, literal Git paths and balanced-paren scanning.
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { join, posix } from "node:path";
|
|
5
7
|
import { opendir } from "node:fs/promises";
|
|
8
|
+
import { parser as markdown } from "@lezer/markdown";
|
|
6
9
|
import { type Memory } from "../store/model/memory.ts";
|
|
7
10
|
|
|
8
11
|
export interface CallForm {
|
|
@@ -160,8 +163,94 @@ const PATH_RE =
|
|
|
160
163
|
/[A-Za-z0-9_@./-]+\.(?:ts|tsx|js|jsx|mjs|cjs)(?!\w|\.\w)(?::\d+)?/g;
|
|
161
164
|
|
|
162
165
|
export function extractPathRefs(content: string): string[] {
|
|
163
|
-
|
|
164
|
-
|
|
166
|
+
return scanPathRefs(content).live.map((m) => m[0]);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// A single path in the documented Git history command is a lookup instruction.
|
|
170
|
+
// It cannot ground a claim about the live tree. Keep offsets in the original
|
|
171
|
+
// text so a second, live citation of the same path is still checked and repaired.
|
|
172
|
+
function scanPathRefs(content: string) {
|
|
173
|
+
const live: RegExpExecArray[] = [];
|
|
174
|
+
const history = new Set<string>();
|
|
175
|
+
if (content.length > REGEX_SCAN_MAX_CHARS) return { live, history };
|
|
176
|
+
const prefix = "`git log -- ";
|
|
177
|
+
let tree: ReturnType<typeof markdown.parse> | undefined;
|
|
178
|
+
for (const m of content.matchAll(PATH_RE)) {
|
|
179
|
+
const end = m.index + m[0].length;
|
|
180
|
+
if (
|
|
181
|
+
content.endsWith(prefix, m.index) &&
|
|
182
|
+
content[end] === "`" &&
|
|
183
|
+
!m[0].includes(":")
|
|
184
|
+
) {
|
|
185
|
+
// Escaped backticks and commands quoted inside examples are literal text.
|
|
186
|
+
tree ??= markdown.parse(content);
|
|
187
|
+
const span = tree.resolveInner(m.index);
|
|
188
|
+
if (
|
|
189
|
+
span.name === "InlineCode" &&
|
|
190
|
+
span.from === m.index - prefix.length &&
|
|
191
|
+
span.to === end + 1
|
|
192
|
+
) {
|
|
193
|
+
history.add(m[0]);
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
live.push(m);
|
|
198
|
+
}
|
|
199
|
+
return { live, history };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const git = promisify(execFile);
|
|
203
|
+
|
|
204
|
+
// Resolve all pointers in one path-limited history walk. Compare literal file
|
|
205
|
+
// names: a directory with the requested spelling is not a historical file.
|
|
206
|
+
export async function missingHistoryPaths(
|
|
207
|
+
root: string,
|
|
208
|
+
history: ReadonlySet<string>,
|
|
209
|
+
): Promise<string[]> {
|
|
210
|
+
if (!history.size) return [];
|
|
211
|
+
const paths = [...history];
|
|
212
|
+
const local = paths.filter(
|
|
213
|
+
(p) => !p.startsWith("/") && !p.split("/").includes(".."),
|
|
214
|
+
);
|
|
215
|
+
if (!root || !local.length) return paths;
|
|
216
|
+
try {
|
|
217
|
+
const { stdout } = await git(
|
|
218
|
+
"git",
|
|
219
|
+
[
|
|
220
|
+
"--literal-pathspecs",
|
|
221
|
+
"log",
|
|
222
|
+
"--format=",
|
|
223
|
+
"--name-only",
|
|
224
|
+
"-z",
|
|
225
|
+
"--relative",
|
|
226
|
+
"--full-history",
|
|
227
|
+
"-m",
|
|
228
|
+
"--root",
|
|
229
|
+
"--diff-filter=AD",
|
|
230
|
+
"--no-renames",
|
|
231
|
+
"HEAD",
|
|
232
|
+
"--",
|
|
233
|
+
...local,
|
|
234
|
+
],
|
|
235
|
+
{
|
|
236
|
+
cwd: root,
|
|
237
|
+
// A host launched by a Git hook can carry another checkout's GIT_DIR.
|
|
238
|
+
env: Object.fromEntries(
|
|
239
|
+
Object.entries(process.env).filter(([k]) => !k.startsWith("GIT_")),
|
|
240
|
+
),
|
|
241
|
+
timeout: 5000,
|
|
242
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
243
|
+
windowsHide: true,
|
|
244
|
+
},
|
|
245
|
+
);
|
|
246
|
+
const found = new Set(stdout.split("\0"));
|
|
247
|
+
return paths.filter(
|
|
248
|
+
(p) => !local.includes(p) || !found.has(posix.normalize(p)),
|
|
249
|
+
);
|
|
250
|
+
} catch {
|
|
251
|
+
// Missing Git, an unborn HEAD or incomplete output proves no exception.
|
|
252
|
+
return paths;
|
|
253
|
+
}
|
|
165
254
|
}
|
|
166
255
|
|
|
167
256
|
// Directory-qualified, repo-relative path refs whose existence gate1 can check
|
|
@@ -186,9 +275,13 @@ export interface PathRefSpan {
|
|
|
186
275
|
* never refuse, because it never sees it. Editing spans cannot.
|
|
187
276
|
*/
|
|
188
277
|
export function checkablePathRefSpans(content: string): PathRefSpan[] {
|
|
189
|
-
|
|
278
|
+
return liveSpans(scanPathRefs(content).live);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function liveSpans(matches: RegExpExecArray[]): PathRefSpan[] {
|
|
190
282
|
const out: PathRefSpan[] = [];
|
|
191
|
-
for (const m of
|
|
283
|
+
for (const m of matches) {
|
|
284
|
+
const content = m.input;
|
|
192
285
|
const ref = m[0].replace(/:\d+$/, "");
|
|
193
286
|
const prev = m.index && m.index > 0 ? content[m.index - 1] : "";
|
|
194
287
|
if (prev === "$" || prev === "~" || prev === "/") continue;
|
|
@@ -210,6 +303,11 @@ export function checkablePathRefSpans(content: string): PathRefSpan[] {
|
|
|
210
303
|
return out;
|
|
211
304
|
}
|
|
212
305
|
|
|
306
|
+
export function auditPathRefs(content: string) {
|
|
307
|
+
const { live, history } = scanPathRefs(content);
|
|
308
|
+
return { spans: liveSpans(live), history };
|
|
309
|
+
}
|
|
310
|
+
|
|
213
311
|
export function checkablePathRefs(content: string): string[] {
|
|
214
312
|
const out: string[] = [];
|
|
215
313
|
for (const s of checkablePathRefSpans(content))
|
|
@@ -497,9 +595,9 @@ export interface ResolveInput {
|
|
|
497
595
|
|
|
498
596
|
export async function gate1(input: ResolveInput): Promise<Gate1Result> {
|
|
499
597
|
const forms = extractCallForms(input.content);
|
|
500
|
-
const
|
|
501
|
-
const refs = forms.length +
|
|
502
|
-
if (refs === 0)
|
|
598
|
+
const { live, history } = scanPathRefs(input.content);
|
|
599
|
+
const refs = forms.length + live.length;
|
|
600
|
+
if (refs === 0 && !history.size)
|
|
503
601
|
return {
|
|
504
602
|
refs: 0,
|
|
505
603
|
resolved: [],
|
|
@@ -514,11 +612,13 @@ export async function gate1(input: ResolveInput): Promise<Gate1Result> {
|
|
|
514
612
|
// Existence check for repo-relative path refs. When liveRoot is not a real
|
|
515
613
|
// tree (unit tests, deleted worktree) nothing is verifiable, so report no
|
|
516
614
|
// missing paths rather than flagging everything.
|
|
517
|
-
const missingPaths
|
|
518
|
-
|
|
519
|
-
|
|
615
|
+
const missingPaths = new Set(
|
|
616
|
+
await missingHistoryPaths(input.liveRoot, history),
|
|
617
|
+
);
|
|
618
|
+
if (live.length && (await isDirectory(input.liveRoot))) {
|
|
619
|
+
for (const ref of new Set(liveSpans(live).map((s) => s.ref))) {
|
|
520
620
|
if (!(await Bun.file(join(input.liveRoot, ref)).exists()))
|
|
521
|
-
missingPaths.
|
|
621
|
+
missingPaths.add(ref);
|
|
522
622
|
}
|
|
523
623
|
}
|
|
524
624
|
|
|
@@ -563,6 +663,6 @@ export async function gate1(input: ResolveInput): Promise<Gate1Result> {
|
|
|
563
663
|
resolved,
|
|
564
664
|
drift,
|
|
565
665
|
candidateStale: drift?.source === "candidate",
|
|
566
|
-
missingPaths,
|
|
666
|
+
missingPaths: [...missingPaths],
|
|
567
667
|
};
|
|
568
668
|
}
|
package/src/index.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { guarded, setGuardedFailureReporter } from "./core/hooks.ts";
|
|
|
13
13
|
import type { PluginCtx } from "./core/host.ts";
|
|
14
14
|
import type { Cleanup, Plugin } from "@opencode/plugin/promise/plugin";
|
|
15
15
|
import { basename, join } from "node:path";
|
|
16
|
+
import { fileURLToPath } from "node:url";
|
|
16
17
|
import { frontierBudget, injectBudget } from "./core/config/budgets.ts";
|
|
17
18
|
import { memoryRoot } from "./core/config/paths.ts";
|
|
18
19
|
import { loadAll, malformedCount } from "./store/files/load.ts";
|
|
@@ -55,6 +56,7 @@ export {
|
|
|
55
56
|
} from "./capture/runtime.ts";
|
|
56
57
|
export { resetSessionModels } from "./capture/session-model.ts";
|
|
57
58
|
import { createInjectionEpochs } from "./inject/epochs.ts";
|
|
59
|
+
import { pullScopeFrom } from "./inject/pull.ts";
|
|
58
60
|
import { createSessionContext } from "./identity/session-context.ts";
|
|
59
61
|
import { registerMemoryTools } from "./tools/registry.ts";
|
|
60
62
|
import {
|
|
@@ -254,6 +256,17 @@ const impl = {
|
|
|
254
256
|
bindSessionFromApi,
|
|
255
257
|
measuredTurns,
|
|
256
258
|
flushStatus,
|
|
259
|
+
// Which tool results carry a pull, and what the pull searches. Measured
|
|
260
|
+
// default in src/inject/pull.ts; `pullOutputChars: 0` in the plugin config
|
|
261
|
+
// restores the old arguments-only behaviour, `pullTools` narrows the set,
|
|
262
|
+
// and `pullTools: []` switches the channel off. A value that does not
|
|
263
|
+
// parse falls back to the measured default and says so on the console —
|
|
264
|
+
// the same setup-time warning style as the Bun floor and captureModel
|
|
265
|
+
// checks above, because a config line that silently does nothing is the
|
|
266
|
+
// failure nobody debugs.
|
|
267
|
+
pullScope: pullScopeFrom(ctx.options, (message) =>
|
|
268
|
+
console.warn(`[opencode-self-improvement] ${message}`),
|
|
269
|
+
),
|
|
257
270
|
getCompactCapture: () => onCompactCapture,
|
|
258
271
|
});
|
|
259
272
|
// ---- auto-capture (turn-end + compaction triggers) ---------------------
|
|
@@ -295,6 +308,12 @@ const impl = {
|
|
|
295
308
|
// broken store must not turn plugin load into a throw.
|
|
296
309
|
await guarded("plugin_load heartbeat", async () => {
|
|
297
310
|
let pluginVersion = "unknown";
|
|
311
|
+
// Which COPY of this plugin the host actually loaded. Version alone could
|
|
312
|
+
// not answer it: a checkout and the published package it came from share
|
|
313
|
+
// a version, and the npm cache has held a stale one while a session ran
|
|
314
|
+
// against something else entirely. The heartbeat now names the directory,
|
|
315
|
+
// so "is my change live?" is one grep instead of an afternoon.
|
|
316
|
+
let entryDir = "unknown";
|
|
298
317
|
try {
|
|
299
318
|
const pkg = await Bun.file(
|
|
300
319
|
new URL("../package.json", import.meta.url),
|
|
@@ -303,6 +322,11 @@ const impl = {
|
|
|
303
322
|
} catch {
|
|
304
323
|
// a heartbeat with an unknown version still beats no heartbeat
|
|
305
324
|
}
|
|
325
|
+
try {
|
|
326
|
+
entryDir = fileURLToPath(new URL("../", import.meta.url));
|
|
327
|
+
} catch {
|
|
328
|
+
// same: the version line is still worth emitting
|
|
329
|
+
}
|
|
306
330
|
// Auto-capture is armed unless the config opts it out: an absent key
|
|
307
331
|
// means on, so the switch is read as a negative opt-out.
|
|
308
332
|
const wantCapture = ctx.options?.autoCapture !== false;
|
|
@@ -339,6 +363,7 @@ const impl = {
|
|
|
339
363
|
"plugin_load",
|
|
340
364
|
{
|
|
341
365
|
version: pluginVersion,
|
|
366
|
+
entry: entryDir,
|
|
342
367
|
capture: captureState,
|
|
343
368
|
capture_on_compact: ctx.options?.captureOnCompact !== false,
|
|
344
369
|
capabilities: `[${capabilities.join(",")}]`,
|
package/src/inject/pull.ts
CHANGED
|
@@ -25,15 +25,229 @@ export interface PullOutput {
|
|
|
25
25
|
output?: unknown;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
// Put the pull onto the host's tool result so the model actually reads it.
|
|
29
|
+
// WHICH field the host forwards is measured, not assumed. On opencode v2.3.0
|
|
30
|
+
// (probed through e2e/support/harness.ts against the real host) `result.content`
|
|
31
|
+
// is an ARRAY of `{type:"text",text}` parts and mutating a text part changes the
|
|
32
|
+
// next request; mutating `result.output` — the file-attachment object
|
|
33
|
+
// `{type,uri,name,content,encoding,mime}` — does not. Older hosts passed a plain
|
|
34
|
+
// string in `content`, which is the shape this function was originally written
|
|
35
|
+
// against, and a string `output` is covered too.
|
|
36
|
+
//
|
|
37
|
+
// Returns true only when the bytes were placed. The caller credits the ledger
|
|
38
|
+
// with what rode, never with what was merely computed: a pull that found nowhere
|
|
39
|
+
// to write showed the model nothing.
|
|
40
|
+
export function writePullIntoResult(
|
|
41
|
+
result: unknown,
|
|
42
|
+
before: string,
|
|
43
|
+
after: string,
|
|
44
|
+
): boolean {
|
|
45
|
+
if (!result || typeof result !== "object") return false;
|
|
46
|
+
// contextualPull APPENDS to the text it was handed, so isolate that append.
|
|
47
|
+
// If the value no longer carries it — another hook rewrote the result between
|
|
48
|
+
// the pull and here — there is no safe place for the block: assigning would
|
|
49
|
+
// clobber the other hook and appending the whole value would duplicate the
|
|
50
|
+
// tool output. Report failure and let the caller log `pull_undelivered`.
|
|
51
|
+
if (!after.startsWith(before)) return false;
|
|
52
|
+
const block = after.slice(before.length);
|
|
53
|
+
if (!block) return false;
|
|
54
|
+
const r = result as { content?: unknown };
|
|
55
|
+
if (typeof r.content === "string") {
|
|
56
|
+
r.content += block;
|
|
57
|
+
return true;
|
|
58
|
+
}
|
|
59
|
+
if (Array.isArray(r.content)) {
|
|
60
|
+
// Append to the LAST text part: the pull is commentary on the output, so it
|
|
61
|
+
// belongs after it, and a result can carry several parts.
|
|
62
|
+
for (let i = r.content.length - 1; i >= 0; i--) {
|
|
63
|
+
const part = r.content[i] as { text?: unknown } | undefined;
|
|
64
|
+
if (part && typeof part === "object" && typeof part.text === "string") {
|
|
65
|
+
part.text += block;
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
r.content.push({ type: "text", text: block });
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// What a pull is allowed to search. Every field exists because it was measured
|
|
76
|
+
// before being changed (bench/runners/pull-precision.ts), not because it seemed
|
|
77
|
+
// reasonable: a pull bolts text onto a tool result the model did not ask for, so
|
|
78
|
+
// the cost of a wrong pull is paid by every later turn.
|
|
79
|
+
export interface PullScope {
|
|
80
|
+
/** Tool results that may carry a pull. */
|
|
81
|
+
tools: readonly string[];
|
|
82
|
+
/** Whether the tool's own output joins the query, not just its arguments. */
|
|
83
|
+
includeOutput: boolean;
|
|
84
|
+
/** How many characters of it. A 40 KB file dump is not a query. */
|
|
85
|
+
outputChars: number;
|
|
86
|
+
/**
|
|
87
|
+
* ALSO search the arguments alone and merge, argument matches first. A longer
|
|
88
|
+
* query raises the scorer's two-concept gate, so a combined search can DROP a
|
|
89
|
+
* row the model's own words already matched; merging recovers it without
|
|
90
|
+
* giving up the reach the output bought. Measured, not assumed:
|
|
91
|
+
* bench/runners/pull-precision.ts.
|
|
92
|
+
*/
|
|
93
|
+
argsUnion?: boolean;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The shipped arm: the arguments AND the first 512 characters of the result,
|
|
98
|
+
* for grep/glob/read, with the arguments-only search merged back in first.
|
|
99
|
+
*
|
|
100
|
+
* Chosen by measurement, not taste — bench/runners/pull-precision.ts
|
|
101
|
+
* (2026-11-20), committed recall dataset, stores of 52/200/800, and the shape
|
|
102
|
+
* held at all three (store = 200 below):
|
|
103
|
+
*
|
|
104
|
+
* arm R@1 arg R@3 arg R@1 out noise% ordinary bytes/call
|
|
105
|
+
* args-only 98.6 100 0 65% 122
|
|
106
|
+
* + output, no merge 92.9 94.3 18.8 0% 216
|
|
107
|
+
* THIS ARM 98.6 100 18.8 65% 252
|
|
108
|
+
*
|
|
109
|
+
* The class it exists for — a fact keyed to something the model only sees in
|
|
110
|
+
* the tool's OUTPUT (an error string, a symbol in a file body) — goes from
|
|
111
|
+
* unreachable to 18.8% R@1 (17.9% at store 800) without moving the class that
|
|
112
|
+
* already worked. The merge is what buys that: a combined query is longer, and
|
|
113
|
+
* a longer query raises the scorer's two-concept gate, so a precise search
|
|
114
|
+
* ("table_manager.save") otherwise loses its exact-match row to boilerplate
|
|
115
|
+
* output ("grep results"). That is not hypothetical — it broke
|
|
116
|
+
* test/host/scenarios.test.ts's I3 case the first time.
|
|
117
|
+
*
|
|
118
|
+
* The merge takes slots in ORDER: argument matches are placed first and the
|
|
119
|
+
* combined matches fill what is left, not the reverse. Three slots is the whole
|
|
120
|
+
* delivery, so an order that appends argument matches can only recover a row
|
|
121
|
+
* when the output matches nothing — a grep whose output names three other rows
|
|
122
|
+
* leaves the exact match past the cap. This scope's own bench cannot see the
|
|
123
|
+
* difference: both orders score byte-identical at stores 200 and 800, because
|
|
124
|
+
* no fixture call pairs a precise argument with three output-matching rows.
|
|
125
|
+
* Where the bench DOES see it is the rejected `+ shell` arm — first choice
|
|
126
|
+
* costs it 7.7 points of output-only R@1 (45.3 → 37.6 at store 200), because
|
|
127
|
+
* there the arguments usually fill all three slots. That is the trade stated
|
|
128
|
+
* plainly: intent outranks output, and it is paid for in reach only on calls
|
|
129
|
+
* where the arguments already match three rows. The case the bench is blind to
|
|
130
|
+
* is pinned by test/inject/pull-scope.test.ts.
|
|
131
|
+
*
|
|
132
|
+
* Measured and REJECTED, so the next reader does not "improve" it back:
|
|
133
|
+
* + shell doubles the reach (R@1 out 45.3 merged, 43.9 unmerged at
|
|
134
|
+
* store 800) but takes ordinary-traffic noise to 100% of
|
|
135
|
+
* no-gold calls: every plain read and command
|
|
136
|
+
* gets a block bolted onto it.
|
|
137
|
+
* no merge looks quiet (0% noise) only because its misses are silences —
|
|
138
|
+
* miss-abstain 100%. It spends 5.7 points of arg-visible R@3 to
|
|
139
|
+
* buy the same output reach.
|
|
140
|
+
* error-gated output only on a failure signal: 26% R@1 out, but 100% noise
|
|
141
|
+
* on ordinary traffic once shell is in scope, and no better
|
|
142
|
+
* than this arm without it.
|
|
143
|
+
* outputChars 128 / 512 / 2000 scored identically: the fixture puts the
|
|
144
|
+
* signal early in the output, so this bench cannot rank them.
|
|
145
|
+
* 512 is a bound on cost, not a tuned value.
|
|
146
|
+
* Noise is the share of NO-GOLD calls that pull at least one row. At 65% that is
|
|
147
|
+
* the pre-existing behaviour of the arguments-only arm, inherited unchanged: this
|
|
148
|
+
* change adds reach, it does not add spam. Cutting that number is the next
|
|
149
|
+
* measured step, not this one.
|
|
150
|
+
*/
|
|
151
|
+
export const PULL_SHIPPED: PullScope = {
|
|
152
|
+
tools: ["grep", "glob", "read"],
|
|
153
|
+
includeOutput: true,
|
|
154
|
+
outputChars: 512,
|
|
155
|
+
argsUnion: true,
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The arm from plugin options, so a user can dial the behaviour back without a
|
|
160
|
+
* code change:
|
|
161
|
+
* pullOutputChars: 0 → arguments only (the pre-2026-11 behaviour)
|
|
162
|
+
* pullTools: ["read"] → only reads may carry a pull
|
|
163
|
+
* pullTools: [] → no tool result carries a pull at all
|
|
164
|
+
*
|
|
165
|
+
* An empty list is the only opt-out this channel has, and a pull bolts text
|
|
166
|
+
* onto results the model did not ask for, so it deserves one: an empty list is
|
|
167
|
+
* a decision someone typed. A value that merely FAILS to parse — a string
|
|
168
|
+
* where a list belongs, a list of numbers — is a typo, and a typo falls back
|
|
169
|
+
* to the shipped arm rather than switching delivery off. Both paths say what
|
|
170
|
+
* they did through `warn`, because a config line that does nothing is worse
|
|
171
|
+
* than one that refuses.
|
|
172
|
+
*/
|
|
173
|
+
export function pullScopeFrom(
|
|
174
|
+
options: Record<string, unknown> | undefined,
|
|
175
|
+
warn?: (message: string) => void,
|
|
176
|
+
): PullScope {
|
|
177
|
+
const chars = options?.pullOutputChars;
|
|
178
|
+
const tools = options?.pullTools;
|
|
179
|
+
const charsOk =
|
|
180
|
+
chars === undefined ||
|
|
181
|
+
(typeof chars === "number" && Number.isFinite(chars) && chars >= 0);
|
|
182
|
+
if (!charsOk && warn) {
|
|
183
|
+
warn(
|
|
184
|
+
`pullOutputChars must be a non-negative number; got ${JSON.stringify(chars) ?? String(chars)}. Using ${PULL_SHIPPED.outputChars}.`,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
const outChars = charsOk
|
|
188
|
+
? chars === undefined
|
|
189
|
+
? PULL_SHIPPED.outputChars
|
|
190
|
+
: Math.min(Math.floor(chars as number), 4096)
|
|
191
|
+
: PULL_SHIPPED.outputChars;
|
|
192
|
+
// `undefined` (unset) and `[]` (explicitly nothing) are different inputs, so
|
|
193
|
+
// the raw list is kept apart from the filtered one.
|
|
194
|
+
const raw = Array.isArray(tools) ? tools : undefined;
|
|
195
|
+
if (tools !== undefined && raw === undefined && warn) {
|
|
196
|
+
warn(
|
|
197
|
+
`pullTools must be a list of tool names; got ${JSON.stringify(tools) ?? String(tools)}. Using the default ${PULL_SHIPPED.tools.join(", ")}.`,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
const toolList = raw
|
|
201
|
+
? raw.filter((t): t is string => typeof t === "string" && t.length > 0)
|
|
202
|
+
: [];
|
|
203
|
+
if (raw && raw.length > 0 && toolList.length === 0 && warn) {
|
|
204
|
+
warn(
|
|
205
|
+
`pullTools held no usable tool name; got ${JSON.stringify(tools)}. Using the default ${PULL_SHIPPED.tools.join(", ")}.`,
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
tools:
|
|
210
|
+
raw && raw.length === 0
|
|
211
|
+
? []
|
|
212
|
+
: toolList.length
|
|
213
|
+
? toolList
|
|
214
|
+
: PULL_SHIPPED.tools,
|
|
215
|
+
includeOutput: outChars > 0,
|
|
216
|
+
outputChars: outChars,
|
|
217
|
+
// Only meaningful when the output joins the query; without it the two
|
|
218
|
+
// searches are the same search.
|
|
219
|
+
argsUnion: outChars > 0,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* The query one tool call searches memory with. Args first: the model's own
|
|
225
|
+
* intent outranks whatever the tool happened to print. Returns "" for a tool
|
|
226
|
+
* outside the scope, which is how the pull stays off the write path.
|
|
227
|
+
*/
|
|
228
|
+
export function pullQueryFor(
|
|
229
|
+
tool: string,
|
|
230
|
+
args: unknown,
|
|
231
|
+
resultText: string,
|
|
232
|
+
scope: PullScope,
|
|
233
|
+
): string {
|
|
234
|
+
if (!scope.tools.includes(tool)) return "";
|
|
235
|
+
const arg = argText(args);
|
|
236
|
+
if (!scope.includeOutput) return arg;
|
|
237
|
+
const head = resultText.slice(0, scope.outputChars).trim();
|
|
238
|
+
return arg && head ? `${arg}\n${head}` : arg || head;
|
|
239
|
+
}
|
|
240
|
+
|
|
28
241
|
export async function contextualPull(
|
|
29
242
|
input: PullInput,
|
|
30
243
|
output: PullOutput,
|
|
31
244
|
budget = injectBudget(),
|
|
32
245
|
use?: UseSignals,
|
|
246
|
+
scope: PullScope = PULL_SHIPPED,
|
|
33
247
|
): Promise<Memory[]> {
|
|
34
248
|
const tool = typeof input.tool === "string" ? input.tool : "";
|
|
35
|
-
|
|
36
|
-
const term =
|
|
249
|
+
const own = typeof output.output === "string" ? output.output : "";
|
|
250
|
+
const term = pullQueryFor(tool, input.args, own, scope);
|
|
37
251
|
if (!term) return [];
|
|
38
252
|
// Repo-scoped: model-facing reads see the CALLER's repo + global rows —
|
|
39
253
|
// the pull's own sessionID, resolved before the store read.
|
|
@@ -42,17 +256,37 @@ export async function contextualPull(
|
|
|
42
256
|
readerFromSid(input.sessionID),
|
|
43
257
|
);
|
|
44
258
|
const top = scoreMemories(term, mems, 3, use);
|
|
45
|
-
|
|
259
|
+
// Merge the arguments-only search AHEAD of the combined one. The combined query
|
|
260
|
+
// is longer, and a longer query raises the scorer's two-concept gate, so the
|
|
261
|
+
// row the model's OWN words matched can fall out of a combined search that
|
|
262
|
+
// would otherwise be a strict improvement. Argument matches keep first choice:
|
|
263
|
+
// the model's intent outranks whatever the tool happened to print.
|
|
264
|
+
//
|
|
265
|
+
// First choice, not last refusal. Three slots is the whole delivery, so an
|
|
266
|
+
// order that appends argument matches after the combined ones recovers them
|
|
267
|
+
// only when the output matches nothing — a grep whose output names three other
|
|
268
|
+
// rows leaves the exact match past the cap. That is the regression the review
|
|
269
|
+
// on PR 457 caught, pinned by test/inject/pull-scope.test.ts.
|
|
270
|
+
const merged = scope.argsUnion
|
|
271
|
+
? (() => {
|
|
272
|
+
const args = argText(input.args);
|
|
273
|
+
if (!args || args === term) return top;
|
|
274
|
+
const byArgs = scoreMemories(args, mems, 3, use);
|
|
275
|
+
const seen = new Set(byArgs.map((m) => m.ts));
|
|
276
|
+
return [...byArgs, ...top.filter((m) => !seen.has(m.ts))].slice(0, 3);
|
|
277
|
+
})()
|
|
278
|
+
: top;
|
|
279
|
+
if (!merged.length) return [];
|
|
46
280
|
// Held to the injection budget too: three long rows were ~12 KB per call.
|
|
47
281
|
const block = capToBudget(
|
|
48
|
-
`## Related durable memory (pull)${FRAME}\n${
|
|
282
|
+
`## Related durable memory (pull)${FRAME}\n${merged.map(formatMemory).join("\n")}`,
|
|
49
283
|
budget,
|
|
50
284
|
);
|
|
51
285
|
if (block && typeof output.output === "string") {
|
|
52
286
|
output.output += `\n${block}`;
|
|
53
287
|
// What the ledger counts is what actually rode the result — the budget can
|
|
54
288
|
// drop rows, and crediting a memory the model never saw would inflate it.
|
|
55
|
-
return injectedRows(block,
|
|
289
|
+
return injectedRows(block, merged);
|
|
56
290
|
}
|
|
57
291
|
return [];
|
|
58
292
|
}
|
package/src/recall/relevant.ts
CHANGED
|
@@ -10,6 +10,19 @@ import { RESTATABLE_TAG, USER_GUIDED_TAG } from "../core/tags.ts";
|
|
|
10
10
|
import { cmpTs } from "../core/cmp-ts.ts";
|
|
11
11
|
import { scoreMemories } from "./score.ts";
|
|
12
12
|
|
|
13
|
+
/**
|
|
14
|
+
* The searchable text of a tool call's arguments: the first of `pattern`,
|
|
15
|
+
* `query`, `path`, `filePath`, `command` that holds a non-empty string.
|
|
16
|
+
*
|
|
17
|
+
* That list is the pull's contract with the tools it ships for — grep and glob
|
|
18
|
+
* name their search `pattern`, read names its target `filePath` — and the pull
|
|
19
|
+
* reaches this only for a tool already inside its scope, because `pullQueryFor`
|
|
20
|
+
* returns "" for any other. So the shipped arm covers every call it makes. Two
|
|
21
|
+
* consequences belong to whoever widens `pullTools`: a tool whose searchable
|
|
22
|
+
* text sits under another key, or nested inside an `args` object, contributes
|
|
23
|
+
* nothing here, and a call carrying both a pattern and a path is searched by
|
|
24
|
+
* its pattern alone — the intent, not the directory it ran in.
|
|
25
|
+
*/
|
|
13
26
|
export function argText(args: unknown): string {
|
|
14
27
|
if (!args || typeof args !== "object") return "";
|
|
15
28
|
const a = args as Record<string, unknown>;
|
|
@@ -27,10 +40,9 @@ export function argText(args: unknown): string {
|
|
|
27
40
|
* nothing about the prompt beyond the memory it points at — and it is enough
|
|
28
41
|
* to replay a merge and prove the same reads would still land.
|
|
29
42
|
*/
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
}
|
|
43
|
+
// The text a contextual pull searches with lives with the pull itself
|
|
44
|
+
// (pullQueryFor in src/inject/pull.ts): it is no longer just the arguments, so
|
|
45
|
+
// it cannot be derived from args alone.
|
|
34
46
|
|
|
35
47
|
// Reinforcement: a row the ledger has seen used breaks a tie over a row
|
|
36
48
|
// nobody ever read, and the more recently used one breaks it first. A TIE-BREAK
|
package/src/store/lock.ts
CHANGED
|
@@ -53,7 +53,15 @@
|
|
|
53
53
|
import { Database } from "bun:sqlite";
|
|
54
54
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
55
55
|
import { chmod, unlink } from "node:fs/promises";
|
|
56
|
-
import {
|
|
56
|
+
import {
|
|
57
|
+
basename,
|
|
58
|
+
dirname,
|
|
59
|
+
isAbsolute,
|
|
60
|
+
join,
|
|
61
|
+
relative,
|
|
62
|
+
resolve,
|
|
63
|
+
sep,
|
|
64
|
+
} from "node:path";
|
|
57
65
|
import { ensureDir } from "../core/logfmt/publish.ts";
|
|
58
66
|
import { record } from "../telemetry/record.ts";
|
|
59
67
|
|
|
@@ -690,3 +698,32 @@ export function lockDatabaseFor(file: string): string {
|
|
|
690
698
|
export function heldLockDatabases(): string[] {
|
|
691
699
|
return [...lockDbs.keys()];
|
|
692
700
|
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* Test seam: the lock databases under `dir` whose SECTION is still running in
|
|
704
|
+
* this process, so a caller can tell a handle it can free from one it cannot.
|
|
705
|
+
*
|
|
706
|
+
* A section is a callback awaiting the event loop. `closeAllLockDatabases`
|
|
707
|
+
* leaves it alone — closing would give up a lock its writer still believes it
|
|
708
|
+
* holds — and nothing else in the same turn can make it finish either. So a
|
|
709
|
+
* teardown that owns the loop (a synchronous `afterEach`) learns from this that
|
|
710
|
+
* waiting is pointless, while a teardown that can await learns that one gap is
|
|
711
|
+
* all it needs.
|
|
712
|
+
*/
|
|
713
|
+
export function heldLockSectionsUnder(dir: string): string[] {
|
|
714
|
+
const root = resolve(dir);
|
|
715
|
+
const out: string[] = [];
|
|
716
|
+
for (const [dbPath, pinned] of lockDbs) {
|
|
717
|
+
if (pinned.inUse === 0) continue;
|
|
718
|
+
const below = relative(root, resolve(dbPath));
|
|
719
|
+
if (
|
|
720
|
+
below &&
|
|
721
|
+
!below.startsWith(`..${sep}`) &&
|
|
722
|
+
below !== ".." &&
|
|
723
|
+
!isAbsolute(below)
|
|
724
|
+
) {
|
|
725
|
+
out.push(dbPath);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
return out;
|
|
729
|
+
}
|