opencode-self-improvement 0.33.8 → 0.33.10

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.
@@ -6,7 +6,9 @@
6
6
  // What a "use" is, deliberately narrow:
7
7
  // inject — the rows that actually survived into an epoch block (offered to
8
8
  // the model on every request of that epoch);
9
- // pull — rows appended to a grep/glob/read result by the contextual pull;
9
+ // pull — rows appended to a grep/glob/read result by the contextual pull
10
+ // and still whole in the next request for that call
11
+ // (src/inject/pull-receipts.ts);
10
12
  // recall — rows returned by a memory_recall call.
11
13
  //
12
14
  // What it is NOT: evidence is a different file and a different contract. This
@@ -29,6 +31,8 @@ import { withStoreLock, LOCK_WRITE } from "../store/lock.ts";
29
31
  import type { Memory } from "../store/model/memory.ts";
30
32
  import type { ReadSet } from "../consolidate/propose.ts";
31
33
 
34
+ import { type EvidenceContext, record } from "./record.ts";
35
+
32
36
  export type HitSource = "inject" | "pull" | "recall";
33
37
 
34
38
  export { HITS_FILENAME };
@@ -95,7 +99,7 @@ export function resetHitThrottle(): void {
95
99
  nextAttempt.clear();
96
100
  }
97
101
 
