opencode-self-improvement 0.15.18 → 0.15.19

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.
Files changed (93) hide show
  1. package/README.md +4 -0
  2. package/package.json +4 -2
  3. package/src/capture/candidates.ts +17 -6
  4. package/src/capture/lag.ts +6 -2
  5. package/src/capture/prompt.ts +1 -1
  6. package/src/capture/runtime.ts +85 -21
  7. package/src/capture/session-model.ts +2 -1
  8. package/src/capture/transcript.ts +10 -4
  9. package/src/capture/triggers.ts +48 -14
  10. package/src/command/ensure.ts +6 -1
  11. package/src/consolidate/propose.ts +47 -17
  12. package/src/consolidate/render.ts +3 -1
  13. package/src/core/cmp-ts.ts +2 -2
  14. package/src/core/config/budgets.ts +0 -1
  15. package/src/core/config/paths.ts +2 -3
  16. package/src/core/hooks.ts +8 -3
  17. package/src/core/host.ts +8 -3
  18. package/src/core/logfmt/format.ts +20 -5
  19. package/src/core/logfmt/publish.ts +21 -4
  20. package/src/core/lru.ts +20 -20
  21. package/src/core/permissions.ts +21 -5
  22. package/src/core/runtime.ts +7 -3
  23. package/src/core/state.ts +12 -2
  24. package/src/core/time.ts +0 -1
  25. package/src/core/tokenize.ts +16 -5
  26. package/src/core/types.ts +8 -1
  27. package/src/events.ts +74 -18
  28. package/src/evidence/record.ts +29 -9
  29. package/src/gate/gate.ts +208 -64
  30. package/src/gate/resolver.ts +105 -20
  31. package/src/hits/ledger.ts +35 -10
  32. package/src/identity/host-events.ts +35 -11
  33. package/src/identity/repokey.ts +27 -9
  34. package/src/identity/session-context.ts +39 -8
  35. package/src/index.ts +108 -42
  36. package/src/init/detect.ts +62 -12
  37. package/src/init/run.ts +50 -11
  38. package/src/inject/anchor.ts +11 -5
  39. package/src/inject/attribution.ts +29 -6
  40. package/src/inject/budget.ts +9 -2
  41. package/src/inject/digest.ts +16 -8
  42. package/src/inject/epochs.ts +43 -15
  43. package/src/inject/pull.ts +11 -5
  44. package/src/inject/version.ts +10 -5
  45. package/src/portable/decay.ts +20 -9
  46. package/src/portable/export.ts +30 -10
  47. package/src/portable/import.ts +43 -12
  48. package/src/recall/relevant.ts +11 -5
  49. package/src/recall/score.ts +5 -3
  50. package/src/status/format.ts +8 -2
  51. package/src/status/metrics.ts +22 -6
  52. package/src/status/payload.ts +7 -2
  53. package/src/status/report.ts +63 -18
  54. package/src/status/write.ts +21 -7
  55. package/src/store/blocklist.ts +16 -4
  56. package/src/store/containment.ts +27 -8
  57. package/src/store/files/append.ts +57 -37
  58. package/src/store/files/deletions.ts +5 -2
  59. package/src/store/files/load.ts +37 -11
  60. package/src/store/files/prune.ts +18 -5
  61. package/src/store/files/snapshots.ts +6 -2
  62. package/src/store/files/supersede.ts +32 -12
  63. package/src/store/files/target.ts +4 -1
  64. package/src/store/lock.ts +10 -2
  65. package/src/store/model/visibility.ts +26 -6
  66. package/src/store/prune.ts +1 -1
  67. package/src/store/quarantine/quarantine.ts +36 -9
  68. package/src/store/quarantine/release.ts +9 -3
  69. package/src/store/secrets.ts +4 -2
  70. package/src/store/tombstones/rejection.ts +21 -5
  71. package/src/store/tombstones/tombstone.ts +48 -11
  72. package/src/store/undo.ts +43 -18
  73. package/src/tools/consolidate.ts +18 -8
  74. package/src/tools/decay.ts +37 -9
  75. package/src/tools/deps.ts +10 -2
  76. package/src/tools/evidence.ts +7 -4
  77. package/src/tools/export.ts +10 -4
  78. package/src/tools/forget.ts +15 -5
  79. package/src/tools/import.ts +16 -5
  80. package/src/tools/init.ts +13 -4
  81. package/src/tools/list.ts +12 -6
  82. package/src/tools/merge-review.ts +52 -20
  83. package/src/tools/recall.ts +17 -9
  84. package/src/tools/registry.ts +4 -1
  85. package/src/tools/remember.ts +21 -7
  86. package/src/tools/schema.ts +55 -18
  87. package/src/tools/status-tool.ts +29 -11
  88. package/src/tools/undo.ts +23 -8
  89. package/src/tools/update.ts +116 -40
  90. package/src/tui/panel.tsx +119 -30
  91. package/src/viewer/mutate.ts +57 -20
  92. package/src/viewer/rejections.ts +1 -1
  93. package/src/viewer/server.ts +88 -28
