@vectorize-io/hindsight-coding-agents 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,54 +12,132 @@ tie-break policy. Those decisions live in git history and past conversations. Th
12
12
  in front of the agent at the moment it starts working, and keeps a curated set of **knowledge pages**
13
13
  (architecture, conventions, in-flight initiatives) that future sessions start from.
14
14
 
15
+ ## Install
16
+
17
+ ```bash
18
+ npm install -g @vectorize-io/hindsight-coding-agents
19
+ hindsight-coding-agents install all # every detected agent, wired natively
20
+ hindsight-coding-agents install claude-code # or just one
21
+ hindsight-coding-agents uninstall all # removes exactly what install added
22
+ ```
23
+
24
+ `install` takes an explicit target — `all`, or one or more harness names. A bare
25
+ `hindsight-coding-agents install` changes nothing and prints the choice, so wiring every agent on
26
+ the machine is never something that happens by accident.
27
+
28
+ ### Per agent
29
+
30
+ Same command, only the harness name changes. Run after installing the package globally.
31
+
32
+ | agent | command | what it wires |
33
+ | ------------------ | --------------------------------------------- | ------------------------------------------------------------------------------------------------ |
34
+ | Claude Code | `hindsight-coding-agents install claude-code` | 3 hooks in `~/.claude/settings.json` + MCP (`claude mcp add`, user scope) + companion skill |
35
+ | opencode | `hindsight-coding-agents install opencode` | plugin entry in `~/.config/opencode/opencode.json` (native tools, no MCP needed) |
36
+ | Kilo CLI | `hindsight-coding-agents install kilo` | plugin entry in `~/.config/kilo/kilo.json[c]` |
37
+ | Codex CLI | `hindsight-coding-agents install codex` | 3 hooks in `~/.codex/hooks.json` + `[mcp_servers]` in `config.toml` (needs `codex_hooks = true`) |
38
+ | Cursor CLI | `hindsight-coding-agents install cursor-cli` | hooks in `~/.cursor/hooks.json` + `~/.cursor/mcp.json` + skill |
39
+ | GitHub Copilot CLI | `hindsight-coding-agents install copilot-cli` | `~/.copilot/hooks/` + `mcp-config.json` + skill |
40
+ | Grok Build | `hindsight-coding-agents install grok-build` | native hooks + MCP in `~/.grok/config.toml` + skill |
41
+ | Antigravity CLI | `hindsight-coding-agents install agy` | lifecycle hooks + MCP + the `Hindsight · <bank>` status line |
42
+ | Devin CLI | `hindsight-coding-agents install devin-cli` | hooks in `~/.config/devin/config.json` + MCP (needs Node 22.5+, see below) |
43
+ | Cline CLI | `hindsight-coding-agents install cline-cli` | native plugin via `cline plugin install` + MCP + skill |
44
+
45
+ Uninstall the same way: `hindsight-coding-agents uninstall claude-code` (or `uninstall all`).
46
+
47
+ **Devin CLI needs Node 22.5 or newer.** Its hooks pass only a session id — the conversation itself
48
+ lives in `~/.local/share/devin/cli/sessions.db` — so reading it depends on Node's built-in
49
+ `node:sqlite`. Installing `devin-cli` checks for this first and refuses (with the reason) rather
50
+ than wiring hooks that could never retain anything. Every other agent works on any supported Node.
51
+
52
+ Install globally (not `npx`): the wiring points at this package's files, so it must live at a
53
+ stable path — the installer refuses to run from an npx cache. **Updating** is just
54
+ `npm update -g @vectorize-io/hindsight-coding-agents`: the wired paths stay valid, every new session runs the
55
+ new version; re-run `install` (idempotent) only when a release note says the wiring changed.
56
+
57
+ `install` merges the native wiring (hooks + MCP registration where the host wants them) into each
58
+ agent's own config, preserving everything already there; it is idempotent (re-run after moving the
59
+ package) and backs up any pre-existing file it touches as `<file>.hindsight-backup`. `uninstall`
60
+ removes only our entries. On Claude Code the install also ships a **companion skill**
61
+ (`~/.claude/skills/hindsight-coding-agent`) that teaches the agent how this memory works — what
62
+ "store this in hindsight" should do, the tool surface, per-repo configuration, debugging — so users
63
+ can ask the agent itself. Manual wiring per harness, if you prefer:
64
+
65
+ **opencode** installs directly — point `opencode.json` at the package dir:
66
+
67
+ ```json
68
+ { "plugin": ["/path/to/hindsight-coding-agents"] }
69
+ ```
70
+
71
+ **Claude Code** and **Codex** get their full three-hook + MCP wiring from this package's own
72
+ installer — `hindsight-coding-agents install claude-code` / `install codex`. This package's `bin`
73
+ entries (`hindsight-claude-hook`, `hindsight-codex-hook`,
74
+ `hindsight-cursor-hook`) are the individual injection-only `UserPromptSubmit` entrypoints for a
75
+ minimal, hand-wired setup.
76
+
77
+ Adding an agent: hook-based → write a `HookSpec` entry point (see `src/cursor-hook.ts`) and register
78
+ a `hookAdapter` in `src/harness/registry.ts`; persistent-plugin → implement `HarnessAdapter`
79
+ (`src/core/types.ts`) fully (see `src/harness/opencode.ts`).
80
+
81
+ ## Migrating from the per-agent plugins
82
+
83
+ The older per-agent integrations (`hindsight-claude-code`, `hindsight-cursor-cli`, `hindsight-codex`, …) are superseded by this package. Their memory does **not** carry over automatically, and it cannot be merged:
84
+
85
+ - They scope a bank **per agent per project** (`claude-code::myrepo`); this package uses one **per repo** (`coding-agent::myrepo`) so every agent shares it. Two old banks map onto one new one.
86
+ - The server restores a whole bank rather than merging into an existing one, so the old bank can't be folded in.
87
+
88
+ Instead, re-import the conversations the agent already wrote to disk — they get re-extracted into the current bank:
89
+
90
+ ```bash
91
+ cd /path/to/your/repo
92
+ hindsight-coding-agents install claude-code --import-conversations
93
+ ```
94
+
95
+ **How sessions are matched.** A conversation is imported only when the session itself records the
96
+ directory it ran in — never inferred from a file or folder name. Claude Code writes that directory
97
+ on its entries and Codex in its `session_meta` header, so both can be attributed exactly, including
98
+ sessions started in a subdirectory of the repo. Guessing was tempting (Claude names its history
99
+ folders after the project path) but unsafe: `/` and `.` both encode to `-`, so `repo-sub` is either
100
+ the subdirectory `repo/sub` or an unrelated sibling repo — and a wrong guess files someone else's
101
+ conversation into your bank. Sessions that record nothing are skipped and the count is reported.
102
+ The other harnesses (opencode, Kilo, Cursor, Cline, Copilot, Devin) keep history in internal SQLite
103
+ databases with unversioned schemas and are skipped with a reason.
104
+
105
+ The import is scoped to the **current repo**, safe to re-run (ingestion dedups by document id), and
106
+ runs extraction — so it costs tokens roughly in proportion to the history imported.
107
+
108
+ Prefer to keep the old bank instead? Point this package at it — no data moves:
109
+
110
+ ```jsonc
111
+ { "bankIdTemplate": "{harness}::{gitProject}" } // reproduces the old per-agent naming
112
+ ```
113
+
15
114
  ## How it works
