@vectorize-io/hindsight-coding-agents 0.4.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +202 -52
  2. package/dist/antigravity-hook.js +637 -199
  3. package/dist/antigravity-statusline.js +219 -84
  4. package/dist/antigravity-stop-hook.js +654 -205
  5. package/dist/claude-hook.js +637 -199
  6. package/dist/claude-sessionstart-hook.js +863 -236
  7. package/dist/claude-stop-hook.js +654 -205
  8. package/dist/cline.js +589 -234
  9. package/dist/codex-hook.js +637 -199
  10. package/dist/codex-sessionstart-hook.js +863 -236
  11. package/dist/codex-stop-hook.js +654 -205
  12. package/dist/copilot-hook.js +637 -199
  13. package/dist/copilot-sessionstart-hook.js +863 -236
  14. package/dist/copilot-stop-hook.js +654 -205
  15. package/dist/cursor-hook.js +637 -199
  16. package/dist/cursor-sessionstart-hook.js +863 -236
  17. package/dist/cursor-stop-hook.js +654 -205
  18. package/dist/daemon-start.js +62 -43
  19. package/dist/dcode-hook.js +2577 -0
  20. package/dist/dcode-sessionstart-hook.js +3194 -0
  21. package/dist/dcode-stop-hook.js +2807 -0
  22. package/dist/deepen.js +361 -204
  23. package/dist/devin-hook.js +637 -199
  24. package/dist/devin-sessionstart-hook.js +863 -236
  25. package/dist/devin-stop-hook.js +654 -205
  26. package/dist/dsh.js +592 -235
  27. package/dist/grok-hook.js +637 -199
  28. package/dist/grok-sessionstart-hook.js +863 -236
  29. package/dist/grok-stop-hook.js +654 -205
  30. package/dist/hindsight-seed.js +222 -83
  31. package/dist/index.js +589 -234
  32. package/dist/installer.js +2331 -299
  33. package/dist/kilo.js +589 -234
  34. package/dist/mcp-server.js +363 -169
  35. package/dist/opencode2.js +30092 -0
  36. package/dist/pi.js +17650 -0
  37. package/dist/prime-agent.js +625 -260
  38. package/dist/qwen-hook.js +2577 -0
  39. package/dist/qwen-sessionstart-hook.js +3194 -0
  40. package/dist/qwen-stop-hook.js +2807 -0
  41. package/dist/status.js +300 -136
  42. package/hooks/hooks.json +37 -0
  43. package/index.js +10 -0
  44. package/package.json +15 -8
  45. package/plugin.json +16 -0
  46. package/skill/SKILL.md +114 -43
@@ -1,74 +1,217 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/core/hook.ts
4
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
4
+ import { existsSync as existsSync2, readFileSync as readFileSync4 } from "fs";
5
5
 
6
6
  // src/core/bank.ts
7
- import { execFileSync } from "child_process";
8
7
  import { existsSync } from "fs";
9
8
  import { homedir } from "os";
10
- import { basename, dirname, join, normalize, sep } from "path";
9
+ import { basename, dirname as dirname3, join as join3, normalize, sep } from "path";
10
+
11
+ // src/core/diag.ts
12
+ import { appendFileSync as appendFileSync2 } from "fs";
13
+
14
+ // src/core/log.ts
15
+ import { appendFileSync, mkdirSync } from "fs";
16
+ import { tmpdir } from "os";
17
+ import { dirname, join } from "path";
18
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
19
+ var current = ["debug", "info", "warn", "error"].find(
20
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
21
+ ) ?? "info";
22
+ function setLogLevel(level) {
23
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
24
+ }
25
+ function logFilePath() {
26
+ return process.env.HINDSIGHT_LOG_FILE || join(tmpdir(), "hindsight-coding-agent", "plugin.log");
27
+ }
28
+ function write(level, scope, msg, extra) {
29
+ if (WEIGHT[level] < WEIGHT[current]) return;
30
+ try {
31
+ const file = logFilePath();
32
+ mkdirSync(dirname(file), { recursive: true });
33
+ appendFileSync(
34
+ file,
35
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
36
+ );
37
+ } catch {
38
+ }
39
+ }
40
+ var log = {
41
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
42
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
43
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
44
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
45
+ };
46
+ function describeError(value, maxChars = 200) {
47
+ const parts = [];
48
+ const seen = /* @__PURE__ */ new Set();
49
+ let current2 = value;
50
+ while (current2 && !seen.has(current2)) {
51
+ seen.add(current2);
52
+ const error = current2;
53
+ const text = typeof error.message === "string" ? error.message : String(current2);
54
+ const withCode = error.code ? `${text} (${String(error.code)})` : text;
55
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
56
+ current2 = error.cause;
57
+ }
58
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
59
+ }
60
+
61
+ // src/core/diag.ts
62
+ function diagFilePath() {
63
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
64
+ }
65
+ function diag(harness, event, extra = {}) {
66
+ log.debug(harness, `diag:${event}`, extra);
67
+ try {
68
+ appendFileSync2(
69
+ diagFilePath(),
70
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
71
+ );
72
+ } catch {
73
+ }
74
+ }
75
+
76
+ // src/core/git-layout.ts
77
+ import { lstatSync, readFileSync, realpathSync } from "fs";
78
+ import { dirname as dirname2, isAbsolute, join as join2, resolve } from "path";
79
+ var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
80
+ var ATTEMPTS = 3;
81
+ var BACKOFF_MS = 20;
82
+ function errorCode(error) {
83
+ return error?.code ?? "";
84
+ }
85
+ function sleepSync(ms) {
86
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
87
+ }
88
+ var TransientProbeError = class extends Error {
89
+ };
90
+ function entryKind(path) {
91
+ try {
92
+ const st = lstatSync(path);
93
+ return st.isDirectory() ? "dir" : "file";
94
+ } catch (error) {
95
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
96
+ return "none";
97
+ }
98
+ }
99
+ function readTextOrNull(path) {
100
+ try {
101
+ return readFileSync(path, "utf8");
102
+ } catch (error) {
103
+ if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
104
+ return null;
105
+ }
106
+ }
107
+ function gitDirFromPointer(text, holder) {
108
+ const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
109
+ if (!match) return null;
110
+ const target = match[1];
111
+ return isAbsolute(target) ? target : resolve(holder, target);
112
+ }
113
+ function commonDirOf(gitDir) {
114
+ const pointer = entryKind(join2(gitDir, "commondir")) === "file" ? readTextOrNull(join2(gitDir, "commondir"))?.trim() : null;
115
+ if (!pointer) return gitDir;
116
+ return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
117
+ }
118
+ function isBare(commonDir) {
119
+ const config = readTextOrNull(join2(commonDir, "config"));
120
+ return config !== null && /^\s*bare\s*=\s*true\s*$/im.test(config);
121
+ }
122
+ function looksLikeBareRepository(directory) {
123
+ return entryKind(join2(directory, "HEAD")) === "file" && entryKind(join2(directory, "objects")) === "dir" && entryKind(join2(directory, "refs")) === "dir";
124
+ }
125
+ function canonical(path) {
126
+ try {
127
+ return realpathSync(path);
128
+ } catch {
129
+ return path;
130
+ }
131
+ }
132
+ function resolved(commonDir) {
133
+ if (entryKind(commonDir) !== "dir") return null;
134
+ const canonicalDir = canonical(commonDir);
135
+ return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
136
+ }
137
+ function probeOnce(directory) {
138
+ let current2 = resolve(directory);
139
+ for (; ; ) {
140
+ const dotGit = join2(current2, ".git");
141
+ const kind = entryKind(dotGit);
142
+ if (kind === "dir") {
143
+ const layout = resolved(commonDirOf(dotGit));
144
+ if (layout) return layout;
145
+ } else if (kind === "file") {
146
+ const text = readTextOrNull(dotGit);
147
+ const gitDir = text ? gitDirFromPointer(text, current2) : null;
148
+ const layout = gitDir ? resolved(commonDirOf(gitDir)) : null;
149
+ if (layout) return layout;
150
+ }
151
+ if (looksLikeBareRepository(current2)) {
152
+ const layout = resolved(current2);
153
+ if (layout) return layout;
154
+ }
155
+ const parent = dirname2(current2);
156
+ if (parent === current2) return { status: "absent" };
157
+ current2 = parent;
158
+ }
159
+ }
160
+ function probeGitLayout(directory) {
161
+ if (!directory) return { status: "absent" };
162
+ let last = "";
163
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
164
+ if (attempt) sleepSync(BACKOFF_MS * attempt);
165
+ try {
166
+ return probeOnce(directory);
167
+ } catch (error) {
168
+ last = error instanceof TransientProbeError ? error.message : errorCode(error) || "unknown";
169
+ }
170
+ }
171
+ return { status: "failed", reason: last };
172
+ }
11
173
 
