@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/opencode2.js CHANGED
@@ -15190,6 +15190,22 @@ var KnowledgePagesUnavailableError = class extends Error {
15190
15190
  }
15191
15191
  };
15192
15192
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
15193
+ var ReflectError = class extends Error {
15194
+ constructor(message, status, timedOut, options) {
15195
+ super(message, options);
15196
+ this.status = status;
15197
+ this.timedOut = timedOut;
15198
+ this.name = "ReflectError";
15199
+ }
15200
+ status;
15201
+ timedOut;
15202
+ /** A timeout or a 5xx means reflect's synthesis (the slow LLM path) broke, while the cheap
15203
+ * retrieval endpoints may still answer — worth falling back. A 4xx will fail the same way on
15204
+ * every endpoint (auth, missing bank), so it is not. */
15205
+ get fallbackEligible() {
15206
+ return this.timedOut || this.status !== void 0 && this.status >= 500;
15207
+ }
15208
+ };
15193
15209
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
15194
15210
  var POLL_CYCLE_MS = 5e3;
15195
15211
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
@@ -15273,11 +15289,11 @@ var HindsightClient = class {
15273
15289
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
15274
15290
  }
15275
15291
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
15276
- async req(method, url3, body, tolerate = []) {
15292
+ async req(method, url3, body, tolerate = [], timeoutMs = 15e3) {
15277
15293
  const r = await this.fetchWithAuth(url3, {
15278
15294
  method,
15279
15295
  body: body ? JSON.stringify(body) : void 0,
15280
- signal: AbortSignal.timeout(15e3)
15296
+ signal: AbortSignal.timeout(timeoutMs)
15281
15297
  });
15282
15298
  if (r.status === 429 && !tolerate.includes(429))
15283
15299
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
@@ -15470,7 +15486,7 @@ var HindsightClient = class {
15470
15486
  /**
15471
15487
  * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
15472
15488
  * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
15473
- * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
15489
+ * magnitude between the automatic hook (20s, to fit the host's window) and the agent-invoked
15474
15490
  * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
15475
15491
  * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
15476
15492
  */
@@ -15483,13 +15499,46 @@ var HindsightClient = class {
15483
15499
  body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
15484
15500
  signal: ctrl.signal
15485
15501
  });
15486
- if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
15502
+ if (!resp.ok)
15503
+ throw new ReflectError(
15504
+ `reflect ${resp.status} ${(await resp.text()).slice(0, 1e3)}${this.authHint(resp.status)}`,
15505
+ resp.status,
15506
+ false
15507
+ );
15487
15508
  const data = await resp.json();
15488
15509
  return (data.text || "").trim();
15510
+ } catch (e) {
15511
+ if (ctrl.signal.aborted)
15512
+ throw new ReflectError(`reflect timed out after ${opts.timeoutMs}ms`, void 0, true, {
15513
+ cause: e
15514
+ });
15515
+ throw e;
15489
15516
  } finally {
15490
15517
  clearTimeout(timer);
15491
15518
  }
15492
15519
  }
15520
+ /**
15521
+ * Raw recall restricted to consolidated observations — no LLM in the loop, so it still answers
15522
+ * when reflect's synthesis times out or 5xxs. Returns the observation texts in rank order.
15523
+ */
15524
+ async recallObservations(query, opts) {
15525
+ const r = await this.req(
15526
+ "POST",
15527
+ this.bankUrl("/memories/recall"),
15528
+ {
15529
+ query,
15530
+ types: ["observation"],
15531
+ budget: "low",
15532
+ max_tokens: opts.maxTokens,
15533
+ include: { entities: null }
15534
+ },
15535
+ [],
15536
+ opts.timeoutMs
15537
+ );
15538
+ if (r.status === 404) return [];
15539
+ const j = await r.json();
15540
+ return (j.results ?? []).map((x) => (x.text ?? "").trim()).filter(Boolean);
15541
+ }
15493
15542
  /**
15494
15543
  * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
15495
15544
  * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
@@ -15554,10 +15603,16 @@ var HindsightClient = class {
15554
15603
  /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
15555
15604
  * Returns page-level hits with a relevance snippet — the real search behind
15556
15605
  * hindsight_search_knowledge_pages. */