16
115
 
17
- 1. **Seed a cold repo (automatic, once).** The first time an agent opens a repo whose bank is empty,
18
- the entry point deterministically kicks off a background **seed**: it aggregates the last N commit
19
- **messages** into a single cheap document (`gitlog` strategy) and spawns a short headless
20
- **codebase survey** — run under the current agent's own CLI (claude/codex/antigravity/opencode),
21
- read-only sandboxed — to map the structure. Both feed the knowledge pages.
22
- 1. **Deepen progressively (automatic, every session).** Every session start also fires the
23
- idempotent background **deepen engine**: it ingests any conversations not yet in the bank and the
24
- next batch of recent commits **individually with their full diffs, newest first** — so full
25
- decision-level precision arrives across sessions without a big-bang ingest. A per-bank lock and
26
- document-id dedup make concurrent or repeated runs a no-op. Ask the agent
27
- `hindsight_sync_status` to see where ingestion stands (`synced: true` = seeded memory fully
28
- queryable).
29
- 1. **Reflect once per session.** On the session's first prompt, the entry point runs Hindsight
30
- `reflect` — an agentic synthesis over the bank that returns the past decision explaining the task
31
- at hand, with its exact rule and literal values. The answer is cached for the session and
32
- re-injected on every turn, wrapped in a visible-attribution directive so the agent surfaces a
33
- `🧠 Using Hindsight Memories` header when memory informs its answer.
34
- 1. **Knowledge-page sections every turn.** The repo's knowledge pages are fetched on a cadence and
35
- matched **locally** against each prompt (a lexical section index — no server round-trip, no LLM
36
- call, ~ms): the top-scoring page sections are injected with provenance and a pointer to the full
37
- page. Fast like recall, organized like reflect; below a relevance floor nothing is injected.
38
- 1. **Knowledge pages + tools.** At session start the agent is given the repo's page roster plus a
39
- guide to the `hindsight_*` tools; it lists/reads pages to ground itself, searches raw memory for
40
- specifics (`hindsight_search_memory` is where recall lives now), and calls
41
- `hindsight_capture_initiative` right after a plan is approved to record a new feature as a tracked
42
- page. On opencode these tools are registered natively; the hook harnesses get them through the
43
- bundled **MCP server**.
44
- 1. **Write back.** The live session is upserted into the bank as a JSON transcript — user/assistant
45
- turns plus a compact `action` turn per tool call (tool name + primary target, e.g.
46
- `Edit boltons/strutils.py`; no arguments or outputs) — so sessions compound into memory without
47
- burying decisions in mechanical noise. On Stop for the hook harnesses; for the plugin harnesses
48
- (opencode, Kilo) on the turn cadence **and** again when the session goes idle. The idle pass is
49
- what captures the agent's reply: the per-turn hook fires while the host is building a request, so
50
- the transcript it sees always stops short of the answer that request produces — without the idle
51
- pass, write-back lagged a turn and a session's final exchange was never stored at all.
52
- 1. **Never break the agent — never fail silently.** A failed reflect or page fetch degrades to
53
- no-memory, but every outcome (`reflect_ok` / `reflect_empty` / `reflect_failed`, `pages_ok` /
54
- `pages_failed`, with duration and error) is appended to a diagnostics file, so a memory-less
55
- session can't masquerade as a memory session.
56
-
57
- If the configured Hindsight server predates knowledge pages, the client detects that capability at
58
- session start, skips page seeding and page lookups, and records `knowledge_pages_unavailable`.
59
- Legacy bank configuration, git/session ingestion, reflection, and retention continue normally.
60
-
61
- When memories **conflict** on the same rule, reflect prefers the latest/superseding decision — a rule
62
- amended in a later conversation wins over the original.
116
+ **Ingestion — automatic, no command to run**
117
+
118
+ - On a **cold repo**, the first session kicks off a background seed: recent commit **messages** as one cheap document, plus a short headless **codebase survey** to map the structure.
119
+ - On **every** session, a background "deepen" pass ingests conversations not yet stored and the next batch of recent commits **with full diffs, newest first** — precision arrives across sessions instead of one big ingest.
120
+ - Repeated or concurrent runs are a no-op (per-bank lock + document-id dedup).
121
+ - Ask the agent `hindsight_sync_status` to see where ingestion stands — `synced: true` means everything is queryable.
122
+
123
+ **In the session — what the agent actually receives**
124
+
125
+ - On the first prompt, a **reflect** call returns the past decision behind the task, with its exact rule and values. It's cached and re-injected each turn.
126
+ - Every turn, the repo's **knowledge pages** are matched locally against the prompt (lexical index — no server call, no LLM, ~ms) and the best sections are injected with provenance. Below a relevance floor, nothing is injected.
127
+ - The agent also gets the page roster and the `hindsight_*` tools, so it can read a page, search raw memory, or record a new initiative itself.
128
+ - Injected memory carries a visible-attribution directive, so the agent shows a `🧠 Using Hindsight Memories` header when memory shaped its answer.
129
+
130
+ **Write-back — sessions become memory**
131
+
132
+ - The live session is stored as a transcript: user/assistant turns plus a compact `action` line per tool call (name + target, no arguments or output) — decisions without the mechanical noise.
133
+ - Hook harnesses write on `Stop`. Plugin harnesses (opencode, Kilo) write on a turn cadence **and** when the session goes idle — the idle pass is what captures the agent's own reply, which the per-turn pass runs too early to see.
134
+
135
+ **Guarantees**
136
+
137
+ - A failed reflect or page fetch degrades to a no-memory turn; it never breaks the agent.
138
+ - It never fails _silently_ either: every outcome is written to a diagnostics file, so a memory-less session can't pass for a memory session.
139
+ - When two memories conflict on the same rule, the later decision wins and the superseded one is reported as no longer in effect.
140
+ - Against a Hindsight server that predates knowledge pages, page features are skipped (recorded as `knowledge_pages_unavailable`) and everything else continues.
63
141
 
