@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/cline.js CHANGED
@@ -676,6 +676,22 @@ var KnowledgePagesUnavailableError = class extends Error {
676
676
  }
677
677
  };
678
678
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
679
+ var ReflectError = class extends Error {
680
+ constructor(message, status, timedOut, options) {
681
+ super(message, options);
682
+ this.status = status;
683
+ this.timedOut = timedOut;
684
+ this.name = "ReflectError";
685
+ }
686
+ status;
687
+ timedOut;
688
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
689
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
690
+ * every endpoint (auth, missing bank), so it is not. */
691
+ get fallbackEligible() {
692
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
693
+ }
694
+ };
679
695
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
680
696
  var POLL_CYCLE_MS = 5e3;
681
697
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -759,11 +775,11 @@ var HindsightClient = class {
759
775
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
760
776
  }
761
777
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
762
- async req(method, url2, body, tolerate = []) {
778
+ async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
763
779
  const r = await this.fetchWithAuth(url2, {
764
780
  method,
765
781
  body: body ? JSON.stringify(body) : void 0,
766
- signal: AbortSignal.timeout(15e3)
782
+ signal: AbortSignal.timeout(timeoutMs)
767
783
  });
768
784
  if (r.status === 429 && !tolerate.includes(429))
769
785
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -956,7 +972,7 @@ var HindsightClient = class {
956
972
  /**
957
973
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
958
974
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
959
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
975
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
960
976
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
961
977
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
962
978
  */
@@ -969,13 +985,46 @@ var HindsightClient = class {
969
985
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
970
986
  signal: ctrl.signal
971
987
  });
972
- if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
988
+ if (!resp.ok)
989
+ throw new ReflectError(
990
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
991
+ resp.status,
992
+ false
993
+ );
973
994
  const data = await resp.json();
974
995
  return (data.text || "").trim();
996
+ } catch (e) {
997
+ if (ctrl.signal.aborted)
998
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
999
+ cause: e
1000
+ });
1001
+ throw e;
975
1002
  } finally {
976
1003
  clearTimeout(timer);
977
1004
  }
978
1005
  }
1006
+ /**
1007
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
1008
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
1009
+ */
1010
+ async recallObservations(query, opts) {
1011
+ const r = await this.req(
1012
+ "POST",
1013
+ this.bankUrl("/memories/recall"),
1014
+ {
1015
+ query,
1016
+ types: ["observation"],
1017
+ budget: "low",
1018
+ max_tokens: opts.maxTokens,
1019
+ include: { entities: null }
1020
+ },
1021
+ [],
1022
+ opts.timeoutMs
1023
+ );
1024
+ if (r.status === 404) return [];
1025
+ const j = await r.json();
1026
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
1027
+ }
979
1028
  /**
980
1029
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
981
1030
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -1040,10 +1089,16 @@ var HindsightClient = class {
1040
1089
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
1041
1090
  * Returns page-level hits with a relevance snippet — the real search behind
1042
1091
  * hindsight_search_knowledge_pages. */