15557
- async searchKnowledgePages(query, limit = 3) {
15606
+ async searchKnowledgePages(query, limit = 3, timeoutMs) {
15558
15607
  if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15559
15608
  const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
15560
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
15609
+ const r = await this.req(
15610
+ "GET",
15611
+ this.bankUrl(`/knowledge-base/search${q}`),
15612
+ void 0,
15613
+ [],
15614
+ timeoutMs
15615
+ );
15561
15616
  const j = await r.json();
15562
15617
  return (j.results ?? []).map((x) => ({
15563
15618
  id: x.id,
@@ -16353,7 +16408,7 @@ function preflightDaemon(cfg, harness) {
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 registry3 = readJson(join13(claudeDir, "plugins", "installed_plugins.json"));
17289
+ const plugins = registry3?.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, sessionId) {
17126
- return join12(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
17324
+ return join14(tmpdir4(), `hindsight-${harness}`, `${sessionId}.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,9 +17552,9 @@ 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
 
17343
17559
  // src/core/transcript-util.ts
17344
17560
  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;
@@ -17379,7 +17595,52 @@ function actionLine(tool2, input) {
17379
17595
  var JOURNAL_MAX_BYTES = 8 * 1024 * 1024;
17380
17596
 
17381
17597
  // src/core/hook.ts
17382
- var HOOK_REFLECT_CAP_MS = 25e3;
17598
+ var HOOK_REFLECT_CAP_MS = 2e4;
17599
+ var HOOK_FALLBACK_BUDGET_MS = 7e3;
17600
+ var FALLBACK_PAGE_LIMIT = 3;
17601
+ var FALLBACK_RECALL_MAX_TOKENS = 2e3;
17602
+ async function reflectFallback(harness, prompt, client) {
17603
+ const deadline = Date.now() + HOOK_FALLBACK_BUDGET_MS;
17604
+ const remaining = () => Math.max(deadline - Date.now(), 1);
17605
+ const query = prompt.slice(0, 500);
17606
+ let t0 = Date.now();
17607
+ try {
17608
+ const hits = await client.searchKnowledgePages(query, FALLBACK_PAGE_LIMIT, remaining());
17609
+ diag(harness, "reflect_fallback_pages", { ms: Date.now() - t0, count: hits.length });
17610
+ if (hits.length) {
17611
+ return { memory: formatPageFallback(hits), source: "knowledge_pages", count: hits.length };
17612
+ }
17613
+ } catch (e) {
17614
+ diag(harness, "reflect_fallback_pages_failed", {
17615
+ ms: Date.now() - t0,
17616
+ error: describeError(e)
17617
+ });
17618
+ }
17619
+ t0 = Date.now();
17620
+ try {
17621
+ const observations = await client.recallObservations(prompt.slice(0, 2e3), {
17622
+ maxTokens: FALLBACK_RECALL_MAX_TOKENS,
17623
+ timeoutMs: remaining()
17624
+ });
17625
+ diag(harness, "reflect_fallback_observations", {
17626
+ ms: Date.now() - t0,
17627
+ count: observations.length
17628
+ });
17629
+ if (observations.length) {
17630
+ return {
17631
+ memory: formatObservationFallback(observations),
17632
+ source: "observations",
17633
+ count: observations.length
17634
+ };
17635
+ }
17636
+ } catch (e) {
17637
+ diag(harness, "reflect_fallback_observations_failed", {
17638
+ ms: Date.now() - t0,
17639
+ error: describeError(e)
17640
+ });
17641
+ }
17642
+ return void 0;
17643
+ }
17383
17644
  async function buildHookOutput(args) {
17384
17645
  const { harness, prompt, cfg, client, cacheFile } = args;
17385
17646
  const cached3 = readSessionCache(cacheFile);
@@ -17387,19 +17648,21 @@ async function buildHookOutput(args) {
17387
17648
  let reflectAnswer = cached3.reflectAnswer;
17388
17649
  let reflectRanThisTurn = false;
17389
17650
  let reflectFailed = false;
17651
+ let fallback;
17390
17652
  const deferInitialReflect = cached3.deferInitialReflect === true;
17391
17653
  if (deferInitialReflect) {
17392
17654
  diag(harness, "reflect_deferred_new_bank", { query: prompt.slice(0, 80) });
17393
17655
  } else if (cfg.autoReflect && reflectAnswer === void 0) {
17394
17656
  reflectRanThisTurn = true;
17395
17657
  const t0 = Date.now();
17658
+ const timeoutMs = Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS);
17396
17659
  try {
17397
17660
  reflectAnswer = await client.reflect(buildReflectQuery(prompt), {
17398
- // Automatic reflection runs inside a hard 25s hook window. Hindsight's low budget is the
17661
+ // Automatic reflection runs inside a hard 20s slot of the hook window. Hindsight's low budget is the
17399
17662
  // supported default for bounded reflect calls; callers that explicitly invoke the MCP
17400
17663
  // tool still get the deeper high-budget path.
17401
17664
  budget: "low",
17402
- timeoutMs: Math.min(cfg.reflectTimeoutMs, HOOK_REFLECT_CAP_MS)
17665
+ timeoutMs
17403
17666
  });
17404
17667
  diag(harness, reflectAnswer ? "reflect_ok" : "reflect_empty", {
17405
17668
  ms: Date.now() - t0,
@@ -17417,9 +17680,16 @@ async function buildHookOutput(args) {
17417
17680
  });
17418
17681
  diag(harness, "reflect_failed", {
17419
17682
  ms: Date.now() - t0,
17420
- error: describeError(e),
17683
+ bank: client.bank,
17684
+ timeoutMs,
17685
+ // Wider than describeError's default: the server's error body is the useful part.
17686
+ error: describeError(e, 1500),
17421
17687
  query: prompt.slice(0, 80)
17422
17688
  });
17689
+ if (e instanceof ReflectError && e.fallbackEligible) {
17690
+ fallback = await reflectFallback(harness, prompt, client);
17691
+ if (fallback) reflectAnswer = fallback.memory;
17692
+ }
17423
17693
  }
17424
17694
  }
17425
17695
  const cadence = cfg.pageRefreshEveryTurns;
@@ -17453,7 +17723,10 @@ async function buildHookOutput(args) {
17453
17723
  }
17454
17724
  const kept = blocks.filter(Boolean);
17455
17725
  let notice;
17456
- if (reflectRanThisTurn && reflectAnswer) {
17726
+ if (fallback) {
17727
+ const what = fallback.source === "knowledge_pages" ? "knowledge page" : "observation";
17728
+ notice = `${brandWord()} \xB7 reflect unavailable \u2014 fell back to ${fallback.count} ${what}${fallback.count === 1 ? "" : "s"} (see ${diagFilePath()})`;
17729
+ } else if (reflectRanThisTurn && reflectAnswer) {
17457
17730
  const q = prompt.replace(/\s+/g, " ").trim();
17458
17731
  const excerpt = q.length > 48 ? `${q.slice(0, 48)}\u2026` : q;
17459
17732
  const preview = reflectAnswer.replace(/\s+/g, " ").trim();
@@ -30138,12 +30411,12 @@ function tool(input) {
30138
30411
  tool.schema = external_exports2;
30139
30412
 
30140
30413
  // src/harness/registry.ts
30141
- import { readFileSync as readFileSync9 } from "fs";
30414
+ import { readFileSync as readFileSync10 } from "fs";
30142
30415
  var jsonChatReader = (harness) => ({
30143
30416
  describe: `${harness} sessions via a normalized JSON export (--conversations file: [{ id, turns:[{role,text,timestamp?}] }])`,
30144
30417
  async read(opts) {
30145
30418
  if (!opts.conversations) return [];
30146
- return JSON.parse(readFileSync9(opts.conversations, "utf8"));
30419
+ return JSON.parse(readFileSync10(opts.conversations, "utf8"));
30147
30420
  }
30148
30421
  });
30149
30422