12
174
  // src/core/template.ts
13
175
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
14
176
  function applyTemplate(template, resolvers, what) {
15
177
  return template.replace(PLACEHOLDER, (_, name) => {
16
- const resolve2 = resolvers[name];
17
- if (!resolve2) {
178
+ const resolve3 = resolvers[name];
179
+ if (!resolve3) {
18
180
  console.error(
19
181
  `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
20
182
  );
21
183
  return "unknown";
22
184
  }
23
- return resolve2();
185
+ return resolve3();
24
186
  });
25
187
  }
26
188
 
27
189
  // src/core/bank.ts
28
190
  var DEFAULT_BANK_NAME = "coding";
29
191
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
30
- function getProjectRootFromGit(directory) {
31
- if (!directory) return null;
32
- try {
33
- const commonDir = execFileSync(
34
- "git",
35
- ["rev-parse", "--path-format=absolute", "--git-common-dir"],
36
- {
37
- cwd: directory,
38
- encoding: "utf-8",
39
- stdio: ["ignore", "pipe", "ignore"],
40
- timeout: 1e3,
41
- windowsHide: true
42
- }
43
- ).trim();
44
- if (!commonDir) return null;
45
- if (basename(commonDir) === ".git") return dirname(commonDir);
46
- if (basename(commonDir).startsWith(".") && isBareRepository(commonDir)) {
47
- return dirname(commonDir);
48
- }
49
- return commonDir;
50
- } catch {
51
- return null;
192
+ var BankResolutionError = class extends Error {
193
+ constructor(message) {
194
+ super(message);
195
+ this.name = "BankResolutionError";
52
196
  }
53
- }
54
- function isBareRepository(commonDir) {
55
- try {
56
- return execFileSync("git", ["-C", commonDir, "rev-parse", "--is-bare-repository"], {
57
- encoding: "utf-8",
58
- stdio: ["ignore", "pipe", "ignore"],
59
- timeout: 1e3,
60
- env: { ...process.env, GIT_DIR: void 0, GIT_WORK_TREE: void 0 }
61
- }).trim() === "true";
62
- } catch {
63
- return false;
197
+ };
198
+ function resolveProjectRoot(directory) {
199
+ if (!directory) return { status: "absent" };
200
+ const layout = probeGitLayout(directory);
201
+ if (layout.status !== "resolved") return layout;
202
+ const commonDir = layout.commonDir;
203
+ if (basename(commonDir) === ".git") return { status: "resolved", root: dirname3(commonDir) };
204
+ if (basename(commonDir).startsWith(".") && layout.bare) {
205
+ return { status: "resolved", root: dirname3(commonDir) };
64
206
  }
207
+ return { status: "resolved", root: commonDir };
65
208
  }
66
209
  var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
67
210
  function nearestExistingDir(directory) {
68
211
  let current2 = directory;
69
212
  while (current2) {
70
213
  if (existsSync(current2)) return current2;
71
- const parent = dirname(current2);
214
+ const parent = dirname3(current2);
72
215
  if (parent === current2) return "";
73
216
  current2 = parent;
74
217
  }
@@ -83,21 +226,29 @@ function mainWorktreeRoot(directory, sessionRoot = "") {
83
226
  sessionRoot,
84
227
  ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
85
228
  ];
229
+ let failure = null;
86
230
  for (const candidate of candidates) {
87
- const root = candidate ? getProjectRootFromGit(candidate) : null;
88
- if (root) return root;
231
+ if (!candidate) continue;
232
+ const projectRoot = resolveProjectRoot(candidate);
233
+ if (projectRoot.status === "resolved") return projectRoot;
234
+ if (projectRoot.status === "failed") failure = projectRoot;
89
235
  }
90
- return null;
236
+ return failure ?? { status: "absent" };
91
237
  }
92
238
  function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
93
239
  if (resolveWorktrees) {
94
- const root = mainWorktreeRoot(directory, sessionRoot);
95
- if (root) return basename(root);
240
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
241
+ if (projectRoot.status === "resolved") return basename(projectRoot.root);
242
+ if (projectRoot.status === "failed") {
243
+ throw new BankResolutionError(
244
+ `git probe failed for ${directory} (${projectRoot.reason}) \u2014 refusing to guess a bank id`
245
+ );
246
+ }
96
247
  }
97
248
  return dirName(sessionRoot || directory);
98
249
  }
99
250
  function configuredDir(dir) {
100
- const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
251
+ const expanded = dir === "~" || dir.startsWith("~/") ? join3(homedir(), dir.slice(1)) : dir;
101
252
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
102
253
  }
103
254
  function isWithin(directory, configured) {
@@ -117,8 +268,8 @@ function mapLookup(map, directory) {
117
268
  function lookupDirectories(config, directory, sessionRoot = "") {
118
269
  const directories = [normalize(directory)];
119
270
  if (config.resolveWorktrees ?? true) {
120
- const root = mainWorktreeRoot(directory, sessionRoot);
121
- const normalizedRoot = root ? normalize(root) : "";
271
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
272
+ const normalizedRoot = projectRoot.status === "resolved" ? normalize(projectRoot.root) : "";
122
273
  if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
123
274
  }
124
275
  return directories;
@@ -151,21 +302,34 @@ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
151
302
  };
152
303
  return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
153
304
  }
305
+ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot) {
306
+ try {
307
+ return deriveBankId(config, directory, harness, sessionRoot);
308
+ } catch (error) {
309
+ if (!(error instanceof BankResolutionError)) throw error;
310
+ log.warn(harness, "bank unresolved: skipping (repository could not be identified)", {
311
+ directory,
312
+ error: error.message
313
+ });
314
+ diag(harness, "bank_unresolved", { directory, error: error.message });
315
+ return null;
316
+ }
317
+ }
154
318
 
155
319
  // src/core/config.ts
156
- import { readFileSync } from "fs";
320
+ import { readFileSync as readFileSync2 } from "fs";
157
321
  import { homedir as homedir2 } from "os";
158
- import { join as join4 } from "path";
322
+ import { join as join6 } from "path";
159
323
 
160
324
  // src/core/seed.ts
161
325
  import { spawn as realSpawn } from "child_process";
162
- import { dirname as dirname2, join as join2 } from "path";
326
+ import { dirname as dirname4, join as join4 } from "path";
163
327
  import { fileURLToPath } from "url";
164
328
  var DEFAULT_SEED_LIMIT = 300;
165
329
  function startBackgroundSeed(repoDir, opts = {}) {
166
330
  try {
167
331
  const spawnFn = opts.spawn ?? realSpawn;
168
- const enginePath = opts.enginePath ?? join2(dirname2(fileURLToPath(import.meta.url)), "deepen.js");
332
+ const enginePath = opts.enginePath ?? join4(dirname4(fileURLToPath(import.meta.url)), "deepen.js");
169
333
  const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
170
334
  const child = spawnFn(
171
335
  "node",
@@ -190,53 +354,6 @@ function startBackgroundSeed(repoDir, opts = {}) {
190
354
  }
191
355
  }
192
356
 
193
- // src/core/log.ts
194
- import { appendFileSync, mkdirSync } from "fs";
195
- import { tmpdir } from "os";
196
- import { dirname as dirname3, join as join3 } from "path";
197
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
198
- var current = ["debug", "info", "warn", "error"].find(
199
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
200
- ) ?? "info";
201
- function setLogLevel(level) {
202
- if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
203
- }
204
- function logFilePath() {
205
- return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
206
- }
207
- function write(level, scope, msg, extra) {
208
- if (WEIGHT[level] < WEIGHT[current]) return;
209
- try {
210
- const file = logFilePath();
211
- mkdirSync(dirname3(file), { recursive: true });
212
- appendFileSync(
213
- file,
214
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
215
- );
216
- } catch {
217
- }
218
- }
219
- var log = {
220
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
221
- info: (scope, msg, extra) => write("info", scope, msg, extra),
222
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
223
- error: (scope, msg, extra) => write("error", scope, msg, extra)
224
- };
225
- function describeError(value, maxChars = 200) {
226
- const parts = [];
227
- const seen = /* @__PURE__ */ new Set();
228
- let current2 = value;
229
- while (current2 && !seen.has(current2)) {
230
- seen.add(current2);
231
- const error = current2;
232
- const text = typeof error.message === "string" ? error.message : String(current2);
233
- const withCode = error.code ? `${text} (${String(error.code)})` : text;
234
- if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
235
- current2 = error.cause;
236
- }
237
- return (parts.join(": ") || String(value)).slice(0, maxChars);
238
- }
239
-
240
357
  // src/core/missions.ts
241
358
  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.";
242
359
  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.";
@@ -374,15 +491,41 @@ var CODING_BANK_TEMPLATE = {
374
491
  entities_allow_free_form: true
375
492
  }
376
493
  };
377
- var CODING_BANK_STRUCTURE = {
378
- version: "1",
379
- bank: {
380
- retain_strategies: RETAIN_STRATEGIES,
381
- entity_labels: [KNOWLEDGE_LABELS]
382
- }
383
- };
494
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
495
+ function isSet(v) {
496
+ if (v === null || v === void 0) return false;
497
+ if (typeof v === "string") return v.trim() !== "";
498
+ return true;
499
+ }
500
+ function codingBankManifest(overrides) {
501
+ const current2 = overrides ?? {};
502
+ const template = CODING_BANK_TEMPLATE.bank;
503
+ const bank = {};
504
+ if (!MISSION_FIELDS.some((f) => isSet(current2[f]))) {
505
+ bank.reflect_mission = template.reflect_mission;
506
+ bank.enable_observations = template.enable_observations;
507
+ bank.observations_mission = template.observations_mission;
508
+ bank.retain_mission = template.retain_mission;
509
+ bank.retain_extraction_mode = template.retain_extraction_mode;
510
+ }
511
+ if (!isSet(current2.retain_default_strategy))
512
+ bank.retain_default_strategy = template.retain_default_strategy;
513
+ if (!isSet(current2.entities_allow_free_form))
514
+ bank.entities_allow_free_form = template.entities_allow_free_form;
515
+ const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
516
+ const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
517
+ if (missing.length > 0)
518
+ bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
519
+ const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
520
+ const [knowledgeGroup] = template.entity_labels;
521
+ if (!labels.some((g) => g?.key === knowledgeGroup.key))
522
+ bank.entity_labels = [...labels, knowledgeGroup];
523
+ return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
524
+ }
384
525
 
385
526
  // src/core/util.ts
527
+ import { accessSync, constants } from "fs";
528
+ import { delimiter, join as join5 } from "path";
386
529
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
387
530
  function semverGte(version, min) {
388
531
  const parts = (v) => {
@@ -414,6 +557,11 @@ async function pool(items, n, fn, onError, onProgress) {
414
557
  }
415
558
 
416
559
  // src/core/hindsight.ts
560
+ function resolveRetainScopes(tags, configured) {
561
+ if (configured !== "per_source") return configured;
562
+ const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
563
+ return [[], ...sources.map((s) => [s])];
564
+ }
417
565
  var DEFAULT_OBSERVATION_SCOPES = "shared";
418
566
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
419
567
  var RateLimitedError = class extends Error {
@@ -444,7 +592,6 @@ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
444
592
  var POLL_CYCLE_MS = 5e3;
445
593
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
446
594
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
447
- var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
448
595
  var HindsightClient = class {
449
596
  apiUrl;
450
597
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -550,7 +697,7 @@ var HindsightClient = class {
550
697
  // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
551
698
  // observations were built under is a property of the write rather than of whichever server
552
699
  // version happened to process it. Servers older than 0.4.15 ignore the field.
553
- observation_scopes: this.observationScopes
700
+ observation_scopes: resolveRetainScopes(tags, this.observationScopes)
554
701
  };
555
702
  if (opts.timestamp) item.timestamp = opts.timestamp;
556
703
  if (opts.metadata) item.metadata = opts.metadata;
@@ -591,11 +738,11 @@ var HindsightClient = class {
591
738
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
592
739
  * with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
593
740
  */
594
- async listDocumentIds(tag) {
741
+ async listDocumentIds(tag, tagsMatch = "all") {
595
742
  const ids = /* @__PURE__ */ new Set();
596
743
  const limit = 500;
597
744
  for (let offset = 0; ; offset += limit) {
598
- const q = `?tags=${encodeURIComponent(tag)}&tags_match=all&limit=${limit}&offset=${offset}`;
745
+ const q = `?tags=${encodeURIComponent(tag)}&tags_match=${tagsMatch}&limit=${limit}&offset=${offset}`;
599
746
  const r = await this.req("GET", this.bankUrl(`/documents${q}`));
600
747
  let items = [];
601
748
  let total = 0;
@@ -611,49 +758,54 @@ var HindsightClient = class {
611
758
  }
612
759
  return ids;
613
760
  }
614
- /** Configure the bank: POST the coding bank template manifest to /import (missions, retain
615
- * strategies, entity labels), then seed knowledge pages when the server supports them. Both
616
- * halves are idempotent, so the deepen engine can re-run this every pass. Creates the bank if
617
- * missing; legacy servers continue with the template-only path. */
761
+ /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
762
+ * entity labels), then seed knowledge pages when the server supports them. Both halves are
763
+ * idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
764
+ * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
765
+ * continue with the template-only path.
766
+ *
767
+ * `manage: false` skips the config half entirely, for a bank whose owner shapes it themselves.
768
+ * That bank should then define the strategies this plugin writes under (`git`, `gitlog`,
769
+ * `conversation`, `document`, `survey`): an unknown strategy name is not an error server-side,
770
+ * it just falls back to the bank's own config, so the miss is silent. */
618
771
  async configureBank(opts = {}) {
619
772
  if (opts.reset) {
620
773
  await this.req("DELETE", this.bankUrl());
621
774
  this.log(`[bank] reset ${this.bank}`);
622
775
  }
623
- const seeded = opts.reset ? false : await this.hasBankMissions();
624
- await this.req(
625
- "POST",
626
- this.bankUrl("/import"),
627
- seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
628
- );
629
- this.log(
630
- seeded ? `[bank] structure applied to ${this.bank}: entity_labels {knowledge}, strategies {git, gitlog, conversation, document} \u2014 missions left as configured` : `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
631
- );
776
+ if (opts.manage === false) {
777
+ this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
778
+ } else {
779
+ const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
780
+ if (!manifest) {
781
+ this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
782
+ } else {
783
+ await this.req("POST", this.bankUrl("/import"), manifest);
784
+ this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
785
+ }
786
+ }
632
787
  await this.seedPages(opts.pageTrigger);
633
788
  }
634
789
  /**
635
- * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
636
- * the user's own edit. Either way they are not ours to overwrite.
790
+ * This bank's own config OVERRIDES, or undefined when there are none to read.
637
791
  *
638
- * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
639
- * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
640
- * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
641
- * missions in the first place.
792
+ * Deliberately the overrides and not the resolved config: an inherited global default is not
793
+ * something this bank's owner chose, so it must not read as "already set". `undefined` means the
794
+ * bank does not exist yet, or the deployment has the bank-config API switched off — in neither
795
+ * case can anything have been customised, so the caller seeds the full template.
642
796
  */
643
- async hasBankMissions() {
797
+ async readBankOverrides() {
644
798
  try {
645
799
  const r = await this.req("GET", this.bankUrl("/config"));
646
- if (!r.ok) return false;
800
+ if (!r.ok) return void 0;
647
801
  const j = await r.json();
648
- return MISSION_FIELDS.some((f) => {
649
- const v = j.overrides?.[f];
650
- return typeof v === "string" && v.trim() !== "";
651
- });
802
+ return j.overrides ?? {};
652
803
  } catch {
653
- return false;
804
+ return void 0;
654
805
  }
655
806
  }
656
- /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
807
+ /** Explicitly delete one document (and its cascaded memory units/links). Background sync must
808
+ * never use this as a cleanup primitive: a document id alone does not prove repository ownership. */
657
809
  async deleteDocument(documentId) {
658
810
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
659
811
  }
@@ -954,7 +1106,7 @@ var HindsightClient = class {
954
1106
  };
955
1107
 
956
1108
  // src/core/config.ts
957
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
1109
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
958
1110
  var DEFAULT_DAEMON_PORT = 9077;
959
1111
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
960
1112
  function resolvePageTriggerType(raw) {
@@ -978,7 +1130,13 @@ function resolveReflectBudget(raw) {
978
1130
  log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
979
1131
  return "high";
980
1132
  }
981
- var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
1133
+ var OBSERVATION_SCOPE_MODES = [
1134
+ "shared",
1135
+ "combined",
1136
+ "per_tag",
1137
+ "all_combinations",
1138
+ "per_source"
1139
+ ];
982
1140
  function resolveObservationScopes(raw) {
983
1141
  const value = raw;
984
1142
  if (typeof value === "string")
@@ -1016,6 +1174,7 @@ function resolveConfig(raw = {}) {
1016
1174
  disabled: raw.disabled ?? false,
1017
1175
  retainSessions: raw.retainSessions ?? true,
1018
1176
  // write sessions back by default, every harness
1177
+ manageBankConfig: raw.manageBankConfig ?? true,
1019
1178
  maxParallelRetains: raw.maxParallelRetains || 10,
1020
1179
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
1021
1180
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
@@ -1042,12 +1201,13 @@ function resolveConfig(raw = {}) {
1042
1201
  ) : {},
1043
1202
  observationScopes: resolveObservationScopes(raw.observationScopes),
1044
1203
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
1045
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
1204
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
1205
+ autoUpdate: raw.autoUpdate ?? true
1046
1206
  };
1047
1207
  }
1048
1208
  function readRaw(path) {
1049
1209
  try {
1050
- return JSON.parse(readFileSync(path, "utf8"));
1210
+ return JSON.parse(readFileSync2(path, "utf8"));
1051
1211
  } catch (e) {
1052
1212
  if (e?.code !== "ENOENT") {
1053
1213
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -1100,13 +1260,15 @@ var ENV_KEYS = {
1100
1260
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
1101
1261
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
1102
1262
  logLevel: "HINDSIGHT_LOG_LEVEL",
1263
+ autoUpdate: "HINDSIGHT_AUTO_UPDATE",
1103
1264
  gitIngest: "HINDSIGHT_GIT_INGEST",
1104
1265
  // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
1105
1266
  // list is a list OF lists, which does not survive flattening into one variable — file-only.
1106
1267
  observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
1107
1268
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
1108
1269
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
1109
- retainTags: "HINDSIGHT_RETAIN_TAGS"
1270
+ retainTags: "HINDSIGHT_RETAIN_TAGS",
1271
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
1110
1272
  };
1111
1273
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1112
1274
  "dynamicBankId",
@@ -1116,7 +1278,9 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
1116
1278
  "retainSessions",
1117
1279
  "autoReflect",
1118
1280
  "autoSeed",
1119
- "codebaseSurvey"
1281
+ "codebaseSurvey",
1282
+ "autoUpdate",
1283
+ "manageBankConfig"
1120
1284
  ]);
1121
1285
  var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
1122
1286
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
@@ -1191,22 +1355,6 @@ function resolvePartial(cfg, patch) {
1191
1355
  return out;
1192
1356
  }
1193
1357
 
1194
- // src/core/diag.ts
1195
- import { appendFileSync as appendFileSync2 } from "fs";
1196
- function diagFilePath() {
1197
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
1198
- }
1199
- function diag(harness, event, extra = {}) {
1200
- log.debug(harness, `diag:${event}`, extra);
1201
- try {
1202
- appendFileSync2(
1203
- diagFilePath(),
1204
- JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
1205
- );
1206
- } catch {
1207
- }
1208
- }
1209
-
1210
1358
  // src/core/brand.ts
1211
1359
  function brandWord() {
1212
1360
  const start = [0, 116, 217];
@@ -1284,21 +1432,21 @@ ${toolGuide(opts)}
1284
1432
  }
1285
1433
 
1286
1434
  // src/core/session-cache.ts
1287
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "fs";
1435
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync } from "fs";
1288
1436
  import { tmpdir as tmpdir2 } from "os";
1289
- import { dirname as dirname4, join as join5 } from "path";
1437
+ import { dirname as dirname5, join as join7 } from "path";
1290
1438
  function sessionCacheFile(harness, sessionId) {
1291
- return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.json`);
1439
+ return join7(tmpdir2(), `hindsight-${harness}`, `${sessionId}.json`);
1292
1440
  }
1293
1441
  function readSessionCache(cacheFile) {
1294
1442
  try {
1295
- return JSON.parse(readFileSync2(cacheFile, "utf8"));
1443
+ return JSON.parse(readFileSync3(cacheFile, "utf8"));
1296
1444
  } catch {
1297
1445
  return {};
1298
1446
  }
1299
1447
  }
1300
1448
  function writeFileAtomic(path, body) {
1301
- mkdirSync2(dirname4(path), { recursive: true });
1449
+ mkdirSync2(dirname5(path), { recursive: true });
1302
1450
  const tmp = `${path}.${process.pid}.tmp`;
1303
1451
  try {
1304
1452
  writeFileSync(tmp, body);
@@ -1318,13 +1466,13 @@ function writeSessionCache(cacheFile, cache) {
1318
1466
  }
1319
1467
  }
1320
1468
  function sessionRootFile(harness, sessionId) {
1321
- return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
1469
+ return join7(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
1322
1470
  }
1323
1471
  function sessionRootDir(harness, sessionId, cwd) {
1324
1472
  if (!sessionId || !cwd) return cwd;
1325
1473
  const file = sessionRootFile(harness, sessionId);
1326
1474
  try {
1327
- const recorded = readFileSync2(file, "utf8").trim();
1475
+ const recorded = readFileSync3(file, "utf8").trim();
1328
1476
  if (recorded) return recorded;
1329
1477
  } catch {
1330
1478
  }
@@ -1425,7 +1573,7 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1425
1573
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
1426
1574
  let ev = {};
1427
1575
  try {
1428
- ev = JSON.parse(readFileSync3(0, "utf8"));
1576
+ ev = JSON.parse(readFileSync4(0, "utf8"));
1429
1577
  } catch {
1430
1578
  return;
1431
1579
  }
@@ -1442,9 +1590,11 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1442
1590
  }
1443
1591
  const out = (context, notice) => process.stdout.write(JSON.stringify(spec.emit(context ?? "", notice, ev)));
1444
1592
  const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
1445
- const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness, sessionRoot), cwd);
1446
- cfg = resolved.cfg;
1447
- const bankId = resolved.bankId;
1593
+ const derived = deriveBankIdOrSkip(cfg, cwd, spec.harness, sessionRoot);
1594
+ if (derived === null) return;
1595
+ const resolved2 = applyBankConfig(cfg, derived, cwd);
1596
+ cfg = resolved2.cfg;
1597
+ const bankId = resolved2.bankId;
1448
1598
  if (cfg.disabled) {
1449
1599
  log.debug(spec.harness, "hook skipped: bank disabled via banks override", { bank: bankId });
1450
1600
  return;
@@ -1468,7 +1618,7 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1468
1618
  }
1469
1619
 
1470
1620
  // src/core/retain-hook.ts
1471
- import { readFileSync as readFileSync4 } from "fs";
1621
+ import { readFileSync as readFileSync5 } from "fs";
1472
1622
 
1473
1623
  // src/core/retain-cursor.ts
1474
1624
  import { createHash } from "crypto";
@@ -1477,8 +1627,8 @@ import { createHash } from "crypto";
1477
1627
  import { createHash as createHash2 } from "crypto";
1478
1628
 
1479
1629
  // src/core/daemon.ts
1480
- import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
1481
- import { dirname as dirname5, join as join6 } from "path";
1630
+ import { execFileSync, spawn as realSpawn2 } from "child_process";
1631
+ import { dirname as dirname6, join as join8 } from "path";
1482
1632
  import { fileURLToPath as fileURLToPath2 } from "url";
1483
1633
 
1484
1634
  // src/core/retain-stamp.ts
@@ -1581,27 +1731,43 @@ function actionLine(tool, input) {
1581
1731
  }
1582
1732
 
1583
1733
  // src/core/session-start.ts
1584
- import { readFileSync as readFileSync6 } from "fs";
1734
+ import { readFileSync as readFileSync8 } from "fs";
1585
1735
 
1586
1736
  // src/core/git.ts
1587
- import { execFileSync as execFileSync3 } from "child_process";
1588
- import { resolve } from "path";
1737
+ import { execFileSync as execFileSync2 } from "child_process";
1738
+ import { resolve as resolve2 } from "path";
1589
1739
 
1590
1740
  // src/core/status.ts
1591
- import { execFileSync as execFileSync4 } from "child_process";
1741
+ import { execFileSync as execFileSync3 } from "child_process";
1592
1742
 
1593
1743
  // src/core/survey.ts
1594
1744
  import { spawn as realSpawn3 } from "child_process";
1595
- import { accessSync, constants, existsSync as existsSync3 } from "fs";
1745
+ import { existsSync as existsSync3 } from "fs";
1596
1746
  import { homedir as homedir3 } from "os";
1597
- import { delimiter, dirname as dirname6, join as join7 } from "path";
1747
+ import { dirname as dirname7, join as join9 } from "path";
1598
1748
  import { fileURLToPath as fileURLToPath3 } from "url";
1599
1749
 
1600
- // src/core/skill-sync.ts
1601
- import { cpSync, existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
1602
- import { homedir as homedir4 } from "os";
1603
- import { dirname as dirname7, join as join8 } from "path";
1750
+ // src/core/auto-update.ts
1751
+ import { spawn as realSpawn4 } from "child_process";
1752
+ import {
1753
+ existsSync as existsSync4,
1754
+ mkdirSync as mkdirSync3,
1755
+ readFileSync as readFileSync6,
1756
+ realpathSync as realpathSync2,
1757
+ unlinkSync,
1758
+ writeFileSync as writeFileSync2
1759
+ } from "fs";
1760
+ import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
1761
+ import { dirname as dirname8, join as join10 } from "path";
1604
1762
  import { fileURLToPath as fileURLToPath4 } from "url";
1763
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
1764
+ var LOCK_STALE_MS = 10 * 60 * 1e3;
1765
+
1766
+ // src/core/skill-sync.ts
1767
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
1768
+ import { homedir as homedir5 } from "os";
1769
+ import { dirname as dirname9, join as join11 } from "path";
1770
+ import { fileURLToPath as fileURLToPath5 } from "url";
1605
1771
 
1606
1772
  // src/core/transcript-codex.ts
1607
1773
  function isSyntheticUserText(text) {
@@ -1733,19 +1899,19 @@ function readCopilotTranscript(path) {
1733
1899
  }
1734
1900
 
1735
1901
  // src/core/transcript-grok.ts
1736
- import { existsSync as existsSync5, readFileSync as readFileSync7, readdirSync } from "fs";
1737
- import { homedir as homedir5 } from "os";
1738
- import { join as join9 } from "path";
1902
+ import { existsSync as existsSync6, readFileSync as readFileSync9, readdirSync } from "fs";
1903
+ import { homedir as homedir6 } from "os";
1904
+ import { join as join12 } from "path";
1739
1905
  var CHAT_HISTORY = "chat_history.jsonl";
1740
- function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join9(homedir5(), ".grok")) {
1741
- const sessionsDir = join9(grokHome, "sessions");
1742
- const direct = join9(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1743
- if (existsSync5(direct)) return direct;
1906
+ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join12(homedir6(), ".grok")) {
1907
+ const sessionsDir = join12(grokHome, "sessions");
1908
+ const direct = join12(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
1909
+ if (existsSync6(direct)) return direct;
1744
1910
  try {
1745
1911
  for (const candidate of readdirSync(sessionsDir)) {
1746
- const directory = join9(sessionsDir, candidate);
1747
- if (readFileSync7(join9(directory, ".cwd"), "utf8").trim() === cwd) {
1748
- return join9(directory, sessionId, CHAT_HISTORY);
1912
+ const directory = join12(sessionsDir, candidate);
1913
+ if (readFileSync9(join12(directory, ".cwd"), "utf8").trim() === cwd) {
1914
+ return join12(directory, sessionId, CHAT_HISTORY);
1749
1915
  }
1750
1916
  }
1751
1917
  } catch {
@@ -1780,12 +1946,12 @@ function readGrokTranscript(path) {
1780
1946
  }
1781
1947
 
1782
1948
  // src/core/transcript-devin.ts
1783
- import { existsSync as existsSync6 } from "fs";
1949
+ import { existsSync as existsSync7 } from "fs";
1784
1950
  import { createRequire } from "module";
1785
- import { homedir as homedir6 } from "os";
1786
- import { join as join10 } from "path";
1787
- function devinSessionDb(home = homedir6()) {
1788
- return join10(home, ".local", "share", "devin", "cli", "sessions.db");
1951
+ import { homedir as homedir7 } from "os";
1952
+ import { join as join13 } from "path";
1953
+ function devinSessionDb(home = homedir7()) {
1954
+ return join13(home, ".local", "share", "devin", "cli", "sessions.db");
1789
1955
  }
1790
1956
  function parseDevinMessages(nodes) {
1791
1957
  const messages = /* @__PURE__ */ new Map();
@@ -1822,7 +1988,7 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
1822
1988
  diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
1823
1989
  return [];
1824
1990
  }
1825
- if (!existsSync6(dbPath)) {
1991
+ if (!existsSync7(dbPath)) {
1826
1992
  diag("devin-cli", "session_db_missing", { dbPath });
1827
1993
  return [];
1828
1994
  }
@@ -1844,6 +2010,212 @@ function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
1844
2010
  }
1845
2011
  }
1846
2012
 
2013
+ // src/core/transcript-dcode.ts
2014
+ var BLOCK_JOIN = "\n";
2015
+ function contentText(content) {
2016
+ if (typeof content === "string") return content;
2017
+ if (!Array.isArray(content)) return "";
2018
+ return content.flatMap((block) => {
2019
+ if (typeof block === "string") return [block];
2020
+ if (!block || typeof block !== "object") return [];
2021
+ const text = block.text;
2022
+ return typeof text === "string" ? [text] : [];
2023
+ }).join(BLOCK_JOIN);
2024
+ }
2025
+ function readPyValue(s, i) {
2026
+ const skip = (j) => {
2027
+ while (j < s.length && /\s/.test(s[j])) j++;
2028
+ return j;
2029
+ };
2030
+ i = skip(i);
2031
+ if (i >= s.length) return null;
2032
+ const c = s[i];
2033
+ if (c === "'" || c === '"') {
2034
+ let out = "";
2035
+ let j = i + 1;
2036
+ while (j < s.length) {
2037
+ const ch = s[j];
2038
+ if (ch === "\\") {
2039
+ const esc = s[j + 1];
2040
+ if (esc === void 0) return null;
2041
+ if (esc === "n") out += "\n";
2042
+ else if (esc === "t") out += " ";
2043
+ else if (esc === "r") out += "\r";
2044
+ else if (esc === "x") {
2045
+ const hex = s.slice(j + 2, j + 4);
2046
+ if (!/^[0-9a-fA-F]{2}$/.test(hex)) return null;
2047
+ out += String.fromCharCode(parseInt(hex, 16));
2048
+ j += 4;
2049
+ continue;
2050
+ } else if (esc === "u") {
2051
+ const hex = s.slice(j + 2, j + 6);
2052
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null;
2053
+ out += String.fromCharCode(parseInt(hex, 16));
2054
+ j += 6;
2055
+ continue;
2056
+ } else out += esc;
2057
+ j += 2;
2058
+ continue;
2059
+ }
2060
+ if (ch === c) return { value: out, end: j + 1 };
2061
+ out += ch;
2062
+ j++;
2063
+ }
2064
+ return null;
2065
+ }
2066
+ if (s.startsWith("True", i)) return { value: true, end: i + 4 };
2067
+ if (s.startsWith("False", i)) return { value: false, end: i + 5 };
2068
+ if (s.startsWith("None", i)) return { value: null, end: i + 4 };
2069
+ if (c === "[" || c === "{") {
2070
+ const isList = c === "[";
2071
+ const close = isList ? "]" : "}";
2072
+ const list = [];
2073
+ const obj = {};
2074
+ let j = skip(i + 1);
2075
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
2076
+ for (; ; ) {
2077
+ const key = readPyValue(s, j);
2078
+ if (!key) return null;
2079
+ j = skip(key.end);
2080
+ if (isList) {
2081
+ list.push(key.value);
2082
+ } else {
2083
+ if (s[j] !== ":" || typeof key.value !== "string") return null;
2084
+ const val = readPyValue(s, j + 1);
2085
+ if (!val) return null;
2086
+ obj[key.value] = val.value;
2087
+ j = skip(val.end);
2088
+ }
2089
+ if (s[j] === ",") {
2090
+ j = skip(j + 1);
2091
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
2092
+ continue;
2093
+ }
2094
+ if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
2095
+ return null;
2096
+ }
2097
+ }
2098
+ const num = /^-?\d+(\.\d+)?([eE][-+]?\d+)?/.exec(s.slice(i));
2099
+ if (num) return { value: Number(num[0]), end: i + num[0].length };
2100
+ return null;
2101
+ }
2102
+ function dcodeAssistantText(raw) {
2103
+ const trimmed = raw.trim();
2104
+ if (!trimmed.startsWith("[{") && !trimmed.startsWith("[ {")) return raw;
2105
+ const parsed = readPyValue(trimmed, 0);
2106
+ if (!parsed || readPyValue(trimmed, parsed.end) !== null) return "";
2107
+ if (!Array.isArray(parsed.value)) return "";
2108
+ return contentText(parsed.value);
2109
+ }
2110
+ function readDcodeTranscript(path) {
2111
+ const turns = [];
2112
+ for (const rawLine of readJsonlTail(path, { scope: "dcode" }).lines) {
2113
+ if (!rawLine.trim()) continue;
2114
+ let parsed;
2115
+ try {
2116
+ parsed = JSON.parse(rawLine);
2117
+ } catch {
2118
+ continue;
2119
+ }
2120
+ if (!parsed || typeof parsed !== "object") continue;
2121
+ const record = parsed;
2122
+ if (record.schema_version !== 1) continue;
2123
+ const role = record.role;
2124
+ const stamp = typeof record.timestamp === "string" && record.timestamp ? { timestamp: record.timestamp } : {};
2125
+ if (role === "user" || role === "assistant") {
2126
+ const text = stripInjectedMemory(contentText(record.content)).trim();
2127
+ if (text) turns.push({ role, content: text, ...stamp });
2128
+ } else if (role === "tool" && typeof record.name === "string" && record.name.trim()) {
2129
+ turns.push({ role: "action", content: actionLine(record.name, record.content), ...stamp });
2130
+ }
2131
+ }
2132
+ return turns;
2133
+ }
2134
+
2135
+ // src/core/transcript-qwen.ts
2136
+ var HOOK_CONTEXT_PART_RE = /^\s*<qwen:user-prompt-submit-context>[\s\S]*<\/qwen:user-prompt-submit-context>\s*$/;
2137
+ function isWholeHookContextPart(part) {
2138
+ return typeof part.text === "string" && HOOK_CONTEXT_PART_RE.test(part.text);
2139
+ }
2140
+ function isRealUser(line) {
2141
+ if (typeof line.provenance === "string") return line.provenance === "real_user";
2142
+ if (line.provenance !== void 0) return false;
2143
+ const isSubagentEnvelope = line.agentId !== void 0 || line.isSidechain !== void 0;
2144
+ if (!isSubagentEnvelope) return false;
2145
+ return line.subtype === void 0 || line.subtype === "mid_turn_user_message";
2146
+ }
2147
+ function renderLine(parts, type) {
2148
+ if (!Array.isArray(parts)) return [];
2149
+ const last = parts.length > 1 ? parts[parts.length - 1] : void 0;
2150
+ const dropLast = !!last && typeof last === "object" && isWholeHookContextPart(last) ? parts.length - 1 : -1;
2151
+ const texts = [];
2152
+ const actions = [];
2153
+ for (const [i, part] of parts.entries()) {
2154
+ if (!part || typeof part !== "object") continue;
2155
+ if (i === dropLast) continue;
2156
+ if (part.thought === true) continue;
2157
+ if (typeof part.text === "string") {
2158
+ const text = stripInjectedMemory(part.text).trim();
2159
+ if (text) texts.push(text);
2160
+ } else if (part.functionCall && typeof part.functionCall.name === "string") {
2161
+ actions.push({
2162
+ role: "action",
2163
+ content: actionLine(part.functionCall.name, part.functionCall.args)
2164
+ });
2165
+ }
2166
+ }
2167
+ const out = [];
2168
+ const joined = texts.join("\n").trim();
2169
+ if (joined) out.push({ role: type, content: joined });
2170
+ out.push(...actions);
2171
+ return out;
2172
+ }
2173
+ function readQwenTranscript(path) {
2174
+ const turns = [];
2175
+ try {
2176
+ collectQwenTurns(path, turns);
2177
+ } catch (err) {
2178
+ log.warn("qwen-code", "transcript read failed \u2014 retaining what was parsed", {
2179
+ path,
2180
+ turns: turns.length,
2181
+ error: err instanceof Error ? err.message : String(err)
2182
+ });
2183
+ }
2184
+ return turns;
2185
+ }
2186
+ function collectQwenTurns(path, turns) {
2187
+ for (const rawLine of readJsonlTail(path, { scope: "qwen-code" }).lines) {
2188
+ const trimmed = rawLine.trim();
2189
+ if (!trimmed) continue;
2190
+ let parsed;
2191
+ try {
2192
+ parsed = JSON.parse(trimmed);
2193
+ } catch {
2194
+ continue;
2195
+ }
2196
+ if (typeof parsed !== "object" || parsed === null) continue;
2197
+ const line = parsed;
2198
+ if (line.type !== "user" && line.type !== "assistant") continue;
2199
+ if (line.type === "user" && !isRealUser(line)) continue;
2200
+ if (typeof line.message !== "object" || line.message === null) continue;
2201
+ const sp = line.systemPayload;
2202
+ if (line.type === "user" && sp && typeof sp === "object" && typeof sp.hookContext === "string" && typeof sp.displayText === "string") {
2203
+ const content = stripInjectedMemory(sp.displayText).trim();
2204
+ if (content) {
2205
+ const turn = { role: "user", content };
2206
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
2207
+ turns.push(turn);
2208
+ }
2209
+ continue;
2210
+ }
2211
+ for (const rendered of renderLine(line.message.parts, line.type)) {
2212
+ const turn = { role: rendered.role, content: rendered.content };
2213
+ if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
2214
+ turns.push(turn);
2215
+ }
2216
+ }
2217
+ }
2218
+
1847
2219
  // src/harness/hook-lifecycle.ts
1848
2220
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
1849
2221
  var claudePrompt = {
@@ -1867,6 +2239,19 @@ var codexPrompt = {
1867
2239
  sessionId: ev.session_id
1868
2240
  })
1869
2241
  };
2242
+ var dcodePrompt = {
2243
+ ...claudePrompt,
2244
+ harness: "dcode"
2245
+ };
2246
+ var qwenPrompt = {
2247
+ ...claudePrompt,
2248
+ harness: "qwen-code",
2249
+ parse: (ev) => ({
2250
+ prompt: ev.submitted_prompt,
2251
+ cwd: ev.cwd,
2252
+ sessionId: ev.session_id
2253
+ })
2254
+ };
1870
2255
  var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
1871
2256
  var antigravityPrompt = {
1872
2257
  harness: "antigravity-cli",
@@ -1971,6 +2356,28 @@ var HOOK_HARNESSES = {
1971
2356
  readTranscript: readCodexTranscript
1972
2357
  }
1973
2358
  },
2359
+ dcode: {
2360
+ configStyle: "nested",
2361
+ install: {
2362
+ sessionStart: { event: "SessionStart", entry: "dcode-sessionstart-hook.js", timeout: 30 },
2363
+ prompt: { event: "UserPromptSubmit", entry: "dcode-hook.js", timeout: 30 },
2364
+ stop: { event: "Stop", entry: "dcode-stop-hook.js", timeout: 60 }
2365
+ },
2366
+ sessionStart: standardSessionStart("dcode"),
2367
+ prompt: dcodePrompt,
2368
+ retain: {
2369
+ hostTimeoutSec: 60,
2370
+ harness: "dcode",
2371
+ parse: (ev) => ({
2372
+ sessionId: ev.session_id,
2373
+ transcriptPath: ev.transcript_path,
2374
+ cwd: ev.cwd,
2375
+ lastAssistantMessage: ev.last_assistant_message
2376
+ }),
2377
+ readTranscript: readDcodeTranscript,
2378
+ readLastMessage: dcodeAssistantText
2379
+ }
2380
+ },
1974
2381
  "antigravity-cli": {
1975
2382
  configStyle: "flat",
1976
2383
  install: {
@@ -2131,6 +2538,37 @@ var HOOK_HARNESSES = {
2131
2538
  }),
2132
2539
  readTranscript: readGrokTranscript
2133
2540
  }
2541
+ },
2542
+ "qwen-code": {
2543
+ configStyle: "nested",
2544
+ timeoutUnit: "milliseconds",
2545
+ // TIMEOUTS ARE MILLISECONDS HERE, not seconds like every other harness in this table: Qwen's
2546
+ // hookRunner does `setTimeout(..., hookConfig.timeout ?? DEFAULT_HOOK_TIMEOUT)` with
2547
+ // DEFAULT_HOOK_TIMEOUT = 60_000 ("Timeout in milliseconds, default 60000"). Writing 30/60
2548
+ // registers 30ms/60ms hooks, which die before a Node process starts — and Qwen spawns hooks
2549
+ // `detached` and terminates the whole process TREE on timeout, so the retain is genuinely lost
2550
+ // rather than merely orphaned. `retain.hostTimeoutSec` below stays SECONDS, as its name says;
2551
+ // these two numbers are the same budget in different units for this harness alone.
2552
+ // The prompt timeout must also stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
2553
+ install: {
2554
+ sessionStart: { event: "SessionStart", entry: "qwen-sessionstart-hook.js", timeout: 3e4 },
2555
+ prompt: { event: "UserPromptSubmit", entry: "qwen-hook.js", timeout: 3e4 },
2556
+ stop: { event: "Stop", entry: "qwen-stop-hook.js", timeout: 6e4 }
2557
+ },
2558
+ sessionStart: standardSessionStart("qwen-code"),
2559
+ prompt: qwenPrompt,
2560
+ retain: {
2561
+ hostTimeoutSec: 60,
2562
+ harness: "qwen-code",
2563
+ parse: (ev) => ({
2564
+ sessionId: ev.session_id,
2565
+ // Qwen supplies the path, but as the EMPTY STRING (not null, not absent) when chat
2566
+ // recording is off — runRetainHook's `if (!transcriptPath) return` already covers that.
2567
+ transcriptPath: ev.transcript_path,
2568
+ cwd: ev.cwd
2569
+ }),
2570
+ readTranscript: readQwenTranscript
2571
+ }
2134
2572
  }
2135
2573
  };
2136
2574
  var runHarnessPrompt = (harness) => runHook(HOOK_HARNESSES[harness].prompt);