64
142
  ## Harnesses
65
143
 
@@ -108,52 +186,19 @@ Its write-back retains only user-visible user/assistant text; tool arguments, to
108
186
  command output, tool-role messages, reasoning parts, and Hindsight's injected context are excluded.
109
187
  Cline IDE extensions are not currently supported by this CLI integration.
110
188
 
111
- ### Install — one command, every agent
112
-
113
- ```bash
114
- npm install -g hindsight-coding-agents
115
- hindsight-coding-agents install # detects your agents, wires each natively
116
- hindsight-coding-agents install codex # or pick specific harnesses
117
- hindsight-coding-agents uninstall # removes exactly what install added
118
- ```
119
-
120
- Install globally (not `npx`): the wiring points at this package's files, so it must live at a
121
- stable path — the installer refuses to run from an npx cache. **Updating** is just
122
- `npm update -g hindsight-coding-agents`: the wired paths stay valid, every new session runs the
123
- new version; re-run `install` (idempotent) only when a release note says the wiring changed.
124
-
125
- `install` merges the native wiring (hooks + MCP registration where the host wants them) into each
126
- agent's own config, preserving everything already there; it is idempotent (re-run after moving the
127
- package) and backs up any pre-existing file it touches as `<file>.hindsight-backup`. `uninstall`
128
- removes only our entries. On Claude Code the install also ships a **companion skill**
129
- (`~/.claude/skills/hindsight-coding-agent`) that teaches the agent how this memory works — what
130
- "store this in hindsight" should do, the tool surface, per-repo configuration, debugging — so users
131
- can ask the agent itself. Manual wiring per harness, if you prefer:
132
-
133
- **opencode** installs directly — point `opencode.json` at the package dir:
134
-
135
- ```json
136
- { "plugin": ["/path/to/hindsight-coding-agents"] }
137
- ```
138
-
139
- **Claude Code** and **Codex** get their full three-hook + MCP wiring from this package's own
140
- installer — `hindsight-coding-agents install claude-code` / `install codex`. This package's `bin`
141
- entries (`hindsight-claude-hook`, `hindsight-codex-hook`,
142
- `hindsight-cursor-hook`) are the individual injection-only `UserPromptSubmit` entrypoints for a
143
- minimal, hand-wired setup.
144
-
145
- Adding an agent: hook-based → write a `HookSpec` entry point (see `src/cursor-hook.ts`) and register
146
- a `hookAdapter` in `src/harness/registry.ts`; persistent-plugin → implement `HarnessAdapter`
147
- (`src/core/types.ts`) fully (see `src/harness/opencode.ts`).
148
-
149
189
  ## Configuration
