@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/index.js CHANGED
@@ -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, url3, body, tolerate = []) {
781
+ async req(method, url3, body, tolerate = [], timeoutMs = 15e3) {
766
782
  const r = await this.fetchWithAuth(url3, {
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 {
@@ -16581,11 +16711,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
16581
16711
  }
16582
16712
  }
16583
16713
  }
16584
- function startCodebaseSurvey(repoDir, opts = {}) {
16714
+ async function startCodebaseSurvey(repoDir, opts = {}) {
16585
16715
  try {
16586
- const spawnFn = opts.spawn ?? realSpawn4;
16716
+ const spawnFn = opts.spawn ?? realSpawn5;
16587
16717
  const exists = opts.exists ?? binOnPath;
16588
- const mcpServerPath = opts.mcpServerPath ?? join9(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16718
+ const mcpServerPath = opts.mcpServerPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16589
16719
  const preferred = opts.harness ?? "claude-code";
16590
16720
  const order = [
16591
16721
  preferred,
@@ -16605,20 +16735,51 @@ function startCodebaseSurvey(repoDir, opts = {}) {
16605
16735
  budgetUsd: opts.budgetUsd,
16606
16736
  mcpServerPath
16607
16737
  });
16608
- const child = spawnFn(plan.bin, plan.args, {
16609
- cwd: repoDir,
16610
- detached: true,
16611
- stdio: "ignore",
16612
- windowsHide: true,
16613
- env: plan.env
16614
- });
16615
- child.on("error", () => {
16738
+ const { cfg, bankId } = resolveHostConfig(harness, repoDir);
16739
+ if (cfg.disabled) return false;
16740
+ const key = createHash2("sha256").update(JSON.stringify([cfg.apiUrl.replace(/\/+$/, ""), cfg.apiToken ?? "", bankId])).digest("hex");
16741
+ const lease = acquireLease(
16742
+ opts.lease?.dir ?? join10(tmpdir3(), "hindsight-coding-agent", "surveys"),
16743
+ key,
16744
+ opts.lease?.staleMs ?? LEASE_STALE_MS
16745
+ );
16746
+ if (!lease) return false;
16747
+ const spec = {
16748
+ lease,
16749
+ bin: plan.bin,
16750
+ args: plan.args,
16751
+ ...opts.lease?.heartbeatMs ? { heartbeatMs: opts.lease.heartbeatMs } : {}
16752
+ };
16753
+ const supervisorPath = opts.supervisorPath ?? join10(dirname7(fileURLToPath4(import.meta.url)), "survey-supervisor.js");
16754
+ return await new Promise((resolve3) => {
16755
+ try {
16756
+ const child = spawnFn("node", [supervisorPath], {
16757
+ cwd: repoDir,
16758
+ detached: true,
16759
+ stdio: "ignore",
16760
+ windowsHide: true,
16761
+ env: { ...plan.env, [SURVEY_SPEC_ENV]: JSON.stringify(spec) }
16762
+ });
16763
+ let spawned = false;
16764
+ child.on("error", () => {
16765
+ if (spawned) return;
16766
+ releaseLease(lease);
16767
+ resolve3(false);
16768
+ });
16769
+ child.once("spawn", () => {
16770
+ spawned = true;
16771
+ child.unref();
16772
+ resolve3(true);
16773
+ });
16774
+ } catch {
16775
+ releaseLease(lease);
16776
+ resolve3(false);
16777
+ }
16616
16778
  });
16617
- child.unref();
16618
- return;
16619
16779
  }
16620
16780
  } catch {
16621
16781
  }
16782
+ return false;
16622
16783
  }
16623
16784
 
16624
16785
  // src/core/status.ts
@@ -16731,7 +16892,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16731
16892
  inputSchema: {},
16732
16893
  annotations: READ_ONLY_ANNOTATIONS,
16733
16894
  handler: async (_args) => {
16734
- const configPath = process.env.HINDSIGHT_CONFIG || join10(homedir5(), ".hindsight", "coding-agent.json");
16895
+ const configPath = process.env.HINDSIGHT_CONFIG || join11(homedir5(), ".hindsight", "coding-agent.json");
16735
16896
  const harness = opts.harness ?? "unknown";
16736
16897
  const cfg = applyBankConfig(
16737
16898
  loadConfig({ harness: opts.harness }),
@@ -16867,7 +17028,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16867
17028
  }
16868
17029
 
16869
17030
  // src/core/retain-cursor.ts
16870
- import { createHash as createHash2 } from "crypto";
17031
+ import { createHash as createHash3 } from "crypto";
16871
17032
  var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
16872
17033
  var PENDING_MAX_BYTES = 256 * 1024;
16873
17034
  function pendingReplayable(cursor, now) {
@@ -16877,7 +17038,7 @@ function pendingReplayable(cursor, now) {
16877
17038
  return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
16878
17039
  }
16879
17040
  function fingerprintTurns(turns, count) {
16880
- const h = createHash2("sha1").update(String(count));
17041
+ const h = createHash3("sha1").update(String(count));
16881
17042
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
16882
17043
  return h.digest("hex");
16883
17044
  }
@@ -16900,13 +17061,13 @@ function memoryCursorStore() {
16900
17061
  }
16901
17062
 
16902
17063
  // src/core/uuid.ts
16903
- import { createHash as createHash3 } from "crypto";
17064
+ import { createHash as createHash4 } from "crypto";
16904
17065
  var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
16905
17066
  function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
16906
17067
  const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
16907
17068
  if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
16908
17069
  const bytes = Buffer.from(
16909
- createHash3("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
17070
+ createHash4("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
16910
17071
  );
16911
17072
  bytes[6] = bytes[6] & 15 | 80;
16912
17073
  bytes[8] = bytes[8] & 63 | 128;
@@ -17110,12 +17271,12 @@ function buildRetainStamp(cfg, ctx) {
17110
17271
  }
17111
17272
 
17112
17273
  // src/core/session-start.ts
17113
- import { readFileSync as readFileSync6 } from "fs";
17274
+ import { readFileSync as readFileSync7 } from "fs";
17114
17275
 
17115
17276
  // src/core/skill-sync.ts
17116
17277
  import { cpSync, existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
17117
17278
  import { homedir as homedir6 } from "os";
17118
- import { dirname as dirname8, join as join11 } from "path";
17279
+ import { dirname as dirname8, join as join12 } from "path";
17119
17280
  import { fileURLToPath as fileURLToPath5 } from "url";
17120
17281
 
17121
17282
  // src/core/brand.ts
@@ -17132,29 +17293,66 @@ function brandWord() {
17132
17293
  return `${out}\x1B[0m`;
17133
17294
  }
17134
17295
 
17296
+ // src/core/legacy.ts
17297
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "fs";
17298
+ import { homedir as homedir7 } from "os";
17299
+ import { join as join13, relative, isAbsolute as isAbsolute2 } from "path";
17300
+ var LEGACY_CLAUDE_PLUGIN = "hindsight-memory";
17301
+ function detectLegacyClaudePlugin(cwd, claudeDir = join13(homedir7(), ".claude")) {
17302
+ const registry3 = readJson(join13(claudeDir, "plugins", "installed_plugins.json"));
17303
+ const plugins = registry3?.plugins;
17304
+ if (!plugins || typeof plugins !== "object") return void 0;
17305
+ const enabled = readJson(join13(claudeDir, "settings.json"))?.enabledPlugins;
17306
+ for (const [key, raw] of Object.entries(plugins)) {
17307
+ if (key.split("@")[0] !== LEGACY_CLAUDE_PLUGIN) continue;
17308
+ if (enabled && enabled[key] === false) continue;
17309
+ const installs = Array.isArray(raw) ? raw : [raw];
17310
+ const active = installs.some((i) => {
17311
+ if (!i || typeof i !== "object") return false;
17312
+ if (typeof i.projectPath !== "string") return true;
17313
+ const rel = relative(i.projectPath, cwd);
17314
+ return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
17315
+ });
17316
+ if (active) return key;
17317
+ }
17318
+ return void 0;
17319
+ }
17320
+ function readJson(path) {
17321
+ try {
17322
+ const parsed = JSON.parse(readFileSync5(path, "utf8"));
17323
+ return parsed && typeof parsed === "object" ? parsed : void 0;
17324
+ } catch {
17325
+ return void 0;
17326
+ }
17327
+ }
17328
+ function legacyClaudePluginWarning(key) {
17329
+ 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.
17330
+ \u21B3 remove it: claude plugin uninstall ${key}`;
17331
+ }
17332
+
17135
17333
  // src/core/session-cache.ts
17136
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
17137
- import { tmpdir as tmpdir3 } from "os";
17138
- import { dirname as dirname9, join as join12 } from "path";
17334
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync6, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "fs";
17335
+ import { tmpdir as tmpdir4 } from "os";
17336
+ import { dirname as dirname9, join as join14 } from "path";
17139
17337
  function sessionCacheFile(harness, sessionId) {
17140
- return join12(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
17338
+ return join14(tmpdir4(), `hindsight-${harness}`, `${sessionId}.json`);
17141
17339
  }
17142
17340
  function readSessionCache(cacheFile) {
17143
17341
  try {
17144
- return JSON.parse(readFileSync5(cacheFile, "utf8"));
17342
+ return JSON.parse(readFileSync6(cacheFile, "utf8"));
17145
17343
  } catch {
17146
17344
  return {};
17147
17345
  }
17148
17346
  }
17149
17347
  function writeFileAtomic(path, body) {
17150
- mkdirSync3(dirname9(path), { recursive: true });
17348
+ mkdirSync4(dirname9(path), { recursive: true });
17151
17349
  const tmp = `${path}.${process.pid}.tmp`;
17152
17350
  try {
17153
- writeFileSync2(tmp, body);
17154
- renameSync(tmp, path);
17351
+ writeFileSync3(tmp, body);
17352
+ renameSync2(tmp, path);
17155
17353
  } catch (e) {
17156
17354
  try {
17157
- rmSync(tmp, { force: true });
17355
+ rmSync2(tmp, { force: true });
17158
17356
  } catch {
17159
17357
  }
17160
17358
  throw e;
@@ -17247,13 +17445,13 @@ async function buildSessionStartContext(args) {
17247
17445
  startSeed(cwd, { limit: cfg.seedLimit, harness });
17248
17446
  if (docIds.size === 0) {
17249
17447
  if (cfg.codebaseSurvey !== false) {
17250
- startSurvey(cwd, {
17448
+ const started = await startSurvey(cwd, {
17251
17449
  harness,
17252
17450
  model: cfg.surveyModel,
17253
17451
  budgetUsd: cfg.surveyBudgetUsd
17254
17452
  });
17255
17453
  const sha = resolveHeadSha(cwd);
17256
- if (sha) recordSurveyBaseline(sha);
17454
+ if (started && sha) recordSurveyBaseline(sha);
17257
17455
  }
17258
17456
  diag(harness, "seed_started", { bank: bankId });
17259
17457
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
@@ -17270,17 +17468,19 @@ async function buildSessionStartContext(args) {
17270
17468
  const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
17271
17469
  const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
17272
17470
  if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
17273
- startSurvey(cwd, {
17471
+ const started = await startSurvey(cwd, {
17274
17472
  harness,
17275
17473
  model: cfg.surveyModel,
17276
17474
  budgetUsd: cfg.surveyBudgetUsd
17277
17475
  });
17278
- recordSurveyBaseline(sha);
17279
- diag(harness, "survey_refresh", {
17280
- bank: bankId,
17281
- commits: sinceLast,
17282
- retry: findingsAbsent
17283
- });
17476
+ if (started) {
17477
+ recordSurveyBaseline(sha);
17478
+ diag(harness, "survey_refresh", {
17479
+ bank: bankId,
17480
+ commits: sinceLast,
17481
+ retry: findingsAbsent
17482
+ });
17483
+ }
17284
17484
  } else if (sinceLast === null) {
17285
17485
  recordSurveyBaseline(sha);
17286
17486
  }
@@ -17313,12 +17513,19 @@ async function buildSessionStartContext(args) {
17313
17513
  }).catch(() => void 0);
17314
17514
  }
17315
17515
  systemMessage = buildSeedBanner(bankId, cold === true, gitNote);
17516
+ const detectLegacy = args.detectLegacyPlugin ?? (harness === "claude-code" ? detectLegacyClaudePlugin : void 0);
17517
+ const legacyPlugin = detectLegacy?.(cwd);
17518
+ if (legacyPlugin) {
17519
+ systemMessage += `
17520
+ ${legacyClaudePluginWarning(legacyPlugin)}`;
17521
+ diag(harness, "legacy_plugin_active", { plugin: legacyPlugin });
17522
+ }
17316
17523
  diag(harness, "session_start", { bank: bankId, cold, pages: pages.length, ms: Date.now() - t0 });
17317
17524
  return { systemMessage, additionalContext, deferInitialReflect };
17318
17525
  }
17319
17526
 
17320
17527
  // src/core/hook.ts
17321
- import { existsSync as existsSync6, readFileSync as readFileSync8 } from "fs";
17528
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
17322
17529
 
17323
17530
  // src/core/inject.ts
17324
17531
  function buildReflectQuery(prompt) {
@@ -17336,6 +17543,15 @@ Report what this bank's history genuinely bears on that goal. Rendering rules, s
17336
17543
  - 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.
17337
17544
  - If the bank holds nothing that bears on the goal, say so in one line.`;
17338
17545
  }
17546
+ function formatPageFallback(hits) {
17547
+ 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) => {
17548
+ const snippet = h.snippet.replace(/\s+/g, " ").trim();
17549
+ return `- ${h.name} (${h.id})${snippet ? `: ${snippet}` : ""}`;
17550
+ }).join("\n");
17551
+ }
17552
+ function formatObservationFallback(observations) {
17553
+ 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");
17554
+ }
17339
17555
  function buildSystemInjection(memory) {
17340
17556
  return `<hindsight_memory>
17341
17557
  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.
@@ -17350,9 +17566,9 @@ If you VERIFY this memory is wrong or outdated (the code or facts contradict it)
17350
17566
  }
17351
17567
 
17352
17568
  // src/core/turn-journal.ts
17353
- import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync7, statSync } from "fs";
17354
- import { tmpdir as tmpdir4 } from "os";
17355
- import { dirname as dirname10, join as join13 } from "path";
17569
+ import { appendFileSync as appendFileSync3, mkdirSync as mkdirSync5, readFileSync as readFileSync8, statSync as statSync2 } from "fs";
17570
+ import { tmpdir as tmpdir5 } from "os";
17571
+ import { dirname as dirname10, join as join15 } from "path";
17356
17572
 
17357
17573
  // src/core/transcript-util.ts
17358
17574
  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;
@@ -17393,7 +17609,52 @@ function actionLine(tool2, input) {
17393
17609
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17394
17610
 
17395
17611
  // src/core/hook.ts
17396
- var HOOK_REFLECT_CAP_MS = 25e3;
17612
+ var HOOK_REFLECT_CAP_MS = 2e4;
17613
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
17614
+ var FALLBACK_PAGE_LIMIT = 3;
17615
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
17616
+ async function reflectFallback(harness, prompt, client) {
17617
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
17618
+ const remaining = () => Math.max(deadline - Date.now(), 1);
17619
+ const query = prompt.slice(0, 500);
17620
+ let t0 = Date.now();
17621
+ try {
17622
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17623
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17624
+ if (hits.length) {
17625
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17626
+ }
17627
+ } catch (e) {
17628
+ diag(harness, "reflect_fallback_pages_failed", {
17629
+ ms: Date.now() - t0,
17630
+ error: describeError(e)
17631
+ });
17632
+ }
17633
+ t0 = Date.now();
17634
+ try {
17635
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
17636
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
17637
+ timeoutMs: remaining()
17638
+ });
17639
+ diag(harness, "reflect_fallback_observations", {
17640
+ ms: Date.now() - t0,
17641
+ count: observations.length
17642
+ });
17643
+ if (observations.length) {
17644
+ return {
17645
+ memory: formatObservationFallback(observations),
17646
+ source: "observations",
17647
+ count: observations.length
17648
+ };
17649
+ }
17650
+ } catch (e) {
17651
+ diag(harness, "reflect_fallback_observations_failed", {
17652
+ ms: Date.now() - t0,
17653
+ error: describeError(e)
17654
+ });
17655
+ }
17656
+ return void 0;
17657
+ }
17397
17658
  async function buildHookOutput(args) {
17398
17659
  const { harness, prompt, cfg, client, cacheFile } = args;
17399
17660
  const cached3 = readSessionCache(cacheFile);
@@ -17401,19 +17662,21 @@ async function buildHookOutput(args) {
17401
17662
  let reflectAnswer = cached3.reflectAnswer;
17402
17663
  let reflectRanThisTurn = false;
17403
17664
  let reflectFailed = false;
17665
+ let fallback;
17404
17666
  const deferInitialReflect = cached3.deferInitialReflect === true;
17405
17667
  if (deferInitialReflect) {
17406
17668
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
17407
17669
  } else if (cfg.autoReflect && reflectAnswer === void 0) {
17408
17670
  reflectRanThisTurn = true;
17409
17671
  const t0 = Date.now();
17672
+ const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17410
17673
  try {
17411
17674
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17412
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17675
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
17413
17676
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17414
17677
  // tool still get the deeper high-budget path.
17415
17678
  budget: "low",
17416
- timeoutMs: Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS)
17679
+ timeoutMs
17417
17680
  });
17418
17681
  diag(harness, reflectAnswer ? "reflect_ok" : "reflect_empty", {
17419
17682
  ms: Date.now() - t0,
@@ -17431,9 +17694,16 @@ async function buildHookOutput(args) {
17431
17694
  });
17432
17695
  diag(harness, "reflect_failed", {
17433
17696
  ms: Date.now() - t0,
17434
- error: describeError(e),
17697
+ bank: client.bank,
17698
+ timeoutMs,
17699
+ // Wider than describeError's default: the server's error body is the useful part.
17700
+ error: describeError(e, 1500),
17435
17701
  query: prompt.slice(0, 80)
17436
17702
  });
17703
+ if (e instanceof ReflectError && e.fallbackEligible) {
17704
+ fallback = await reflectFallback(harness, prompt, client);
17705
+ if (fallback) reflectAnswer = fallback.memory;
17706
+ }
17437
17707
  }
17438
17708
  }
17439
17709
  const cadence = cfg.pageRefreshEveryTurns;
@@ -17467,7 +17737,10 @@ async function buildHookOutput(args) {
17467
17737
  }
17468
17738
  const kept = blocks.filter(Boolean);
17469
17739
  let notice;
17470
- if (reflectRanThisTurn && reflectAnswer) {
17740
+ if (fallback) {
17741
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17742
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17743
+ } else if (reflectRanThisTurn && reflectAnswer) {
17471
17744
  const q = prompt.replace(/\s+/g, " ").trim();
17472
17745
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
17473
17746
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();
@@ -30154,12 +30427,12 @@ function tool(input) {
30154
30427
  tool.schema = external_exports2;
30155
30428
 
30156
30429
  // src/harness/registry.ts
30157
- import { readFileSync as readFileSync9 } from "fs";
30430
+ import { readFileSync as readFileSync10 } from "fs";
30158
30431
  var jsonChatReader = (harness) => ({
30159
30432
  describe: `${harness} sessions via a normalized JSON export (--conversations file: [{ id, turns:[{role,text,timestamp?}] }])`,
30160
30433
  async read(opts) {
30161
30434
  if (!opts.conversations) return [];
30162
- return JSON.parse(readFileSync9(opts.conversations, "utf8"));
30435
+ return JSON.parse(readFileSync10(opts.conversations, "utf8"));
30163
30436
  }
30164
30437
  });
30165
30438