@vectorize-io/hindsight-coding-agents 0.0.1

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.
@@ -0,0 +1,1814 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/core/hook.ts
4
+ import { existsSync, readFileSync as readFileSync3 } from "fs";
5
+
6
+ // src/core/bank.ts
7
+ import { execFileSync } from "child_process";
8
+ import { homedir } from "os";
9
+ import { basename, dirname, join, normalize, sep } from "path";
10
+ var DEFAULT_BANK_NAME = "coding";
11
+ var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
12
+ var PLACEHOLDER = /\{([a-zA-Z]+)\}/g;
13
+ function getProjectRootFromGit(directory) {
14
+ if (!directory) return null;
15
+ try {
16
+ const commonDir = execFileSync(
17
+ "git",
18
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
19
+ { cwd: directory, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1e3 }
20
+ ).trim();
21
+ if (!commonDir) return null;
22
+ return basename(commonDir) === ".git" ? dirname(commonDir) : commonDir;
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+ function gitProjectName(directory, resolveWorktrees) {
28
+ if (resolveWorktrees) {
29
+ const root = getProjectRootFromGit(directory);
30
+ if (root) return basename(root);
31
+ }
32
+ return directory ? basename(directory) : "unknown";
33
+ }
34
+ function mapLookup(map, directory) {
35
+ const cwd = normalize(directory);
36
+ let best;
37
+ for (const [dir, bank] of Object.entries(map)) {
38
+ const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
39
+ const p = normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
40
+ if (cwd === p || cwd.startsWith(p + sep)) {
41
+ if (!best || p.length > best.len) best = { len: p.length, bank };
42
+ }
43
+ }
44
+ return best?.bank;
45
+ }
46
+ function deriveBankId(config, directory, harness = "coding") {
47
+ const mapped = directory && config.mapPathToBank ? mapLookup(config.mapPathToBank, directory) : void 0;
48
+ if (mapped) return mapped;
49
+ const dynamic = config.dynamicBankId ?? !config.bankId;
50
+ if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
51
+ const resolvers = {
52
+ harness: () => harness,
53
+ project: () => directory ? basename(directory) : "unknown",
54
+ gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
55
+ channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
56
+ user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
57
+ };
58
+ return (config.bankIdTemplate || DEFAULT_TEMPLATE).replace(PLACEHOLDER, (_, name) => {
59
+ const r = resolvers[name];
60
+ if (!r) {
61
+ console.error(
62
+ `hindsight: unknown bankIdTemplate placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
63
+ );
64
+ return "unknown";
65
+ }
66
+ return r();
67
+ });
68
+ }
69
+
70
+ // src/core/config.ts
71
+ import { readFileSync } from "fs";
72
+ import { homedir as homedir2 } from "os";
73
+ import { join as join3 } from "path";
74
+
75
+ // src/core/seed.ts
76
+ import { spawn as realSpawn } from "child_process";
77
+ import { dirname as dirname2, join as join2 } from "path";
78
+ import { fileURLToPath } from "url";
79
+ var DEFAULT_SEED_LIMIT = 300;
80
+ function startBackgroundSeed(repoDir, opts = {}) {
81
+ try {
82
+ const spawnFn = opts.spawn ?? realSpawn;
83
+ const enginePath = opts.enginePath ?? join2(dirname2(fileURLToPath(import.meta.url)), "deepen.js");
84
+ const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
85
+ const child = spawnFn(
86
+ "node",
87
+ [
88
+ enginePath,
89
+ "--repo",
90
+ repoDir,
91
+ "--gitlog-limit",
92
+ String(limit),
93
+ ...opts.harness ? ["--harness", opts.harness] : []
94
+ ],
95
+ {
96
+ detached: true,
97
+ stdio: "ignore"
98
+ }
99
+ );
100
+ child.on("error", () => {
101
+ });
102
+ child.unref();
103
+ } catch {
104
+ }
105
+ }
106
+
107
+ // src/core/config.ts
108
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
109
+ function resolveConfig(raw = {}) {
110
+ return {
111
+ apiUrl: raw.apiUrl ?? "https://api.hindsight.vectorize.io",
112
+ apiToken: raw.apiToken || void 0,
113
+ bankId: raw.bankId,
114
+ dynamicBankId: raw.dynamicBankId,
115
+ bankIdTemplate: raw.bankIdTemplate,
116
+ mapPathToBank: raw.mapPathToBank,
117
+ resolveWorktrees: raw.resolveWorktrees,
118
+ harness: raw.harness ?? "opencode",
119
+ disabled: raw.disabled ?? false,
120
+ retainSessions: raw.retainSessions ?? true,
121
+ // opencode: write back by default (parity with hook-harness Stop)
122
+ retainEveryTurns: raw.retainEveryTurns || 1,
123
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
124
+ autoReflect: raw.autoReflect ?? true,
125
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
126
+ autoSeed: raw.autoSeed ?? true,
127
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
128
+ codebaseSurvey: raw.codebaseSurvey ?? true,
129
+ surveyModel: raw.surveyModel || "haiku",
130
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
131
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
132
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
133
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
134
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
135
+ };
136
+ }
137
+ function readRaw(path) {
138
+ try {
139
+ return JSON.parse(readFileSync(path, "utf8"));
140
+ } catch (e) {
141
+ if (e?.code !== "ENOENT") {
142
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
143
+ }
144
+ return {};
145
+ }
146
+ }
147
+ function mergeRaw(a, b) {
148
+ const { harnesses: _drop, ...flat } = b;
149
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
150
+ }
151
+ function applyLayer(raw, layer, harness) {
152
+ let out = mergeRaw(raw, layer);
153
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
154
+ if (perHarness) out = mergeRaw(out, perHarness);
155
+ return out;
156
+ }
157
+ function loadConfig(opts = {}) {
158
+ const o = typeof opts === "string" ? { path: opts } : opts;
159
+ return resolveConfig(applyLayer({}, readRaw(o.path ?? CONFIG_PATH), o.harness));
160
+ }
161
+ var BANK_OVERRIDE_EXCLUDED = [
162
+ "bankId",
163
+ "bankIdTemplate",
164
+ "mapPathToBank",
165
+ "dynamicBankId",
166
+ "resolveWorktrees",
167
+ "harness"
168
+ ];
169
+ function applyBankConfig(cfg, resolvedId) {
170
+ const section = cfg.banks[resolvedId];
171
+ if (!section) return { cfg, bankId: resolvedId };
172
+ const safe = { ...section };
173
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
174
+ delete safe.banks;
175
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
176
+ delete safe.bank;
177
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
178
+ }
179
+ function resolvePartial(cfg, patch) {
180
+ const full = resolveConfig(patch);
181
+ const out = {};
182
+ for (const key of Object.keys(patch)) {
183
+ if (key in full)
184
+ out[key] = full[key];
185
+ }
186
+ return out;
187
+ }
188
+
189
+ // src/core/diag.ts
190
+ import { appendFileSync as appendFileSync2 } from "fs";
191
+
192
+ // src/core/log.ts
193
+ import { appendFileSync, mkdirSync } from "fs";
194
+ import { tmpdir } from "os";
195
+ import { dirname as dirname3, join as join4 } from "path";
196
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
197
+ var current = ["debug", "info", "warn", "error"].find(
198
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
199
+ ) ?? "info";
200
+ function setLogLevel(level) {
201
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
202
+ }
203
+ function logFilePath() {
204
+ return process.env.HINDSIGHT_LOG_FILE || join4(tmpdir(), "hindsight-coding-agent", "plugin.log");
205
+ }
206
+ function write(level, scope, msg, extra) {
207
+ if (WEIGHT[level] < WEIGHT[current]) return;
208
+ try {
209
+ const file = logFilePath();
210
+ mkdirSync(dirname3(file), { recursive: true });
211
+ appendFileSync(
212
+ file,
213
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
214
+ );
215
+ } catch {
216
+ }
217
+ }
218
+ var log = {
219
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
220
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
221
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
222
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
223
+ };
224
+
225
+ // src/core/diag.ts
226
+ function diag(harness, event, extra = {}) {
227
+ log.debug(harness, `diag:${event}`, extra);
228
+ try {
229
+ appendFileSync2(
230
+ process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log",
231
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
232
+ );
233
+ } catch {
234
+ }
235
+ }
236
+
237
+ // src/core/missions.ts
238
+ var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
239
+ var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
240
+ var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
241
+ var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
242
+ var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
243
+ var OBSERVATIONS_MISSION = "Consolidate durable knowledge about THIS codebase \u2014 recurring patterns, conventions, module responsibilities, and how components relate \u2014 from the ingested commits and conversations. Favor stable structural understanding over one-off details.";
244
+ var RETAIN_STRATEGIES = {
245
+ git: { retain_mission: GIT_MISSION, retain_extraction_mode: "verbose" },
246
+ // ONE big aggregated document (last N commit messages, no diffs) -> a larger chunk size so it stays
247
+ // in as few chunks as possible and the extractor sees the whole history arc at once.
248
+ gitlog: {
249
+ retain_mission: GITLOG_MISSION,
250
+ retain_extraction_mode: "verbose",
251
+ retain_chunk_size: 12e3
252
+ },
253
+ // ONE strategy for ALL developer conversations — backfilled decision chats and live working
254
+ // sessions alike (they are the same content type in the same JSON transcript format; the mission
255
+ // scales extraction to the substance, final-state-wins). Chunk big enough to hold a whole typical
256
+ // conversation in ONE chunk so the extractor sees the full proposal→revision arc (the 3000
257
+ // default SPLIT them into per-chunk fragments); very long sessions still split and fall back to
258
+ // the consolidation layer.
259
+ conversation: {
260
+ retain_mission: CONVERSATION_MISSION,
261
+ retain_extraction_mode: "verbose",
262
+ retain_chunk_size: 12e3
263
+ },
264
+ // Structural documents (e.g. the codebase survey's ingested findings) aren't dialogue — the
265
+ // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. Verbose mode
266
+ // with a bigger chunk size (documents can run long) captures the concrete facts/structure instead.
267
+ document: {
268
+ retain_mission: DOCUMENT_MISSION,
269
+ retain_extraction_mode: "verbose",
270
+ retain_chunk_size: 12e3
271
+ },
272
+ // Codebase-SURVEY lifecycle documents, ONE strategy with conditional rules: the survey's
273
+ // internal status markers ("researching…"/"completed" baselines) must yield ZERO memories,
274
+ // while any actual survey findings routed here extract as concrete structural facts.
275
+ survey: {
276
+ retain_extraction_mode: "custom",
277
+ retain_custom_instructions: "This document belongs to the Hindsight codebase-survey lifecycle. Apply ONE of two rules: (1) If the content is an internal status marker \u2014 it says it is an internal marker, or merely announces that a survey started/completed at some commit \u2014 extract NOTHING: return an empty list of facts. (2) Otherwise the content is survey FINDINGS about the codebase: extract the concrete structural facts it states (components and their responsibilities, key concepts, conventions, tech stack), preserving identifiers verbatim.",
278
+ retain_chunk_size: 12e3
279
+ }
280
+ };
281
+ var KNOWLEDGE_LABELS = {
282
+ key: "knowledge",
283
+ type: "multi-values",
284
+ // 0, 1, or several — empty is normal
285
+ optional: true,
286
+ tag: true,
287
+ // emits knowledge:<value> onto the fact's tags
288
+ description: "Routing labels for this project's Hindsight KNOWLEDGE PAGES \u2014 curated, human-readable summaries of the repo's DURABLE engineering knowledge (architecture, key decisions, conventions, ongoing initiatives), each page rebuilt automatically from the facts labeled for it. Mark a fact only when it is durable, reusable knowledge a developer would still want surfaced in future sessions. IMPORTANT: leave this EMPTY for routine, transient, or operational facts \u2014 a passing test, a one-off command, a status update, a debugging dead-end. MOST facts should get no label here. Assign more than one value only when the fact genuinely fits several.",
289
+ values: [
290
+ {
291
+ value: "feature-work",
292
+ description: "A new feature, initiative, or enhancement being planned or built \u2014 the capability being added and the intent behind it. Not routine bug-fixes or chores."
293
+ },
294
+ {
295
+ value: "decision",
296
+ description: "A technical decision that will constrain future work, with its rationale \u2014 why this approach was chosen over alternatives, or a rule deliberately adopted."
297
+ },
298
+ {
299
+ value: "convention",
300
+ description: "An established way this project does things \u2014 naming, structure, testing, error handling, or another recurring pattern a contributor is expected to follow."
301
+ },
302
+ {
303
+ value: "component",
304
+ description: "What a specific module, file, service, or subsystem is responsible for, or how components depend on and connect to one another."
305
+ },
306
+ {
307
+ value: "concept",
308
+ description: "A domain concept, key abstraction, or piece of project vocabulary a new contributor must understand to work effectively."
309
+ }
310
+ ]
311
+ };
312
+ var PAGES = [
313
+ {
314
+ name: "Component map",
315
+ source_query: "From this project's commit history and past discussions, what are the main components/modules/subsystems, what is each responsible for, and how do they relate to or depend on one another? Describe the structure and responsibilities.",
316
+ tags: ["knowledge:component"]
317
+ },
318
+ {
319
+ name: "Core concepts",
320
+ source_query: "What are the core concepts, domain abstractions, and key entities in this project \u2014 the vocabulary a developer must understand? For each, explain what it represents and its role, drawn from how they are introduced and discussed across the history and conversations.",
321
+ tags: ["knowledge:concept"]
322
+ },
323
+ {
324
+ name: "Conventions and patterns",
325
+ source_query: "What conventions, idioms, and recurring patterns does this project follow \u2014 its approach to testing, error handling, naming, structure, and how changes are typically made? Describe how THIS project does things, as evidenced across its history and discussions.",
326
+ tags: ["knowledge:convention"]
327
+ },
328
+ {
329
+ name: "Key decisions and rationale",
330
+ source_query: "What are the significant technical decisions made in this project and the rationale behind them \u2014 the durable 'why we do it this way' a developer should know? Summarize the decisions and their reasoning from the commit rationales and past conversations.",
331
+ tags: ["knowledge:decision"]
332
+ },
333
+ {
334
+ name: "Initiatives and enhancements",
335
+ source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory carries a tag of the form `relatedPageId:<id>`, include a Markdown link `[[page:<id>]]` to that page in the summary, so each initiative links to its detailed page.",
336
+ tags: ["knowledge:feature-work"]
337
+ }
338
+ ];
339
+ var PAGE_MAX_TOKENS = 4096;
340
+ var PAGE_TRIGGER = {
341
+ fact_types: ["world", "experience", "observation"],
342
+ refresh_after_consolidation: true
343
+ };
344
+ var CODING_BANK_TEMPLATE = {
345
+ version: "1",
346
+ bank: {
347
+ reflect_mission: REFLECT_MISSION,
348
+ enable_observations: true,
349
+ observations_mission: OBSERVATIONS_MISSION,
350
+ retain_mission: GIT_MISSION,
351
+ retain_extraction_mode: "verbose",
352
+ retain_default_strategy: "git",
353
+ retain_strategies: RETAIN_STRATEGIES,
354
+ entity_labels: [KNOWLEDGE_LABELS],
355
+ entities_allow_free_form: true
356
+ }
357
+ };
358
+
359
+ // src/core/util.ts
360
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
361
+
362
+ // src/core/hindsight.ts
363
+ var KnowledgePagesUnavailableError = class extends Error {
364
+ code = "knowledge_pages_unavailable";
365
+ constructor() {
366
+ super("Hindsight server does not support knowledge pages");
367
+ this.name = "KnowledgePagesUnavailableError";
368
+ }
369
+ };
370
+ var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
371
+ var HindsightClient = class {
372
+ apiUrl;
373
+ apiToken;
374
+ bank;
375
+ opIds = [];
376
+ // async operation ids collected by retain(), for drain()
377
+ /** Tri-state capability probe: unknown until the first page request, then cached. */
378
+ knowledgePagesSupported;
379
+ log;
380
+ constructor(o) {
381
+ this.apiUrl = o.apiUrl.replace(/\/$/, "");
382
+ this.apiToken = o.apiToken;
383
+ this.bank = o.bank;
384
+ this.log = o.log ?? (() => {
385
+ });
386
+ }
387
+ headers() {
388
+ const h = { "Content-Type": "application/json" };
389
+ if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
390
+ return h;
391
+ }
392
+ bankUrl(suffix = "") {
393
+ return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
394
+ }
395
+ /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
396
+ async req(method, url, body, tolerate = []) {
397
+ const r = await fetch(url, {
398
+ method,
399
+ headers: this.headers(),
400
+ body: body ? JSON.stringify(body) : void 0,
401
+ signal: AbortSignal.timeout(15e3)
402
+ });
403
+ if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
404
+ throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
405
+ return r;
406
+ }
407
+ /** Retain one memory. Async by default: enqueue extraction server-side and collect its op-id for drain(). */
408
+ async retain(content, context, documentId, tags, strategy, opts = {}) {
409
+ const item = {
410
+ content,
411
+ context,
412
+ document_id: documentId,
413
+ tags,
414
+ strategy
415
+ };
416
+ if (opts.timestamp) item.timestamp = opts.timestamp;
417
+ if (opts.metadata) item.metadata = opts.metadata;
418
+ const isAsync = opts.async !== false;
419
+ const r = await this.req("POST", this.bankUrl("/memories"), { items: [item], async: isAsync });
420
+ if (isAsync) {
421
+ try {
422
+ const j = await r.json();
423
+ if (j.operation_id) this.opIds.push(j.operation_id);
424
+ } catch {
425
+ }
426
+ }
427
+ }
428
+ /**
429
+ * Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
430
+ * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
431
+ * with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
432
+ */
433
+ async listDocumentIds(tag) {
434
+ const ids = /* @__PURE__ */ new Set();
435
+ const limit = 500;
436
+ for (let offset = 0; ; offset += limit) {
437
+ const q = `?tags=${encodeURIComponent(tag)}&tags_match=all&limit=${limit}&offset=${offset}`;
438
+ const r = await this.req("GET", this.bankUrl(`/documents${q}`));
439
+ let items = [];
440
+ let total = 0;
441
+ try {
442
+ const j = await r.json();
443
+ items = j.items || [];
444
+ total = j.total ?? 0;
445
+ } catch {
446
+ break;
447
+ }
448
+ for (const it of items) if (it.id) ids.add(it.id);
449
+ if (items.length < limit || ids.size >= total) break;
450
+ }
451
+ return ids;
452
+ }
453
+ /** Configure the bank: POST the coding bank template manifest to /import (missions, retain
454
+ * strategies, entity labels), then seed knowledge pages when the server supports them. Both
455
+ * halves are idempotent, so the deepen engine can re-run this every pass. Creates the bank if
456
+ * missing; legacy servers continue with the template-only path. */
457
+ async configureBank(opts = {}) {
458
+ if (opts.reset) {
459
+ await this.req("DELETE", this.bankUrl());
460
+ this.log(`[bank] reset ${this.bank}`);
461
+ }
462
+ await this.req("POST", this.bankUrl("/import"), CODING_BANK_TEMPLATE);
463
+ this.log(
464
+ `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
465
+ );
466
+ await this.seedPages();
467
+ }
468
+ /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
469
+ async deleteDocument(documentId) {
470
+ await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
471
+ }
472
+ /** Count of operations still ACTIVE on this bank — the list includes terminal ops (completed/
473
+ * failed/cancelled), so filter by status. Powers syncStatus's "extractions drained" check. */
474
+ async activeOperations() {
475
+ const r = await this.req("GET", this.bankUrl("/operations"));
476
+ try {
477
+ const j = await r.json();
478
+ const ops = j.operations ?? j.items ?? [];
479
+ return ops.filter((o) => !TERMINAL.has((o?.status || "").toLowerCase())).length;
480
+ } catch {
481
+ return 0;
482
+ }
483
+ }
484
+ /** Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable. */
485
+ async drain(ids, label, maxMs = 60 * 60 * 1e3) {
486
+ if (!ids.length) return;
487
+ this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
488
+ const start = Date.now();
489
+ const pending = new Set(ids);
490
+ let failed = 0;
491
+ while (pending.size && Date.now() - start < maxMs) {
492
+ await Promise.all(
493
+ [...pending].map(async (id) => {
494
+ try {
495
+ const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
496
+ if (!r.ok) return;
497
+ const st = ((await r.json()).status || "").toLowerCase();
498
+ if (TERMINAL.has(st)) {
499
+ pending.delete(id);
500
+ if (st !== "completed") failed++;
501
+ }
502
+ } catch {
503
+ }
504
+ })
505
+ );
506
+ if (pending.size) {
507
+ this.log(` \u2026 ${pending.size}/${ids.length} ${label} ops pending`);
508
+ await sleep(5e3);
509
+ }
510
+ }
511
+ this.log(
512
+ `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
513
+ );
514
+ }
515
+ /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
516
+ async reflect(query, opts = {}) {
517
+ const ctrl = new AbortController();
518
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
519
+ try {
520
+ const resp = await fetch(this.bankUrl("/reflect"), {
521
+ method: "POST",
522
+ headers: this.headers(),
523
+ body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
524
+ signal: ctrl.signal
525
+ });
526
+ if (!resp.ok) throw new Error(`reflect ${resp.status}`);
527
+ const data = await resp.json();
528
+ return (data.text || "").trim();
529
+ } finally {
530
+ clearTimeout(timer);
531
+ }
532
+ }
533
+ /**
534
+ * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
535
+ * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
536
+ */
537
+ async tree() {
538
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
539
+ const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
540
+ if ([404, 405, 501].includes(r.status)) {
541
+ this.knowledgePagesSupported = false;
542
+ throw new KnowledgePagesUnavailableError();
543
+ }
544
+ this.knowledgePagesSupported = true;
545
+ try {
546
+ return (await r.json()).roots ?? [];
547
+ } catch {
548
+ return [];
549
+ }
550
+ }
551
+ /**
552
+ * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
553
+ * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
554
+ * to read, and a caller enumerating pages wants leaves, not structure.
555
+ *
556
+ * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
557
+ * page read/update in this client goes through the same knowledge-base ids, so a page id from
558
+ * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
559
+ */
560
+ async listPages() {
561
+ const items = [];
562
+ const walk = (nodes, folder) => {
563
+ for (const n of nodes) {
564
+ if (!n?.id || !n?.name) continue;
565
+ if (n.kind === "page") {
566
+ items.push({
567
+ id: n.id,
568
+ name: n.name,
569
+ ...n.description ? { description: n.description } : {},
570
+ ...folder ? { folder } : {}
571
+ });
572
+ }
573
+ if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
574
+ }
575
+ };
576
+ walk(await this.tree());
577
+ return { items };
578
+ }
579
+ /**
580
+ * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
581
+ * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
582
+ * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
583
+ * token cap.
584
+ */
585
+ async getPage(pageId) {
586
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
587
+ const r = await this.req(
588
+ "GET",
589
+ this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
590
+ );
591
+ if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
592
+ return await r.json();
593
+ }
594
+ /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
595
+ * Returns page-level hits with a relevance snippet — the real search behind
596
+ * hindsight_search_knowledge_pages. */
597
+ async searchKnowledgePages(query, limit = 3) {
598
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
599
+ const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
600
+ const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
601
+ const j = await r.json();
602
+ return (j.results ?? []).map((x) => ({
603
+ id: x.id,
604
+ name: x.name,
605
+ snippet: x.snippet ?? "",
606
+ score: x.score ?? 0
607
+ }));
608
+ }
609
+ /**
610
+ * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
611
+ *
612
+ * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
613
+ * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
614
+ * off a slug). Names are unique per folder server-side, which makes them a sound key.
615
+ *
616
+ * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
617
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
618
+ */
619
+ async seedPages() {
620
+ const existing = /* @__PURE__ */ new Map();
621
+ let roots;
622
+ try {
623
+ roots = await this.tree();
624
+ } catch (e) {
625
+ if (e instanceof KnowledgePagesUnavailableError) {
626
+ this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
627
+ return;
628
+ }
629
+ throw e;
630
+ }
631
+ for (const n of roots) {
632
+ if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
633
+ }
634
+ let created = 0;
635
+ let updated = 0;
636
+ for (const page of PAGES) {
637
+ const hit = existing.get(page.name.toLowerCase());
638
+ const body = {
639
+ name: page.name,
640
+ source_query: page.source_query,
641
+ tags: page.tags,
642
+ max_tokens: PAGE_MAX_TOKENS,
643
+ trigger: PAGE_TRIGGER
644
+ };
645
+ if (!hit) {
646
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
647
+ if ([404, 405, 501].includes(r.status)) {
648
+ this.knowledgePagesSupported = false;
649
+ this.log(
650
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
651
+ );
652
+ return;
653
+ }
654
+ if (r.status !== 409) created++;
655
+ } else if (hit.description !== page.source_query) {
656
+ const r = await this.req(
657
+ "PATCH",
658
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
659
+ { source_query: page.source_query, tags: page.tags }
660
+ );
661
+ if ([404, 405, 501].includes(r.status)) {
662
+ this.knowledgePagesSupported = false;
663
+ this.log(
664
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
665
+ );
666
+ return;
667
+ }
668
+ updated++;
669
+ }
670
+ }
671
+ this.log(
672
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
673
+ );
674
+ }
675
+ /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
676
+ slugify(s) {
677
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
678
+ }
679
+ /**
680
+ * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
681
+ * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
682
+ * Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
683
+ */
684
+ async captureInitiative(args) {
685
+ let pageId = args.relatesToPageId;
686
+ if (!pageId) {
687
+ const folderId = await this.ensureFolder("Initiatives");
688
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
689
+ name: args.title,
690
+ source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.`,
691
+ parent_id: folderId,
692
+ tags: ["knowledge:feature-work"],
693
+ trigger: {
694
+ fact_types: ["world", "experience", "observation"],
695
+ refresh_after_consolidation: true
696
+ }
697
+ });
698
+ try {
699
+ const j = await r.json();
700
+ pageId = j.page_id ?? j.id;
701
+ } catch {
702
+ }
703
+ pageId ||= `initiative-${this.slugify(args.title)}`;
704
+ }
705
+ const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
706
+ const content = `${verb}: ${args.title}. ${args.summary}`;
707
+ const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
708
+ await this.retain(
709
+ content,
710
+ "initiative marker",
711
+ markerId,
712
+ ["knowledge:feature-work", `relatedPageId:${pageId}`],
713
+ "document",
714
+ { async: true }
715
+ );
716
+ return { page_id: pageId };
717
+ }
718
+ /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
719
+ async ensureFolder(name) {
720
+ try {
721
+ const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
722
+ const hit = (tree.roots || []).find(
723
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
724
+ );
725
+ if (hit?.id) return hit.id;
726
+ } catch {
727
+ }
728
+ try {
729
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
730
+ return (await r.json()).id;
731
+ } catch {
732
+ return void 0;
733
+ }
734
+ }
735
+ };
736
+
737
+ // src/core/brand.ts
738
+ function brandWord() {
739
+ const start = [0, 116, 217];
740
+ const end = [0, 146, 150];
741
+ const word = "Hindsight";
742
+ let out = "";
743
+ for (let i = 0; i < word.length; i++) {
744
+ const t = i / (word.length - 1);
745
+ const [r, g, b] = start.map((s, k) => Math.round(s + (end[k] - s) * t));
746
+ out += `\x1B[38;2;${r};${g};${b}m${word[i]}`;
747
+ }
748
+ return `${out}\x1B[0m`;
749
+ }
750
+
751
+ // src/core/knowledge-injection.ts
752
+ function parsePageList(raw) {
753
+ const items = raw?.items;
754
+ if (!Array.isArray(items)) return [];
755
+ const out = [];
756
+ for (const it of items) {
757
+ const id = it?.id;
758
+ const name = it?.name;
759
+ if (typeof id === "string" && typeof name === "string") out.push({ id, title: name });
760
+ }
761
+ return out;
762
+ }
763
+ function roster(pages) {
764
+ return pages.map((p) => `- ${p.title} (${p.id})`).join("\n");
765
+ }
766
+ var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP for any question the project's accumulated knowledge might answer (components, conventions, past decisions, initiatives): search the knowledge pages and credit results visibly with a markdown blockquote so it renders as a callout, exactly: "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>".
767
+ - hindsight_list_knowledge_pages / hindsight_read_knowledge_page \u2014 BEFORE substantial work, list the pages and read the relevant ones to ground yourself in this repo's architecture, conventions, and past decisions instead of re-deriving them from the code; follow any [[page:<id>]] links you see.
768
+ - hindsight_reflect(query) \u2014 when pages are too shallow and you need the WHY: deep reasoning over the repo's full memory for the past decision and exact values that explain a behavior or bug (slower \u2014 use deliberately, and credit results with a blockquote header "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>").
769
+ - hindsight_capture_initiative(title, summary) \u2014 right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing (BEFORE you write any code), call this ONCE to record it as a tracked page. Skip bug fixes, small tweaks, and chores.
770
+ - hindsight_ingest_document(title, content) \u2014 save an external document or durable notes/findings you want remembered (not the current conversation \u2014 that is captured automatically at session end).`;
771
+ var REFLECT_ON_GOALS = "- The user just set a NEW task or goal \u2192 call hindsight_reflect with that goal FIRST, before planning: no memory is injected automatically in this configuration, so this call is the only way past decisions, constraints, and failed attempts relevant to the goal reach you.\n";
772
+ function toolGuide(opts) {
773
+ return (opts?.reflectOnNewGoals ? REFLECT_ON_GOALS : "") + TOOL_GUIDE;
774
+ }
775
+ function buildKnowledgePreamble(pages, opts) {
776
+ const body = pages.length ? `Knowledge pages currently in this repository:
777
+ ${roster(pages)}` : "No knowledge pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
778
+ return `<hindsight_knowledge>
779
+ This repository has a Hindsight memory + knowledge base (curated, continuously-updated pages plus the raw memory behind them). The tools below are registered, but you must actually CALL them at the right moments:
780
+ ${toolGuide(opts)}
781
+ ALSO your correction tool: when you verify a Hindsight memory is wrong or stale, ingest a "Correction: <topic>" doc stating what memory claimed, what is true now, and the evidence \u2014 newer facts supersede older ones.
782
+ ${body}
783
+ This tool guide and the page list are re-injected for you periodically as things change.
784
+ </hindsight_knowledge>`;
785
+ }
786
+
787
+ // src/core/session-cache.ts
788
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
789
+ import { tmpdir as tmpdir2 } from "os";
790
+ import { dirname as dirname4, join as join5 } from "path";
791
+ function sessionCacheFile(harness, sessionId) {
792
+ return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.json`);
793
+ }
794
+ function writeSessionCache(cacheFile, cache) {
795
+ try {
796
+ mkdirSync2(dirname4(cacheFile), { recursive: true });
797
+ writeFileSync(cacheFile, JSON.stringify(cache));
798
+ } catch {
799
+ }
800
+ }
801
+
802
+ // src/core/retain-hook.ts
803
+ import { readFileSync as readFileSync5 } from "fs";
804
+
805
+ // src/core/transcript.ts
806
+ import { readFileSync as readFileSync4 } from "fs";
807
+
808
+ // src/core/transcript-util.ts
809
+ var MEMORY_TAG_RE = /<(hook_prompt|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
810
+ function stripInjectedMemory(s) {
811
+ return s.replace(MEMORY_TAG_RE, "");
812
+ }
813
+ var TARGET_KEYS = [
814
+ "file_path",
815
+ "path",
816
+ "notebook_path",
817
+ "command",
818
+ "pattern",
819
+ "query",
820
+ "url",
821
+ "name",
822
+ "id"
823
+ ];
824
+ var ACTION_TARGET_CAP = 100;
825
+ function actionLine(tool, input) {
826
+ let target = "";
827
+ if (input && typeof input === "object") {
828
+ const rec = input;
829
+ for (const k of TARGET_KEYS) {
830
+ const v = rec[k];
831
+ if (typeof v === "string" && v.trim()) {
832
+ target = v.trim().split("\n")[0];
833
+ break;
834
+ }
835
+ }
836
+ } else if (typeof input === "string") {
837
+ target = input.trim().split("\n")[0];
838
+ }
839
+ if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
840
+ return target ? `${tool} ${target}` : tool;
841
+ }
842
+
843
+ // src/core/session-start.ts
844
+ import { readFileSync as readFileSync7 } from "fs";
845
+
846
+ // src/core/git.ts
847
+ import { execFileSync as execFileSync2 } from "child_process";
848
+ import { resolve } from "path";
849
+ function git(repo, ...args) {
850
+ return execFileSync2("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
851
+ }
852
+ function gitHeadSha(dir) {
853
+ try {
854
+ return git(dir, "rev-parse", "HEAD").trim() || null;
855
+ } catch {
856
+ return null;
857
+ }
858
+ }
859
+ function commitsSince(dir, sinceSha) {
860
+ try {
861
+ const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
862
+ return Number.isFinite(n) ? n : null;
863
+ } catch {
864
+ return null;
865
+ }
866
+ }
867
+ function hasGitHistory(dir) {
868
+ try {
869
+ return git(dir, "rev-list", "--max-count=1", "HEAD").trim().length > 0;
870
+ } catch {
871
+ return false;
872
+ }
873
+ }
874
+
875
+ // src/core/status.ts
876
+ import { execFileSync as execFileSync3 } from "child_process";
877
+
878
+ // src/core/survey.ts
879
+ import { spawn as realSpawn2 } from "child_process";
880
+ import { accessSync, constants, existsSync as existsSync2 } from "fs";
881
+ import { homedir as homedir3 } from "os";
882
+ import { delimiter, dirname as dirname5, join as join6 } from "path";
883
+ import { fileURLToPath as fileURLToPath2 } from "url";
884
+ var SURVEY_DOC_IDS = [
885
+ "repository-component-map",
886
+ "repository-core-concepts",
887
+ "repository-conventions-and-patterns",
888
+ "repository-tech-stack-and-features"
889
+ ];
890
+ function resolveClaudeBin(explicit) {
891
+ if (explicit) return explicit;
892
+ if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
893
+ const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
894
+ try {
895
+ if (existsSync2(nativeInstallPath)) return nativeInstallPath;
896
+ } catch {
897
+ }
898
+ return "claude";
899
+ }
900
+ function resolveAgentBin(harness, claudeBin) {
901
+ switch (harness) {
902
+ case "claude-code":
903
+ return resolveClaudeBin(claudeBin);
904
+ case "codex":
905
+ return process.env.HINDSIGHT_CODEX_BIN || "codex";
906
+ case "antigravity-cli":
907
+ return process.env.HINDSIGHT_ANTIGRAVITY_BIN || "agy";
908
+ case "opencode":
909
+ return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
910
+ }
911
+ }
912
+ function binExists(bin) {
913
+ try {
914
+ if (bin.includes("/")) {
915
+ accessSync(bin, constants.X_OK);
916
+ return true;
917
+ }
918
+ for (const dir of (process.env.PATH || "").split(delimiter)) {
919
+ if (!dir) continue;
920
+ try {
921
+ accessSync(join6(dir, bin), constants.X_OK);
922
+ return true;
923
+ } catch {
924
+ }
925
+ }
926
+ return false;
927
+ } catch {
928
+ return false;
929
+ }
930
+ }
931
+ var SURVEY_PROMPT = `You are performing a one-time structural survey of THIS repository to seed its Hindsight memory. Work efficiently \u2014 DO NOT read every file; sample enough to understand the architecture: the directory layout, entry points, package manifests (package.json / pyproject.toml / Cargo.toml / go.mod), the README, and a few representative source files per major area.
932
+ IMPORTANT \u2014 DO NOT read, quote, summarize, or ingest agent-instruction files: CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*, or .github/copilot-instructions.md. These are live, user-controlled instructions (not repository knowledge); capturing them as memory would let a stale copy override the user's current instructions. Exclude them entirely from your survey and from every ingested document.
933
+ Then use the hindsight_ingest_document tool to save what you learned as separate documents (one call each), with these titles and factual, developer-oriented content grounded in what you actually saw:
934
+ - "Repository component map": the top-level modules/directories, each one's responsibility, and how they connect (data flow / dependencies).
935
+ - "Repository core concepts": the domain model and key abstractions a new contributor must understand.
936
+ - "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.
937
+ - "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.
938
+ Keep each a few hundred words. When done, stop.`;
939
+ var SURVEY_DISALLOWED_TOOLS = [
940
+ "Bash",
941
+ "Write",
942
+ "Edit",
943
+ "NotebookEdit",
944
+ "WebFetch",
945
+ "WebSearch",
946
+ "Task"
947
+ ];
948
+ function buildSurveyPlan(harness, bin, repoDir, opts) {
949
+ const env = {
950
+ ...process.env,
951
+ // Anti-recursion: the survey's own agent session must not fire our hooks (session-start,
952
+ // UserPromptSubmit/BeforeAgent, Stop/SessionEnd) or re-seed — see the HINDSIGHT_DISABLE_HOOKS
953
+ // guard in hook.ts / retain-hook.ts / session-start.ts / runtime.ts.
954
+ HINDSIGHT_DISABLE_HOOKS: "1",
955
+ // Bank scoping for the MCP server the survey agent spawns.
956
+ HINDSIGHT_MCP_PROJECT_CWD: repoDir
957
+ };
958
+ switch (harness) {
959
+ case "claude-code": {
960
+ const mcpConfig = JSON.stringify({
961
+ mcpServers: {
962
+ hindsight: {
963
+ command: "node",
964
+ args: [opts.mcpServerPath],
965
+ env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir }
966
+ }
967
+ }
968
+ });
969
+ return {
970
+ bin,
971
+ args: [
972
+ "-p",
973
+ SURVEY_PROMPT,
974
+ "--model",
975
+ opts.model ?? "haiku",
976
+ "--mcp-config",
977
+ mcpConfig,
978
+ "--strict-mcp-config",
979
+ "--allowedTools",
980
+ "Read",
981
+ "Glob",
982
+ "Grep",
983
+ "mcp__hindsight__hindsight_ingest_document",
984
+ "--disallowedTools",
985
+ ...SURVEY_DISALLOWED_TOOLS,
986
+ "--max-budget-usd",
987
+ String(opts.budgetUsd ?? 2)
988
+ ],
989
+ env
990
+ };
991
+ }
992
+ case "codex": {
993
+ return {
994
+ bin,
995
+ args: [
996
+ "exec",
997
+ "--sandbox",
998
+ "read-only",
999
+ "-c",
1000
+ `mcp_servers.hindsight.command="node"`,
1001
+ "-c",
1002
+ `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
1003
+ "-c",
1004
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
1005
+ SURVEY_PROMPT
1006
+ ],
1007
+ env
1008
+ };
1009
+ }
1010
+ case "antigravity-cli": {
1011
+ return {
1012
+ bin,
1013
+ args: ["-p", SURVEY_PROMPT, "--mode=plan"],
1014
+ env
1015
+ };
1016
+ }
1017
+ case "opencode": {
1018
+ return {
1019
+ bin,
1020
+ args: ["run", "--agent", "plan", SURVEY_PROMPT],
1021
+ env
1022
+ };
1023
+ }
1024
+ }
1025
+ }
1026
+ function startCodebaseSurvey(repoDir, opts = {}) {
1027
+ try {
1028
+ const spawnFn = opts.spawn ?? realSpawn2;
1029
+ const exists = opts.exists ?? binExists;
1030
+ const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath2(import.meta.url)), "mcp-server.js");
1031
+ const preferred = opts.harness ?? "claude-code";
1032
+ const order = [
1033
+ preferred,
1034
+ "claude-code",
1035
+ "codex",
1036
+ "antigravity-cli",
1037
+ "opencode"
1038
+ ];
1039
+ const seen = /* @__PURE__ */ new Set();
1040
+ for (const harness of order) {
1041
+ if (seen.has(harness)) continue;
1042
+ seen.add(harness);
1043
+ const bin = resolveAgentBin(harness, opts.claudeBin);
1044
+ if (!exists(bin)) continue;
1045
+ const plan = buildSurveyPlan(harness, bin, repoDir, {
1046
+ model: opts.model,
1047
+ budgetUsd: opts.budgetUsd,
1048
+ mcpServerPath
1049
+ });
1050
+ const child = spawnFn(plan.bin, plan.args, {
1051
+ cwd: repoDir,
1052
+ detached: true,
1053
+ stdio: "ignore",
1054
+ env: plan.env
1055
+ });
1056
+ child.on("error", () => {
1057
+ });
1058
+ child.unref();
1059
+ return;
1060
+ }
1061
+ } catch {
1062
+ }
1063
+ }
1064
+
1065
+ // src/core/status.ts
1066
+ var DEEPEN_DIFF_TARGET = 300;
1067
+
1068
+ // src/core/skill-sync.ts
1069
+ import { cpSync, existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
1070
+ import { homedir as homedir4 } from "os";
1071
+ import { dirname as dirname6, join as join7 } from "path";
1072
+ import { fileURLToPath as fileURLToPath3 } from "url";
1073
+ var SKILL_DIRS = {
1074
+ "claude-code": [".claude", "skills"],
1075
+ codex: [".agents", "skills"],
1076
+ // agentskills-standard shared dir
1077
+ "antigravity-cli": [".gemini", "config", "skills"],
1078
+ "cursor-cli": [".cursor", "skills"]
1079
+ };
1080
+ function packagedSkillDir() {
1081
+ return join7(dirname6(fileURLToPath3(import.meta.url)), "..", "skill");
1082
+ }
1083
+ function syncCompanionSkill(harness, opts = {}) {
1084
+ try {
1085
+ const parts = SKILL_DIRS[harness];
1086
+ if (!parts) return;
1087
+ const src = opts.srcDir ?? packagedSkillDir();
1088
+ const srcMd = join7(src, "SKILL.md");
1089
+ if (!existsSync3(srcMd)) return;
1090
+ const dst = join7(opts.home ?? homedir4(), ...parts, "hindsight-coding-agent");
1091
+ const dstMd = join7(dst, "SKILL.md");
1092
+ if (!existsSync3(dstMd)) return;
1093
+ if (readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
1094
+ cpSync(src, dst, { recursive: true });
1095
+ }
1096
+ } catch {
1097
+ }
1098
+ }
1099
+
1100
+ // src/core/session-start.ts
1101
+ function buildSeedBanner(bankId, cold = true, gitNote) {
1102
+ const headline = cold ? `${brandWord()} is learning this repo \u2014 ingesting its decisions, conventions and history` : `${brandWord()} is tracking the decisions, conventions and history of this repo`;
1103
+ const details = ` \u21B3 memory bank \u201C${bankId}\u201D` + (gitNote ? ` \xB7 ${gitNote}` : "");
1104
+ return `${headline}
1105
+ ${details}`;
1106
+ }
1107
+ async function gitSyncNote(args) {
1108
+ const { client, cwd, gitIds, mode, cold } = args;
1109
+ if (mode === "none" || cold) return void 0;
1110
+ const head = gitHeadSha(cwd);
1111
+ if (!head) return void 0;
1112
+ const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`).then((s) => s.size > 0).catch(() => void 0);
1113
+ if (gitlogCurrent === void 0) return void 0;
1114
+ if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
1115
+ const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
1116
+ let target = DEEPEN_DIFF_TARGET;
1117
+ try {
1118
+ const { execFileSync: execFileSync5 } = await import("child_process");
1119
+ const n = Number(
1120
+ execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], { encoding: "utf8" }).trim()
1121
+ );
1122
+ if (n > 0) target = Math.min(DEEPEN_DIFF_TARGET, n);
1123
+ } catch {
1124
+ }
1125
+ return gitlogCurrent && deepened >= target ? "git in sync" : `syncing git history (${Math.min(deepened, target)}/${target})`;
1126
+ }
1127
+ async function buildSessionStartContext(args) {
1128
+ const { cwd, bankId, cfg, client, stateDir } = args;
1129
+ const t0 = Date.now();
1130
+ let cold;
1131
+ let gitDocIds;
1132
+ const harness = args.harness ?? "claude-code";
1133
+ const hasGit = args.hasGit ?? hasGitHistory;
1134
+ const startSeed = args.startSeed ?? startBackgroundSeed;
1135
+ const startSurvey = args.startSurvey ?? startCodebaseSurvey;
1136
+ const resolveHeadSha = args.headSha ?? gitHeadSha;
1137
+ const countCommitsSince = args.commitsSince ?? commitsSince;
1138
+ const SURVEY_BASELINE_TAG = "source:survey-baseline";
1139
+ const SURVEY_BASELINE_PREFIX = "survey-baseline:";
1140
+ const recordSurveyBaseline = (sha) => {
1141
+ if (!client.retain) return;
1142
+ try {
1143
+ void Promise.resolve(
1144
+ client.retain(
1145
+ `\u{1F6F0}\uFE0F Hindsight is researching this codebase \u2014 survey started at commit ${sha.slice(0, 12)}. (Internal marker: no memories are extracted from this document.)`,
1146
+ "hindsight codebase-survey baseline",
1147
+ `${SURVEY_BASELINE_PREFIX}${sha}`,
1148
+ [SURVEY_BASELINE_TAG],
1149
+ "survey",
1150
+ { async: true }
1151
+ )
1152
+ ).catch(() => {
1153
+ });
1154
+ } catch {
1155
+ }
1156
+ };
1157
+ let systemMessage;
1158
+ if (cfg.autoSeed !== false) {
1159
+ if (hasGit(cwd)) {
1160
+ {
1161
+ let docIds;
1162
+ try {
1163
+ docIds = await client.listDocumentIds("source:git");
1164
+ } catch {
1165
+ docIds = void 0;
1166
+ }
1167
+ cold = docIds !== void 0 ? docIds.size === 0 : void 0;
1168
+ gitDocIds = docIds;
1169
+ if (docIds !== void 0) {
1170
+ startSeed(cwd, { limit: cfg.seedLimit });
1171
+ if (docIds.size === 0) {
1172
+ if (cfg.codebaseSurvey !== false) {
1173
+ startSurvey(cwd, {
1174
+ harness,
1175
+ model: cfg.surveyModel,
1176
+ budgetUsd: cfg.surveyBudgetUsd
1177
+ });
1178
+ const sha = resolveHeadSha(cwd);
1179
+ if (sha) recordSurveyBaseline(sha);
1180
+ }
1181
+ diag(harness, "seed_started", { bank: bankId });
1182
+ } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
1183
+ const sha = resolveHeadSha(cwd);
1184
+ if (sha) {
1185
+ const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG).catch(() => /* @__PURE__ */ new Set());
1186
+ const counts = [];
1187
+ for (const id of markers) {
1188
+ if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
1189
+ const n = countCommitsSince(cwd, id.slice(SURVEY_BASELINE_PREFIX.length));
1190
+ if (n !== null) counts.push(n);
1191
+ }
1192
+ const sinceLast = counts.length ? Math.min(...counts) : null;
1193
+ const uploads = await client.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
1194
+ const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
1195
+ if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
1196
+ startSurvey(cwd, {
1197
+ harness,
1198
+ model: cfg.surveyModel,
1199
+ budgetUsd: cfg.surveyBudgetUsd
1200
+ });
1201
+ recordSurveyBaseline(sha);
1202
+ diag(harness, "survey_refresh", {
1203
+ bank: bankId,
1204
+ commits: sinceLast,
1205
+ retry: findingsAbsent
1206
+ });
1207
+ } else if (sinceLast === null) {
1208
+ recordSurveyBaseline(sha);
1209
+ }
1210
+ }
1211
+ }
1212
+ }
1213
+ }
1214
+ }
1215
+ }
1216
+ let pages = [];
1217
+ let pageListKnown = false;
1218
+ try {
1219
+ pages = parsePageList(await client.listPages());
1220
+ pageListKnown = true;
1221
+ } catch {
1222
+ if (client.knowledgePagesSupported === false) {
1223
+ diag(harness, "knowledge_pages_unavailable", { bank: bankId });
1224
+ }
1225
+ }
1226
+ const additionalContext = buildKnowledgePreamble(pages, { reflectOnNewGoals: !cfg.autoReflect });
1227
+ const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
1228
+ let gitNote;
1229
+ if (gitDocIds) {
1230
+ gitNote = await gitSyncNote({
1231
+ client,
1232
+ cwd,
1233
+ gitIds: gitDocIds,
1234
+ mode: cfg.gitIngest,
1235
+ cold: cold === true
1236
+ }).catch(() => void 0);
1237
+ }
1238
+ systemMessage = buildSeedBanner(bankId, cold === true, gitNote);
1239
+ diag(harness, "session_start", { bank: bankId, cold, pages: pages.length, ms: Date.now() - t0 });
1240
+ return { systemMessage, additionalContext, deferInitialReflect };
1241
+ }
1242
+ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient(o)) {
1243
+ if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
1244
+ try {
1245
+ let ev = {};
1246
+ try {
1247
+ ev = JSON.parse(readFileSync7(0, "utf8"));
1248
+ } catch {
1249
+ return;
1250
+ }
1251
+ const { harness } = spec;
1252
+ const { cwd: rawCwd, sessionId } = spec.parse(ev);
1253
+ const cwd = rawCwd || process.cwd();
1254
+ let cfg = loadConfig({ harness });
1255
+ setLogLevel(cfg.logLevel);
1256
+ syncCompanionSkill(harness);
1257
+ if (cfg.disabled) return;
1258
+ const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, harness));
1259
+ cfg = resolved.cfg;
1260
+ const bankId = resolved.bankId;
1261
+ if (cfg.disabled) return;
1262
+ const client = makeClient({ apiUrl: cfg.apiUrl, apiToken: cfg.apiToken, bank: bankId });
1263
+ const out = await buildSessionStartContext({ cwd, bankId, cfg, client, harness });
1264
+ if (out.deferInitialReflect && sessionId) {
1265
+ writeSessionCache(sessionCacheFile(harness, sessionId), { deferInitialReflect: true });
1266
+ }
1267
+ const payload = spec.emit(out);
1268
+ if (out.systemMessage || out.additionalContext) {
1269
+ process.stdout.write(JSON.stringify(payload));
1270
+ }
1271
+ } catch {
1272
+ }
1273
+ }
1274
+
1275
+ // src/core/transcript-codex.ts
1276
+ import { readFileSync as readFileSync8 } from "fs";
1277
+ function isSyntheticUserText(text) {
1278
+ const s = text.trimStart();
1279
+ return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
1280
+ }
1281
+ function messageText(payload) {
1282
+ return (payload.content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
1283
+ }
1284
+ function readCodexTranscript(path) {
1285
+ let raw;
1286
+ try {
1287
+ raw = readFileSync8(path, "utf8");
1288
+ } catch {
1289
+ return [];
1290
+ }
1291
+ const turns = [];
1292
+ for (const rawLine of raw.split("\n")) {
1293
+ const trimmed = rawLine.trim();
1294
+ if (!trimmed) continue;
1295
+ let parsed;
1296
+ try {
1297
+ parsed = JSON.parse(trimmed);
1298
+ } catch {
1299
+ continue;
1300
+ }
1301
+ if (typeof parsed !== "object" || parsed === null) continue;
1302
+ const line = parsed;
1303
+ if (line.type !== "response_item") continue;
1304
+ const p = line.payload;
1305
+ if (!p || typeof p !== "object") continue;
1306
+ if (p.type === "message") {
1307
+ if (p.role !== "user" && p.role !== "assistant") continue;
1308
+ const text = stripInjectedMemory(messageText(p)).trim();
1309
+ if (!text) continue;
1310
+ if (p.role === "user" && isSyntheticUserText(text)) continue;
1311
+ turns.push({ role: p.role, content: text });
1312
+ } else if (p.type === "function_call" && typeof p.name === "string") {
1313
+ let input;
1314
+ try {
1315
+ input = JSON.parse(p.arguments || "");
1316
+ } catch {
1317
+ input = void 0;
1318
+ }
1319
+ turns.push({ role: "action", content: actionLine(p.name, input) });
1320
+ }
1321
+ }
1322
+ return turns;
1323
+ }
1324
+
1325
+ // src/core/transcript-cursor.ts
1326
+ import { readFileSync as readFileSync9 } from "fs";
1327
+ function withTimestamp(turn, timestamp) {
1328
+ return timestamp ? { ...turn, timestamp } : turn;
1329
+ }
1330
+ function textFrom(content) {
1331
+ if (typeof content === "string") return content;
1332
+ if (!Array.isArray(content)) return "";
1333
+ return content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
1334
+ }
1335
+ function readCursorTranscript(path) {
1336
+ let raw;
1337
+ try {
1338
+ raw = readFileSync9(path, "utf8");
1339
+ } catch {
1340
+ return [];
1341
+ }
1342
+ const turns = [];
1343
+ for (const rawLine of raw.split("\n")) {
1344
+ let parsed;
1345
+ try {
1346
+ parsed = JSON.parse(rawLine);
1347
+ } catch {
1348
+ continue;
1349
+ }
1350
+ if (typeof parsed !== "object" || parsed === null) continue;
1351
+ const line = parsed;
1352
+ const role = line.message?.role ?? line.role ?? (line.type === "user" || line.type === "assistant" ? line.type : void 0);
1353
+ const content = line.message?.content ?? line.content;
1354
+ if (role === "user" || role === "assistant") {
1355
+ const text = stripInjectedMemory(textFrom(content)).trim();
1356
+ if (text) turns.push(withTimestamp({ role, content: text }, line.timestamp));
1357
+ if (role === "assistant" && Array.isArray(content)) {
1358
+ for (const block of content) {
1359
+ if (block?.type === "tool_use" && typeof block.name === "string") {
1360
+ turns.push(
1361
+ withTimestamp(
1362
+ { role: "action", content: actionLine(block.name, block.input) },
1363
+ line.timestamp
1364
+ )
1365
+ );
1366
+ }
1367
+ }
1368
+ }
1369
+ } else if (line.type === "tool_call" && typeof line.name === "string") {
1370
+ turns.push(
1371
+ withTimestamp({ role: "action", content: actionLine(line.name, line.args) }, line.timestamp)
1372
+ );
1373
+ }
1374
+ }
1375
+ return turns;
1376
+ }
1377
+
1378
+ // src/core/transcript-antigravity.ts
1379
+ import { readFileSync as readFileSync10 } from "fs";
1380
+ function readAntigravityTranscript(path) {
1381
+ if (!path) return [];
1382
+ let raw;
1383
+ try {
1384
+ raw = readFileSync10(path, "utf8");
1385
+ } catch {
1386
+ return [];
1387
+ }
1388
+ const turns = [];
1389
+ for (const line of raw.split("\n")) {
1390
+ try {
1391
+ const event = JSON.parse(line);
1392
+ const role = event.role ?? event.message?.role ?? event.type;
1393
+ const normalizedRole = role === "user" || role === "USER_INPUT" ? "user" : role === "assistant" || role === "model" || role === "PLANNER_RESPONSE" ? "assistant" : void 0;
1394
+ const content = event.content ?? event.text ?? event.message?.content ?? event.message?.text;
1395
+ const clean = typeof content === "string" ? stripInjectedMemory(content).trim() : "";
1396
+ if (normalizedRole && clean) {
1397
+ turns.push({
1398
+ role: normalizedRole,
1399
+ content: clean,
1400
+ ...event.timestamp ? { timestamp: event.timestamp } : {}
1401
+ });
1402
+ }
1403
+ } catch {
1404
+ }
1405
+ }
1406
+ return turns;
1407
+ }
1408
+
1409
+ // src/core/transcript-copilot.ts
1410
+ import { readFileSync as readFileSync11 } from "fs";
1411
+ function readCopilotTranscript(path) {
1412
+ let raw;
1413
+ try {
1414
+ raw = readFileSync11(path, "utf8");
1415
+ } catch {
1416
+ return [];
1417
+ }
1418
+ const turns = [];
1419
+ for (const rawLine of raw.split("\n")) {
1420
+ try {
1421
+ const event = JSON.parse(rawLine);
1422
+ const role = event.type === "user.message" ? "user" : event.type === "assistant.message" ? "assistant" : void 0;
1423
+ const content = typeof event.data?.content === "string" ? stripInjectedMemory(event.data.content).trim() : "";
1424
+ if (!role || !content) continue;
1425
+ turns.push({ role, content, ...event.timestamp ? { timestamp: event.timestamp } : {} });
1426
+ } catch {
1427
+ }
1428
+ }
1429
+ return turns;
1430
+ }
1431
+
1432
+ // src/core/transcript-grok.ts
1433
+ import { existsSync as existsSync4, readFileSync as readFileSync12, readdirSync } from "fs";
1434
+ import { homedir as homedir5 } from "os";
1435
+ import { join as join8 } from "path";
1436
+ var CHAT_HISTORY = "chat_history.jsonl";
1437
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join8(homedir5(), ".grok")) {
1438
+ const sessionsDir = join8(grokHome, "sessions");
1439
+ const direct = join8(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1440
+ if (existsSync4(direct)) return direct;
1441
+ try {
1442
+ for (const candidate of readdirSync(sessionsDir)) {
1443
+ const directory = join8(sessionsDir, candidate);
1444
+ if (readFileSync12(join8(directory, ".cwd"), "utf8").trim() === cwd) {
1445
+ return join8(directory, sessionId, CHAT_HISTORY);
1446
+ }
1447
+ }
1448
+ } catch {
1449
+ }
1450
+ return direct;
1451
+ }
1452
+ function readGrokTranscript(path) {
1453
+ let raw;
1454
+ try {
1455
+ raw = readFileSync12(path, "utf8");
1456
+ } catch {
1457
+ return [];
1458
+ }
1459
+ const turns = [];
1460
+ for (const rawLine of raw.split("\n")) {
1461
+ try {
1462
+ const event = JSON.parse(rawLine);
1463
+ if (event.type !== "user" && event.type !== "assistant") continue;
1464
+ if (event.type === "user" && typeof event.prompt_index !== "number") continue;
1465
+ const content = typeof event.content === "string" ? event.content : Array.isArray(event.content) ? event.content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n") : "";
1466
+ const clean = stripInjectedMemory(content).trim();
1467
+ if (clean) turns.push({ role: event.type, content: clean });
1468
+ for (const toolCall of event.tool_calls ?? []) {
1469
+ if (!toolCall.name) continue;
1470
+ let input = toolCall.arguments;
1471
+ if (typeof input === "string") {
1472
+ try {
1473
+ input = JSON.parse(input);
1474
+ } catch {
1475
+ }
1476
+ }
1477
+ turns.push({ role: "action", content: actionLine(toolCall.name, input) });
1478
+ }
1479
+ } catch {
1480
+ }
1481
+ }
1482
+ return turns;
1483
+ }
1484
+
1485
+ // src/core/transcript-devin.ts
1486
+ import { execFileSync as execFileSync4 } from "child_process";
1487
+ import { homedir as homedir6 } from "os";
1488
+ import { join as join9 } from "path";
1489
+ var sessionDb = join9(homedir6(), ".local", "share", "devin", "cli", "sessions.db");
1490
+ function parseDevinMessages(nodes) {
1491
+ const messages = /* @__PURE__ */ new Map();
1492
+ for (const node of nodes) {
1493
+ try {
1494
+ const message = JSON.parse(node.chat_message);
1495
+ if (message.role !== "user" && message.role !== "assistant" || !message.content?.trim())
1496
+ continue;
1497
+ const content = stripInjectedMemory(message.content).trim();
1498
+ if (!content) continue;
1499
+ const id = message.message_id || `node:${node.node_id}`;
1500
+ messages.set(id, {
1501
+ index: messages.get(id)?.index ?? node.node_id,
1502
+ role: message.role,
1503
+ content
1504
+ });
1505
+ } catch {
1506
+ }
1507
+ }
1508
+ return [...messages.values()].sort((a, b) => a.index - b.index).map(({ role, content }) => ({ role, content }));
1509
+ }
1510
+ function readDevinTranscript(sessionId) {
1511
+ if (!sessionId) return [];
1512
+ try {
1513
+ const quotedId = sessionId.replace(/'/g, "''");
1514
+ const raw = execFileSync4(
1515
+ "sqlite3",
1516
+ [
1517
+ "-json",
1518
+ sessionDb,
1519
+ `SELECT node_id, chat_message FROM message_nodes WHERE session_id = '${quotedId}' ORDER BY node_id`
1520
+ ],
1521
+ { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2e3 }
1522
+ );
1523
+ return parseDevinMessages(JSON.parse(raw));
1524
+ } catch {
1525
+ return [];
1526
+ }
1527
+ }
1528
+
1529
+ // src/harness/hook-lifecycle.ts
1530
+ var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
1531
+ var claudePrompt = {
1532
+ harness: "claude-code",
1533
+ parse: (ev) => ({
1534
+ prompt: ev.prompt,
1535
+ cwd: ev.cwd,
1536
+ sessionId: ev.session_id
1537
+ }),
1538
+ emit: (context, notice) => ({
1539
+ ...notice ? { systemMessage: notice } : {},
1540
+ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
1541
+ })
1542
+ };
1543
+ var codexPrompt = {
1544
+ ...claudePrompt,
1545
+ harness: "codex",
1546
+ parse: (ev) => ({
1547
+ prompt: ev.prompt ?? ev.user_prompt,
1548
+ cwd: ev.cwd,
1549
+ sessionId: ev.session_id
1550
+ })
1551
+ };
1552
+ var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
1553
+ var antigravityPrompt = {
1554
+ harness: "antigravity-cli",
1555
+ requireCwd: true,
1556
+ parse: (ev) => ({
1557
+ // Antigravity's PreInvocation payload deliberately omits the prompt. Its transcript is already
1558
+ // persisted at that point, so recover the latest real user turn from the supplied JSONL path.
1559
+ prompt: readAntigravityTranscript(ev.transcriptPath).filter((turn) => turn.role === "user").at(-1)?.content,
1560
+ cwd: antigravityCwd(ev),
1561
+ sessionId: ev.conversationId
1562
+ }),
1563
+ emit: (context) => ({ injectSteps: context ? [{ ephemeralMessage: context }] : [] })
1564
+ };
1565
+ var cursorPrompt = {
1566
+ harness: "cursor-cli",
1567
+ parse: (ev) => ({
1568
+ prompt: ev.prompt ?? ev.user_prompt,
1569
+ cwd: cursorCwd(ev),
1570
+ sessionId: ev.conversation_id ?? ev.session_id
1571
+ }),
1572
+ emit: (context) => ({ continue: true, additional_context: context })
1573
+ };
1574
+ var copilotPrompt = {
1575
+ harness: "copilot-cli",
1576
+ parse: (ev) => ({
1577
+ prompt: ev.prompt,
1578
+ cwd: ev.cwd,
1579
+ sessionId: ev.sessionId
1580
+ }),
1581
+ emit: (context, _notice, ev) => ({
1582
+ // Copilot's userPromptTransformed hook replaces model-facing content rather than appending
1583
+ // hook context. Preserve its transformed prompt and add the shared Hindsight injection.
1584
+ modifiedTransformedPrompt: `${ev?.transformedPrompt ?? ""}
1585
+
1586
+ ${context}`.trim()
1587
+ })
1588
+ };
1589
+ var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
1590
+ var devinPrompt = {
1591
+ harness: "devin-cli",
1592
+ requireCwd: true,
1593
+ parse: (ev) => ({
1594
+ prompt: ev.prompt,
1595
+ cwd: devinCwd(),
1596
+ sessionId: ev.session_id
1597
+ }),
1598
+ emit: (context) => ({
1599
+ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
1600
+ })
1601
+ };
1602
+ var standardSessionStart = (harness) => ({
1603
+ harness,
1604
+ parse: (ev) => ({
1605
+ cwd: ev.cwd,
1606
+ sessionId: ev.session_id
1607
+ }),
1608
+ emit: (out) => ({
1609
+ ...out.systemMessage ? { systemMessage: out.systemMessage } : {},
1610
+ hookSpecificOutput: {
1611
+ hookEventName: "SessionStart",
1612
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
1613
+ }
1614
+ })
1615
+ });
1616
+ var HOOK_HARNESSES = {
1617
+ "claude-code": {
1618
+ configStyle: "nested",
1619
+ install: {
1620
+ sessionStart: { event: "SessionStart", entry: "claude-sessionstart-hook.js", timeout: 30 },
1621
+ prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
1622
+ stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
1623
+ },
1624
+ sessionStart: standardSessionStart("claude-code"),
1625
+ prompt: claudePrompt,
1626
+ retain: {
1627
+ harness: "claude-code",
1628
+ parse: (ev) => ({
1629
+ sessionId: ev.session_id,
1630
+ transcriptPath: ev.transcript_path,
1631
+ cwd: ev.cwd
1632
+ })
1633
+ }
1634
+ },
1635
+ codex: {
1636
+ configStyle: "nested",
1637
+ install: {
1638
+ sessionStart: { event: "SessionStart", entry: "codex-sessionstart-hook.js", timeout: 30 },
1639
+ prompt: { event: "UserPromptSubmit", entry: "codex-hook.js", timeout: 30 },
1640
+ stop: { event: "Stop", entry: "codex-stop-hook.js", timeout: 60 }
1641
+ },
1642
+ sessionStart: standardSessionStart("codex"),
1643
+ prompt: codexPrompt,
1644
+ retain: {
1645
+ harness: "codex",
1646
+ parse: (ev) => ({
1647
+ sessionId: ev.session_id,
1648
+ transcriptPath: ev.transcript_path,
1649
+ cwd: ev.cwd
1650
+ }),
1651
+ readTranscript: readCodexTranscript
1652
+ }
1653
+ },
1654
+ "antigravity-cli": {
1655
+ configStyle: "flat",
1656
+ install: {
1657
+ // PreInvocation is Antigravity's only lifecycle point that can inject context. Its first
1658
+ // invocation also performs the SessionStart responsibilities through runHook's seed guard.
1659
+ sessionStart: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
1660
+ prompt: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
1661
+ stop: { event: "Stop", entry: "antigravity-stop-hook.js", timeout: 30 }
1662
+ },
1663
+ sessionStart: {
1664
+ harness: "antigravity-cli",
1665
+ parse: (ev) => ({
1666
+ cwd: antigravityCwd(ev),
1667
+ sessionId: ev.conversationId
1668
+ }),
1669
+ emit: () => ({})
1670
+ },
1671
+ prompt: antigravityPrompt,
1672
+ retain: {
1673
+ harness: "antigravity-cli",
1674
+ parse: (ev) => ({
1675
+ sessionId: ev.conversationId,
1676
+ transcriptPath: ev.transcriptPath,
1677
+ cwd: antigravityCwd(ev)
1678
+ }),
1679
+ readTranscript: readAntigravityTranscript
1680
+ }
1681
+ },
1682
+ "cursor-cli": {
1683
+ configStyle: "flat",
1684
+ install: {
1685
+ sessionStart: { event: "sessionStart", entry: "cursor-sessionstart-hook.js", timeout: 30 },
1686
+ prompt: { event: "beforeSubmitPrompt", entry: "cursor-hook.js" },
1687
+ stop: { event: "stop", entry: "cursor-stop-hook.js", timeout: 30 }
1688
+ },
1689
+ sessionStart: {
1690
+ harness: "cursor-cli",
1691
+ parse: (ev) => ({
1692
+ cwd: cursorCwd(ev),
1693
+ sessionId: ev.conversation_id ?? ev.session_id
1694
+ }),
1695
+ emit: (out) => ({
1696
+ ...out.additionalContext ? { additional_context: out.additionalContext } : {}
1697
+ })
1698
+ },
1699
+ prompt: cursorPrompt,
1700
+ retain: {
1701
+ harness: "cursor-cli",
1702
+ parse: (ev) => ({
1703
+ sessionId: ev.conversation_id ?? ev.session_id,
1704
+ transcriptPath: ev.transcript_path,
1705
+ cwd: cursorCwd(ev)
1706
+ }),
1707
+ readTranscript: readCursorTranscript
1708
+ }
1709
+ },
1710
+ "copilot-cli": {
1711
+ configStyle: "flat",
1712
+ install: {
1713
+ sessionStart: { event: "sessionStart", entry: "copilot-sessionstart-hook.js", timeout: 30 },
1714
+ prompt: { event: "userPromptTransformed", entry: "copilot-hook.js", timeout: 30 },
1715
+ stop: { event: "agentStop", entry: "copilot-stop-hook.js", timeout: 60 }
1716
+ },
1717
+ sessionStart: {
1718
+ harness: "copilot-cli",
1719
+ parse: (ev) => ({
1720
+ cwd: ev.cwd,
1721
+ sessionId: ev.sessionId
1722
+ }),
1723
+ // Copilot CLI's SessionStart response only has model-facing `additionalContext`; unlike
1724
+ // Claude/Cursor it has no supported in-TUI system-message/banner channel. Keep memory
1725
+ // quiet rather than auto-submitting a synthetic prompt or showing an OS notification. When
1726
+ // Copilot exposes a real TUI extension point, add the banner there without changing this
1727
+ // shared lifecycle output.
1728
+ emit: (out) => ({
1729
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
1730
+ })
1731
+ },
1732
+ prompt: copilotPrompt,
1733
+ retain: {
1734
+ harness: "copilot-cli",
1735
+ parse: (ev) => ({
1736
+ sessionId: ev.sessionId,
1737
+ transcriptPath: ev.transcriptPath,
1738
+ cwd: ev.cwd
1739
+ }),
1740
+ readTranscript: readCopilotTranscript
1741
+ }
1742
+ },
1743
+ "devin-cli": {
1744
+ configStyle: "nested",
1745
+ install: {
1746
+ sessionStart: { event: "SessionStart", entry: "devin-sessionstart-hook.js", timeout: 30 },
1747
+ prompt: { event: "UserPromptSubmit", entry: "devin-hook.js", timeout: 30 },
1748
+ stop: { event: "Stop", entry: "devin-stop-hook.js", timeout: 60 }
1749
+ },
1750
+ sessionStart: {
1751
+ harness: "devin-cli",
1752
+ parse: (ev) => ({ cwd: devinCwd(), sessionId: ev.session_id }),
1753
+ emit: (out) => ({
1754
+ hookSpecificOutput: {
1755
+ hookEventName: "SessionStart",
1756
+ ...out.additionalContext ? { additionalContext: out.additionalContext } : {}
1757
+ }
1758
+ })
1759
+ },
1760
+ prompt: devinPrompt,
1761
+ retain: {
1762
+ harness: "devin-cli",
1763
+ parse: (ev) => {
1764
+ const sessionId = ev.session_id;
1765
+ return {
1766
+ sessionId,
1767
+ // RetainHook calls the supplied reader with transcriptPath; Devin's reader uses its
1768
+ // session id because the CLI persists conversations in sessions.db rather than a file.
1769
+ transcriptPath: sessionId,
1770
+ cwd: devinCwd()
1771
+ };
1772
+ },
1773
+ readTranscript: readDevinTranscript
1774
+ }
1775
+ },
1776
+ "grok-build": {
1777
+ configStyle: "nested",
1778
+ install: {
1779
+ sessionStart: { event: "SessionStart", entry: "grok-sessionstart-hook.js", timeout: 30 },
1780
+ prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
1781
+ stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
1782
+ },
1783
+ sessionStart: {
1784
+ ...standardSessionStart("grok-build"),
1785
+ // Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
1786
+ parse: (ev) => ({
1787
+ cwd: ev.cwd,
1788
+ sessionId: ev.sessionId
1789
+ })
1790
+ },
1791
+ prompt: {
1792
+ ...claudePrompt,
1793
+ harness: "grok-build",
1794
+ parse: (ev) => ({
1795
+ prompt: ev.prompt,
1796
+ cwd: ev.cwd,
1797
+ sessionId: ev.sessionId
1798
+ })
1799
+ },
1800
+ retain: {
1801
+ harness: "grok-build",
1802
+ parse: (ev) => ({
1803
+ sessionId: ev.sessionId,
1804
+ transcriptPath: typeof ev.cwd === "string" && typeof ev.sessionId === "string" ? grokTranscriptPath(ev.cwd, ev.sessionId) : void 0,
1805
+ cwd: ev.cwd
1806
+ }),
1807
+ readTranscript: readGrokTranscript
1808
+ }
1809
+ }
1810
+ };
1811
+ var runHarnessSessionStart = (harness) => runSessionStartHook(HOOK_HARNESSES[harness].sessionStart);
1812
+
1813
+ // src/devin-sessionstart-hook.ts
1814
+ void runHarnessSessionStart("devin-cli");