opencode-self-improvement 0.15.18 → 0.15.20

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 +244 -94
  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
@@ -1,7 +1,7 @@
1
1
  // supersede — split from src/memory.ts (#168 domain restructure). Declaration bodies are unchanged.
2
2
  import { join } from "node:path";
3
- import { formatLine, parseLine } from "../../core/logfmt/format.ts"
4
- import { fileIdentity, writeAtomic } from "../../core/logfmt/publish.ts"
3
+ import { formatLine, parseLine } from "../../core/logfmt/format.ts";
4
+ import { fileIdentity, writeAtomic } from "../../core/logfmt/publish.ts";
5
5
  import { readLines } from "../../core/logfmt/read.ts";
6
6
  import { withStoreLock, LOCK_WRITE } from "../lock.ts";
7
7
  import { redactSecrets } from "../secrets.ts";
@@ -20,8 +20,15 @@ export interface SupersedeFields {
20
20
 
21
21
  // Mark an existing memory as superseded IN PLACE (entry retained, recoverable).
22
22
  // Idempotent: a second call is a no-op, so no double `superseded_by`.
23
- export async function markSuperseded(ts: string, fields: SupersedeFields, durable?: string[]): Promise<boolean> {
24
- return (await markManySupersededReport([{ ts, fields }], durable)).marked.length > 0;
23
+ export async function markSuperseded(
24
+ ts: string,
25
+ fields: SupersedeFields,
26
+ durable?: string[],
27
+ ): Promise<boolean> {
28
+ return (
29
+ (await markManySupersededReport([{ ts, fields }], durable)).marked.length >
30
+ 0
31
+ );
25
32
  }
26
33
 
27
34
  // Batch supersession (#61): one lock acquisition, one read, one snapshot and
@@ -33,7 +40,10 @@ export async function markSuperseded(ts: string, fields: SupersedeFields, durabl
33
40
  // so a repeat run marks nothing and writes nothing. Duplicate ts entries in
34
41
  // one batch: the FIRST entry's fields win (mirrors row-by-row first-call-wins).
35
42
  // Returns the number of rows actually marked.
36
- export async function markManySuperseded(entries: { ts: string; fields: SupersedeFields }[], durable?: string[]): Promise<number> {
43
+ export async function markManySuperseded(
44
+ entries: { ts: string; fields: SupersedeFields }[],
45
+ durable?: string[],
46
+ ): Promise<number> {
37
47
  return (await markManySupersededReport(entries, durable)).marked.length;
38
48
  }
39
49
 
@@ -58,16 +68,17 @@ export async function markManySupersededReport(
58
68
  ...(await withStoreLock(
59
69
  file,
60
70
  async () => {
61
- // #106: identity BEFORE the read, like every other whole-file
62
- // read-modify-write (#89's contract) - the publish below may retry a
63
- // Windows handover only while the destination still matches this.
71
+ // #106: identity BEFORE the read, like every other whole-file
72
+ // read-modify-write (#89's contract) - the publish below may retry a
73
+ // Windows handover only while the destination still matches this.
64
74
  const since = await fileIdentity(file);
65
75
  const lines = await readLines(file);
66
76
  const ids: string[] = [];
67
77
  for (let i = 0; i < lines.length; i++) {
68
78
  const parsed = parseLine(lines[i]);
69
79
  if (!parsed || typeof parsed.superseded_by === "string") continue;
70
- const fields = typeof parsed.ts === "string" ? wanted.get(parsed.ts) : undefined;
80
+ const fields =
81
+ typeof parsed.ts === "string" ? wanted.get(parsed.ts) : undefined;
71
82
  if (!fields) continue;
72
83
  // Whole line rewritten, not extended: an old-format line comes out in
73
84
  // the current format with its values unchanged (as markSuperseded did).
@@ -80,7 +91,9 @@ export async function markManySupersededReport(
80
91
  const clean: SupersedeFields = { ...fields };
81
92
  for (const k of Object.keys(clean)) {
82
93
  const v = (clean as unknown as Record<string, unknown>)[k];
83
- if (typeof v === "string") (clean as unknown as Record<string, unknown>)[k] = redactSecrets(v);
94
+ if (typeof v === "string")
95
+ (clean as unknown as Record<string, unknown>)[k] =
96
+ redactSecrets(v);
84
97
  }
85
98
  lines[i] = formatLine({ ...parsed, ...clean });
86
99
  ids.push(parsed.ts as string);
@@ -92,7 +105,7 @@ export async function markManySupersededReport(
92
105
  return ids;
93
106
  },
94
107
  LOCK_WRITE,
95
- ))
108
+ )),
96
109
  );
97
110
  }
98
111
  // A ts that appears in several files (should not exist - append mints unique
@@ -112,7 +125,14 @@ export async function clearSuperseded(ts: string): Promise<boolean> {
112
125
  // update and merge_review), never by appendMemory, so they are all part of
113
126
  // the marker and go with it. Field order round-trips because parseLine
114
127
  // inserts keys in source order.
115
- for (const key of ["superseded_by", "reason", "symbol", "from", "to", "entity"]) {
128
+ for (const key of [
129
+ "superseded_by",
130
+ "reason",
131
+ "symbol",
132
+ "from",
133
+ "to",
134
+ "entity",
135
+ ]) {
116
136
  delete parsed[key];
117
137
  }
118
138
  return formatLine(parsed);
@@ -10,7 +10,10 @@ export type TargetResolution =
10
10
  // Pick the row an update/merge call means. Without a query the caller keeps the
11
11
  // legacy "most recent active row of this scope+type" behaviour; with one, a
12
12
  // miss or a tie fails CLOSED rather than silently rewriting a different row.
13
- export function resolveMemoryTarget(rows: Memory[], query?: string): TargetResolution {
13
+ export function resolveMemoryTarget(
14
+ rows: Memory[],
15
+ query?: string,
16
+ ): TargetResolution {
14
17
  if (!query || !query.trim()) {
15
18
  const last = rows[rows.length - 1];
16
19
  return last ? { status: "ok", target: last } : { status: "not_found" };
package/src/store/lock.ts CHANGED
@@ -103,7 +103,9 @@ async function probeLock(lockPath: string): Promise<LockProbe> {
103
103
  await stat(lockPath);
104
104
  return "present";
105
105
  } catch (probe) {
106
- return (probe as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : "unknown";
106
+ return (probe as NodeJS.ErrnoException).code === "ENOENT"
107
+ ? "absent"
108
+ : "unknown";
107
109
  }
108
110
  }
109
111
 
@@ -261,7 +263,13 @@ export async function withStoreLock<T>(
261
263
  }
262
264
 
263
265
  try {
264
- return await holdFileLock(lockPath, file, fn, opts, timeoutMs - (Date.now() - started));
266
+ return await holdFileLock(
267
+ lockPath,
268
+ file,
269
+ fn,
270
+ opts,
271
+ timeoutMs - (Date.now() - started),
272
+ );
265
273
  } finally {
266
274
  finish();
267
275
  }
@@ -1,6 +1,11 @@
1
1
  // Repository visibility, shared by memory rows, restore lines, and evidence.
2
2
  import { createHash } from "node:crypto";
3
- import { normalizeDirPath, repoScopeFor, sessionScope, type RepoScope } from "../../identity/repokey.ts";
3
+ import {
4
+ normalizeDirPath,
5
+ repoScopeFor,
6
+ sessionScope,
7
+ type RepoScope,
8
+ } from "../../identity/repokey.ts";
4
9
  import { getCurrent } from "../../core/state.ts";
5
10
  import { parseLine } from "../../core/logfmt/format.ts";
6
11
  import { prune } from "../files/prune.ts";
@@ -68,13 +73,20 @@ export function readerFromSid(sid?: unknown): Reader {
68
73
  // real symlink/case-insensitive aliases, instead of trusting that key alone.
69
74
  // Remote-derived keys still share across clones with different paths. A stamp
70
75
  // without repoPath cannot be classified this way and keeps key-only matching.
71
- function matchesRepository(repo: string, repoPath: string | undefined, scope: RepoScope): boolean {
76
+ function matchesRepository(
77
+ repo: string,
78
+ repoPath: string | undefined,
79
+ scope: RepoScope,
80
+ ): boolean {
72
81
  if (repoPath === scope.path) return true; // pre-hash and legacy owner access
73
82
  if (repoPath) {
74
83
  // The historical hash used realpath too: repoPath itself may name a
75
84
  // symlink/junction, a short Windows spelling, or contain dot segments.
76
85
  const canonical = normalizeDirPath(repoPath);
77
- const legacyKey = createHash("sha1").update(canonical.toLowerCase()).digest("hex").slice(0, 12);
86
+ const legacyKey = createHash("sha1")
87
+ .update(canonical.toLowerCase())
88
+ .digest("hex")
89
+ .slice(0, 12);
78
90
  if (repo === legacyKey) return canonical === normalizeDirPath(scope.path);
79
91
  }
80
92
  return repo === scope.key;
@@ -86,7 +98,10 @@ function matchesRepository(repo: string, repoPath: string | undefined, scope: Re
86
98
  // processes with no scope, e.g. the viewer), or was written in the reader's
87
99
  // repo. Keeping it one predicate is what stops the filtering from drifting
88
100
  // between entry points.
89
- export function isVisibleTo(m: Pick<Memory, "repo" | "repoPath">, reader: Reader): boolean {
101
+ export function isVisibleTo(
102
+ m: Pick<Memory, "repo" | "repoPath">,
103
+ reader: Reader,
104
+ ): boolean {
90
105
  if (reader.kind === "admin") return true;
91
106
  if (!m.repo || m.repo === "global") return true;
92
107
  if (reader.kind === "global-only") return false;
@@ -109,7 +124,8 @@ export function lineVisibleTo(line: string, reader: Reader): boolean {
109
124
  return isVisibleTo(
110
125
  {
111
126
  repo: typeof fields?.repo === "string" ? fields.repo : undefined,
112
- repoPath: typeof fields?.repoPath === "string" ? fields.repoPath : undefined,
127
+ repoPath:
128
+ typeof fields?.repoPath === "string" ? fields.repoPath : undefined,
113
129
  },
114
130
  reader,
115
131
  );
@@ -136,7 +152,11 @@ export function evidenceVisibleTo(
136
152
  if (repo === "global") return true;
137
153
  if (reader.kind === "global-only") return false;
138
154
  const repoPath = fields.repoPath;
139
- return matchesRepository(repo, typeof repoPath === "string" ? repoPath : undefined, reader.scope);
155
+ return matchesRepository(
156
+ repo,
157
+ typeof repoPath === "string" ? repoPath : undefined,
158
+ reader.scope,
159
+ );
140
160
  }
141
161
  const sid = fields.sid;
142
162
  if (typeof sid === "string" && sid !== "" && sid !== "?") {
@@ -2,7 +2,7 @@
2
2
  // reversible (snapshot) and never touches a repo. The `prune` evidence line is
3
3
  // emitted before/around the mutation so S5 can assert the reason and snapshot.
4
4
  import { deletionsFile } from "../core/config/paths.ts";
5
- import { prune, type PruneResult } from "./files/prune.ts"
5
+ import { prune, type PruneResult } from "./files/prune.ts";
6
6
  import { readerFromSid } from "./model/visibility.ts";
7
7
  import { record } from "../evidence/record.ts";
8
8
 
@@ -2,15 +2,32 @@
2
2
  // against prompt injection. Matches are identifiers only; never audit the text.
3
3
  export const QUARANTINE_TAG = "quarantine";
4
4
  const PATTERNS: readonly [string, RegExp][] = [
5
- ["instruction_override", /\b(?:ignore|disregard|override)\s+(?:all\s+)?(?:previous|prior|above)\s+(?:instructions|rules|prompts)\b/i],
6
- ["role_header", /(?:^|\n)[ \t]*(?:#{1,6}[ \t]*)?(?:\*\*|__)?(?:system|developer|assistant)[ \t]*:/i],
7
- ["role_delimiter", /<\|(?:im_start|start_header_id)\|>|<\/?(?:system|developer|assistant)>|\[(?:system|developer|assistant)\]/i],
8
- ["download_execute", /\b(?:curl|wget)\b[^\r\n|]{0,2048}(?:\||&&)\s*(?:sh|bash|zsh|powershell|pwsh)\b/i],
9
- ["dynamic_execute", /(?<![$\w.])(?:eval|exec)\s*\(|\b(?:Invoke-Expression|iex)\s+/i],
5
+ [
6
+ "instruction_override",
7
+ /\b(?:ignore|disregard|override)\s+(?:all\s+)?(?:previous|prior|above)\s+(?:instructions|rules|prompts)\b/i,
8
+ ],
9
+ [
10
+ "role_header",
11
+ /(?:^|\n)[ \t]*(?:#{1,6}[ \t]*)?(?:\*\*|__)?(?:system|developer|assistant)[ \t]*:/i,
12
+ ],
13
+ [
14
+ "role_delimiter",
15
+ /<\|(?:im_start|start_header_id)\|>|<\/?(?:system|developer|assistant)>|\[(?:system|developer|assistant)\]/i,
16
+ ],
17
+ [
18
+ "download_execute",
19
+ /\b(?:curl|wget)\b[^\r\n|]{0,2048}(?:\||&&)\s*(?:sh|bash|zsh|powershell|pwsh)\b/i,
20
+ ],
21
+ [
22
+ "dynamic_execute",
23
+ /(?<![$\w.])(?:eval|exec)\s*\(|\b(?:Invoke-Expression|iex)\s+/i,
24
+ ],
10
25
  ];
11
26
 
12
27
  export function quarantinePatterns(content: string): string[] {
13
- return PATTERNS.filter(([, pattern]) => pattern.test(content)).map(([id]) => id);
28
+ return PATTERNS.filter(([, pattern]) => pattern.test(content)).map(
29
+ ([id]) => id,
30
+ );
14
31
  }
15
32
 
16
33
  export function isQuarantined(row: { tags?: string[] }): boolean {
@@ -18,14 +35,24 @@ export function isQuarantined(row: { tags?: string[] }): boolean {
18
35
  }
19
36
 
20
37
  export function quarantineReasons(row: { tags?: string[] }): string[] {
21
- return PATTERNS.map(([id]) => id).filter((id) => row.tags?.includes(`quarantine:${id}`));
38
+ return PATTERNS.map(([id]) => id).filter((id) =>
39
+ row.tags?.includes(`quarantine:${id}`),
40
+ );
22
41
  }
23
42
 
24
- export function quarantineCandidate<T extends { content: string; tags?: string[] }>(candidate: T): T {
43
+ export function quarantineCandidate<
44
+ T extends { content: string; tags?: string[] },
45
+ >(candidate: T): T {
25
46
  const hits = quarantinePatterns(candidate.content);
26
47
  if (!hits.length) return candidate;
27
48
  return {
28
49
  ...candidate,
29
- tags: [...new Set([...(candidate.tags ?? []), QUARANTINE_TAG, ...hits.map((id) => `quarantine:${id}`)])],
50
+ tags: [
51
+ ...new Set([
52
+ ...(candidate.tags ?? []),
53
+ QUARANTINE_TAG,
54
+ ...hits.map((id) => `quarantine:${id}`),
55
+ ]),
56
+ ],
30
57
  };
31
58
  }
@@ -7,12 +7,18 @@ import { stampRow } from "../files/snapshots.ts";
7
7
 
8
8
  // Human viewer action only. Preserve identity, origin, and all non-quarantine
9
9
  // metadata; stampRow snapshots and atomically publishes under the store lock.
10
- export async function releaseQuarantine(ts: string): Promise<"released" | "not_found" | "not_quarantined"> {
10
+ export async function releaseQuarantine(
11
+ ts: string,
12
+ ): Promise<"released" | "not_found" | "not_quarantined"> {
11
13
  for (const file of await memoryFiles()) {
12
14
  const result = await stampRow(file, ts, (fields) => {
13
- const tags = typeof fields.tags === "string" ? fields.tags.split(",") : [];
15
+ const tags =
16
+ typeof fields.tags === "string" ? fields.tags.split(",") : [];
14
17
  if (!tags.includes(QUARANTINE_TAG)) return null;
15
- const scanTags = new Set([QUARANTINE_TAG, ...quarantineReasons({ tags }).map((id) => `quarantine:${id}`)]);
18
+ const scanTags = new Set([
19
+ QUARANTINE_TAG,
20
+ ...quarantineReasons({ tags }).map((id) => `quarantine:${id}`),
21
+ ]);
16
22
  const kept = tags.filter((tag) => !scanTags.has(tag));
17
23
  if (kept.length) fields.tags = kept.join(",");
18
24
  else delete fields.tags;
@@ -9,11 +9,13 @@ const PRIVATE_KEY_BLOCK =
9
9
  const PREFIXED_SECRET =
10
10
  /\b(?:sk-[A-Za-z0-9_-]{16,}|gh[po]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|xox[bp]-[A-Za-z0-9-]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/g;
11
11
  // A real bearer token has digits; prose like "Bearer authentication-scheme" doesn't.
12
- const BEARER_SECRET = /\bBearer\s+(?=[A-Za-z0-9._~+/=-]*\d)[A-Za-z0-9._~+/=-]{16,}/gi;
12
+ const BEARER_SECRET =
13
+ /\bBearer\s+(?=[A-Za-z0-9._~+/=-]*\d)[A-Za-z0-9._~+/=-]{16,}/gi;
13
14
  const ASSIGNED_SECRET =
14
15
  /(\b(?:[A-Za-z][A-Za-z0-9_]*(?:_KEY|_TOKEN|_SECRET|_PASSWORD)|password)\b["']?\s*(?::|=)\s*["']?)([A-Za-z0-9+/_=.-]{16,})/gi;
15
16
  // `API_KEY=process.env.OPENAI_API_KEY` names where the key lives; keep it.
16
- const DOTTED_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/;
17
+ const DOTTED_IDENTIFIER =
18
+ /^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/;
17
19
 
18
20
  function looksHighEntropy(value: string): boolean {
19
21
  if (value.length < 16 || new Set(value).size < 10) return false;
@@ -2,7 +2,16 @@
2
2
  import { join } from "node:path";
3
3
  import { contentHash } from "../../evidence/record.ts";
4
4
  import { memoryRoot } from "../../core/config/paths.ts";
5
- import { NEAR_FLOOR, NEAR_MIN_SHARED, type Tombstone, differsIn, sketchOf, tombstone, tombstones, valueSigOf } from "./tombstone.ts";
5
+ import {
6
+ NEAR_FLOOR,
7
+ NEAR_MIN_SHARED,
8
+ type Tombstone,
9
+ differsIn,
10
+ sketchOf,
11
+ tombstone,
12
+ tombstones,
13
+ valueSigOf,
14
+ } from "./tombstone.ts";
6
15
 
7
16
  const REJECTED_FILENAME = "rejected.logfmt";
8
17
 
@@ -70,21 +79,28 @@ export async function probeRejection(content: string): Promise<RejectionProbe> {
70
79
  if (shared < NEAR_MIN_SHARED || score < NEAR_FLOOR) continue;
71
80
  const differs = differsIn(values, { num: t.num ?? [], pol: t.pol ?? [] });
72
81
  if (differs) {
73
- if (!vetoed || score > vetoed.score) vetoed = { tombstone: t, score, shared, differs };
82
+ if (!vetoed || score > vetoed.score)
83
+ vetoed = { tombstone: t, score, shared, differs };
74
84
  continue;
75
85
  }
76
- if (!best || score > best.score) best = { kind: "near", tombstone: t, score, shared };
86
+ if (!best || score > best.score)
87
+ best = { kind: "near", tombstone: t, score, shared };
77
88
  }
78
89
  if (best) return { rejection: best };
79
90
  return vetoed ? { vetoed } : {};
80
91
  }
81
92
 
82
93
  /** The verdict without the veto telemetry — see {@link probeRejection}. */
83
- export async function findRejection(content: string): Promise<Rejection | undefined> {
94
+ export async function findRejection(
95
+ content: string,
96
+ ): Promise<Rejection | undefined> {
84
97
  return (await probeRejection(content)).rejection;
85
98
  }
86
99
 
87
- function jaccardShared(a: string[], b: string[]): { score: number; shared: number } {
100
+ function jaccardShared(
101
+ a: string[],
102
+ b: string[],
103
+ ): { score: number; shared: number } {
88
104
  const setB = new Set(b);
89
105
  let shared = 0;
90
106
  for (const h of a) if (setB.has(h)) shared++;
@@ -46,13 +46,27 @@ import { readFile } from "node:fs/promises";
46
46
  import { createHash } from "node:crypto";
47
47
  import { join } from "node:path";
48
48
  import { contentHash } from "../../evidence/record.ts";
49
- import { formatLine, parseLine } from "../../core/logfmt/format.ts"
50
- import { appendLog, fileIdentity, writeAtomic } from "../../core/logfmt/publish.ts"
49
+ import { formatLine, parseLine } from "../../core/logfmt/format.ts";
50
+ import {
51
+ appendLog,
52
+ fileIdentity,
53
+ writeAtomic,
54
+ } from "../../core/logfmt/publish.ts";
51
55
  import { readLines } from "../../core/logfmt/read.ts";
52
56
  import { withStoreLock, LOCK_WRITE } from "../lock.ts";
53
57
  import { redactSecrets } from "../secrets.ts";
54
- import { STOPWORDS, tokens, numericTokens, polaritySigns } from "../../core/tokenize.ts";
55
- import { type Rejection, type ValueDifference, findRejection, rejectedFile } from "./rejection.ts";
58
+ import {
59
+ STOPWORDS,
60
+ tokens,
61
+ numericTokens,
62
+ polaritySigns,
63
+ } from "../../core/tokenize.ts";
64
+ import {
65
+ type Rejection,
66
+ type ValueDifference,
67
+ findRejection,
68
+ rejectedFile,
69
+ } from "./rejection.ts";
56
70
 
57
71
  /** How many lowest token-hashes the sketch keeps. */
58
72
  const SKETCH_SIZE = 64;
@@ -118,7 +132,10 @@ export interface Tombstone {
118
132
  }
119
133
 
120
134
  function tokenHash(token: string): string {
121
- return createHash("sha1").update(token).digest("hex").slice(0, TOKEN_HASH_CHARS);
135
+ return createHash("sha1")
136
+ .update(token)
137
+ .digest("hex")
138
+ .slice(0, TOKEN_HASH_CHARS);
122
139
  }
123
140
 
124
141
  /** The GATE-3 token set minus the filler words, so the sketch is a set of
@@ -193,7 +210,10 @@ export function valueSigOf(content: string): ValueSig {
193
210
  * near-match decides exactly as it shipped (every row from here on carries
194
211
  * both signatures, so that degradation does not grow).
195
212
  */
196
- export function differsIn(a: ValueSig, b: ValueSig): ValueDifference | undefined {
213
+ export function differsIn(
214
+ a: ValueSig,
215
+ b: ValueSig,
216
+ ): ValueDifference | undefined {
197
217
  if (moved(a.num, b.num)) return "numeric_value";
198
218
  if (moved(a.pol, b.pol)) return "polarity";
199
219
  return undefined;
@@ -252,8 +272,14 @@ export async function tombstones(): Promise<Tombstone[]> {
252
272
  sig: typeof f.sig === "string" ? f.sig.split(".").filter(Boolean) : [],
253
273
  // Present-but-empty ("num=") means tracked with nothing asserted; absent
254
274
  // means the row predates value tracking. differsIn treats them apart.
255
- num: typeof f.num === "string" ? f.num.split(".").filter(Boolean) : undefined,
256
- pol: typeof f.pol === "string" ? f.pol.split(".").filter(Boolean) : undefined,
275
+ num:
276
+ typeof f.num === "string"
277
+ ? f.num.split(".").filter(Boolean)
278
+ : undefined,
279
+ pol:
280
+ typeof f.pol === "string"
281
+ ? f.pol.split(".").filter(Boolean)
282
+ : undefined,
257
283
  });
258
284
  }
259
285
  cache = { at: identity, rows: out };
@@ -319,7 +345,11 @@ export async function tombstoneMany(
319
345
  // batch must be joined with newlines. Joining on "" silently published every
320
346
  // record in the batch as one line, of which only the first parsed — and a
321
347
  // caller forgetting one row at a time could not see it.
322
- await withStoreLock(file, () => appendLog(file, fresh.join("\n")), LOCK_WRITE);
348
+ await withStoreLock(
349
+ file,
350
+ () => appendLog(file, fresh.join("\n")),
351
+ LOCK_WRITE,
352
+ );
323
353
  resetTombstoneCache();
324
354
  return { recorded: fresh.length, chs };
325
355
  }
@@ -332,7 +362,10 @@ export async function tombstone(
332
362
  content: string,
333
363
  opts: { reason: string; source: string; scope?: string; type?: string },
334
364
  ): Promise<{ ch: string; recorded: boolean }> {
335
- const { recorded, chs } = await tombstoneMany([{ content, scope: opts.scope, type: opts.type }], opts);
365
+ const { recorded, chs } = await tombstoneMany(
366
+ [{ content, scope: opts.scope, type: opts.type }],
367
+ opts,
368
+ );
336
369
  return { ch: chs[0], recorded: recorded > 0 };
337
370
  }
338
371
 
@@ -360,7 +393,11 @@ export async function removeTombstone(ch: string): Promise<boolean> {
360
393
  const row = parseLine(l);
361
394
  return !(row && row.ch === ch);
362
395
  });
363
- await writeAtomic(file, kept.join("\n") + (kept.length ? "\n" : ""), since);
396
+ await writeAtomic(
397
+ file,
398
+ kept.join("\n") + (kept.length ? "\n" : ""),
399
+ since,
400
+ );
364
401
  resetTombstoneCache();
365
402
  return true;
366
403
  },
package/src/store/undo.ts CHANGED
@@ -28,12 +28,20 @@ import { lstat, readFile, realpath, stat } from "node:fs/promises";
28
28
  import { basename, isAbsolute, join, relative, resolve } from "node:path";
29
29
  import { deletionsFile, snapshotDir } from "../core/config/paths.ts";
30
30
  import { isWithin } from "./containment.ts";
31
- import { parseLine } from "../core/logfmt/format.ts"
32
- import { ensureDir, fileIdentity, writeAtomic } from "../core/logfmt/publish.ts"
31
+ import { parseLine } from "../core/logfmt/format.ts";
32
+ import {
33
+ ensureDir,
34
+ fileIdentity,
35
+ writeAtomic,
36
+ } from "../core/logfmt/publish.ts";
33
37
  import { readLines } from "../core/logfmt/read.ts";
34
38
  import { withStoreLock, LOCK_RESTORE } from "./lock.ts";
35
- import { snapshotFiles } from "./files/snapshots.ts"
36
- import { ADMIN_READER, lineVisibleTo, type Reader } from "./model/visibility.ts";
39
+ import { snapshotFiles } from "./files/snapshots.ts";
40
+ import {
41
+ ADMIN_READER,
42
+ lineVisibleTo,
43
+ type Reader,
44
+ } from "./model/visibility.ts";
37
45
 
38
46
  const SNAPSHOT_NAME = /^(\d+)-(\d{4}-\d{2}-\d{2}\.logfmt)$/;
39
47
 
@@ -126,7 +134,9 @@ async function resolveSnapshot(
126
134
  throw new Error(`invalid snapshot name: ${name}`);
127
135
  }
128
136
  if (!isAbsolute(snapshot) && snapshot !== name) {
129
- throw new Error("snapshot must be a bare name from memory_undo list or a full path");
137
+ throw new Error(
138
+ "snapshot must be a bare name from memory_undo list or a full path",
139
+ );
130
140
  }
131
141
 
132
142
  const rootResolved = resolve(memoryRootDir);
@@ -175,7 +185,8 @@ async function auditedDeletions(): Promise<Set<string>> {
175
185
  const deleted = new Set<string>();
176
186
  for (const line of await readLines(deletionsFile())) {
177
187
  const fields = parseLine(line);
178
- if (fields?.action !== "deleted" || typeof fields.original_ts !== "string") continue;
188
+ if (fields?.action !== "deleted" || typeof fields.original_ts !== "string")
189
+ continue;
179
190
  deleted.add(fields.original_ts);
180
191
  }
181
192
  return deleted;
@@ -195,23 +206,31 @@ export async function restoreSnapshot(
195
206
  const rootReal = await realpath(resolve(memoryRootDir));
196
207
  const realTarget = resolve(rootReal, snap.original);
197
208
  if (!isWithin(rootReal, realTarget)) {
198
- throw new Error(`snapshot target escapes the memory root: ${snap.original}`);
209
+ throw new Error(
210
+ `snapshot target escapes the memory root: ${snap.original}`,
211
+ );
199
212
  }
200
213
  let targetInfo: Awaited<ReturnType<typeof lstat>> | undefined;
201
214
  try {
202
215
  targetInfo = await lstat(realTarget);
203
216
  } catch (err) {
204
- if (!(err instanceof Error && "code" in err && err.code === "ENOENT")) throw err;
217
+ if (!(err instanceof Error && "code" in err && err.code === "ENOENT"))
218
+ throw err;
205
219
  }
206
220
  if (targetInfo) {
207
221
  if (targetInfo.isSymbolicLink()) {
208
- throw new Error(`snapshot target must not be a symbolic link: ${snap.original}`);
222
+ throw new Error(
223
+ `snapshot target must not be a symbolic link: ${snap.original}`,
224
+ );
209
225
  }
210
226
  const targetReal = await realpath(realTarget);
211
227
  if (relative(realTarget, targetReal) !== "") {
212
- throw new Error(`snapshot target must not be a symbolic link: ${snap.original}`);
228
+ throw new Error(
229
+ `snapshot target must not be a symbolic link: ${snap.original}`,
230
+ );
213
231
  }
214
- if (!targetInfo.isFile()) throw new Error(`snapshot target is not a file: ${snap.original}`);
232
+ if (!targetInfo.isFile())
233
+ throw new Error(`snapshot target is not a file: ${snap.original}`);
215
234
  }
216
235
  // Checks above ran on real paths; lock and write through the same lexical
217
236
  // path every other writer uses, so the in-process lock queue is shared.
@@ -238,7 +257,8 @@ export async function restoreSnapshot(
238
257
  const curLines = rows(current);
239
258
  // Deliberate deletions are read inside the lock too, so a forget that
240
259
  // finished just before this restore is honoured.
241
- const audited = mode !== "force" ? await auditedDeletions() : new Set<string>();
260
+ const audited =
261
+ mode !== "force" ? await auditedDeletions() : new Set<string>();
242
262
  // Ownership before anything else (#153): rows a foreign repo owns are
243
263
  // excluded from the snapshot side in EVERY mode (never revived, never
244
264
  // rewound), excluded from the deletion audit and the divergence
@@ -249,7 +269,8 @@ export async function restoreSnapshot(
249
269
  // has no business parsing every line three times.
250
270
  const curOwn: string[] = [];
251
271
  const curForeign: string[] = [];
252
- for (const l of curLines) (lineVisibleTo(l, reader) ? curOwn : curForeign).push(l);
272
+ for (const l of curLines)
273
+ (lineVisibleTo(l, reader) ? curOwn : curForeign).push(l);
253
274
  const live = new Set(curOwn.map(rowKey));
254
275
  const deletedOmitted: string[] = [];
255
276
  const snapLines = snapOwn.filter((line) => {
@@ -286,7 +307,10 @@ export async function restoreSnapshot(
286
307
  }
287
308
  }
288
309
 
289
- if (mode === "check" && (concurrentAdded.length || concurrentChanged.length)) {
310
+ if (
311
+ mode === "check" &&
312
+ (concurrentAdded.length || concurrentChanged.length)
313
+ ) {
290
314
  return {
291
315
  target,
292
316
  restored: false,
@@ -302,7 +326,8 @@ export async function restoreSnapshot(
302
326
  // snapshotted HERE — inside the lock, which is what makes rows a
303
327
  // concurrent session appended moments earlier part of the copy. A caller
304
328
  // that snapshots before this call races the very write it means to save.
305
- const safety = mode === "force" ? (await snapshotFiles([target]))[0] : undefined;
329
+ const safety =
330
+ mode === "force" ? (await snapshotFiles([target]))[0] : undefined;
306
331
 
307
332
  let out = snapLines;
308
333
  if (mode === "merge") {
@@ -311,9 +336,9 @@ export async function restoreSnapshot(
311
336
  // rows the snapshot never saw. Merge is a deliberate superset: rows the
312
337
  // snapshotter wrote after the snapshot are NOT dropped here; choose FORCE
313
338
  // for that.
314
- out = snapLines.map((l) => curByKey.get(rowKey(l)) ?? l).concat(
315
- curOwn.filter((l) => !snapByKey.has(rowKey(l))),
316
- );
339
+ out = snapLines
340
+ .map((l) => curByKey.get(rowKey(l)) ?? l)
341
+ .concat(curOwn.filter((l) => !snapByKey.has(rowKey(l))));
317
342
  }
318
343
  // FORCE's "exact rollback" is exact FOR THE CALLER'S REPOSITORY, not
319
344
  // beyond it: foreign live lines rejoin the file verbatim in every mode,