opencode-self-improvement 0.15.4 → 0.15.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/README.md +2 -0
  2. package/package.json +2 -2
  3. package/src/capture/candidates.ts +110 -0
  4. package/src/capture/lag.ts +18 -0
  5. package/src/capture/prompt.ts +50 -0
  6. package/src/capture/transcript.ts +59 -0
  7. package/src/{triggers.ts → capture/triggers.ts} +6 -5
  8. package/src/{command.ts → command/ensure.ts} +2 -2
  9. package/src/{consolidate.ts → consolidate/propose.ts} +7 -30
  10. package/src/consolidate/render.ts +30 -0
  11. package/src/core/cmp-ts.ts +16 -0
  12. package/src/core/config/budgets.ts +28 -0
  13. package/src/{config.ts → core/config/paths.ts} +6 -31
  14. package/src/core/logfmt/format.ts +82 -0
  15. package/src/{logfmt.ts → core/logfmt/publish.ts} +20 -96
  16. package/src/core/logfmt/read.ts +15 -0
  17. package/src/core/permissions.ts +47 -0
  18. package/src/{state.ts → core/state.ts} +1 -1
  19. package/src/core/time.ts +6 -0
  20. package/src/{evidence.ts → evidence/record.ts} +7 -5
  21. package/src/{gates.ts → gate/gate.ts} +19 -21
  22. package/src/{resolver.ts → gate/resolver.ts} +1 -1
  23. package/src/{hits.ts → hits/ledger.ts} +8 -6
  24. package/src/index.ts +64 -943
  25. package/src/init/detect.ts +144 -0
  26. package/src/init/format.ts +25 -0
  27. package/src/init/run.ts +188 -0
  28. package/src/inject/anchor.ts +43 -0
  29. package/src/{attribution.ts → inject/attribution.ts} +2 -2
  30. package/src/inject/budget.ts +78 -0
  31. package/src/inject/digest.ts +89 -0
  32. package/src/{injection-epochs.ts → inject/epochs.ts} +15 -14
  33. package/src/inject/format.ts +32 -0
  34. package/src/inject/pull.ts +52 -0
  35. package/src/inject/version.ts +31 -0
  36. package/src/portable/decay.ts +20 -0
  37. package/src/portable/export.ts +194 -0
  38. package/src/portable/import.ts +173 -0
  39. package/src/recall/relevant.ts +72 -0
  40. package/src/recall/score.ts +106 -0
  41. package/src/recall/shared-terms.ts +15 -0
  42. package/src/status/format.ts +58 -0
  43. package/src/status/metrics.ts +65 -0
  44. package/src/status/payload.ts +145 -0
  45. package/src/status/report.ts +202 -0
  46. package/src/status/write.ts +114 -0
  47. package/src/{blocklist.ts → store/blocklist.ts} +4 -2
  48. package/src/store/files/append.ts +176 -0
  49. package/src/store/files/deletions.ts +31 -0
  50. package/src/store/files/load.ts +106 -0
  51. package/src/store/files/prune.ts +81 -0
  52. package/src/store/files/snapshots.ts +88 -0
  53. package/src/store/files/supersede.ts +123 -0
  54. package/src/store/files/target.ts +36 -0
  55. package/src/{lock.ts → store/lock.ts} +5 -4
  56. package/src/store/model/memory.ts +91 -0
  57. package/src/store/model/predicates.ts +12 -0
  58. package/src/store/model/visibility.ts +140 -0
  59. package/src/{prune.ts → store/prune.ts} +4 -3
  60. package/src/store/quarantine/release.ts +24 -0
  61. package/src/store/tombstones/rejection.ts +93 -0
  62. package/src/{tombstones.ts → store/tombstones/tombstone.ts} +12 -97
  63. package/src/{undo.ts → store/undo.ts} +6 -3
  64. package/src/tools/consolidate.ts +42 -0
  65. package/src/tools/decay.ts +83 -0
  66. package/src/tools/deps.ts +27 -0
  67. package/src/tools/evidence.ts +48 -0
  68. package/src/tools/export.ts +27 -0
  69. package/src/tools/forget.ts +23 -0
  70. package/src/tools/import.ts +57 -0
  71. package/src/tools/init.ts +30 -0
  72. package/src/tools/list.ts +36 -0
  73. package/src/tools/merge-review.ts +138 -0
  74. package/src/tools/recall.ts +72 -0
  75. package/src/tools/registry.ts +40 -0
  76. package/src/tools/remember.ts +49 -0
  77. package/src/{schema.ts → tools/schema.ts} +3 -3
  78. package/src/tools/status-tool.ts +59 -0
  79. package/src/tools/undo.ts +57 -0
  80. package/src/tools/update.ts +342 -0
  81. package/src/{tui.tsx → tui/panel.tsx} +7 -17
  82. package/src/viewer/mutate.ts +15 -15
  83. package/src/viewer/server.ts +10 -8
  84. package/tui.ts +1 -1
  85. package/src/capture.ts +0 -222
  86. package/src/init.ts +0 -333
  87. package/src/inject.ts +0 -471
  88. package/src/memory.ts +0 -851
  89. package/src/portable.ts +0 -379
  90. package/src/status.ts +0 -536
  91. /package/src/{sessions.ts → core/lru.ts} +0 -0
  92. /package/src/{runtime.ts → core/runtime.ts} +0 -0
  93. /package/src/{tokenize.ts → core/tokenize.ts} +0 -0
  94. /package/src/{types.ts → core/types.ts} +0 -0
  95. /package/src/{host.ts → identity/host-events.ts} +0 -0
  96. /package/src/{repokey.ts → identity/repokey.ts} +0 -0
  97. /package/src/{containment.ts → store/containment.ts} +0 -0
  98. /package/src/{quarantine.ts → store/quarantine/quarantine.ts} +0 -0
  99. /package/src/{sanitize.ts → store/sanitize.ts} +0 -0
  100. /package/src/{secrets.ts → store/secrets.ts} +0 -0
