@vectorize-io/hindsight-coding-agents 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +42 -8
  2. package/dist/antigravity-hook.js +335 -91
  3. package/dist/antigravity-statusline.js +17 -10
  4. package/dist/antigravity-stop-hook.js +340 -92
  5. package/dist/claude-hook.js +335 -91
  6. package/dist/claude-sessionstart-hook.js +459 -132
  7. package/dist/claude-stop-hook.js +340 -92
  8. package/dist/cline.js +283 -64
  9. package/dist/codex-hook.js +335 -91
  10. package/dist/codex-sessionstart-hook.js +459 -132
  11. package/dist/codex-stop-hook.js +340 -92
  12. package/dist/copilot-hook.js +335 -91
  13. package/dist/copilot-sessionstart-hook.js +459 -132
  14. package/dist/copilot-stop-hook.js +340 -92
  15. package/dist/cursor-hook.js +335 -91
  16. package/dist/cursor-sessionstart-hook.js +459 -132
  17. package/dist/cursor-stop-hook.js +340 -92
  18. package/dist/daemon-start.js +17 -10
  19. package/dist/dcode-hook.js +335 -91
  20. package/dist/dcode-sessionstart-hook.js +459 -132
  21. package/dist/dcode-stop-hook.js +340 -92
  22. package/dist/deepen.js +113 -32
  23. package/dist/devin-hook.js +335 -91
  24. package/dist/devin-sessionstart-hook.js +459 -132
  25. package/dist/devin-stop-hook.js +340 -92
  26. package/dist/droid-hook.js +335 -91
  27. package/dist/droid-sessionstart-hook.js +459 -132
  28. package/dist/droid-stop-hook.js +340 -92
  29. package/dist/dsh.js +322 -101
  30. package/dist/grok-hook.js +335 -91
  31. package/dist/grok-sessionstart-hook.js +459 -132
  32. package/dist/grok-stop-hook.js +340 -92
  33. package/dist/hindsight-seed.js +17 -10
  34. package/dist/index.js +322 -101
  35. package/dist/installer.js +1252 -325
  36. package/dist/kilo.js +322 -101
  37. package/dist/mcp-server.js +100 -23
  38. package/dist/opencode2.js +322 -101
  39. package/dist/pi.js +321 -100
  40. package/dist/prime-agent.js +321 -100
  41. package/dist/qwen-hook.js +335 -91
  42. package/dist/qwen-sessionstart-hook.js +459 -132
  43. package/dist/qwen-stop-hook.js +340 -92
  44. package/dist/status.js +98 -21
  45. package/dist/survey-supervisor.js +81 -0
  46. package/dist/zcode-hook.js +2954 -0
  47. package/dist/zcode-sessionstart-hook.js +3655 -0
  48. package/dist/zcode-stop-hook.js +3218 -0
  49. package/package.json +7 -3
  50. package/plugin.json +1 -1
  51. package/skill/SKILL.md +17 -7
