@vectorize-io/hindsight-coding-agents 0.5.3 → 0.5.5

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 (48) hide show
  1. package/README.md +5 -2
  2. package/dist/antigravity-hook.js +185 -41
  3. package/dist/antigravity-stop-hook.js +114 -36
  4. package/dist/claude-hook.js +185 -41
  5. package/dist/claude-sessionstart-hook.js +292 -76
  6. package/dist/claude-stop-hook.js +114 -36
  7. package/dist/cline.js +331 -58
  8. package/dist/codex-hook.js +185 -41
  9. package/dist/codex-sessionstart-hook.js +292 -76
  10. package/dist/codex-stop-hook.js +114 -36
  11. package/dist/copilot-hook.js +185 -41
  12. package/dist/copilot-sessionstart-hook.js +292 -76
  13. package/dist/copilot-stop-hook.js +114 -36
  14. package/dist/cursor-hook.js +185 -41
  15. package/dist/cursor-sessionstart-hook.js +292 -76
  16. package/dist/cursor-stop-hook.js +114 -36
  17. package/dist/dcode-hook.js +185 -41
  18. package/dist/dcode-sessionstart-hook.js +292 -76
  19. package/dist/dcode-stop-hook.js +114 -36
  20. package/dist/deepen.js +93 -18
  21. package/dist/devin-hook.js +185 -41
  22. package/dist/devin-sessionstart-hook.js +292 -76
  23. package/dist/devin-stop-hook.js +114 -36
  24. package/dist/droid-hook.js +185 -41
  25. package/dist/droid-sessionstart-hook.js +292 -76
  26. package/dist/droid-stop-hook.js +114 -36
  27. package/dist/dsh.js +333 -60
  28. package/dist/grok-hook.js +185 -41
  29. package/dist/grok-sessionstart-hook.js +292 -76
  30. package/dist/grok-stop-hook.js +114 -36
  31. package/dist/index.js +333 -60
  32. package/dist/installer.js +1030 -268
  33. package/dist/kilo.js +333 -60
  34. package/dist/mcp-server.js +86 -11
  35. package/dist/opencode2.js +333 -60
  36. package/dist/pi.js +332 -59
  37. package/dist/prime-agent.js +332 -59
  38. package/dist/qwen-hook.js +185 -41
  39. package/dist/qwen-sessionstart-hook.js +292 -76
  40. package/dist/qwen-stop-hook.js +114 -36
  41. package/dist/status.js +84 -9
  42. package/dist/survey-supervisor.js +81 -0
  43. package/dist/zcode-hook.js +185 -41
  44. package/dist/zcode-sessionstart-hook.js +292 -76
  45. package/dist/zcode-stop-hook.js +114 -36
  46. package/package.json +2 -1
  47. package/plugin.json +1 -1
  48. package/skill/SKILL.md +5 -2
package/dist/dsh.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // src/dsh.ts
8
- import { randomUUID } from "crypto";
8
+ import { randomUUID as randomUUID2 } from "crypto";
9
9
 
10
10
  // src/core/config.ts
11
11
  import { readFileSync as readFileSync2 } from "fs";
@@ -679,6 +679,22 @@ var KnowledgePagesUnavailableError = class extends Error {
679
679
  }
680
680
  };
681
681
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
682
+ var ReflectError = class extends Error {
683
+ constructor(message, status, timedOut, options) {
684
+ super(message, options);
685
+ this.status = status;
686
+ this.timedOut = timedOut;
687
+ this.name = "ReflectError";
688
+ }
689
+ status;
690
+ timedOut;
691
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
692
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
693
+ * every endpoint (auth, missing bank), so it is not. */
694
+ get fallbackEligible() {
695
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
696
+ }
697
+ };
682
698
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
683
699
  var POLL_CYCLE_MS = 5e3;
684
700
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -762,11 +778,11 @@ var HindsightClient = class {
762
778
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
763
779
  }