package/src/gate/gate.ts CHANGED
@@ -2,21 +2,34 @@
2
2
  // canonical-graph correctness, GATE-2 stale-ref scan + supersession, GATE-3
3
3
  // dedup, GATE-4 promotion/block. Every step emits an ordered evidence line.
4
4
  import { join } from "node:path";
5
- import { isQuarantined, quarantineReasons } from "../store/quarantine/quarantine.ts";
5
+ import {
6
+ isQuarantined,
7
+ quarantineReasons,
8
+ } from "../store/quarantine/quarantine.ts";
6
9
  import { canonicalFile, memoryRoot } from "../core/config/paths.ts";
7
- import { bracketList, parseLine } from "../core/logfmt/format.ts"
10
+ import { bracketList, parseLine } from "../core/logfmt/format.ts";
8
11
  import { readLines } from "../core/logfmt/read.ts";
9
- import { appendMemory } from "../store/files/append.ts"
10
- import { loadScope } from "../store/files/load.ts"
11
- import { snapshotFiles } from "../store/files/snapshots.ts"
12
- import { markManySupersededReport, type SupersedeFields } from "../store/files/supersede.ts"
12
+ import { appendMemory } from "../store/files/append.ts";
13
+ import { loadScope } from "../store/files/load.ts";
14
+ import { snapshotFiles } from "../store/files/snapshots.ts";
15
+ import {
16
+ markManySupersededReport,
17
+ type SupersedeFields,
18
+ } from "../store/files/supersede.ts";
13
19
  import { MAX_CONTENT_CHARS, type Memory } from "../store/model/memory.ts";
14
- import { captureEvidenceContext, type EvidenceContext, chainId, contentHash, record, recordWriteBlocked } from "../evidence/record.ts";
20
+ import {
21
+ captureEvidenceContext,
22
+ type EvidenceContext,
23
+ chainId,
24
+ contentHash,
25
+ record,
26
+ recordWriteBlocked,
27
+ } from "../evidence/record.ts";
15
28
  import { getCurrent, noteAuthored } from "../core/state.ts";
16
29
  import { MAX_WRITE_EVIDENCE_REFS } from "../capture/triggers.ts";
17
30
  import { flattenMemoryText } from "../store/sanitize.ts";
18
31
  import { containsSecret, redactSecrets } from "../store/secrets.ts";
19
- import { UnresolvedWriterError } from "../store/files/append.ts"
32
+ import { UnresolvedWriterError } from "../store/files/append.ts";
20
33
  import { readerFromSid, type Reader } from "../store/model/visibility.ts";
21
34
  import { writeTarget, type WriteTarget } from "../identity/repokey.ts";