package/dist/cline.js CHANGED
@@ -475,6 +475,7 @@ function pagesFor(project) {
475
475
  var PAGE_MAX_TOKENS = 4096;
476
476
  var PAGE_TAGS_MATCH = "all";
477
477
  var PAGE_FACT_TYPES = ["world", "experience", "observation"];
478
+ var DEFAULT_PAGE_TRIGGER_CRON = "H * * * *";
478
479
  var CRON_FIELD_RANGES = [
479
480
  [0, 59],
480
481
  // minute
@@ -528,14 +529,23 @@ function pageTriggerFor(trigger, bank, page) {
528
529
  function buildPageTrigger(cfg = {}) {
529
530
  const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
530
531
  switch (cfg.pageTriggerType) {
531
- case "cron":
532
- return { ...base, refresh_cron: cfg.pageTriggerCron };
532
+ case "auto-refresh":
533
+ return { ...base, refresh_after_consolidation: true };
533
534
  case "manual":
534
535
  return { ...base, refresh_after_consolidation: false };
536
+ // "cron" and an unset type alike: the default schedule stands in for a missing expression, so
537
+ // a trigger built from a partial config is never a cron trigger with nothing to fire on.
535
538
  default:
536
- return { ...base, refresh_after_consolidation: true };
539
+ return { ...base, refresh_cron: cfg.pageTriggerCron || DEFAULT_PAGE_TRIGGER_CRON };
537
540
  }
538
541
  }
542
+ function pageTriggerDrifted(current2, desired) {
543
+ return current2.tags_match !== desired.tags_match || (current2.refresh_cron ?? null) !== (desired.refresh_cron ?? null) || Boolean(current2.refresh_after_consolidation) !== Boolean(desired.refresh_after_consolidation);
544
+ }
545
+ function pageTriggerPatch(desired) {
546
+ if (desired.refresh_after_consolidation === false) return { ...desired, refresh_cron: null };
547
+ return desired;
548
+ }
539
549
  var CODING_BANK_TEMPLATE = {
540
550
  version: "1",
541
551
  bank: {
@@ -959,9 +969,16 @@ var HindsightClient = class {
959
969
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
960
970
  signal: ctrl.signal
961
971
  });
962
- if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
972
+ if (!resp.ok)
973
+ throw new Error(
974
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`
975
+ );
963
976
  const data = await resp.json();
964
977
  return (data.text || "").trim();
978
+ } catch (e) {
979
+ if (ctrl.signal.aborted)
980
+ throw new Error(`reflect timed out after ${opts.timeoutMs}ms`, { cause: e });
981
+ throw e;
965
982
  } finally {
966
983
  clearTimeout(timer);
967
984
  }
@@ -1094,14 +1111,14 @@ var HindsightClient = class {
1094
1111
  if (r.status !== 409) created++;
1095
1112
  } else {
1096
1113
  const sourceDrift = hit.description !== page.source_query;
1097
- const triggerDrift = hit.trigger != null && hit.trigger.tags_match !== pageTrigger.tags_match;
1114
+ const triggerDrift = hit.trigger != null && pageTriggerDrifted(hit.trigger, body.trigger);
1098
1115
  if (!sourceDrift && !triggerDrift) continue;
1099
1116
  const patch = {};
1100
1117
  if (sourceDrift) {
1101
1118
  patch.source_query = page.source_query;
1102
1119
  patch.tags = page.tags;
1103
1120
  }
1104
- if (triggerDrift) patch.trigger = pageTrigger;
1121
+ if (triggerDrift) patch.trigger = pageTriggerPatch(body.trigger);
1105
1122
  const r = await this.req(
1106
1123
  "PATCH",
1107
1124
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
@@ -1117,9 +1134,41 @@ var HindsightClient = class {
1117
1134
  updated++;
1118
1135
  }
1119
1136
  }
1137
+ const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
1120
1138
  this.log(
1121
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
1139
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged` + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
1140
+ );
1141
+ }
1142
+ /**
1143
+ * Bring the captured initiative pages onto the same refresh policy as the seeded taxonomy.
1144
+ *
1145
+ * `captureInitiative` stamps this very trigger when it creates a page, so on a bank seeded under
1146
+ * an older default they are the same drift as the taxonomy — and on a real repo they are most of
1147
+ * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
1148
+ * consolidation under the auto-refresh that used to be the default (#3506).
1149
+ *
1150
+ * Only the trigger is touched. Their `name` and `source_query` are written once, from the
1151
+ * initiative's own title, and re-stating either would rebuild a page whose question never
1152
+ * changed. The tree read above is reused rather than re-fetched.
1153
+ */
1154
+ async resyncInitiativeTriggers(roots, pageTrigger) {
1155
+ const folder = roots.find(
1156
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
1122
1157
  );
1158
+ let updated = 0;
1159
+ for (const page of folder?.children ?? []) {
1160
+ if (page.kind !== "page" || page.trigger == null) continue;
1161
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
1162
+ if (!pageTriggerDrifted(page.trigger, desired)) continue;
1163
+ const r = await this.req(
1164
+ "PATCH",
1165
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
1166
+ { trigger: pageTriggerPatch(desired) }
1167
+ );
1168
+ if ([404, 405, 501].includes(r.status)) break;
1169
+ updated++;
1170
+ }
1171
+ return updated;
1123
1172
  }
1124
1173
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
1125
1174
  slugify(s) {
@@ -1142,11 +1191,13 @@ var HindsightClient = class {
1142
1191
  let pageId = args.relatesToPageId;
1143
1192
  if (!pageId) {
1144
1193
  const folderId = await this.ensureFolder("Initiatives");
1194
+ const subject = this.project ?? this.bank;
1145
1195
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
1146
1196
  name: args.title,
1147
- 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.`,
1197
+ 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.` + pageScopeRule(subject),
1148
1198
  parent_id: folderId,
1149
1199
  tags: ["knowledge:feature-work"],
1200
+ max_tokens: PAGE_MAX_TOKENS,
1150
1201
  trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1151
1202
  });
1152
1203
  try {
@@ -1189,17 +1240,22 @@ var HindsightClient = class {
1189
1240
  var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
1190
1241
  var DEFAULT_DAEMON_PORT = 9077;
1191
1242
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
1192
- function resolvePageTriggerType(raw) {
1193
- if (raw.pageTriggerType === "manual") return "manual";
1194
- if (raw.pageTriggerType === "cron") {
1195
- const cron = raw.pageTriggerCron?.trim();
1196
- if (cron && (!isHashedCron(cron) || parseHashedCron(cron))) return "cron";
1243
+ function resolvePageTrigger(raw) {
1244
+ if (raw.pageTriggerType === "manual") return { type: "manual" };
1245
+ if (raw.pageTriggerType === "auto-refresh") return { type: "auto-refresh" };
1246
+ if (raw.pageTriggerType !== void 0 && raw.pageTriggerType !== "cron")
1197
1247
  log.warn(
1198
1248
  "config",
1199
- cron ? `pageTriggerCron ${JSON.stringify(cron)} has a malformed hashed field \u2014 write \`H\` or \`H(<lo>-<hi>)\` within the field's own range, e.g. "H H(0-5) * * *" \u2014 falling back to "auto-refresh"` : 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "H H * * *") \u2014 falling back to "auto-refresh"'
1249
+ `ignoring pageTriggerType=${JSON.stringify(raw.pageTriggerType)} \u2014 expected cron|auto-refresh|manual`
1200
1250
  );
1201
- }
1202
- return "auto-refresh";
1251
+ const cron = raw.pageTriggerCron?.trim();
1252
+ if (!cron) return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1253
+ if (!isHashedCron(cron) || parseHashedCron(cron)) return { type: "cron", cron };
1254
+ log.warn(
1255
+ "config",
1256
+ `pageTriggerCron ${JSON.stringify(cron)} has a malformed hashed field \u2014 write \`H\` or \`H(<lo>-<hi>)\` within the field's own range, e.g. "H H(0-5) * * *" \u2014 falling back to ${JSON.stringify(DEFAULT_PAGE_TRIGGER_CRON)}`
1257
+ );
1258
+ return { type: "cron", cron: DEFAULT_PAGE_TRIGGER_CRON };
1203
1259
  }
1204
1260
  var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
1205
1261
  var REFLECT_BUDGETS = ["low", "mid", "high"];
@@ -1231,6 +1287,7 @@ function resolveObservationScopes(raw) {
1231
1287
  function resolveConfig(raw = {}) {
1232
1288
  const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
1233
1289
  const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
1290
+ const pageTrigger = resolvePageTrigger(raw);
1234
1291
  return {
1235
1292
  serverMode,
1236
1293
  // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
@@ -1265,8 +1322,8 @@ function resolveConfig(raw = {}) {
1265
1322
  reflectBudget: resolveReflectBudget(raw),
1266
1323
  autoReflect: raw.autoReflect ?? true,
1267
1324
  pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
1268
- pageTriggerType: resolvePageTriggerType(raw),
1269
- pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
1325
+ pageTriggerType: pageTrigger.type,
1326
+ pageTriggerCron: pageTrigger.cron,
1270
1327
  autoSeed: raw.autoSeed ?? true,
1271
1328
  seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
1272
1329
  codebaseSurvey: raw.codebaseSurvey ?? true,
@@ -16303,7 +16360,7 @@ config(en_default());
16303
16360
  // src/core/knowledge-tools.ts
16304
16361
  import { existsSync as existsSync4 } from "fs";
16305
16362
  import { homedir as homedir5 } from "os";
16306
- import { join as join10 } from "path";
16363
+ import { join as join11 } from "path";
16307
16364
 
16308
16365
  // src/core/status.ts
16309
16366
  import { execFileSync as execFileSync3 } from "child_process";
@@ -16389,11 +16446,86 @@ ${toolGuide(opts)}
16389
16446
  }
16390
16447
 
16391
16448
  // src/core/survey.ts
16392
- import { spawn as realSpawn4 } from "child_process";
16449
+ import { spawn as realSpawn5 } from "child_process";
16450
+ import { createHash as createHash2 } from "crypto";
16393
16451
  import { existsSync as existsSync3 } from "fs";
16394
- import { homedir as homedir4 } from "os";
16395
- import { dirname as dirname7, join as join9 } from "path";
16452
+ import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
16453
+ import { dirname as dirname7, join as join10 } from "path";
16396
16454
  import { fileURLToPath as fileURLToPath4 } from "url";
16455
+
16456
+ // src/core/survey-lease.ts
16457
+ import { spawn as realSpawn4 } from "child_process";
16458
+ import { randomUUID } from "crypto";
16459
+ import {
16460
+ mkdirSync as mkdirSync3,
16461
+ mkdtempSync,
16462
+ readdirSync,
16463
+ renameSync,
16464
+ rmdirSync,
16465
+ rmSync,
16466
+ statSync,
16467
+ unlinkSync as unlinkSync2,
16468
+ utimesSync,
16469
+ writeFileSync as writeFileSync2
16470
+ } from "fs";
16471
+ import { join as join9 } from "path";
16472
+ var LEASE_STALE_MS = 3e4;
16473
+ var SURVEY_SPEC_ENV = "HINDSIGHT_SURVEY_SPEC";
16474
+ function tryRename(from, to) {
16475
+ try {
16476
+ renameSync(from, to);
16477
+ return true;
16478
+ } catch {
16479
+ return false;
16480
+ }
16481
+ }
16482
+ function releaseLease(lease) {
16483
+ try {
16484
+ unlinkSync2(join9(lease.directory, lease.owner));
16485
+ } catch {
16486
+ return;
16487
+ }
16488
+ try {
16489
+ rmdirSync(lease.directory);
16490
+ } catch {
16491
+ }
16492
+ }
16493
+ function reclaimIfStale(directory, staleMs) {
16494
+ const owners = readdirSync(directory);
16495
+ if (owners.length === 0) {
16496
+ try {
16497
+ rmdirSync(directory);
16498
+ } catch {
16499
+ }
16500
+ return true;
16501
+ }
16502
+ if (owners.length !== 1) return false;
16503
+ const age = Date.now() - statSync(join9(directory, owners[0])).mtimeMs;
16504
+ if (Math.abs(age) <= staleMs) return false;
16505
+ releaseLease({ directory, owner: owners[0] });
16506
+ return true;
16507
+ }
16508
+ function acquireLease(root, key, staleMs = LEASE_STALE_MS) {
16509
+ let staging;
16510
+ try {
16511
+ mkdirSync3(root, { recursive: true, mode: 448 });
16512
+ staging = mkdtempSync(join9(root, "claim-"));
16513
+ const owner = randomUUID();
16514
+ writeFileSync2(join9(staging, owner), "", { flag: "wx", mode: 384 });
16515
+ const directory = join9(root, `survey-${key}.lock`);
16516
+ if (!tryRename(staging, directory)) {
16517
+ if (!reclaimIfStale(directory, staleMs)) return void 0;
16518
+ if (!tryRename(staging, directory)) return void 0;
16519
+ }
16520
+ return { directory, owner };
16521
+ } catch {
16522
+ return void 0;
16523
+ } finally {
16524
+ if (staging) rmSync(staging, { recursive: true, force: true });
16525
+ }
16526
+ }
16527
+
16528
+ // src/core/survey.ts
16397
16529
  var SURVEY_DOC_IDS = [
16398
16530
  "repository-component-map",
16399
16531
  "repository-core-concepts",
@@ -16403,7 +16535,7 @@ var SURVEY_DOC_IDS = [
16403
16535
  function resolveClaudeBin(explicit) {
16404
16536
  if (explicit) return explicit;
16405
16537
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
16406
- const nativeInstallPath = join9(homedir4(), ".claude", "local", "claude");
16538
+ const nativeInstallPath = join10(homedir4(), ".claude", "local", "claude");
16407
16539
  try {
16408
16540
  if (existsSync3(nativeInstallPath)) return nativeInstallPath;
16409
16541
  } catch {
@@ -16517,11 +16649,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
16517
16649
  }
16518
16650
  }
16519
16651
  }
16520
- function startCodebaseSurvey(repoDir, opts = {}) {
16652
+ async function startCodebaseSurvey(repoDir, opts = {}) {
16521
16653
  try {
16522
- const spawnFn = opts.spawn ?? realSpawn4;
16654
+ const spawnFn = opts.spawn ?? realSpawn5;
16523
16655
  const exists = opts.exists ?? binOnPath;
16524
- const mcpServerPath = opts.mcpServerPath ?? join9(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16656
+ const mcpServerPath = opts.mcpServerPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16525
16657
  const preferred = opts.harness ?? "claude-code";
16526
16658
  const order = [
16527
16659
  preferred,
@@ -16541,20 +16673,51 @@ function startCodebaseSurvey(repoDir, opts = {}) {
16541
16673
  budgetUsd: opts.budgetUsd,
16542
16674
  mcpServerPath
16543
16675
  });
16544
- const child = spawnFn(plan.bin, plan.args, {
16545
- cwd: repoDir,
16546
- detached: true,
16547
- stdio: "ignore",
16548
- windowsHide: true,
16549
- env: plan.env
16550
- });
16551
- child.on("error", () => {
16676
+ const { cfg, bankId } = resolveHostConfig(harness, repoDir);
16677
+ if (cfg.disabled) return false;
16678
+ const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
16679
+ const lease = acquireLease(
16680
+ opts.lease?.dir ?? join10(tmpdir3(), "hindsight-coding-agent", "surveys"),
16681
+ key,
16682
+ opts.lease?.staleMs ?? LEASE_STALE_MS
16683
+ );
16684
+ if (!lease) return false;
16685
+ const spec = {
16686
+ lease,
16687
+ bin: plan.bin,
16688
+ args: plan.args,
16689
+ ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
16690
+ };
16691
+ const supervisorPath = opts.supervisorPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
16692
+ return await new Promise((resolve3) => {
16693
+ try {
16694
+ const child = spawnFn("node", [supervisorPath], {
16695
+ cwd: repoDir,
16696
+ detached: true,
16697
+ stdio: "ignore",
16698
+ windowsHide: true,
16699
+ env: { ...plan.env, [SURVEY_SPEC_ENV]: JSON.stringify(spec) }
16700
+ });
16701
+ let spawned = false;
16702
+ child.on("error", () => {
16703
+ if (spawned) return;
16704
+ releaseLease(lease);
16705
+ resolve3(false);
16706
+ });
16707
+ child.once("spawn", () => {
16708
+ spawned = true;
16709
+ child.unref();
16710
+ resolve3(true);
16711
+ });
16712
+ } catch {
16713
+ releaseLease(lease);
16714
+ resolve3(false);
16715
+ }
16552
16716
  });
16553
- child.unref();
16554
- return;
16555
16717
  }
16556
16718
  } catch {
16557
16719
  }
16720
+ return false;
16558
16721
  }
16559
16722
 
16560
16723
  // src/core/status.ts
@@ -16667,7 +16830,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16667
16830
  inputSchema: {},
16668
16831
  annotations: READ_ONLY_ANNOTATIONS,
16669
16832
  handler: async (_args) => {
16670
- const configPath = process.env.HINDSIGHT_CONFIG || join10(homedir5(), ".hindsight", "coding-agent.json");
16833
+ const configPath = process.env.HINDSIGHT_CONFIG || join11(homedir5(), ".hindsight", "coding-agent.json");
16671
16834
  const harness = opts.harness ?? "unknown";
16672
16835
  const cfg = applyBankConfig(
16673
16836
  loadConfig({ harness: opts.harness }),
@@ -16803,7 +16966,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16803
16966
  }
16804
16967
 
16805
16968
  // src/core/retain-cursor.ts
16806
- import { createHash as createHash2 } from "crypto";
16969
+ import { createHash as createHash3 } from "crypto";
16807
16970
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
16808
16971
  var PENDING_MAX_BYTES = 256 * 1024;
16809
16972
  function pendingReplayable(cursor, now) {
@@ -16813,7 +16976,7 @@ function pendingReplayable(cursor, now) {
16813
16976
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
16814
16977
  }
16815
16978
  function fingerprintTurns(turns, count) {
16816
- const h = createHash2("sha1").update(String(count));
16979
+ const h = createHash3("sha1").update(String(count));
16817
16980
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
16818
16981
  return h.digest("hex");
16819
16982
  }
@@ -16836,13 +16999,13 @@ function memoryCursorStore() {
16836
16999
  }
16837
17000
 
16838
17001
  // src/core/uuid.ts
16839
- import { createHash as createHash3 } from "crypto";
17002
+ import { createHash as createHash4 } from "crypto";
16840
17003
  var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
16841
17004
  function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
16842
17005
  const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
16843
17006
  if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
16844
17007
  const bytes = Buffer.from(
16845
- createHash3("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
17008
+ createHash4("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
16846
17009
  );
16847
17010
  bytes[6] = bytes[6] & 15 | 80;
16848
17011
  bytes[8] = bytes[8] & 63 | 128;
@@ -17046,12 +17209,12 @@ function buildRetainStamp(cfg, ctx) {
17046
17209
  }
17047
17210
 
17048
17211
  // src/core/session-start.ts
17049
- import { readFileSync as readFileSync6 } from "fs";
17212
+ import { readFileSync as readFileSync7 } from "fs";
17050
17213
 
17051
17214
  // src/core/skill-sync.ts
17052
17215
  import { cpSync, existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
17053
17216
  import { homedir as homedir6 } from "os";
17054
- import { dirname as dirname8, join as join11 } from "path";
17217
+ import { dirname as dirname8, join as join12 } from "path";
17055
17218
  import { fileURLToPath as fileURLToPath5 } from "url";
17056
17219
 
17057
17220
  // src/core/brand.ts
@@ -17068,29 +17231,66 @@ function brandWord() {
17068
17231
  return `${out}\x1B[0m`;
17069
17232
  }
17070
17233
 
17234
+ // src/core/legacy.ts
17235
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17236
+ import { homedir as homedir7 } from "os";
17237
+ import { join as join13, relative, isAbsolute as isAbsolute2 } from "path";
17238
+ var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17239
+ function detectLegacyClaudePlugin(cwd, claudeDir = join13(homedir7(), ".claude")) {
17240
+ const registry2 = readJson(join13(claudeDir, "plugins", "installed_plugins.json"));
17241
+ const plugins = registry2?.plugins;
17242
+ if (!plugins || typeof plugins !== "object") return void 0;
17243
+ const enabled = readJson(join13(claudeDir, "settings.json"))?.enabledPlugins;
17244
+ for (const [key, raw] of Object.entries(plugins)) {
17245
+ if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
17246
+ if (enabled && enabled[key] === false) continue;
17247
+ const installs = Array.isArray(raw) ? raw : [raw];
17248
+ const active = installs.some((i) => {
17249
+ if (!i || typeof i !== "object") return false;
17250
+ if (typeof i.projectPath !== "string") return true;
17251
+ const rel = relative(i.projectPath, cwd);
17252
+ return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
17253
+ });
17254
+ if (active) return key;
17255
+ }
17256
+ return void 0;
17257
+ }
17258
+ function readJson(path) {
17259
+ try {
17260
+ const parsed = JSON.parse(readFileSync5(path, "utf8"));
17261
+ return parsed && typeof parsed === "object" ? parsed : void 0;
17262
+ } catch {
17263
+ return void 0;
17264
+ }
17265
+ }
17266
+ function legacyClaudePluginWarning(key) {
17267
+ return `\u26A0\uFE0F The old Hindsight Claude Code plugin (${key}) is still installed \u2014 it runs alongside this one, so memory is recalled and retained twice.
17268
+ \u21B3 remove it: claude plugin uninstall ${key}`;
17269
+ }
17270
+
17071
17271
  // src/core/session-cache.ts
17072
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
17073
- import { tmpdir as tmpdir3 } from "os";
17074
- import { dirname as dirname9, join as join12 } from "path";
17272
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync6, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17273
+ import { tmpdir as tmpdir4 } from "os";
17274
+ import { dirname as dirname9, join as join14 } from "path";
17075
17275
  function sessionCacheFile(harness, sessionId2) {
17076
- return join12(tmpdir3(), `hindsight-${harness}`, `${sessionId2}.json`);
17276
+ return join14(tmpdir4(), `hindsight-${harness}`, `${sessionId2}.json`);
17077
17277
  }
17078
17278
  function readSessionCache(cacheFile) {
17079
17279
  try {
17080
- return JSON.parse(readFileSync5(cacheFile, "utf8"));
17280
+ return JSON.parse(readFileSync6(cacheFile, "utf8"));
17081
17281
  } catch {
17082
17282
  return {};
17083
17283
  }
17084
17284
  }
17085
17285
  function writeFileAtomic(path, body) {
17086
- mkdirSync3(dirname9(path), { recursive: true });
17286
+ mkdirSync4(dirname9(path), { recursive: true });
17087
17287
  const tmp = `${path}.${process.pid}.tmp`;
17088
17288
  try {
17089
- writeFileSync2(tmp, body);
17090
- renameSync(tmp, path);
17289
+ writeFileSync3(tmp, body);
17290
+ renameSync2(tmp, path);
17091
17291
  } catch (e) {
17092
17292
  try {
17093
- rmSync(tmp, { force: true });
17293
+ rmSync2(tmp, { force: true });
17094
17294
  } catch {
17095
17295
  }
17096
17296
  throw e;
@@ -17183,13 +17383,13 @@ async function buildSessionStartContext(args) {
17183
17383
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17184
17384
  if (docIds.size === 0) {
17185
17385
  if (cfg.codebaseSurvey !== false) {
17186
- startSurvey(cwd, {
17386
+ const started = await startSurvey(cwd, {
17187
17387
  harness,
17188
17388
  model: cfg.surveyModel,
17189
17389
  budgetUsd: cfg.surveyBudgetUsd
17190
17390
  });
17191
17391
  const sha = resolveHeadSha(cwd);
17192
- if (sha) recordSurveyBaseline(sha);
17392
+ if (started && sha) recordSurveyBaseline(sha);
17193
17393
  }
17194
17394
  diag(harness, "seed_started", { bank: bankId });
17195
17395
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
@@ -17206,17 +17406,19 @@ async function buildSessionStartContext(args) {
17206
17406
  const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
17207
17407
  const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
17208
17408
  if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
17209
- startSurvey(cwd, {
17409
+ const started = await startSurvey(cwd, {
17210
17410
  harness,
17211
17411
  model: cfg.surveyModel,
17212
17412
  budgetUsd: cfg.surveyBudgetUsd
17213
17413
  });
17214
- recordSurveyBaseline(sha);
17215
- diag(harness, "survey_refresh", {
17216
- bank: bankId,
17217
- commits: sinceLast,
17218
- retry: findingsAbsent
17219
- });
17414
+ if (started) {
17415
+ recordSurveyBaseline(sha);
17416
+ diag(harness, "survey_refresh", {
17417
+ bank: bankId,
17418
+ commits: sinceLast,
17419
+ retry: findingsAbsent
17420
+ });
17421
+ }
17220
17422
  } else if (sinceLast === null) {
17221
17423
  recordSurveyBaseline(sha);
17222
17424
  }
@@ -17249,12 +17451,19 @@ async function buildSessionStartContext(args) {
17249
17451
  }).catch(() => void 0);
17250
17452
  }
17251
17453
  systemMessage = buildSeedBanner(bankId, cold === true, gitNote);
17454
+ const detectLegacy = args.detectLegacyPlugin ?? (harness === "claude-code" ? detectLegacyClaudePlugin : void 0);
17455
+ const legacyPlugin = detectLegacy?.(cwd);
17456
+ if (legacyPlugin) {
17457
+ systemMessage += `
17458
+ ${legacyClaudePluginWarning(legacyPlugin)}`;
17459
+ diag(harness, "legacy_plugin_active", { plugin: legacyPlugin });
17460
+ }
17252
17461
  diag(harness, "session_start", { bank: bankId, cold, pages: pages.length, ms: Date.now() - t0 });
17253
17462
  return { systemMessage, additionalContext, deferInitialReflect };
17254
17463
  }
17255
17464
 
17256
17465
  // src/core/hook.ts
17257
- import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
17466
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
17258
17467
 
17259
17468
  // src/core/inject.ts
17260
17469
  function buildReflectQuery(prompt) {
@@ -17285,6 +17494,12 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
17285
17494
  ` + memory + "\n</hindsight_memory>";
17286
17495
  }
17287
17496
 
17497
+ // src/core/turn-journal.ts
17498
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync8, statSync as statSync2 } from "fs";
17499
+ import { tmpdir as tmpdir5 } from "os";
17500
+ import { dirname as dirname10, join as join15 } from "path";
17501
+ var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17502
+
17288
17503
  // src/core/hook.ts
17289
17504
  var HOOK_REFLECT_CAP_MS = 25e3;
17290
17505
  async function buildHookOutput(args) {
@@ -17300,13 +17515,14 @@ async function buildHookOutput(args) {
17300
17515
  } else if (cfg.autoReflect && reflectAnswer === void 0) {
17301
17516
  reflectRanThisTurn = true;
17302
17517
  const t0 = Date.now();
17518
+ const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17303
17519
  try {
17304
17520
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17305
17521
  // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17306
17522
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17307
17523
  // tool still get the deeper high-budget path.
17308
17524
  budget: "low",
17309
- timeoutMs: Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS)
17525
+ timeoutMs
17310
17526
  });
17311
17527
  diag(harness, reflectAnswer ? "reflect_ok" : "reflect_empty", {
17312
17528
  ms: Date.now() - t0,
@@ -17324,7 +17540,10 @@ async function buildHookOutput(args) {
17324
17540
  });
17325
17541
  diag(harness, "reflect_failed", {
17326
17542
  ms: Date.now() - t0,
17327
- error: describeError(e),
17543
+ bank: client.bank,
17544
+ timeoutMs,
17545
+ // Wider than describeError's default: the server's error body is the useful part.
17546
+ error: describeError(e, 1500),
17328
17547
  query: prompt.slice(0, 80)
17329
17548
  });
17330
17549
  }