764
780
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
765
- async req(method, url2, body, tolerate = []) {
781
+ async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
766
782
  const r = await this.fetchWithAuth(url2, {
767
783
  method,
768
784
  body: body ? JSON.stringify(body) : void 0,
769
- signal: AbortSignal.timeout(15e3)
785
+ signal: AbortSignal.timeout(timeoutMs)
770
786
  });
771
787
  if (r.status === 429 && !tolerate.includes(429))
772
788
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -959,7 +975,7 @@ var HindsightClient = class {
959
975
  /**
960
976
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
961
977
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
962
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
978
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
963
979
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
964
980
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
965
981
  */
@@ -972,13 +988,46 @@ var HindsightClient = class {
972
988
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
973
989
  signal: ctrl.signal
974
990
  });
975
- if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
991
+ if (!resp.ok)
992
+ throw new ReflectError(
993
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
994
+ resp.status,
995
+ false
996
+ );
976
997
  const data = await resp.json();
977
998
  return (data.text || "").trim();
999
+ } catch (e) {
1000
+ if (ctrl.signal.aborted)
1001
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
1002
+ cause: e
1003
+ });
1004
+ throw e;
978
1005
  } finally {
979
1006
  clearTimeout(timer);
980
1007
  }
981
1008
  }
1009
+ /**
1010
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
1011
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
1012
+ */
1013
+ async recallObservations(query, opts) {
1014
+ const r = await this.req(
1015
+ "POST",
1016
+ this.bankUrl("/memories/recall"),
1017
+ {
1018
+ query,
1019
+ types: ["observation"],
1020
+ budget: "low",
1021
+ max_tokens: opts.maxTokens,
1022
+ include: { entities: null }
1023
+ },
1024
+ [],
1025
+ opts.timeoutMs
1026
+ );
1027
+ if (r.status === 404) return [];
1028
+ const j = await r.json();
1029
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1030
+ }
982
1031
  /**
983
1032
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
984
1033
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -1043,10 +1092,16 @@ var HindsightClient = class {
1043
1092
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1044
1093
  * Returns page-level hits with a relevance snippet — the real search behind
1045
1094
  * hindsight_search_knowledge_pages. */