1043
- async searchKnowledgePages(query, limit = 3) {
1092
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
1044
1093
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
1045
1094
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
1046
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
1095
+ const r = await this.req(
1096
+ "GET",
1097
+ this.bankUrl(`/knowledge-base/search${q}`),
1098
+ void 0,
1099
+ [],
1100
+ timeoutMs
1101
+ );
1047
1102
  const j = await r.json();
1048
1103
  return (j.results ?? []).map((x) => ({
1049
1104
  id: x.id,
@@ -16353,7 +16408,7 @@ config(en_default());
16353
16408
  // src/core/knowledge-tools.ts
16354
16409
  import { existsSync as existsSync4 } from "fs";
16355
16410
  import { homedir as homedir5 } from "os";
16356
- import { join as join10 } from "path";
16411
+ import { join as join11 } from "path";
16357
16412
 
16358
16413
  // src/core/status.ts
16359
16414
  import { execFileSync as execFileSync3 } from "child_process";
@@ -16439,11 +16494,86 @@ ${toolGuide(opts)}
16439
16494
  }
16440
16495
 
16441
16496
  // src/core/survey.ts
16442
- import { spawn as realSpawn4 } from "child_process";
16497
+ import { spawn as realSpawn5 } from "child_process";
16498
+ import { createHash as createHash2 } from "crypto";
16443
16499
  import { existsSync as existsSync3 } from "fs";
16444
- import { homedir as homedir4 } from "os";
16445
- import { dirname as dirname7, join as join9 } from "path";
16500
+ import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
16501
+ import { dirname as dirname7, join as join10 } from "path";
16446
16502
  import { fileURLToPath as fileURLToPath4 } from "url";
16503
+
16504
+ // src/core/survey-lease.ts
16505
+ import { spawn as realSpawn4 } from "child_process";
16506
+ import { randomUUID } from "crypto";
16507
+ import {
16508
+ mkdirSync as mkdirSync3,
16509
+ mkdtempSync,
16510
+ readdirSync,
16511
+ renameSync,
16512
+ rmdirSync,
16513
+ rmSync,
16514
+ statSync,
16515
+ unlinkSync as unlinkSync2,
16516
+ utimesSync,
16517
+ writeFileSync as writeFileSync2
16518
+ } from "fs";
16519
+ import { join as join9 } from "path";
16520
+ var LEASE_STALE_MS = 3e4;
16521
+ var SURVEY_SPEC_ENV = "HINDSIGHT_SURVEY_SPEC";
16522
+ function tryRename(from, to) {
16523
+ try {
16524
+ renameSync(from, to);
16525
+ return true;
16526
+ } catch {
16527
+ return false;
16528
+ }
16529
+ }
16530
+ function releaseLease(lease) {
16531
+ try {
16532
+ unlinkSync2(join9(lease.directory, lease.owner));
16533
+ } catch {
16534
+ return;
16535
+ }
16536
+ try {
16537
+ rmdirSync(lease.directory);
16538
+ } catch {
16539
+ }
16540
+ }
16541
+ function reclaimIfStale(directory, staleMs) {
16542
+ const owners = readdirSync(directory);
16543
+ if (owners.length === 0) {
16544
+ try {
16545
+ rmdirSync(directory);
16546
+ } catch {
16547
+ }
16548
+ return true;
16549
+ }
16550
+ if (owners.length !== 1) return false;
16551
+ const age = Date.now() - statSync(join9(directory, owners[0])).mtimeMs;
16552
+ if (Math.abs(age) <= staleMs) return false;
16553
+ releaseLease({ directory, owner: owners[0] });
16554
+ return true;
16555
+ }
16556
+ function acquireLease(root, key, staleMs = LEASE_STALE_MS) {
16557
+ let staging;
16558
+ try {
16559
+ mkdirSync3(root, { recursive: true, mode: 448 });
16560
+ staging = mkdtempSync(join9(root, "claim-"));
16561
+ const owner = randomUUID();
16562
+ writeFileSync2(join9(staging, owner), "", { flag: "wx", mode: 384 });
16563
+ const directory = join9(root, `survey-${key}.lock`);
16564
+ if (!tryRename(staging, directory)) {
16565
+ if (!reclaimIfStale(directory, staleMs)) return void 0;
16566
+ if (!tryRename(staging, directory)) return void 0;
16567
+ }
16568
+ return { directory, owner };
16569
+ } catch {
16570
+ return void 0;
16571
+ } finally {
16572
+ if (staging) rmSync(staging, { recursive: true, force: true });
16573
+ }
16574
+ }
16575
+
16576
+ // src/core/survey.ts
16447
16577
  var SURVEY_DOC_IDS = [
16448
16578
  "repository-component-map",
16449
16579
  "repository-core-concepts",
@@ -16453,7 +16583,7 @@ var SURVEY_DOC_IDS = [
16453
16583
  function resolveClaudeBin(explicit) {
16454
16584
  if (explicit) return explicit;
16455
16585
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
16456
- const nativeInstallPath = join9(homedir4(), ".claude", "local", "claude");
16586
+ const nativeInstallPath = join10(homedir4(), ".claude", "local", "claude");
16457
16587
  try {
16458
16588
  if (existsSync3(nativeInstallPath)) return nativeInstallPath;
16459
16589
  } catch {
@@ -16567,11 +16697,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
16567
16697
  }
16568
16698
  }
16569
16699
  }
16570
- function startCodebaseSurvey(repoDir, opts = {}) {
16700
+ async function startCodebaseSurvey(repoDir, opts = {}) {
16571
16701
  try {
16572
- const spawnFn = opts.spawn ?? realSpawn4;
16702
+ const spawnFn = opts.spawn ?? realSpawn5;
16573
16703
  const exists = opts.exists ?? binOnPath;
16574
- const mcpServerPath = opts.mcpServerPath ?? join9(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16704
+ const mcpServerPath = opts.mcpServerPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16575
16705
  const preferred = opts.harness ?? "claude-code";
16576
16706
  const order = [
16577
16707
  preferred,
@@ -16591,20 +16721,51 @@ function startCodebaseSurvey(repoDir, opts = {}) {
16591
16721
  budgetUsd: opts.budgetUsd,
16592
16722
  mcpServerPath
16593
16723
  });
16594
- const child = spawnFn(plan.bin, plan.args, {
16595
- cwd: repoDir,
16596
- detached: true,
16597
- stdio: "ignore",
16598
- windowsHide: true,
16599
- env: plan.env
16600
- });
16601
- child.on("error", () => {
16724
+ const { cfg, bankId } = resolveHostConfig(harness, repoDir);
16725
+ if (cfg.disabled) return false;
16726
+ const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
16727
+ const lease = acquireLease(
16728
+ opts.lease?.dir ?? join10(tmpdir3(), "hindsight-coding-agent", "surveys"),
16729
+ key,
16730
+ opts.lease?.staleMs ?? LEASE_STALE_MS
16731
+ );
16732
+ if (!lease) return false;
16733
+ const spec = {
16734
+ lease,
16735
+ bin: plan.bin,
16736
+ args: plan.args,
16737
+ ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
16738
+ };
16739
+ const supervisorPath = opts.supervisorPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
16740
+ return await new Promise((resolve3) => {
16741
+ try {
16742
+ const child = spawnFn("node", [supervisorPath], {
16743
+ cwd: repoDir,
16744
+ detached: true,
16745
+ stdio: "ignore",
16746
+ windowsHide: true,
16747
+ env: { ...plan.env, [SURVEY_SPEC_ENV]: JSON.stringify(spec) }
16748
+ });
16749
+ let spawned = false;
16750
+ child.on("error", () => {
16751
+ if (spawned) return;
16752
+ releaseLease(lease);
16753
+ resolve3(false);
16754
+ });
16755
+ child.once("spawn", () => {
16756
+ spawned = true;
16757
+ child.unref();
16758
+ resolve3(true);
16759
+ });
16760
+ } catch {
16761
+ releaseLease(lease);
16762
+ resolve3(false);
16763
+ }
16602
16764
  });
16603
- child.unref();
16604
- return;
16605
16765
  }
16606
16766
  } catch {
16607
16767
  }
16768
+ return false;
16608
16769
  }
16609
16770
 
16610
16771
  // src/core/status.ts
@@ -16717,7 +16878,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16717
16878
  inputSchema: {},
16718
16879
  annotations: READ_ONLY_ANNOTATIONS,
16719
16880
  handler: async (_args) => {
16720
- const configPath = process.env.HINDSIGHT_CONFIG || join10(homedir5(), ".hindsight", "coding-agent.json");
16881
+ const configPath = process.env.HINDSIGHT_CONFIG || join11(homedir5(), ".hindsight", "coding-agent.json");
16721
16882
  const harness = opts.harness ?? "unknown";
16722
16883
  const cfg = applyBankConfig(
16723
16884
  loadConfig({ harness: opts.harness }),
@@ -16853,7 +17014,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16853
17014
  }
16854
17015
 
16855
17016
  // src/core/retain-cursor.ts
16856
- import { createHash as createHash2 } from "crypto";
17017
+ import { createHash as createHash3 } from "crypto";
16857
17018
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
16858
17019
  var PENDING_MAX_BYTES = 256 * 1024;
16859
17020
  function pendingReplayable(cursor, now) {
@@ -16863,7 +17024,7 @@ function pendingReplayable(cursor, now) {
16863
17024
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
16864
17025
  }
16865
17026
  function fingerprintTurns(turns, count) {
16866
- const h = createHash2("sha1").update(String(count));
17027
+ const h = createHash3("sha1").update(String(count));
16867
17028
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
16868
17029
  return h.digest("hex");
16869
17030
  }
@@ -16886,13 +17047,13 @@ function memoryCursorStore() {
16886
17047
  }
16887
17048
 
16888
17049
  // src/core/uuid.ts
16889
- import { createHash as createHash3 } from "crypto";
17050
+ import { createHash as createHash4 } from "crypto";
16890
17051
  var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
16891
17052
  function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
16892
17053
  const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
16893
17054
  if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
16894
17055
  const bytes = Buffer.from(
16895
- createHash3("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
17056
+ createHash4("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
16896
17057
  );
16897
17058
  bytes[6] = bytes[6] & 15 | 80;
16898
17059
  bytes[8] = bytes[8] & 63 | 128;
@@ -17096,12 +17257,12 @@ function buildRetainStamp(cfg, ctx) {
17096
17257
  }
17097
17258
 
17098
17259
  // src/core/session-start.ts
17099
- import { readFileSync as readFileSync6 } from "fs";
17260
+ import { readFileSync as readFileSync7 } from "fs";
17100
17261
 
17101
17262
  // src/core/skill-sync.ts
17102
17263
  import { cpSync, existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
17103
17264
  import { homedir as homedir6 } from "os";
17104
- import { dirname as dirname8, join as join11 } from "path";
17265
+ import { dirname as dirname8, join as join12 } from "path";
17105
17266
  import { fileURLToPath as fileURLToPath5 } from "url";
17106
17267
 
17107
17268
  // src/core/brand.ts
@@ -17118,29 +17279,66 @@ function brandWord() {
17118
17279
  return `${out}\x1B[0m`;
17119
17280
  }
17120
17281
 
17282
+ // src/core/legacy.ts
17283
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17284
+ import { homedir as homedir7 } from "os";
17285
+ import { join as join13, relative, isAbsolute as isAbsolute2 } from "path";
17286
+ var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17287
+ function detectLegacyClaudePlugin(cwd, claudeDir = join13(homedir7(), ".claude")) {
17288
+ const registry2 = readJson(join13(claudeDir, "plugins", "installed_plugins.json"));
17289
+ const plugins = registry2?.plugins;
17290
+ if (!plugins || typeof plugins !== "object") return void 0;
17291
+ const enabled = readJson(join13(claudeDir, "settings.json"))?.enabledPlugins;
17292
+ for (const [key, raw] of Object.entries(plugins)) {
17293
+ if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
17294
+ if (enabled && enabled[key] === false) continue;
17295
+ const installs = Array.isArray(raw) ? raw : [raw];
17296
+ const active = installs.some((i) => {
17297
+ if (!i || typeof i !== "object") return false;
17298
+ if (typeof i.projectPath !== "string") return true;
17299
+ const rel = relative(i.projectPath, cwd);
17300
+ return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
17301
+ });
17302
+ if (active) return key;
17303
+ }
17304
+ return void 0;
17305
+ }
17306
+ function readJson(path) {
17307
+ try {
17308
+ const parsed = JSON.parse(readFileSync5(path, "utf8"));
17309
+ return parsed && typeof parsed === "object" ? parsed : void 0;
17310
+ } catch {
17311
+ return void 0;
17312
+ }
17313
+ }
17314
+ function legacyClaudePluginWarning(key) {
17315
+ 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.
17316
+ \u21B3 remove it: claude plugin uninstall ${key}`;
17317
+ }
17318
+
17121
17319
  // src/core/session-cache.ts
17122
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
17123
- import { tmpdir as tmpdir3 } from "os";
17124
- import { dirname as dirname9, join as join12 } from "path";
17320
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync6, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17321
+ import { tmpdir as tmpdir4 } from "os";
17322
+ import { dirname as dirname9, join as join14 } from "path";
17125
17323
  function sessionCacheFile(harness, sessionId2) {
17126
- return join12(tmpdir3(), `hindsight-${harness}`, `${sessionId2}.json`);
17324
+ return join14(tmpdir4(), `hindsight-${harness}`, `${sessionId2}.json`);
17127
17325
  }
17128
17326
  function readSessionCache(cacheFile) {
17129
17327
  try {
17130
- return JSON.parse(readFileSync5(cacheFile, "utf8"));
17328
+ return JSON.parse(readFileSync6(cacheFile, "utf8"));
17131
17329
  } catch {
17132
17330
  return {};
17133
17331
  }
17134
17332
  }
17135
17333
  function writeFileAtomic(path, body) {
17136
- mkdirSync3(dirname9(path), { recursive: true });
17334
+ mkdirSync4(dirname9(path), { recursive: true });
17137
17335
  const tmp = `${path}.${process.pid}.tmp`;
17138
17336
  try {
17139
- writeFileSync2(tmp, body);
17140
- renameSync(tmp, path);
17337
+ writeFileSync3(tmp, body);
17338
+ renameSync2(tmp, path);
17141
17339
  } catch (e) {
17142
17340
  try {
17143
- rmSync(tmp, { force: true });
17341
+ rmSync2(tmp, { force: true });
17144
17342
  } catch {
17145
17343
  }
17146
17344
  throw e;
@@ -17233,13 +17431,13 @@ async function buildSessionStartContext(args) {
17233
17431
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17234
17432
  if (docIds.size === 0) {
17235
17433
  if (cfg.codebaseSurvey !== false) {
17236
- startSurvey(cwd, {
17434
+ const started = await startSurvey(cwd, {
17237
17435
  harness,
17238
17436
  model: cfg.surveyModel,
17239
17437
  budgetUsd: cfg.surveyBudgetUsd
17240
17438
  });
17241
17439
  const sha = resolveHeadSha(cwd);
17242
- if (sha) recordSurveyBaseline(sha);
17440
+ if (started && sha) recordSurveyBaseline(sha);
17243
17441
  }
17244
17442
  diag(harness, "seed_started", { bank: bankId });
17245
17443
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
@@ -17256,17 +17454,19 @@ async function buildSessionStartContext(args) {
17256
17454
  const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
17257
17455
  const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
17258
17456
  if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
17259
- startSurvey(cwd, {
17457
+ const started = await startSurvey(cwd, {
17260
17458
  harness,
17261
17459
  model: cfg.surveyModel,
17262
17460
  budgetUsd: cfg.surveyBudgetUsd
17263
17461
  });
17264
- recordSurveyBaseline(sha);
17265
- diag(harness, "survey_refresh", {
17266
- bank: bankId,
17267
- commits: sinceLast,
17268
- retry: findingsAbsent
17269
- });
17462
+ if (started) {
17463
+ recordSurveyBaseline(sha);
17464
+ diag(harness, "survey_refresh", {
17465
+ bank: bankId,
17466
+ commits: sinceLast,
17467
+ retry: findingsAbsent
17468
+ });
17469
+ }
17270
17470
  } else if (sinceLast === null) {
17271
17471
  recordSurveyBaseline(sha);
17272
17472
  }
@@ -17299,12 +17499,19 @@ async function buildSessionStartContext(args) {
17299
17499
  }).catch(() => void 0);
17300
17500
  }
17301
17501
  systemMessage = buildSeedBanner(bankId, cold === true, gitNote);
17502
+ const detectLegacy = args.detectLegacyPlugin ?? (harness === "claude-code" ? detectLegacyClaudePlugin : void 0);
17503
+ const legacyPlugin = detectLegacy?.(cwd);
17504
+ if (legacyPlugin) {
17505
+ systemMessage += `
17506
+ ${legacyClaudePluginWarning(legacyPlugin)}`;
17507
+ diag(harness, "legacy_plugin_active", { plugin: legacyPlugin });
17508
+ }
17302
17509
  diag(harness, "session_start", { bank: bankId, cold, pages: pages.length, ms: Date.now() - t0 });
17303
17510
  return { systemMessage, additionalContext, deferInitialReflect };
17304
17511
  }
17305
17512
 
17306
17513
  // src/core/hook.ts
17307
- import { existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
17514
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
17308
17515
 
17309
17516
  // src/core/inject.ts
17310
17517
  function buildReflectQuery(prompt) {
@@ -17322,6 +17529,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
17322
17529
  - 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.
17323
17530
  - If the bank holds nothing that bears on the goal, say so in one line.`;
17324
17531
  }
17532
+ function formatPageFallback(hits) {
17533
+ 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) => {
17534
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
17535
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
17536
+ }).join("\n");
17537
+ }
17538
+ function formatObservationFallback(observations) {
17539
+ 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");
17540
+ }
17325
17541
  function buildSystemInjection(memory) {
17326
17542
  return `<hindsight_memory>
17327
17543
  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.
@@ -17336,13 +17552,58 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
17336
17552
  }
17337
17553
 
17338
17554
  // src/core/turn-journal.ts
17339
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync7, statSync } from "fs";
17340
- import { tmpdir as tmpdir4 } from "os";
17341
- import { dirname as dirname10, join as join13 } from "path";
17555
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync8, statSync as statSync2 } from "fs";
17556
+ import { tmpdir as tmpdir5 } from "os";
17557
+ import { dirname as dirname10, join as join15 } from "path";
17342
17558
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17343
17559
 
17344
17560
  // src/core/hook.ts
17345
- var HOOK_REFLECT_CAP_MS = 25e3;
17561
+ var HOOK_REFLECT_CAP_MS = 2e4;
17562
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
17563
+ var FALLBACK_PAGE_LIMIT = 3;
17564
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
17565
+ async function reflectFallback(harness, prompt, client) {
17566
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
17567
+ const remaining = () => Math.max(deadline - Date.now(), 1);
17568
+ const query = prompt.slice(0, 500);
17569
+ let t0 = Date.now();
17570
+ try {
17571
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17572
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17573
+ if (hits.length) {
17574
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17575
+ }
17576
+ } catch (e) {
17577
+ diag(harness, "reflect_fallback_pages_failed", {
17578
+ ms: Date.now() - t0,
17579
+ error: describeError(e)
17580
+ });
17581
+ }
17582
+ t0 = Date.now();
17583
+ try {
17584
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
17585
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
17586
+ timeoutMs: remaining()
17587
+ });
17588
+ diag(harness, "reflect_fallback_observations", {
17589
+ ms: Date.now() - t0,
17590
+ count: observations.length
17591
+ });
17592
+ if (observations.length) {
17593
+ return {
17594
+ memory: formatObservationFallback(observations),
17595
+ source: "observations",
17596
+ count: observations.length
17597
+ };
17598
+ }
17599
+ } catch (e) {
17600
+ diag(harness, "reflect_fallback_observations_failed", {
17601
+ ms: Date.now() - t0,
17602
+ error: describeError(e)
17603
+ });
17604
+ }
17605
+ return void 0;
17606
+ }
17346
17607
  async function buildHookOutput(args) {
17347
17608
  const { harness, prompt, cfg, client, cacheFile } = args;
17348
17609
  const cached2 = readSessionCache(cacheFile);
@@ -17350,19 +17611,21 @@ async function buildHookOutput(args) {
17350
17611
  let reflectAnswer = cached2.reflectAnswer;
17351
17612
  let reflectRanThisTurn = false;
17352
17613
  let reflectFailed = false;
17614
+ let fallback;
17353
17615
  const deferInitialReflect = cached2.deferInitialReflect === true;
17354
17616
  if (deferInitialReflect) {
17355
17617
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
17356
17618
  } else if (cfg.autoReflect && reflectAnswer === void 0) {
17357
17619
  reflectRanThisTurn = true;
17358
17620
  const t0 = Date.now();
17621
+ const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17359
17622
  try {
17360
17623
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17361
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17624
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
17362
17625
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17363
17626
  // tool still get the deeper high-budget path.
17364
17627
  budget: "low",
17365
- timeoutMs: Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS)
17628
+ timeoutMs
17366
17629
  });
17367
17630
  diag(harness, reflectAnswer ? "reflect_ok" : "reflect_empty", {
17368
17631
  ms: Date.now() - t0,
@@ -17380,9 +17643,16 @@ async function buildHookOutput(args) {
17380
17643
  });
17381
17644
  diag(harness, "reflect_failed", {
17382
17645
  ms: Date.now() - t0,
17383
- error: describeError(e),
17646
+ bank: client.bank,
17647
+ timeoutMs,
17648
+ // Wider than describeError's default: the server's error body is the useful part.
17649
+ error: describeError(e, 1500),
17384
17650
  query: prompt.slice(0, 80)
17385
17651
  });
17652
+ if (e instanceof ReflectError && e.fallbackEligible) {
17653
+ fallback = await reflectFallback(harness, prompt, client);
17654
+ if (fallback) reflectAnswer = fallback.memory;
17655
+ }
17386
17656
  }
17387
17657
  }
17388
17658
  const cadence = cfg.pageRefreshEveryTurns;
@@ -17416,7 +17686,10 @@ async function buildHookOutput(args) {
17416
17686
  }
17417
17687
  const kept = blocks.filter(Boolean);
17418
17688
  let notice;
17419
- if (reflectRanThisTurn && reflectAnswer) {
17689
+ if (fallback) {
17690
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17691
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17692
+ } else if (reflectRanThisTurn && reflectAnswer) {
17420
17693
  const q = prompt.replace(/\s+/g, " ").trim();
17421
17694
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
17422
17695
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();