150
190
 
151
- All configuration is **ONE JSON file, no environment variables** (exception: `HINDSIGHT_DIAG_FILE`
152
- for the diagnostics path): `~/.hindsight/coding-agent.json`. Layering, later wins per field:
191
+ Configuration is **one JSON file**: `~/.hindsight/coding-agent.json`. Layering, later wins per field:
153
192
 
154
193
  1. built-in defaults
155
- 2. the file's top level
156
- 3. its `harnesses.<name>` section — per-agent override
194
+ 2. environment variables — `HINDSIGHT_API_URL`, `HINDSIGHT_API_TOKEN`, and one per scalar setting
195
+ (`HINDSIGHT_<FIELD_IN_CAPS>`), for containers and CI that inject config rather than write a file
196
+ 3. the file's top level
197
+ 4. its `harnesses.<name>` section — per-agent override
198
+
199
+ Environment variables are a **fallback**: the file wins wherever it sets a value, so adding env to
200
+ an existing setup changes nothing. The map-valued settings (`mapPathToBank`, `harnesses`, `banks`)
201
+ are file-only — nested branching doesn't survive flattening into one variable.
157
202
 
158
203
  There is deliberately no repo-carried config file — per-repo bank routing is `mapPathToBank`,
159
204
  per-agent differences are `harnesses.<name>`.