1046
- async searchKnowledgePages(query, limit = 3) {
1095
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
1047
1096
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1048
1097
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
1049
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
1098
+ const r = await this.req(
1099
+ "GET",
1100
+ this.bankUrl(`/knowledge-base/search${q}`),
1101
+ void 0,
1102
+ [],
1103
+ timeoutMs
1104
+ );
1050
1105
  const j = await r.json();
1051
1106
  return (j.results ?? []).map((x) => ({
1052
1107
  id: x.id,
@@ -16356,7 +16411,7 @@ config(en_default());
16356
16411
  // src/core/knowledge-tools.ts
16357
16412
  import { existsSync as existsSync4 } from "fs";
16358
16413
  import { homedir as homedir5 } from "os";
16359
- import { join as join10 } from "path";
16414
+ import { join as join11 } from "path";
16360
16415
 
16361
16416
  // src/core/status.ts
16362
16417
  import { execFileSync as execFileSync3 } from "child_process";
@@ -16442,11 +16497,86 @@ ${toolGuide(opts)}
16442
16497
  }
16443
16498
 
16444
16499
  // src/core/survey.ts
16445
- import { spawn as realSpawn4 } from "child_process";
16500
+ import { spawn as realSpawn5 } from "child_process";
16501
+ import { createHash as createHash2 } from "crypto";
16446
16502
  import { existsSync as existsSync3 } from "fs";
16447
- import { homedir as homedir4 } from "os";
16448
- import { dirname as dirname7, join as join9 } from "path";
16503
+ import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
16504
+ import { dirname as dirname7, join as join10 } from "path";
16449
16505
  import { fileURLToPath as fileURLToPath4 } from "url";
16506
+
16507
+ // src/core/survey-lease.ts
16508
+ import { spawn as realSpawn4 } from "child_process";
16509
+ import { randomUUID } from "crypto";
16510
+ import {
16511
+ mkdirSync as mkdirSync3,
16512
+ mkdtempSync,
16513
+ readdirSync,
16514
+ renameSync,
16515
+ rmdirSync,
16516
+ rmSync,
16517
+ statSync,
16518
+ unlinkSync as unlinkSync2,
16519
+ utimesSync,
16520
+ writeFileSync as writeFileSync2
16521
+ } from "fs";
16522
+ import { join as join9 } from "path";
16523
+ var LEASE_STALE_MS = 3e4;
16524
+ var SURVEY_SPEC_ENV = "HINDSIGHT_SURVEY_SPEC";
16525
+ function tryRename(from, to) {
16526
+ try {
16527
+ renameSync(from, to);
16528
+ return true;
16529
+ } catch {
16530
+ return false;
16531
+ }
16532
+ }
16533
+ function releaseLease(lease) {
16534
+ try {
16535
+ unlinkSync2(join9(lease.directory, lease.owner));
16536
+ } catch {
16537
+ return;
16538
+ }
16539
+ try {
16540
+ rmdirSync(lease.directory);
16541
+ } catch {
16542
+ }
16543
+ }
16544
+ function reclaimIfStale(directory, staleMs) {
16545
+ const owners = readdirSync(directory);
16546
+ if (owners.length === 0) {
16547
+ try {
16548
+ rmdirSync(directory);
16549
+ } catch {
16550
+ }
16551
+ return true;
16552
+ }
16553
+ if (owners.length !== 1) return false;
16554
+ const age = Date.now() - statSync(join9(directory, owners[0])).mtimeMs;
16555
+ if (Math.abs(age) <= staleMs) return false;
16556
+ releaseLease({ directory, owner: owners[0] });
16557
+ return true;
16558
+ }
16559
+ function acquireLease(root, key, staleMs = LEASE_STALE_MS) {
16560
+ let staging;
16561
+ try {
16562
+ mkdirSync3(root, { recursive: true, mode: 448 });
16563
+ staging = mkdtempSync(join9(root, "claim-"));
16564
+ const owner = randomUUID();
16565
+ writeFileSync2(join9(staging, owner), "", { flag: "wx", mode: 384 });
16566
+ const directory = join9(root, `survey-${key}.lock`);
16567
+ if (!tryRename(staging, directory)) {
16568
+ if (!reclaimIfStale(directory, staleMs)) return void 0;
16569
+ if (!tryRename(staging, directory)) return void 0;
16570
+ }
16571
+ return { directory, owner };
16572
+ } catch {
16573
+ return void 0;
16574
+ } finally {
16575
+ if (staging) rmSync(staging, { recursive: true, force: true });
16576
+ }
16577
+ }
16578
+
16579
+ // src/core/survey.ts
16450
16580
  var SURVEY_DOC_IDS = [
16451
16581
  "repository-component-map",
16452
16582
  "repository-core-concepts",
@@ -16456,7 +16586,7 @@ var SURVEY_DOC_IDS = [
16456
16586
  function resolveClaudeBin(explicit) {
16457
16587
  if (explicit) return explicit;
16458
16588
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
16459
- const nativeInstallPath = join9(homedir4(), ".claude", "local", "claude");
16589
+ const nativeInstallPath = join10(homedir4(), ".claude", "local", "claude");
16460
16590
  try {
16461
16591
  if (existsSync3(nativeInstallPath)) return nativeInstallPath;
16462
16592
  } catch {
@@ -16570,11 +16700,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
16570
16700
  }
16571
16701
  }
16572
16702
  }
16573
- function startCodebaseSurvey(repoDir, opts = {}) {
16703
+ async function startCodebaseSurvey(repoDir, opts = {}) {
16574
16704
  try {
16575
- const spawnFn = opts.spawn ?? realSpawn4;
16705
+ const spawnFn = opts.spawn ?? realSpawn5;
16576
16706
  const exists = opts.exists ?? binOnPath;
16577
- const mcpServerPath = opts.mcpServerPath ?? join9(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16707
+ const mcpServerPath = opts.mcpServerPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16578
16708
  const preferred = opts.harness ?? "claude-code";
16579
16709
  const order = [
16580
16710
  preferred,
@@ -16594,20 +16724,51 @@ function startCodebaseSurvey(repoDir, opts = {}) {
16594
16724
  budgetUsd: opts.budgetUsd,
16595
16725
  mcpServerPath
16596
16726
  });
16597
- const child = spawnFn(plan.bin, plan.args, {
16598
- cwd: repoDir,
16599
- detached: true,
16600
- stdio: "ignore",
16601
- windowsHide: true,
16602
- env: plan.env
16603
- });
16604
- child.on("error", () => {
16727
+ const { cfg, bankId } = resolveHostConfig(harness, repoDir);
16728
+ if (cfg.disabled) return false;
16729
+ const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
16730
+ const lease = acquireLease(
16731
+ opts.lease?.dir ?? join10(tmpdir3(), "hindsight-coding-agent", "surveys"),
16732
+ key,
16733
+ opts.lease?.staleMs ?? LEASE_STALE_MS
16734
+ );
16735
+ if (!lease) return false;
16736
+ const spec = {
16737
+ lease,
16738
+ bin: plan.bin,
16739
+ args: plan.args,
16740
+ ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
16741
+ };
16742
+ const supervisorPath = opts.supervisorPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
16743
+ return await new Promise((resolve3) => {
16744
+ try {
16745
+ const child = spawnFn("node", [supervisorPath], {
16746
+ cwd: repoDir,
16747
+ detached: true,
16748
+ stdio: "ignore",
16749
+ windowsHide: true,
16750
+ env: { ...plan.env, [SURVEY_SPEC_ENV]: JSON.stringify(spec) }
16751
+ });
16752
+ let spawned = false;
16753
+ child.on("error", () => {
16754
+ if (spawned) return;
16755
+ releaseLease(lease);
16756
+ resolve3(false);
16757
+ });
16758
+ child.once("spawn", () => {
16759
+ spawned = true;
16760
+ child.unref();
16761
+ resolve3(true);
16762
+ });
16763
+ } catch {
16764
+ releaseLease(lease);
16765
+ resolve3(false);
16766
+ }
16605
16767
  });
16606
- child.unref();
16607
- return;
16608
16768
  }
16609
16769
  } catch {
16610
16770
  }
16771
+ return false;
16611
16772
  }
16612
16773
 
16613
16774
  // src/core/status.ts
@@ -16720,7 +16881,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16720
16881
  inputSchema: {},
16721
16882
  annotations: READ_ONLY_ANNOTATIONS,
16722
16883
  handler: async (_args) => {
16723
- const configPath = process.env.HINDSIGHT_CONFIG || join10(homedir5(), ".hindsight", "coding-agent.json");
16884
+ const configPath = process.env.HINDSIGHT_CONFIG || join11(homedir5(), ".hindsight", "coding-agent.json");
16724
16885
  const harness = opts.harness ?? "unknown";
16725
16886
  const cfg = applyBankConfig(
16726
16887
  loadConfig({ harness: opts.harness }),
@@ -16856,7 +17017,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16856
17017
  }
16857
17018
 
16858
17019
  // src/core/retain-cursor.ts
16859
- import { createHash as createHash2 } from "crypto";
17020
+ import { createHash as createHash3 } from "crypto";
16860
17021
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
16861
17022
  var PENDING_MAX_BYTES = 256 * 1024;
16862
17023
  function pendingReplayable(cursor, now) {
@@ -16866,7 +17027,7 @@ function pendingReplayable(cursor, now) {
16866
17027
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
16867
17028
  }
16868
17029
  function fingerprintTurns(turns, count) {
16869
- const h = createHash2("sha1").update(String(count));
17030
+ const h = createHash3("sha1").update(String(count));
16870
17031
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
16871
17032
  return h.digest("hex");
16872
17033
  }
@@ -16889,13 +17050,13 @@ function memoryCursorStore() {
16889
17050
  }
16890
17051
 
16891
17052
  // src/core/uuid.ts
16892
- import { createHash as createHash3 } from "crypto";
17053
+ import { createHash as createHash4 } from "crypto";
16893
17054
  var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
16894
17055
  function uuidV5(name2, namespace = HINDSIGHT_NAMESPACE) {
16895
17056
  const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
16896
17057
  if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
16897
17058
  const bytes = Buffer.from(
16898
- createHash3("sha1").update(ns).update(Buffer.from(name2, "utf8")).digest().subarray(0, 16)
17059
+ createHash4("sha1").update(ns).update(Buffer.from(name2, "utf8")).digest().subarray(0, 16)
16899
17060
  );
16900
17061
  bytes[6] = bytes[6] & 15 | 80;
16901
17062
  bytes[8] = bytes[8] & 63 | 128;
@@ -17099,12 +17260,12 @@ function buildRetainStamp(cfg, ctx) {
17099
17260
  }
17100
17261
 
17101
17262
  // src/core/session-start.ts
17102
- import { readFileSync as readFileSync6 } from "fs";
17263
+ import { readFileSync as readFileSync7 } from "fs";
17103
17264
 
17104
17265
  // src/core/skill-sync.ts
17105
17266
  import { cpSync, existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
17106
17267
  import { homedir as homedir6 } from "os";
17107
- import { dirname as dirname8, join as join11 } from "path";
17268
+ import { dirname as dirname8, join as join12 } from "path";
17108
17269
  import { fileURLToPath as fileURLToPath5 } from "url";
17109
17270
 
17110
17271
  // src/core/brand.ts
@@ -17121,29 +17282,66 @@ function brandWord() {
17121
17282
  return `${out}\x1B[0m`;
17122
17283
  }
17123
17284
 
17285
+ // src/core/legacy.ts
17286
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17287
+ import { homedir as homedir7 } from "os";
17288
+ import { join as join13, relative, isAbsolute as isAbsolute2 } from "path";
17289
+ var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17290
+ function detectLegacyClaudePlugin(cwd, claudeDir = join13(homedir7(), ".claude")) {
17291
+ const registry2 = readJson(join13(claudeDir, "plugins", "installed_plugins.json"));
17292
+ const plugins = registry2?.plugins;
17293
+ if (!plugins || typeof plugins !== "object") return void 0;
17294
+ const enabled = readJson(join13(claudeDir, "settings.json"))?.enabledPlugins;
17295
+ for (const [key, raw] of Object.entries(plugins)) {
17296
+ if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
17297
+ if (enabled && enabled[key] === false) continue;
17298
+ const installs = Array.isArray(raw) ? raw : [raw];
17299
+ const active = installs.some((i) => {
17300
+ if (!i || typeof i !== "object") return false;
17301
+ if (typeof i.projectPath !== "string") return true;
17302
+ const rel = relative(i.projectPath, cwd);
17303
+ return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
17304
+ });
17305
+ if (active) return key;
17306
+ }
17307
+ return void 0;
17308
+ }
17309
+ function readJson(path) {
17310
+ try {
17311
+ const parsed = JSON.parse(readFileSync5(path, "utf8"));
17312
+ return parsed && typeof parsed === "object" ? parsed : void 0;
17313
+ } catch {
17314
+ return void 0;
17315
+ }
17316
+ }
17317
+ function legacyClaudePluginWarning(key) {
17318
+ 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.
17319
+ \u21B3 remove it: claude plugin uninstall ${key}`;
17320
+ }
17321
+
17124
17322
  // src/core/session-cache.ts
17125
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
17126
- import { tmpdir as tmpdir3 } from "os";
17127
- import { dirname as dirname9, join as join12 } from "path";
17323
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync6, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17324
+ import { tmpdir as tmpdir4 } from "os";
17325
+ import { dirname as dirname9, join as join14 } from "path";
17128
17326
  function sessionCacheFile(harness, sessionId) {
17129
- return join12(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
17327
+ return join14(tmpdir4(), `hindsight-${harness}`, `${sessionId}.json`);
17130
17328
  }
17131
17329
  function readSessionCache(cacheFile) {
17132
17330
  try {
17133
- return JSON.parse(readFileSync5(cacheFile, "utf8"));
17331
+ return JSON.parse(readFileSync6(cacheFile, "utf8"));
17134
17332
  } catch {
17135
17333
  return {};
17136
17334
  }
17137
17335
  }
17138
17336
  function writeFileAtomic(path, body) {
17139
- mkdirSync3(dirname9(path), { recursive: true });
17337
+ mkdirSync4(dirname9(path), { recursive: true });
17140
17338
  const tmp = `${path}.${process.pid}.tmp`;
17141
17339
  try {
17142
- writeFileSync2(tmp, body);
17143
- renameSync(tmp, path);
17340
+ writeFileSync3(tmp, body);
17341
+ renameSync2(tmp, path);
17144
17342
  } catch (e) {
17145
17343
  try {
17146
- rmSync(tmp, { force: true });
17344
+ rmSync2(tmp, { force: true });
17147
17345
  } catch {
17148
17346
  }
17149
17347
  throw e;
@@ -17236,13 +17434,13 @@ async function buildSessionStartContext(args) {
17236
17434
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17237
17435
  if (docIds.size === 0) {
17238
17436
  if (cfg.codebaseSurvey !== false) {
17239
- startSurvey(cwd, {
17437
+ const started = await startSurvey(cwd, {
17240
17438
  harness,
17241
17439
  model: cfg.surveyModel,
17242
17440
  budgetUsd: cfg.surveyBudgetUsd
17243
17441
  });
17244
17442
  const sha = resolveHeadSha(cwd);
17245
- if (sha) recordSurveyBaseline(sha);
17443
+ if (started && sha) recordSurveyBaseline(sha);
17246
17444
  }
17247
17445
  diag(harness, "seed_started", { bank: bankId });
17248
17446
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
@@ -17259,17 +17457,19 @@ async function buildSessionStartContext(args) {
17259
17457
  const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
17260
17458
  const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
17261
17459
  if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
17262
- startSurvey(cwd, {
17460
+ const started = await startSurvey(cwd, {
17263
17461
  harness,
17264
17462
  model: cfg.surveyModel,
17265
17463
  budgetUsd: cfg.surveyBudgetUsd
17266
17464
  });
17267
- recordSurveyBaseline(sha);
17268
- diag(harness, "survey_refresh", {
17269
- bank: bankId,
17270
- commits: sinceLast,
17271
- retry: findingsAbsent
17272
- });
17465
+ if (started) {
17466
+ recordSurveyBaseline(sha);
17467
+ diag(harness, "survey_refresh", {
17468
+ bank: bankId,
17469
+ commits: sinceLast,
17470
+ retry: findingsAbsent
17471
+ });
17472
+ }
17273
17473
  } else if (sinceLast === null) {
17274
17474
  recordSurveyBaseline(sha);
17275
17475
  }
@@ -17302,12 +17502,19 @@ async function buildSessionStartContext(args) {
17302
17502
  }).catch(() => void 0);
17303
17503
  }
17304
17504
  systemMessage = buildSeedBanner(bankId, cold === true, gitNote);
17505
+ const detectLegacy = args.detectLegacyPlugin ?? (harness === "claude-code" ? detectLegacyClaudePlugin : void 0);
17506
+ const legacyPlugin = detectLegacy?.(cwd);
17507
+ if (legacyPlugin) {
17508
+ systemMessage += `
17509
+ ${legacyClaudePluginWarning(legacyPlugin)}`;
17510
+ diag(harness, "legacy_plugin_active", { plugin: legacyPlugin });
17511
+ }
17305
17512
  diag(harness, "session_start", { bank: bankId, cold, pages: pages.length, ms: Date.now() - t0 });
17306
17513
  return { systemMessage, additionalContext, deferInitialReflect };
17307
17514
  }
17308
17515
 
17309
17516
  // src/core/hook.ts
17310
- import { existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
17517
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
17311
17518
 
17312
17519
  // src/core/inject.ts
17313
17520
  function buildReflectQuery(prompt) {
@@ -17325,6 +17532,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
17325
17532
  - Do not connect unrelated episodes into one narrative; if two facts are not explicitly linked in the record, report them separately or leave the weaker one out.
17326
17533
  - If the bank holds nothing that bears on the goal, say so in one line.`;
17327
17534
  }
17535
+ function formatPageFallback(hits) {
17536
+ return "(Hindsight's synthesis was unavailable this turn; these knowledge pages matched the goal by search. Read one with hindsight_read_knowledge_page(<id>) if it looks relevant.)\n" + hits.map((h) => {
17537
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
17538
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
17539
+ }).join("\n");
17540
+ }
17541
+ function formatObservationFallback(observations) {
17542
+ return "(Hindsight's synthesis was unavailable this turn; these consolidated observations were recalled from the bank for the goal, unsynthesized.)\n" + observations.map((o) => `- ${o.replace(/\s+/g, " ").trim()}`).join("\n");
17543
+ }
17328
17544
  function buildSystemInjection(memory) {
17329
17545
  return `<hindsight_memory>
17330
17546
  Automatically retrieved by Hindsight from THIS repository's own history (git rationale and past developer sessions) \u2014 real memory, but retrieval is heuristic: it may or may not bear on the current task.
@@ -17339,9 +17555,9 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
17339
17555
  }
17340
17556
 
17341
17557
  // src/core/turn-journal.ts
17342
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync7, statSync } from "fs";
17343
- import { tmpdir as tmpdir4 } from "os";
17344
- import { dirname as dirname10, join as join13 } from "path";
17558
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync8, statSync as statSync2 } from "fs";
17559
+ import { tmpdir as tmpdir5 } from "os";
17560
+ import { dirname as dirname10, join as join15 } from "path";
17345
17561
 
17346
17562
  // src/core/transcript-util.ts
17347
17563
  var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
@@ -17382,7 +17598,52 @@ function actionLine(tool, input) {
17382
17598
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17383
17599
 
17384
17600
  // src/core/hook.ts
17385
- var HOOK_REFLECT_CAP_MS = 25e3;
17601
+ var HOOK_REFLECT_CAP_MS = 2e4;
17602
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
17603
+ var FALLBACK_PAGE_LIMIT = 3;
17604
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
17605
+ async function reflectFallback(harness, prompt, client) {
17606
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
17607
+ const remaining = () => Math.max(deadline - Date.now(), 1);
17608
+ const query = prompt.slice(0, 500);
17609
+ let t0 = Date.now();
17610
+ try {
17611
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17612
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17613
+ if (hits.length) {
17614
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17615
+ }
17616
+ } catch (e) {
17617
+ diag(harness, "reflect_fallback_pages_failed", {
17618
+ ms: Date.now() - t0,
17619
+ error: describeError(e)
17620
+ });
17621
+ }
17622
+ t0 = Date.now();
17623
+ try {
17624
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
17625
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
17626
+ timeoutMs: remaining()
17627
+ });
17628
+ diag(harness, "reflect_fallback_observations", {
17629
+ ms: Date.now() - t0,
17630
+ count: observations.length
17631
+ });
17632
+ if (observations.length) {
17633
+ return {
17634
+ memory: formatObservationFallback(observations),
17635
+ source: "observations",
17636
+ count: observations.length
17637
+ };
17638
+ }
17639
+ } catch (e) {
17640
+ diag(harness, "reflect_fallback_observations_failed", {
17641
+ ms: Date.now() - t0,
17642
+ error: describeError(e)
17643
+ });
17644
+ }
17645
+ return void 0;
17646
+ }
17386
17647
  async function buildHookOutput(args) {
17387
17648
  const { harness, prompt, cfg, client, cacheFile } = args;
17388
17649
  const cached2 = readSessionCache(cacheFile);
@@ -17390,19 +17651,21 @@ async function buildHookOutput(args) {
17390
17651
  let reflectAnswer = cached2.reflectAnswer;
17391
17652
  let reflectRanThisTurn = false;
17392
17653
  let reflectFailed = false;
17654
+ let fallback;
17393
17655
  const deferInitialReflect = cached2.deferInitialReflect === true;
17394
17656
  if (deferInitialReflect) {
17395
17657
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
17396
17658
  } else if (cfg.autoReflect && reflectAnswer === void 0) {
17397
17659
  reflectRanThisTurn = true;
17398
17660
  const t0 = Date.now();
17661
+ const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17399
17662
  try {
17400
17663
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17401
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17664
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
17402
17665
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17403
17666
  // tool still get the deeper high-budget path.
17404
17667
  budget: "low",
17405
- timeoutMs: Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS)
17668
+ timeoutMs
17406
17669
  });
17407
17670
  diag(harness, reflectAnswer ? "reflect_ok" : "reflect_empty", {
17408
17671
  ms: Date.now() - t0,
@@ -17420,9 +17683,16 @@ async function buildHookOutput(args) {
17420
17683
  });
17421
17684
  diag(harness, "reflect_failed", {
17422
17685
  ms: Date.now() - t0,
17423
- error: describeError(e),
17686
+ bank: client.bank,
17687
+ timeoutMs,
17688
+ // Wider than describeError's default: the server's error body is the useful part.
17689
+ error: describeError(e, 1500),
17424
17690
  query: prompt.slice(0, 80)
17425
17691
  });
17692
+ if (e instanceof ReflectError && e.fallbackEligible) {
17693
+ fallback = await reflectFallback(harness, prompt, client);
17694
+ if (fallback) reflectAnswer = fallback.memory;
17695
+ }
17426
17696
  }
17427
17697
  }
17428
17698
  const cadence = cfg.pageRefreshEveryTurns;
@@ -17456,7 +17726,10 @@ async function buildHookOutput(args) {
17456
17726
  }
17457
17727
  const kept = blocks.filter(Boolean);
17458
17728
  let notice;
17459
- if (reflectRanThisTurn && reflectAnswer) {
17729
+ if (fallback) {
17730
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17731
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17732
+ } else if (reflectRanThisTurn && reflectAnswer) {
17460
17733
  const q = prompt.replace(/\s+/g, " ").trim();
17461
17734
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
17462
17735
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();
@@ -17775,7 +18048,7 @@ function promptOf(messages) {
17775
18048
  }
17776
18049
  function injectionMessage(text) {
17777
18050
  return {
17778
- id: randomUUID(),
18051
+ id: randomUUID2(),
17779
18052
  role: "user",
17780
18053
  content: [{ type: "text", text }],
17781
18054
  source: { kind: "plugin", plugin: HINDSIGHT_PLUGIN, form: "recall" }