@@ -1,91 +1,22 @@
1
+ // publish — split from src/logfmt.ts (#168 domain restructure). Declaration bodies are unchanged.
1
2
  // Minimal logfmt reader/writer shared by the durable store and the evidence
2
3
  // log. Field order is preserved on write so chains are diffable.
3
4
  import { dirname } from "node:path";
4
- import { appendFile, mkdir, readFile, rename, stat, unlink } from "node:fs/promises";
5
-
6
- const IS_WINDOWS = process.platform === "win32";
7
-
8
- export type Fields = Record<string, unknown>;
9
-
10
- // Escapes for quoted values. One record is one line, so a raw newline inside a
11
- // value would end the record early and the rest of the value would be read
12
- // back as a separate line of fields. Backslash is escaped too, so a value
13
- // ending in `\` cannot swallow its closing quote.
14
- const ESCAPE: Record<string, string> = { "\\": "\\\\", '"': '\\"', "\n": "\\n", "\r": "\\r", "\t": "\\t" };
15
- const UNESCAPE: Record<string, string> = { "\\": "\\", '"': '"', n: "\n", r: "\r", t: "\t" };
16
-
17
- // Lines written before these escapes existed stored backslashes raw, so in an
18
- // old line `C:\new` is a backslash and an `n`, not a newline. A line whose
19
- // values use the escapes ends with this marker, and only fields before it are
20
- // unescaped; everything else is read the old way, where only `\"` is an escape.
21
- // Fields after the marker were appended by an older version (supersede adds
22
- // fields to the end of an existing line). Lines without backslashes, newlines
23
- // or tabs read the same either way, so they don't carry the marker.
24
- const MARKER = "esc";
25
- const MARKER_VALUE = "1";
26
-
27
- export function quote(value: unknown): string {
28
- const s = String(value);
29
- if (s === "") return '""';
30
- return /[\s"=]/.test(s) ? `"${s.replace(/[\\"\n\r\t]/g, (c) => ESCAPE[c])}"` : s;
31
- }
32
-
33
- export function formatLine(fields: Fields): string {
34
- const parts: string[] = [];
35
- let escaped = false;
36
- for (const [k, v] of Object.entries(fields)) {
37
- if (v === undefined || v === null || k === MARKER) continue;
38
- const q = quote(v);
39
- if (q.startsWith('"') && /[\\\n\r\t]/.test(String(v))) escaped = true;
40
- parts.push(`${k}=${q}`);
41
- }
42
- if (escaped) parts.push(`${MARKER}=${MARKER_VALUE}`);
43
- return parts.join(" ");
44
- }
45
-
46
- // Unescape a quoted logfmt value and read it back. Unknown sequences are kept
47
- // as written.
48
- function unquote(s: string): string {
49
- return s.replace(/\\(.)/g, (seq, c: string) => UNESCAPE[c] ?? seq);
50
- }
51
-
52
- function unquoteLegacy(s: string): string {
53
- return s.replace(/\\"/g, '"');
54
- }
55
-
56
- export function parseLine(line: string): Fields | null {
57
- const trimmed = line.trim();
58
- if (!trimmed || !trimmed.includes("=")) return null;
59
- const tokens: [string, string][] = [];
60
- const re = /([A-Za-z0-9_.-]+)=("(?:[^"\\]|\\.)*"|[^\s]*)/g;
61
- for (;;) {
62
- const m = re.exec(trimmed);
63
- if (!m) break;
64
- tokens.push([m[1], m[2]]);
65
- }
66
- const marker = tokens.findIndex(([k, v]) => k === MARKER && v === MARKER_VALUE);
67
- const fields: Fields = {};
68
- tokens.forEach(([key, value], i) => {
69
- if (key === MARKER) return;
70
- let raw = value;
71
- if (raw.startsWith('"') && raw.endsWith('"')) {
72
- raw = (i < marker ? unquote : unquoteLegacy)(raw.slice(1, -1));
73
- }
74
- fields[key] = raw;
75
- });
76
- // parse booleans/numbers as strings is fine; callers coerce.
77
- return fields;
78
- }
5
+ import { mkdir, open, rename, stat, unlink } from "node:fs/promises";
6
+ import { constants } from "node:fs";
7
+ import { tightenDirectory } from "../permissions.ts";
8
+ import { IS_WINDOWS } from "./format.ts";
79
9
 
80
10
  export async function ensureDir(path: string): Promise<void> {
81
- await mkdir(path, { recursive: true });
11
+ await mkdir(path, { recursive: true, mode: 0o700 });
12
+ tightenDirectory(path);
82
13
  }
83
14
 
84
15
  export async function appendLog(file: string, line: string): Promise<void> {
85
16
  await ensureDir(dirname(file));
86
17
  const next = line.endsWith("\n") ? line : line + "\n";
87
18
  // One O_APPEND write: read-modify-write loses rows under concurrent
88
- // appenders (20 concurrent appends left 2 on disk). appendFile's "a" flag is
19
+ // appenders (20 concurrent appends left 2 on disk). The handle uses
89
20
  // O_APPEND|O_CREAT — atomic small writes on local POSIX filesystems,
90
21
  // covering interleaved async tasks in the service AND a second process
91
22
  // (the viewer) appending the same day file. Do NOT "simplify" back to
@@ -93,7 +24,13 @@ export async function appendLog(file: string, line: string): Promise<void> {
93
24
  // Appending is safe against other appenders only. Callers writing a file that
94
25
  // is ALSO rewritten whole (a daily memory file, the blocklist) hold the store
95
26
  // lock around this — see lock.ts.
96
- await appendFile(file, next);
27
+ const handle = await open(file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 0o600);
28
+ try {
29
+ if (!IS_WINDOWS) await handle.chmod((await handle.stat()).mode & 0o600);
30
+ await handle.appendFile(next);
31
+ } finally {
32
+ await handle.close();
33
+ }
97
34
  }
98
35
 
99
36
  // A change-detection token for one file: any append, rewrite or replacement
@@ -129,11 +66,15 @@ export async function writeAtomic(file: string, content: string, since?: string)
129
66
  // name would let one call replace the bytes another call's anchored publish
130
67
  // is retrying. Keep separate temps even when the caller holds a lock.
131
68
  const tmp = `${file}.${process.pid}.${++tmpSeq}.tmp`;
69
+ let claimed = false;
132
70
  try {
71
+ const handle = await open(tmp, "wx", 0o600);
72
+ claimed = true;
73
+ await handle.close();
133
74
  await Bun.write(tmp, content);
134
75
  await handoverRename(tmp, file, since);
135
76
  } catch (err) {
136
- await unlink(tmp).catch(() => undefined);
77
+ if (claimed) await unlink(tmp).catch(() => undefined);
137
78
  throw err;
138
79
  }
139
80
  }
@@ -177,20 +118,3 @@ async function handoverRename(tmp: string, file: string, since?: string): Promis
177
118
  }
178
119
  }
179
120
  }
180
-
181
- export async function readLines(file: string): Promise<string[]> {
182
- // BunFile.exists() and .size cache the size; a later text() can crop a larger
183
- // atomic replacement. Read metadata and bytes through one handle instead.
184
- let text: string;
185
- try {
186
- text = await readFile(file, "utf8");
187
- } catch (err) {
188
- if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];
189
- throw err;
190
- }
191
- return text.split("\n").filter((l) => l.trim().length > 0);
192
- }
193
-
194
- export function bracketList(items: string[]): string {
195
- return `[${items.join(",")}]`;
196
- }
@@ -0,0 +1,15 @@
1
+ // read — split from src/logfmt.ts (#168 domain restructure). Declaration bodies are unchanged.
2
+ import { readFile } from "node:fs/promises";
3
+
4
+ export async function readLines(file: string): Promise<string[]> {
5
+ // BunFile.exists() and .size cache the size; a later text() can crop a larger
6
+ // atomic replacement. Read metadata and bytes through one handle instead.
7
+ let text: string;
8
+ try {
9
+ text = await readFile(file, "utf8");
10
+ } catch (err) {
11
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];
12
+ throw err;
13
+ }
14
+ return text.split("\n").filter((l) => l.trim().length > 0);
15
+ }
@@ -0,0 +1,47 @@
1
+ // POSIX modes protect local store data, not Windows ACLs. Never follow a
2
+ // final-component link while tightening permissions, or add owner access that
3
+ // an operator deliberately removed (e.g. a read-only store).
4
+ import { closeSync, constants, fchmodSync, fstatSync, mkdirSync, openSync } from "node:fs";
5
+ import { dirname } from "node:path";
6
+
7
+ export function tightenDirectory(path: string): void {
8
+ if (process.platform === "win32") return;
9
+ let fd: number;
10
+ try {
11
+ fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
12
+ } catch (err) {
13
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return;
14
+ throw err;
15
+ }
16
+ try {
17
+ const mode = fstatSync(fd).mode & 0o7777;
18
+ const privateMode = mode & 0o700;
19
+ if (mode !== privateMode) {
20
+ try {
21
+ fchmodSync(fd, privateMode);
22
+ } catch (err) {
23
+ // A readable store may be immutable, foreign-owned, or on a mount
24
+ // without chmod support. Keep reads available without claiming that
25
+ // its existing permissions were tightened. Open-time refusals above
26
+ // remain policy errors; unexpected I/O failures still propagate.
27
+ const code = (err as NodeJS.ErrnoException).code;
28
+ if (!code || !["EPERM", "EROFS", "EOPNOTSUPP", "ENOSYS"].includes(code)) throw err;
29
+ }
30
+ }
31
+ } finally {
32
+ closeSync(fd);
33
+ }
34
+ }
35
+
36
+ // Status publication keeps its existing Bun.write scheduling. Claim/tighten
37
+ // the file before that write, without first exposing its contents at 0644.
38
+ export function preparePrivateFile(path: string): void {
39
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
40
+ tightenDirectory(dirname(path));
41
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 0o600);
42
+ try {
43
+ if (process.platform !== "win32") fchmodSync(fd, fstatSync(fd).mode & 0o600);
44
+ } finally {
45
+ closeSync(fd);
46
+ }
47
+ }
@@ -1,7 +1,7 @@
1
1
  // Per-session in-memory state shared by the hooks and the gate pipeline.
2
2
  // Deterministic: only tool results and tool invocations mutate it, never the
3
3
  // model. Reset between scenario runs with resetState().
4
- import { SESSION_CAP, SessionLru } from "./sessions.ts";
4
+ import { SESSION_CAP, SessionLru } from "./lru.ts";
5
5
 
6
6
  export interface ToolResult {
7
7
  call: string;
@@ -0,0 +1,6 @@
1
+ // time — split from src/config.ts (#168 domain restructure). Declaration bodies are unchanged.
2
+
3
+
4
+ export function dateStr(d: Date = new Date()): string {
5
+ return d.toISOString().split("T")[0];
6
+ }
@@ -4,11 +4,13 @@
4
4
  import { existsSync, realpathSync } from "node:fs";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
  import { createHash } from "node:crypto";
7
- import { dateStr, evidenceDir } from "./config.ts";
8
- import { appendLog, formatLine } from "./logfmt.ts";
9
- import { repoScope, sessionScope, type RepoScope } from "./repokey.ts";
10
- import { getCurrent } from "./state.ts";
11
- import { redactSecrets } from "./secrets.ts";
7
+ import { evidenceDir } from "../core/config/paths.ts"
8
+ import { dateStr } from "../core/time.ts";
9
+ import { formatLine } from "../core/logfmt/format.ts"
10
+ import { appendLog } from "../core/logfmt/publish.ts";
11
+ import { repoScope, sessionScope, type RepoScope } from "../identity/repokey.ts";
12
+ import { getCurrent } from "../core/state.ts";
13
+ import { redactSecrets } from "../store/secrets.ts";
12
14
 
13
15
  export type EvidenceEvent = string;
14
16
 
@@ -2,25 +2,23 @@
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 "./quarantine.ts";
6
- import { memoryRoot, canonicalFile } from "./config.ts";
7
- import { bracketList, parseLine, readLines } from "./logfmt.ts";
8
- import {
9
- appendMemory,
10
- loadScope,
11
- markManySupersededReport,
12
- snapshotFiles,
13
- MAX_CONTENT_CHARS,
14
- type Memory,
15
- type SupersedeFields,
16
- } from "./memory.ts";
17
- import { captureEvidenceContext, type EvidenceContext, chainId, contentHash, record, recordWriteBlocked } from "./evidence.ts";
18
- import { getCurrent, noteAuthored } from "./state.ts";
19
- import { MAX_WRITE_EVIDENCE_REFS } from "./triggers.ts";
20
- import { flattenMemoryText } from "./sanitize.ts";
21
- import { containsSecret, redactSecrets } from "./secrets.ts";
22
- import { readerFromSid, UnresolvedWriterError, type Reader } from "./memory.ts";
23
- import { writeTarget, type WriteTarget } from "./repokey.ts";
5
+ import { isQuarantined, quarantineReasons } from "../store/quarantine/quarantine.ts";
6
+ import { canonicalFile, memoryRoot } from "../core/config/paths.ts";
7
+ import { bracketList, parseLine } from "../core/logfmt/format.ts"
8
+ 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"
13
+ import { MAX_CONTENT_CHARS, type Memory } from "../store/model/memory.ts";
14
+ import { captureEvidenceContext, type EvidenceContext, chainId, contentHash, record, recordWriteBlocked } from "../evidence/record.ts";
15
+ import { getCurrent, noteAuthored } from "../core/state.ts";
16
+ import { MAX_WRITE_EVIDENCE_REFS } from "../capture/triggers.ts";
17
+ import { flattenMemoryText } from "../store/sanitize.ts";
18
+ import { containsSecret, redactSecrets } from "../store/secrets.ts";
19
+ import { UnresolvedWriterError } from "../store/files/append.ts"
20
+ import { readerFromSid, type Reader } from "../store/model/visibility.ts";
21
+ import { writeTarget, type WriteTarget } from "../identity/repokey.ts";
24
22
  import {
25
23
  displayCall,
26
24
  extractCallForms,
@@ -31,8 +29,8 @@ import {
31
29
  type DriftInfo,
32
30
  type LazyTree,
33
31
  } from "./resolver.ts";
34
- import { STOPWORDS, jaccard, rawTokens, tokens } from "./tokenize.ts";
35
- import { probeRejection } from "./tombstones.ts";
32
+ import { STOPWORDS, jaccard, rawTokens, tokens } from "../core/tokenize.ts";
33
+ import { probeRejection } from "../store/tombstones/rejection.ts";
36
34
 
37
35
  export interface WriteCandidate {
38
36
  type: string;
@@ -4,7 +4,7 @@
4
4
  // regex + balanced-paren scanning, no model involvement.
5
5
  import { join } from "node:path";
6
6
  import { opendir } from "node:fs/promises";
7
- import { type Memory } from "./memory.ts";
7
+ import { type Memory } from "../store/model/memory.ts";
8
8
 
9
9
  export interface CallForm {
10
10
  symbol: string;
@@ -16,12 +16,14 @@
16
16
  // already exists inside that row.
17
17
  import { readFile, stat } from "node:fs/promises";
18
18
  import { join } from "node:path";
19
- import { memoryRoot, HITS_FILENAME } from "./config.ts";
20
- import { appendLog, bracketList, fileIdentity, formatLine, parseLine, readLines, writeAtomic } from "./logfmt.ts";
21
- import type { UseSignals } from "./inject.ts";
22
- import { withStoreLock, LOCK_WRITE } from "./lock.ts";
23
- import type { Memory } from "./memory.ts";
24
- import type { ReadSet } from "./consolidate.ts";
19
+ import { HITS_FILENAME, memoryRoot } from "../core/config/paths.ts";
20
+ import { bracketList, formatLine, parseLine } from "../core/logfmt/format.ts"
21
+ import { appendLog, fileIdentity, writeAtomic } from "../core/logfmt/publish.ts"
22
+ import { readLines } from "../core/logfmt/read.ts";
23
+ import type { UseSignals } from "../recall/relevant.ts";
24
+ import { withStoreLock, LOCK_WRITE } from "../store/lock.ts";
25
+ import type { Memory } from "../store/model/memory.ts";
26
+ import type { ReadSet } from "../consolidate/propose.ts";
25
27
 
26
28
  export type HitSource = "inject" | "pull" | "recall";
27
29