@@ -313,22 +358,3 @@ as a JSON line to `/tmp/hindsight-plugin.log` (override with `HINDSIGHT_DIAG_FIL
313
358
  `reflect_failed` / `pages_failed` record the error; if you're comparing memory-on vs memory-off,
314
359
  check this file — a run whose reflects failed is a no-memory run. Seed starts are logged as
315
360
  `seed_started`.
316
-
317
- ## Layout
318
-
319
- ```
320
- src/
321
- core/ # harness-agnostic: config (layered), bank resolution, hindsight client, missions,
322
- # git + chat ingest, git-sync, seed + survey, pages-index (local section matching),
323
- # knowledge-injection, knowledge-tools, session-start, transcript readers,
324
- # hook runtime, RuntimeCore
325
- harness/ # per-agent adapters + registry (opencode persistent; claude/codex/antigravity/cursor/copilot as hooks)
326
- index.ts # opencode plugin entrypoint
327
- claude-hook.ts / claude-sessionstart-hook.ts / claude-stop-hook.ts # Claude Code entrypoints
328
- codex-hook.ts / codex-sessionstart-hook.ts / codex-stop-hook.ts # Codex CLI entrypoints
329
- antigravity-hook.ts / antigravity-stop-hook.ts # Antigravity CLI entrypoints
330
- cursor-hook.ts # Cursor CLI hook entrypoint (bin: hindsight-cursor-hook)
331
- copilot-*.ts # GitHub Copilot CLI SessionStart/prompt/agentStop entrypoints
332
- mcp-server.ts # hindsight_* knowledge/recall tools for the hook harnesses (MCP)
333
- backfill.ts # backfill CLI (bin: hindsight-coding-backfill)
334
- ```
@@ -154,9 +154,67 @@ function applyLayer(raw, layer, harness) {
154
154
  if (perHarness) out = mergeRaw(out, perHarness);
155
155
  return out;
156
156
  }
157
+ var ENV_KEYS = {
158
+ apiUrl: "HINDSIGHT_API_URL",
159
+ apiToken: "HINDSIGHT_API_TOKEN",
160
+ bankId: "HINDSIGHT_BANK_ID",
161
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
162
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
163
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
164
+ harness: "HINDSIGHT_HARNESS",
165
+ disabled: "HINDSIGHT_DISABLED",
166
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
167
+ retainEveryTurns: "HINDSIGHT_RETAIN_EVERY_TURNS",
168
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
169
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
170
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
171
+ autoSeed: "HINDSIGHT_AUTO_SEED",
172
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
173
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
174
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
175
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
176
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
177
+ logLevel: "HINDSIGHT_LOG_LEVEL",
178
+ gitIngest: "HINDSIGHT_GIT_INGEST"
179
+ };
180
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
181
+ "dynamicBankId",
182
+ "resolveWorktrees",
183
+ "disabled",
184
+ "retainSessions",
185
+ "autoReflect",
186
+ "autoSeed",
187
+ "codebaseSurvey"
188
+ ]);
189
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
190
+ "retainEveryTurns",
191
+ "reflectTimeoutMs",
192
+ "pageRefreshEveryTurns",
193
+ "seedLimit",
194
+ "surveyBudgetUsd",
195
+ "surveyRefreshCommits"
196
+ ]);
197
+ function readEnvConfig(env = process.env) {
198
+ const out = {};
199
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
200
+ const value = env[name];
201
+ if (value === void 0 || value.trim() === "") continue;
202
+ if (ENV_BOOLEANS.has(key)) {
203
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
204
+ } else if (ENV_NUMBERS.has(key)) {
205
+ const n = Number(value);
206
+ if (Number.isFinite(n)) out[key] = n;
207
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
208
+ } else {
209
+ out[key] = value;
210
+ }
211
+ }
212
+ return out;
213
+ }
157
214
  function loadConfig(opts = {}) {
158
215
  const o = typeof opts === "string" ? { path: opts } : opts;
159
- return resolveConfig(applyLayer({}, readRaw(o.path ?? CONFIG_PATH), o.harness));
216
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
217
+ return resolveConfig(applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness));
160
218
  }
161
219
  var BANK_OVERRIDE_EXCLUDED = [
162
220
  "bankId",
@@ -1225,10 +1283,13 @@ function readGrokTranscript(path) {
1225
1283
  }
1226
1284
 
1227
1285
  // src/core/transcript-devin.ts
1228
- import { execFileSync as execFileSync4 } from "child_process";
1286
+ import { existsSync as existsSync5 } from "fs";
1287
+ import { createRequire } from "module";
1229
1288
  import { homedir as homedir6 } from "os";
1230
1289
  import { join as join9 } from "path";
1231
- var sessionDb = join9(homedir6(), ".local", "share", "devin", "cli", "sessions.db");
1290
+ function devinSessionDb(home = homedir6()) {
1291
+ return join9(home, ".local", "share", "devin", "cli", "sessions.db");
1292
+ }
1232
1293
  function parseDevinMessages(nodes) {
1233
1294
  const messages = /* @__PURE__ */ new Map();
1234
1295
  for (const node of nodes) {
@@ -1249,23 +1310,41 @@ function parseDevinMessages(nodes) {
1249
1310
  }
1250
1311
  return [...messages.values()].sort((a, b) => a.index - b.index).map(({ role, content }) => ({ role, content }));
1251
1312
  }
1252
- function readDevinTranscript(sessionId) {
1253
- if (!sessionId) return [];
1313
+ var requireBuiltin = createRequire(import.meta.url);
1314
+ function loadSqlite() {
1254
1315
  try {
1255
- const quotedId = sessionId.replace(/'/g, "''");
1256
- const raw = execFileSync4(
1257
- "sqlite3",
1258
- [
1259
- "-json",
1260
- sessionDb,
1261
- `SELECT node_id, chat_message FROM message_nodes WHERE session_id = '${quotedId}' ORDER BY node_id`
1262
- ],
1263
- { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }
1264
- );
1265
- return parseDevinMessages(JSON.parse(raw));
1316
+ return requireBuiltin("node:sqlite").DatabaseSync;
1266
1317
  } catch {
1318
+ return void 0;
1319
+ }
1320
+ }
1321
+ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
1322
+ if (!sessionId) return [];
1323
+ const Database = loadSqlite();
1324
+ if (!Database) {
1325
+ diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
1326
+ return [];
1327
+ }
1328
+ if (!existsSync5(dbPath)) {
1329
+ diag("devin-cli", "session_db_missing", { dbPath });
1267
1330
  return [];
1268
1331
  }
1332
+ let db;
1333
+ try {
1334
+ db = new Database(dbPath, { readOnly: true });
1335
+ const rows = db.prepare(
1336
+ "SELECT node_id, chat_message FROM message_nodes WHERE session_id = ? ORDER BY node_id"
1337
+ ).all(sessionId);
1338
+ return parseDevinMessages(rows);
1339
+ } catch (error) {
1340
+ diag("devin-cli", "session_db_read_failed", { dbPath, error: String(error) });
1341
+ return [];
1342
+ } finally {
1343
+ try {
1344
+ db?.close();
1345
+ } catch {
1346
+ }
1347
+ }
1269
1348
  }
1270
1349
 
1271
1350
  // src/harness/hook-lifecycle.ts
@@ -61,9 +61,67 @@ function applyLayer(raw, layer, harness) {
61
61
  if (perHarness) out = mergeRaw(out, perHarness);
62
62
  return out;
63
63
  }
64
+ var ENV_KEYS = {
65
+ apiUrl: "HINDSIGHT_API_URL",
66
+ apiToken: "HINDSIGHT_API_TOKEN",
67
+ bankId: "HINDSIGHT_BANK_ID",
68
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
69
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
70
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
71
+ harness: "HINDSIGHT_HARNESS",
72
+ disabled: "HINDSIGHT_DISABLED",
73
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
74
+ retainEveryTurns: "HINDSIGHT_RETAIN_EVERY_TURNS",
75
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
76
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
77
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
78
+ autoSeed: "HINDSIGHT_AUTO_SEED",
79
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
80
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
81
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
82
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
83
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
84
+ logLevel: "HINDSIGHT_LOG_LEVEL",
85
+ gitIngest: "HINDSIGHT_GIT_INGEST"
86
+ };
87
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
88
+ "dynamicBankId",
89
+ "resolveWorktrees",
90
+ "disabled",
91
+ "retainSessions",
92
+ "autoReflect",
93
+ "autoSeed",
94
+ "codebaseSurvey"
95
+ ]);
96
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
97
+ "retainEveryTurns",
98
+ "reflectTimeoutMs",
99
+ "pageRefreshEveryTurns",
100
+ "seedLimit",
101
+ "surveyBudgetUsd",
102
+ "surveyRefreshCommits"
103
+ ]);
104
+ function readEnvConfig(env = process.env) {
105
+ const out = {};
106
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
107
+ const value = env[name];
108
+ if (value === void 0 || value.trim() === "") continue;
109
+ if (ENV_BOOLEANS.has(key)) {
110
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
111
+ } else if (ENV_NUMBERS.has(key)) {
112
+ const n = Number(value);
113
+ if (Number.isFinite(n)) out[key] = n;
114
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
115
+ } else {
116
+ out[key] = value;
117
+ }
118
+ }
119
+ return out;
120
+ }
64
121
  function loadConfig(opts = {}) {
65
122
  const o = typeof opts === "string" ? { path: opts } : opts;
66
- return resolveConfig(applyLayer({}, readRaw(o.path ?? CONFIG_PATH), o.harness));
123
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
124
+ return resolveConfig(applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness));
67
125
  }
68
126
  var BANK_OVERRIDE_EXCLUDED = [
69
127
  "bankId",
@@ -128,9 +128,67 @@ function applyLayer(raw, layer, harness) {
128
128
  if (perHarness) out = mergeRaw(out, perHarness);
129
129
  return out;
130
130
  }
131
+ var ENV_KEYS = {
132
+ apiUrl: "HINDSIGHT_API_URL",
133
+ apiToken: "HINDSIGHT_API_TOKEN",
134
+ bankId: "HINDSIGHT_BANK_ID",
135
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
136
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
137
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
138
+ harness: "HINDSIGHT_HARNESS",
139
+ disabled: "HINDSIGHT_DISABLED",
140
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
141
+ retainEveryTurns: "HINDSIGHT_RETAIN_EVERY_TURNS",
142
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
143
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
144
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
145
+ autoSeed: "HINDSIGHT_AUTO_SEED",
146
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
147
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
148
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
149
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
150
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
151
+ logLevel: "HINDSIGHT_LOG_LEVEL",
152
+ gitIngest: "HINDSIGHT_GIT_INGEST"
153
+ };
154
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
155
+ "dynamicBankId",
156
+ "resolveWorktrees",
157
+ "disabled",
158
+ "retainSessions",
159
+ "autoReflect",
160
+ "autoSeed",
161
+ "codebaseSurvey"
162
+ ]);
163
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
164
+ "retainEveryTurns",
165
+ "reflectTimeoutMs",
166
+ "pageRefreshEveryTurns",
167
+ "seedLimit",
168
+ "surveyBudgetUsd",
169
+ "surveyRefreshCommits"
170
+ ]);
171
+ function readEnvConfig(env = process.env) {
172
+ const out = {};
173
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
174
+ const value = env[name];
175
+ if (value === void 0 || value.trim() === "") continue;
176
+ if (ENV_BOOLEANS.has(key)) {
177
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
178
+ } else if (ENV_NUMBERS.has(key)) {
179
+ const n = Number(value);
180
+ if (Number.isFinite(n)) out[key] = n;
181
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
182
+ } else {
183
+ out[key] = value;
184
+ }
185
+ }
186
+ return out;
187
+ }
131
188
  function loadConfig(opts = {}) {
132
189
  const o = typeof opts === "string" ? { path: opts } : opts;
133
- return resolveConfig(applyLayer({}, readRaw(o.path ?? CONFIG_PATH), o.harness));
190
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
191
+ return resolveConfig(applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness));
134
192
  }
135
193
  var BANK_OVERRIDE_EXCLUDED = [
136
194
  "bankId",
@@ -1122,10 +1180,13 @@ function readGrokTranscript(path) {
1122
1180
  }
1123
1181
 
1124
1182
  // src/core/transcript-devin.ts
1125
- import { execFileSync as execFileSync4 } from "child_process";
1183
+ import { existsSync as existsSync5 } from "fs";
1184
+ import { createRequire } from "module";
1126
1185
  import { homedir as homedir6 } from "os";
1127
1186
  import { join as join9 } from "path";
1128
- var sessionDb = join9(homedir6(), ".local", "share", "devin", "cli", "sessions.db");
1187
+ function devinSessionDb(home = homedir6()) {
1188
+ return join9(home, ".local", "share", "devin", "cli", "sessions.db");
1189
+ }
1129
1190
  function parseDevinMessages(nodes) {
1130
1191
  const messages = /* @__PURE__ */ new Map();
1131
1192
  for (const node of nodes) {
@@ -1146,23 +1207,41 @@ function parseDevinMessages(nodes) {
1146
1207
  }
1147
1208
  return [...messages.values()].sort((a, b) => a.index - b.index).map(({ role, content }) => ({ role, content }));
1148
1209
  }
1149
- function readDevinTranscript(sessionId) {
1150
- if (!sessionId) return [];
1210
+ var requireBuiltin = createRequire(import.meta.url);
1211
+ function loadSqlite() {
1151
1212
  try {
1152
- const quotedId = sessionId.replace(/'/g, "''");
1153
- const raw = execFileSync4(
1154
- "sqlite3",
1155
- [
1156
- "-json",
1157
- sessionDb,
1158
- `SELECT node_id, chat_message FROM message_nodes WHERE session_id = '${quotedId}' ORDER BY node_id`
1159
- ],
1160
- { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }
1161
- );
1162
- return parseDevinMessages(JSON.parse(raw));
1213
+ return requireBuiltin("node:sqlite").DatabaseSync;
1163
1214
  } catch {
1215
+ return void 0;
1216
+ }
1217
+ }
1218
+ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
1219
+ if (!sessionId) return [];
1220
+ const Database = loadSqlite();
1221
+ if (!Database) {
1222
+ diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
1164
1223
  return [];
1165
1224
  }
1225
+ if (!existsSync5(dbPath)) {
1226
+ diag("devin-cli", "session_db_missing", { dbPath });
1227
+ return [];
1228
+ }
1229
+ let db;
1230
+ try {
1231
+ db = new Database(dbPath, { readOnly: true });
1232
+ const rows = db.prepare(
1233
+ "SELECT node_id, chat_message FROM message_nodes WHERE session_id = ? ORDER BY node_id"
1234
+ ).all(sessionId);
1235
+ return parseDevinMessages(rows);
1236
+ } catch (error) {
1237
+ diag("devin-cli", "session_db_read_failed", { dbPath, error: String(error) });
1238
+ return [];
1239
+ } finally {
1240
+ try {
1241
+ db?.close();
1242
+ } catch {
1243
+ }
1244
+ }
1166
1245
  }
1167
1246
 
1168
1247
  // src/harness/hook-lifecycle.ts