98
- async function rotateIfNeeded(): Promise<void> {
102
+ async function rotateIfNeeded(retryRename = true): Promise<void> {
99
103
  let size: number;
100
104
  try {
101
105
  size = (await stat(hitsFile())).size;
@@ -107,7 +111,9 @@ async function rotateIfNeeded(): Promise<void> {
107
111
  // anchor the halving like every other whole-file publish - on
108
112
  // Windows the rename can be refused by a reader's handle, and the retry is
109
113
  // only safe while nothing else moved this file.
110
- const since = await fileIdentity(hitsFile());
114
+ // A request-time pull attempts the atomic handover once. Other writers
115
+ // retain the identity-checked retry window for transient Windows readers.
116
+ const since = retryRename ? await fileIdentity(hitsFile()) : undefined;
111
117
  const lines = (await readFile(hitsFile(), "utf8"))
112
118
  .split("\n")
113
119
  .filter((l) => l.trim());
@@ -136,6 +142,12 @@ export async function recordHits(
136
142
  now = Date.now(),
137
143
  turn?: number,
138
144
  turnKey?: string,
145
+ receipt?: {
146
+ lockWaitMs: number;
147
+ observedAt: number;
148
+ tool?: string;
149
+ evidence?: EvidenceContext;
150
+ },
139
151
  ): Promise<boolean> {
140
152
  if (!rows.length) return false;
141
153
  const ids = rows.map((m) => m.ts);
@@ -143,9 +155,21 @@ export async function recordHits(
143
155
  if (inFlight.has(key)) return false;
144
156
  const eligibleAt = nextAttempt.get(key);
145
157
  if (eligibleAt !== undefined && now < eligibleAt) return false;
158
+ if (receipt && receipt.lockWaitMs <= 0) {
159
+ if (receipt.evidence && receipt.tool) {
160
+ await record(
161
+ "pull_credit_skipped",
162
+ { tool: receipt.tool, rows: rows.length, reason: "budget" },
163
+ false,
164
+ sid,
165
+ receipt.evidence,
166
+ ).catch(() => undefined);
167
+ }
168
+ return false;
169
+ }
146
170
  const line = formatLine({
147
171
  ev: "memory_used",
148
- ts: new Date(now).toISOString(),
172
+ ts: new Date(receipt?.observedAt ?? now).toISOString(),
149
173
  src: source,
150
174
  sid,
151
175
  mem: bracketList(ids),
@@ -162,14 +186,29 @@ export async function recordHits(
162
186
  });
163
187
  inFlight.add(key);
164
188
  let cooldown = RETRY_BACKOFF_MS;
189
+ const evidence = receipt?.evidence;
190
+ const lock = receipt
191
+ ? { ...LOCK_WRITE, timeoutMs: receipt.lockWaitMs }
192
+ : LOCK_WRITE;
193
+ if (receipt && evidence) {
194
+ lock.onEvent = (event, waitedMs) => {
195
+ void record(
196
+ "store_lock",
197
+ { event, waited_ms: waitedMs, op: "write" },
198
+ false,
199
+ sid,
200
+ evidence,
201
+ ).catch(() => undefined);
202
+ };
203
+ }
165
204
  try {
166
205
  await withStoreLock(
167
206
  hitsFile(),
168
207
  async () => {
169
- await rotateIfNeeded();
208
+ await rotateIfNeeded(!receipt);
170
209
  await appendLog(hitsFile(), line);
171
210
  },
172
- LOCK_WRITE,
211
+ lock,
173
212
  );
174
213
  cooldown = THROTTLE_MS;
175
214
  return true;
@@ -177,6 +216,15 @@ export async function recordHits(
177
216
  // Fail-closed lock contention can drop this use observation. Decay and
178
217
  // consolidation therefore see a best-effort ledger, not proof of non-use;
179
218
  // retrieval remains available even when its telemetry cannot be persisted.
219
+ if (evidence && receipt?.tool) {
220
+ await record(
221
+ "pull_credit_skipped",
222
+ { tool: receipt.tool, rows: rows.length, reason: "write_failed" },
223
+ false,
224
+ sid,
225
+ evidence,
226
+ ).catch(() => undefined);
227
+ }
180
228
  return false; // telemetry never breaks retrieval
181
229
  } finally {
182
230
  nextAttempt.set(key, now + cooldown);
@@ -302,3 +302,137 @@ export async function recordWriteBlocked(
302
302
  context,
303
303
  );
304
304
  }
305
+
306
+ // ---- the best-effort evidence policy --------------------------------------
307
+ //
308
+ // The evidence log describes a feature; it is not a dependency of it. A write
309
+ // that fails costs one line and must cost nothing else: not the pass that wrote
310
+ // it, and not the event subscription that hands capture every later turn. The
311
+ // capture path therefore writes only through the wrappers below, which state the
312
+ // decision once instead of at each call site — a per-site `try` is a policy a
313
+ // later receipt can forget.
314
+ //
315
+ // `record` and `recordSync` keep throwing for every other caller. A viewer edit
316
+ // or a gate refusal that cannot write its audit line is a failed operation the
317
+ // operator must see; a capture receipt that cannot write its line is a missing
318
+ // footnote on an operation that succeeded.
319
+ //
320
+ // The counter is the only channel that can report this failure — a line about an
321
+ // unwritable log cannot land either — so it lives in process memory and
322
+ // `memory_status` reads it back. It is keyed by the evidence directory: one
323
+ // store's broken log is not another store's, and a shared server holds several.
324
+ export interface DroppedEvidenceWrites {
325
+ /** Evidence writes this process lost for this store. */
326
+ dropped: number;
327
+ /** Event name of the most recent loss. */
328
+ lastEvent: string;
329
+ /** How the file layer reported the most recent loss. */
330
+ lastError: string;
331
+ }
332
+
333
+ const droppedWrites = new Map<string, DroppedEvidenceWrites>();
334
+
335
+ // Reportable text for a rejection, without becoming the failure it reports.
336
+ // `String` handles a Symbol (`"Symbol(...)"`); what it cannot survive is a
337
+ // rejection whose own `toString` throws, and this runs inside the handler that
338
+ // exists to swallow exactly that class of throw.
339
+ function describeError(err: unknown): string {
340
+ if (err instanceof Error && err.message) return err.message;
341
+ try {
342
+ return String(err);
343
+ } catch {
344
+ return `unprintable ${typeof err}`;
345
+ }
346
+ }
347
+
348
+ // The one rendering every channel of ONE failure shares. The console line and
349
+ // the evidence receipt are the same fact on two channels, so they must not
350
+ // carry different privacy guarantees: neither formats the error itself.
351
+ const MIRRORED_ERROR_MAX = 200;
352
+
353
+ /**
354
+ * A failure as reportable text: message only, credential-scrubbed, capped. Use
355
+ * it for every output that mirrors an error — console, evidence line, counter —
356
+ * and never hand the original object to a surface, because that carries the
357
+ * stack and every unscrubbed field on it.
358
+ */
359
+ export function safeErrorMessage(err: unknown): string {
360
+ return redactSecrets(describeError(err)).slice(0, MIRRORED_ERROR_MAX);
361
+ }
362
+
363
+ function noteDroppedWrite(event: EvidenceEvent, err: unknown): void {
364
+ const key = evidenceDir();
365
+ const prev = droppedWrites.get(key);
366
+ droppedWrites.set(key, {
367
+ dropped: (prev?.dropped ?? 0) + 1,
368
+ lastEvent: event,
369
+ // NOT `(err as Error).message`: a messageless Error or a non-Error
370
+ // rejection would make this field empty, and an empty field reads as
371
+ // "nothing was lost" to every surface that tests it for truth. Scrubbed at
372
+ // the same boundary as every other mirrored error: a path is what an fs
373
+ // failure carries, but a throw from line building carries field values.
374
+ lastError: safeErrorMessage(err),
375
+ });
376
+ // A long-lived server sees many stores. Bound the map the way the ledger's
377
+ // throttle does, and never evict the entry just written — an entry set twice
378
+ // keeps its original position, so the oldest key can be the live one.
379
+ if (droppedWrites.size > 64) {
380
+ for (const k of [...droppedWrites.keys()].slice(0, 32)) {
381
+ if (k !== key) droppedWrites.delete(k);
382
+ }
383
+ }
384
+ }
385
+
386
+ /**
387
+ * This process's lost evidence writes for the current store, or null when this
388
+ * store has lost none. Absent and zero are the same claim here, so only the
389
+ * failure case is worth a line.
390
+ */
391
+ export function droppedEvidenceWrites(): DroppedEvidenceWrites | null {
392
+ return droppedWrites.get(evidenceDir()) ?? null;
393
+ }
394
+
395
+ /** `record` under the best-effort policy: a failed line is counted, not thrown. */
396
+ export async function recordBestEffort(
397
+ ev: EvidenceEvent,
398
+ fields: Record<string, unknown> = {},
399
+ includeContext = true,
400
+ sessionID?: string,
401
+ context?: EvidenceContext,
402
+ ): Promise<void> {
403
+ try {
404
+ await record(ev, fields, includeContext, sessionID, context);
405
+ } catch (err) {
406
+ noteDroppedWrite(ev, err);
407
+ }
408
+ }
409
+
410
+ /** `recordSync` under the best-effort policy. */
411
+ export function recordSyncBestEffort(
412
+ ev: EvidenceEvent,
413
+ fields: Record<string, unknown> = {},
414
+ includeContext = true,
415
+ sessionID?: string,
416
+ context?: EvidenceContext,
417
+ ): void {
418
+ try {
419
+ recordSync(ev, fields, includeContext, sessionID, context);
420
+ } catch (err) {
421
+ noteDroppedWrite(ev, err);
422
+ }
423
+ }
424
+
425
+ /** `recordCaptureLag` under the best-effort policy. */
426
+ export async function recordCaptureLagBestEffort(
427
+ session: string,
428
+ lagMs: number | null,
429
+ outcome: string,
430
+ context?: EvidenceContext,
431
+ model?: string,
432
+ ): Promise<void> {
433
+ try {
434
+ await recordCaptureLag(session, lagMs, outcome, context, model);
435
+ } catch (err) {
436
+ noteDroppedWrite("capture_lag", err);
437
+ }
438
+ }
@@ -4,12 +4,17 @@ import type { ToolRegister } from "./deps.ts";
4
4
  import { memoryRoot } from "../core/config/paths.ts";
5
5
  import { record } from "../telemetry/record.ts";
6
6
  import { withStoreBatch } from "../store/lock.ts";
7
- import { loadAll } from "../store/files/load.ts";
7
+ import { loadAll, toMemory } from "../store/files/load.ts";
8
+ import { stampRow } from "../store/files/snapshots.ts";
9
+ import { formatLine } from "../core/logfmt/format.ts";
10
+ import {
11
+ absorbAliases,
12
+ sameConsolidationScope,
13
+ } from "../consolidate/propose.ts";
8
14
  import { clearSuperseded, markSuperseded } from "../store/files/supersede.ts";
9
15
  import { isVisibleTo, readerFromSid } from "../store/model/visibility.ts";
10
- import { isActive } from "../store/model/predicates.ts";
16
+ import { isActive, isInjectable } from "../store/model/predicates.ts";
11
17
  import { MergeReviewArgs, validated } from "./schema.ts";
12
- import { join } from "node:path";
13
18
 
14
19
  export const register: ToolRegister = (editor, deps) => {
15
20
  const { toolIds, bindSessionIdentity, direct } = deps;
@@ -55,6 +60,7 @@ export const register: ToolRegister = (editor, deps) => {
55
60
  // A batch may publish the loser then refuse a later file. The sink
56
61
  // records that publish before the overall promise settles.
57
62
  const mergeDurable: string[] = [];
63
+ let consolidationStarted = false;
58
64
  try {
59
65
  return await withStoreBatch(
60
66
  memoryRoot(),
@@ -126,6 +132,52 @@ export const register: ToolRegister = (editor, deps) => {
126
132
  ` after this review was written; reviving the survivor would erase that supersession. Nothing was done. No evidence written.`,
127
133
  };
128
134
  }
135
+ if (args.consolidate) {
136
+ if (
137
+ !isInjectable(loserRow) ||
138
+ !isInjectable(survivorRow) ||
139
+ loserRow.status === "open" ||
140
+ survivorRow.status === "open" ||
141
+ !sameConsolidationScope(loserRow, survivorRow) ||
142
+ all.filter(
143
+ (m) => m.ts === args.loser || m.ts === args.survivor,
144
+ ).length !== 2
145
+ ) {
146
+ return {
147
+ content:
148
+ "Consolidation blocked: the proposal requires two distinct, available settled rows of the same type, scope and repository. Run memory_consolidate again.",
149
+ };
150
+ }
151
+ // Publish the aliases first. If retirement fails, the loser
152
+ // remains searchable and reapplying the union is idempotent.
153
+ consolidationStarted = true;
154
+ const present = await stampRow(
155
+ survivorRow.file,
156
+ survivorRow.ts,
157
+ (fields) => {
158
+ const current = toMemory(
159
+ fields,
160
+ survivorRow.file,
161
+ survivorRow.index,
162
+ );
163
+ if (
164
+ !current ||
165
+ !isInjectable(current) ||
166
+ current.status === "open" ||
167
+ !sameConsolidationScope(current, loserRow)
168
+ ) {
169
+ throw new Error("survivor changed since the proposal");
170
+ }
171
+ const merged = absorbAliases(current, loserRow);
172
+ const kw = merged.kw?.join(",");
173
+ const tags = merged.tags!.join(",");
174
+ if (fields.kw === kw && fields.tags === tags) return null;
175
+ return formatLine({ ...fields, kw, tags });
176
+ },
177
+ );
178
+ if (present === null)
179
+ throw new Error("survivor no longer exists");
180
+ }
129
181
  const ok = await markSuperseded(
130
182
  args.loser,
131
183
  {
@@ -138,6 +190,11 @@ export const register: ToolRegister = (editor, deps) => {
138
190
  mergeDurable,
139
191
  );
140
192
  if (!ok) {
193
+ if (args.consolidate)
194
+ return {
195
+ content:
196
+ "Consolidation incomplete: the survivor has its aliases, but the loser was unavailable for retirement. Run memory_consolidate again.",
197
+ };
141
198
  return {
142
199
  content:
143
200
  "merge_review: loser not found or already superseded — nothing to resolve. No evidence written.",
@@ -149,10 +206,12 @@ export const register: ToolRegister = (editor, deps) => {
149
206
  // but only the marker this review owns: the guard above
150
207
  // already refused anything else, and this re-check runs under the
151
208
  // file lock against the line as it is at mutation time.
152
- const revived = await clearSuperseded(args.survivor, {
153
- supersededBy: args.loser,
154
- reason: args.reason,
155
- });
209
+ const revived =
210
+ !args.consolidate &&
211
+ (await clearSuperseded(args.survivor, {
212
+ supersededBy: args.loser,
213
+ reason: args.reason,
214
+ }));
156
215
  // The response has always claimed "Evidence recorded" — now it
157
216
  // is true, and it names the session the merge ran FOR (
158
217
  // residue on this line). The host tool_result hook covers
@@ -197,6 +256,10 @@ export const register: ToolRegister = (editor, deps) => {
197
256
  // follow-up (evidence/revive), not a blanket "nothing was done".
198
257
  const why = err instanceof Error ? err.message : String(err);
199
258
  if (mergeDurable.length === 0) {
259
+ if (consolidationStarted)
260
+ return {
261
+ content: `Consolidation incomplete: no retirement confirmed. The survivor may already have the aliases. Retry after checking the store. ${why}`,
262
+ };
200
263
  return {
201
264
  content: `merge_review blocked: ${why} — nothing was done. Retry.`,
202
265
  };
@@ -147,6 +147,12 @@ export const EvidenceArgs = z.object({
147
147
  });
148
148
 
149
149
  export const MergeReviewArgs = z.object({
150
+ consolidate: z
151
+ .boolean()
152
+ .optional()
153
+ .describe(
154
+ "Apply a consolidation proposal, retaining the absorbed row's retrieval aliases on its same-scope survivor",
155
+ ),
150
156
  loser: z
151
157
  .string()
152
158
  .describe(
@@ -29,6 +29,7 @@ import {
29
29
  import { renderMemoryReport } from "../status/report.ts";
30
30
  import { blockedRecent } from "../status/write.ts";
31
31
  import { summarizeStore } from "../status/store-summary.ts";
32
+ import { droppedEvidenceWrites } from "../telemetry/record.ts";
32
33
 
33
34
  export const register: ToolRegister = (editor, deps) => {
34
35
  const { toolIds, sessions, direct } = deps;
@@ -91,6 +92,9 @@ export const register: ToolRegister = (editor, deps) => {
91
92
  // capture state read from the same evidence window, so the
92
93
  // chat surface distinguishes off / misconfigured / inert / alive.
93
94
  capture: captureHealth(evidenceLines),
95
+ // Lost evidence writes cannot report themselves through the log, so
96
+ // this one number comes from this process instead.
97
+ evidence: droppedEvidenceWrites(),
94
98
  }),
95
99
  };
96
100
  },