22
35
  import {
@@ -58,7 +71,8 @@ export interface WriteCandidate {
58
71
  // collapse an edit whose ordering the caller changed deliberately, and the
59
72
  // conservative direction for a truth-claim is the one that writes more.
60
73
  export const sameStrList = (a?: string[], c?: string[]) =>
61
- (a?.length ?? 0) === (c?.length ?? 0) && (a ?? []).every((x, i) => (c ?? [])[i] === x);
74
+ (a?.length ?? 0) === (c?.length ?? 0) &&
75
+ (a ?? []).every((x, i) => (c ?? [])[i] === x);
62
76
 
63
77
  // The sentence every success reply owes the reader when the gate promoted a
64
78
  // row but its write_promoted audit line failed to land (#155 review): the
@@ -148,10 +162,34 @@ const CONFLICT_OVERLAP_FLOOR = 0.3;
148
162
  // Planning-flavored content (frontier/thread/proposal language). Used only to
149
163
  // turn GATE-4's ambiguous block into a hint pointing at the open-thread home.
150
164
  const PLANNING_WORDS = new Set([
151
- "plan", "plans", "planned", "planning", "frontier", "propos", "proposal",
152
- "open", "goal", "goals", "decide", "decides", "decided", "deciding",
153
- "reject", "rejects", "rejected", "thread", "should", "option", "options",
154
- "candidate", "candidates", "next", "roadmap", "scale", "overhead", "bloat",
165
+ "plan",
166
+ "plans",
167
+ "planned",
168
+ "planning",
169
+ "frontier",
170
+ "propos",
171
+ "proposal",
172
+ "open",
173
+ "goal",
174
+ "goals",
175
+ "decide",
176
+ "decides",
177
+ "decided",
178
+ "deciding",
179
+ "reject",
180
+ "rejects",
181
+ "rejected",
182
+ "thread",
183
+ "should",
184
+ "option",
185
+ "options",
186
+ "candidate",
187
+ "candidates",
188
+ "next",
189
+ "roadmap",
190
+ "scale",
191
+ "overhead",
192
+ "bloat",
155
193
  ]);
156
194
 
157
195
  function looksPlanning(candidate: WriteCandidate): boolean {
@@ -199,7 +237,8 @@ function canonicalMatch(
199
237
  if (!aligns) {
200
238
  const entitySet = new Set(et);
201
239
  const asserted = rawTokens(content).filter(
202
- (t) => !STOPWORDS.has(t.toLowerCase()) && !entitySet.has(t.toLowerCase()),
240
+ (t) =>
241
+ !STOPWORDS.has(t.toLowerCase()) && !entitySet.has(t.toLowerCase()),
203
242
  );
204
243
  conflictingValue = asserted[0];
205
244
  }
@@ -215,9 +254,18 @@ interface StaleRef {
215
254
  to: string;
216
255
  }
217
256
 
218
- async function staleRefFor(m: Memory, liveRoot: string, tree: LazyTree): Promise<StaleRef | null> {
257
+ async function staleRefFor(
258
+ m: Memory,
259
+ liveRoot: string,
260
+ tree: LazyTree,
261
+ ): Promise<StaleRef | null> {
219
262
  for (const form of extractCallForms(m.content)) {
220
- const live = await findLiveCall(form.name, form.fileHint, liveRoot, await tree());
263
+ const live = await findLiveCall(
264
+ form.name,
265
+ form.fileHint,
266
+ liveRoot,
267
+ await tree(),
268
+ );
221
269
  if (!live) continue;
222
270
  if (!sameArgs(form.argsText, live.argsText)) {
223
271
  return {
@@ -231,7 +279,10 @@ async function staleRefFor(m: Memory, liveRoot: string, tree: LazyTree): Promise
231
279
  return null;
232
280
  }
233
281
 
234
- function deltaTokens(candidate: WriteCandidate, drift: DriftInfo | null): string[] {
282
+ function deltaTokens(
283
+ candidate: WriteCandidate,
284
+ drift: DriftInfo | null,
285
+ ): string[] {
235
286
  const set = new Set<string>();
236
287
  for (const form of extractCallForms(candidate.content)) {
237
288
  if (form.fileHint) set.add(form.fileHint);
@@ -249,23 +300,54 @@ export async function runWriteGate(
249
300
  ): Promise<GateOutcome> {
250
301
  const reader = ctx.reader ?? readerFromSid(ctx.sessionID);
251
302
  const writeAt = ctx.writeAt ?? writeTarget(ctx.sessionID ?? getCurrent().sid);
252
- const evidenceContext = ctx.evidenceContext ?? captureEvidenceContext(ctx.sessionID);
303
+ const evidenceContext =
304
+ ctx.evidenceContext ?? captureEvidenceContext(ctx.sessionID);
253
305
  const chain = chainId();
254
306
  // Keep all gate audit lines with entry-time attribution, including refusals.
255
- const rec = (ev: string, fields: Record<string, unknown> = {}, includeContext = true) =>
256
- record(ev, fields, includeContext, ctx.sessionID, evidenceContext);
257
- const recBlocked = (gate: number, reason: string, flags: string[], chain?: string) =>
258
- recordWriteBlocked(gate, reason, flags, chain, ctx.sessionID, evidenceContext);
307
+ const rec = (
308
+ ev: string,
309
+ fields: Record<string, unknown> = {},
310
+ includeContext = true,
311
+ ) => record(ev, fields, includeContext, ctx.sessionID, evidenceContext);
312
+ const recBlocked = (
313
+ gate: number,
314
+ reason: string,
315
+ flags: string[],
316
+ chain?: string,
317
+ ) =>
318
+ recordWriteBlocked(
319
+ gate,
320
+ reason,
321
+ flags,
322
+ chain,
323
+ ctx.sessionID,
324
+ evidenceContext,
325
+ );
259
326
 
260
327
  // Size/type floor BEFORE any scanning: gate analysis regexes
261
328
  // over megabyte content backtrack super-linearly and freeze the service
262
329
  // event loop (100KB write = 6s, 2MB = never returned).
263
330
  if (typeof candidate.content !== "string") {
264
- await recBlocked(4, "invalid_content", [`content_type=${typeof candidate.content}`], chain);
265
- return { action: "blocked", reason: "invalid_content", chain, hint: "content must be a string." };
331
+ await recBlocked(
332
+ 4,
333
+ "invalid_content",
334
+ [`content_type=${typeof candidate.content}`],
335
+ chain,
336
+ );
337
+ return {
338
+ action: "blocked",
339
+ reason: "invalid_content",
340
+ chain,
341
+ hint: "content must be a string.",
342
+ };
266
343
  }
267
344
  if (candidate.content.length > MAX_CONTENT_CHARS) {
268
- await recBlocked(4, "content_too_long", [`len=${candidate.content.length}`, `max=${MAX_CONTENT_CHARS}`], chain);
345
+ await recBlocked(
346
+ 4,
347
+ "content_too_long",
348
+ [`len=${candidate.content.length}`, `max=${MAX_CONTENT_CHARS}`],
349
+ chain,
350
+ );
269
351
  return {
270
352
  action: "blocked",
271
353
  reason: "content_too_long",
@@ -274,11 +356,13 @@ export async function runWriteGate(
274
356
  };
275
357
  }
276
358
 
277
- const badMetadata: string[] = ([
278
- ["type", candidate.type],
279
- ["scope", candidate.scope],
280
- ["issue", candidate.issue],
281
- ] as const)
359
+ const badMetadata: string[] = (
360
+ [
361
+ ["type", candidate.type],
362
+ ["scope", candidate.scope],
363
+ ["issue", candidate.issue],
364
+ ] as const
365
+ )
282
366
  .filter(
283
367
  ([, value]) =>
284
368
  value !== undefined &&
@@ -288,19 +372,28 @@ export async function runWriteGate(
288
372
  if (
289
373
  candidate.tags !== undefined &&
290
374
  (!Array.isArray(candidate.tags) ||
291
- candidate.tags.some((tag) => typeof tag !== "string" || flattenMemoryText(tag) !== tag))
375
+ candidate.tags.some(
376
+ (tag) => typeof tag !== "string" || flattenMemoryText(tag) !== tag,
377
+ ))
292
378
  ) {
293
379
  badMetadata.push("tags");
294
380
  }
295
381
  if (
296
382
  candidate.kw !== undefined &&
297
383
  (!Array.isArray(candidate.kw) ||
298
- candidate.kw.some((k) => typeof k !== "string" || flattenMemoryText(k) !== k))
384
+ candidate.kw.some(
385
+ (k) => typeof k !== "string" || flattenMemoryText(k) !== k,
386
+ ))
299
387
  ) {
300
388
  badMetadata.push("kw");
301
389
  }
302
390
  if (badMetadata.length) {
303
- await recBlocked(4, "invalid_metadata", [`fields=${badMetadata.join(",")}`], chain);
391
+ await recBlocked(
392
+ 4,
393
+ "invalid_metadata",
394
+ [`fields=${badMetadata.join(",")}`],
395
+ chain,
396
+ );
304
397
  return {
305
398
  action: "blocked",
306
399
  reason: "invalid_metadata",
@@ -346,14 +439,13 @@ export async function runWriteGate(
346
439
  type: candidate.type,
347
440
  ch,
348
441
  quarantined: isQuarantined(candidate) || undefined,
349
- quarantine_patterns: isQuarantined(candidate) ? bracketList(quarantineReasons(candidate)) : undefined,
442
+ quarantine_patterns: isQuarantined(candidate)
443
+ ? bracketList(quarantineReasons(candidate))
444
+ : undefined,
350
445
  });
351
446
 
352
447
  const scopeMems = candidate.scope
353
- ? await loadScope(
354
- candidate.scope,
355
- reader,
356
- )
448
+ ? await loadScope(candidate.scope, reader)
357
449
  : [];
358
450
  // One tree index per write, shared by gate1 and every gate2 stale scan.
359
451
  const tree = memoTree(ctx.liveRoot);
@@ -410,7 +502,8 @@ export async function runWriteGate(
410
502
  });
411
503
 
412
504
  let supersededTs: string | undefined;
413
- const driftPlan: { s: StaleRef; target: string; fields: SupersedeFields }[] = [];
505
+ const driftPlan: { s: StaleRef; target: string; fields: SupersedeFields }[] =
506
+ [];
414
507
  for (const s of stale) {
415
508
  await rec("ref_stale", {
416
509
  gate: 2,
@@ -438,11 +531,20 @@ export async function runWriteGate(
438
531
  driftPlan.push({
439
532
  s,
440
533
  target,
441
- fields: { superseded_by: target, reason: "drift", symbol: s.symbol, from: s.from, to: s.to },
534
+ fields: {
535
+ superseded_by: target,
536
+ reason: "drift",
537
+ symbol: s.symbol,
538
+ from: s.from,
539
+ to: s.to,
540
+ },
442
541
  });
443
542
  }
444
543
  if (driftPlan.length > 0) {
445
- const { marked } = await markManySupersededReport(driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })), ctx.durable);
544
+ const { marked } = await markManySupersededReport(
545
+ driftPlan.map((p) => ({ ts: p.s.memory.ts, fields: p.fields })),
546
+ ctx.durable,
547
+ );
446
548
  if (marked.length > 0) {
447
549
  // Ledger BEFORE the audit lines: what is on disk now stays on disk no
448
550
  // matter what the record loop below does (round-3 probe 3).
@@ -483,7 +585,10 @@ export async function runWriteGate(
483
585
  if (m.ts === ctx.supersedesTs) continue;
484
586
  if (tokens(m.content).some((t) => valueSet.has(t))) continue;
485
587
  const from = rawTokens(m.content).find(
486
- (t) => !STOPWORDS.has(t.toLowerCase()) && !entitySet.has(t.toLowerCase()) && !valueSet.has(t.toLowerCase()),
588
+ (t) =>
589
+ !STOPWORDS.has(t.toLowerCase()) &&
590
+ !entitySet.has(t.toLowerCase()) &&
591
+ !valueSet.has(t.toLowerCase()),
487
592
  );
488
593
  canonPlan.push({ ts: m.ts, from });
489
594
  }
@@ -492,7 +597,13 @@ export async function runWriteGate(
492
597
  const { marked: canonMarked } = await markManySupersededReport(
493
598
  canonPlan.map((p) => ({
494
599
  ts: p.ts,
495
- fields: { superseded_by: target, reason: "canonical", entity: canon.entry.entity, from: p.from, to: canon.entry.value },
600
+ fields: {
601
+ superseded_by: target,
602
+ reason: "canonical",
603
+ entity: canon.entry.entity,
604
+ from: p.from,
605
+ to: canon.entry.value,
606
+ },
496
607
  })),
497
608
  ctx.durable,
498
609
  );
@@ -528,7 +639,8 @@ export async function runWriteGate(
528
639
  // (gate_start → gate1 → gate2 → dedup_*) stays intact for every verdict.
529
640
  const probe = await probeRejection(candidate.content);
530
641
  const rejection = probe.rejection;
531
- const conflictProne = candidate.type === "decision" || candidate.type === "preference";
642
+ const conflictProne =
643
+ candidate.type === "decision" || candidate.type === "preference";
532
644
  const active = scopeMems.filter((m) => !m.superseded_by);
533
645
  // Exact duplicates are detected against the full scope (a drift-superseded
534
646
  // twin still collapses), but overlap/merge only considers live entries.
@@ -553,7 +665,9 @@ export async function runWriteGate(
553
665
  );
554
666
  // Same-type live rows that could compete with the incoming statement; the
555
667
  // row an update replaces is never a contender.
556
- const live = active.filter((m) => m.type === candidate.type && m.ts !== ctx.supersedesTs);
668
+ const live = active.filter(
669
+ (m) => m.type === candidate.type && m.ts !== ctx.supersedesTs,
670
+ );
557
671
  const divergent = live.filter((m) => m.content !== candidate.content);
558
672
 
559
673
  let collapseMatch: Memory | undefined;
@@ -670,8 +784,10 @@ export async function runWriteGate(
670
784
  const planningObject = candidate.status === "open";
671
785
  const behaviorGrounded = ctx.hasGateCheck || ctx.hasEngagement === true;
672
786
  const ambiguous =
673
- !ctx.trusted && !canon &&
674
- (candidate.scope === "" || (!planningObject && g1.refs === 0 && !behaviorGrounded));
787
+ !ctx.trusted &&
788
+ !canon &&
789
+ (candidate.scope === "" ||
790
+ (!planningObject && g1.refs === 0 && !behaviorGrounded));
675
791
 
676
792
  let blockReason: string | undefined;
677
793
  let blockFlags: string[] = [];
@@ -683,15 +799,21 @@ export async function runWriteGate(
683
799
  blockFlags =
684
800
  rejection.kind === "exact"
685
801
  ? [`ch=${rejection.tombstone.ch}`, "exact"]
686
- : [`ch=${rejection.tombstone.ch}`, `score=${rejection.score}`, "near_match"];
687
- const when = rejection.tombstone.rejected_at.slice(0, 10) || "an earlier session";
802
+ : [
803
+ `ch=${rejection.tombstone.ch}`,
804
+ `score=${rejection.score}`,
805
+ "near_match",
806
+ ];
807
+ const when =
808
+ rejection.tombstone.rejected_at.slice(0, 10) || "an earlier session";
688
809
  // Scrubbed here as well as on the way in and on the way out of tombstones():
689
810
  // this string goes to the model, and the hint is built from a field a human
690
811
  // typed. If the row already came through clean this is a no-op — deleting it
691
812
  // changes nothing observable today, which is deliberate: the guarantee lives
692
813
  // on the read path (it covers every consumer, the viewer included), and this
693
814
  // is the seam where the value becomes a model-facing sentence.
694
- const why = redactSecrets(rejection.tombstone.reason) || "no reason recorded";
815
+ const why =
816
+ redactSecrets(rejection.tombstone.reason) || "no reason recorded";
695
817
  const tch = rejection.tombstone.ch;
696
818
  // The escape-hatch tail is shared by BOTH kinds. An earlier draft put it
697
819
  // only on the near-match branch, which left the COMMON case — a byte-exact
@@ -706,7 +828,8 @@ export async function runWriteGate(
706
828
  (rejection.kind === "exact"
707
829
  ? `This exact content was rejected on ${when} (reason: ${why}; hash ${tch}). Nothing was stored. `
708
830
  : `Content ${rejection.score} similar to a value rejected on ${when} (reason: ${why}; ` +
709
- `hash ${tch}) — the same statement reworded counts as the rejected value. Nothing was stored. `) + lift;
831
+ `hash ${tch}) — the same statement reworded counts as the rejected value. Nothing was stored. `) +
832
+ lift;
710
833
  } else if (g1.candidateStale) {
711
834
  blockReason = "drift_ref_stale_incoming";
712
835
  blockFlags = ["incoming_embeds_pre_drift_ref"];
@@ -725,7 +848,11 @@ export async function runWriteGate(
725
848
  ];
726
849
  } else if (overlapMatch) {
727
850
  blockReason = "superseded_overlap";
728
- blockFlags = [`supersedes_check_${overlapMatch.ts}`, `score=${overlapScore}`, "review_gated"];
851
+ blockFlags = [
852
+ `supersedes_check_${overlapMatch.ts}`,
853
+ `score=${overlapScore}`,
854
+ "review_gated",
855
+ ];
729
856
  hint =
730
857
  `A live ${candidate.type} row ${overlapMatch.ts} in ${candidate.scope || "(no scope)"} competes ` +
731
858
  `with this write (overlap ${overlapScore}). Nothing was stored. To replace that row, use ` +
@@ -769,25 +896,37 @@ export async function runWriteGate(
769
896
  // The write is specifically promoted on engagement (no refs, no gate check,
770
897
  // not canonical, not an open object). Emitted so the precedent is auditable.
771
898
  const groundedByEngagement =
772
- !ctx.trusted && !canon && !planningObject &&
773
- g1.refs === 0 && !ctx.hasGateCheck &&
774
- ctx.hasEngagement === true && candidate.scope !== "";
899
+ !ctx.trusted &&
900
+ !canon &&
901
+ !planningObject &&
902
+ g1.refs === 0 &&
903
+ !ctx.hasGateCheck &&
904
+ ctx.hasEngagement === true &&
905
+ candidate.scope !== "";
775
906
  if (groundedByEngagement) {
776
907
  await rec("gate_injected", { gate: 4, chain });
777
908
  }
778
909
 
779
- const snapshot = await snapshotFiles([join(memoryRoot(), `${new Date().toISOString().split("T")[0]}.logfmt`)]);
910
+ const snapshot = await snapshotFiles([
911
+ join(memoryRoot(), `${new Date().toISOString().split("T")[0]}.logfmt`),
912
+ ]);
780
913
  // The write carries the CALLER's session, not whatever current says after
781
914
  // the gate's own awaits - capture's stamp must follow the captured session.
782
- if (candidate.repo === undefined && !writeAt.ok) throw new UnresolvedWriterError(writeAt.sid);
915
+ if (candidate.repo === undefined && !writeAt.ok)
916
+ throw new UnresolvedWriterError(writeAt.sid);
783
917
  // A captured unscoped ambient writer deliberately publishes repo=global.
784
918
  // Leaving repo undefined would make appendMemory resolve ambient ownership
785
919
  // again after awaits. This changes the old unstamped shape: exports now keep
786
920
  // this row global on import instead of adopting the importing repository.
787
- const owner = candidate.repo === undefined && writeAt.ok
788
- ? { repo: writeAt.scope?.key ?? "global", repoPath: writeAt.scope?.path }
789
- : {};
790
- const ts = await appendMemory({ ...candidate, ...owner, sessionID: ctx.sessionID });
921
+ const owner =
922
+ candidate.repo === undefined && writeAt.ok
923
+ ? { repo: writeAt.scope?.key ?? "global", repoPath: writeAt.scope?.path }
924
+ : {};
925
+ const ts = await appendMemory({
926
+ ...candidate,
927
+ ...owner,
928
+ sessionID: ctx.sessionID,
929
+ });
791
930
  // #165: remember who made this row, so the writing session is not billed a
792
931
  // prompt-cache bust to be shown its own thought. Only promoted writes are
793
932
  // attributed — a blocked candidate created nothing.
@@ -809,20 +948,25 @@ export async function runWriteGate(
809
948
  ch,
810
949
  supersedes: supersededTs ?? "-",
811
950
  canonical: canon ? `canonical.logfmt:${canon.entry.ts}` : "-",
812
- evidence_refs: bracketList(ctx.evidenceCalls.slice(-MAX_WRITE_EVIDENCE_REFS)),
951
+ evidence_refs: bracketList(
952
+ ctx.evidenceCalls.slice(-MAX_WRITE_EVIDENCE_REFS),
953
+ ),
813
954
  evidence_refs_count: ctx.evidenceCallsCount ?? ctx.evidenceCalls.length,
814
955
  snapshot: snapshot[0] ?? "-",
815
956
  trusted: ctx.trusted ? true : undefined,
816
957
  grounded_by: groundedByEngagement ? "engagement" : undefined,
817
958
  quarantined: isQuarantined(candidate) || undefined,
818
- quarantine_patterns: isQuarantined(candidate) ? bracketList(quarantineReasons(candidate)) : undefined,
959
+ quarantine_patterns: isQuarantined(candidate)
960
+ ? bracketList(quarantineReasons(candidate))
961
+ : undefined,
819
962
  chain,
820
963
  });
821
964
  } catch (err) {
822
965
  // NOT `(err as Error).message`: a messageless Error (or a non-Error
823
966
  // rejection) would make the field FALSY, and callers test it for truth —
824
967
  // the lie this field exists to kill would return as a clean success.
825
- evidenceError = err instanceof Error && err.message ? err.message : String(err);
968
+ evidenceError =
969
+ err instanceof Error && err.message ? err.message : String(err);
826
970
  }
827
971
  return { action: "promoted", ts, chain, evidenceError };
828
972
  }