@vectorize-io/hindsight-coding-agents 0.4.2 → 0.5.0

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 (46) hide show
  1. package/README.md +202 -51
  2. package/dist/antigravity-hook.js +637 -199
  3. package/dist/antigravity-statusline.js +219 -84
  4. package/dist/antigravity-stop-hook.js +654 -205
  5. package/dist/claude-hook.js +637 -199
  6. package/dist/claude-sessionstart-hook.js +863 -236
  7. package/dist/claude-stop-hook.js +654 -205
  8. package/dist/cline.js +589 -234
  9. package/dist/codex-hook.js +637 -199
  10. package/dist/codex-sessionstart-hook.js +863 -236
  11. package/dist/codex-stop-hook.js +654 -205
  12. package/dist/copilot-hook.js +637 -199
  13. package/dist/copilot-sessionstart-hook.js +863 -236
  14. package/dist/copilot-stop-hook.js +654 -205
  15. package/dist/cursor-hook.js +637 -199
  16. package/dist/cursor-sessionstart-hook.js +863 -236
  17. package/dist/cursor-stop-hook.js +654 -205
  18. package/dist/daemon-start.js +62 -43
  19. package/dist/dcode-hook.js +2577 -0
  20. package/dist/dcode-sessionstart-hook.js +3194 -0
  21. package/dist/dcode-stop-hook.js +2807 -0
  22. package/dist/deepen.js +361 -204
  23. package/dist/devin-hook.js +637 -199
  24. package/dist/devin-sessionstart-hook.js +863 -236
  25. package/dist/devin-stop-hook.js +654 -205
  26. package/dist/dsh.js +592 -235
  27. package/dist/grok-hook.js +637 -199
  28. package/dist/grok-sessionstart-hook.js +863 -236
  29. package/dist/grok-stop-hook.js +654 -205
  30. package/dist/hindsight-seed.js +222 -83
  31. package/dist/index.js +589 -234
  32. package/dist/installer.js +2343 -302
  33. package/dist/kilo.js +589 -234
  34. package/dist/mcp-server.js +363 -169
  35. package/dist/opencode2.js +30092 -0
  36. package/dist/pi.js +17650 -0
  37. package/dist/prime-agent.js +625 -260
  38. package/dist/qwen-hook.js +2577 -0
  39. package/dist/qwen-sessionstart-hook.js +3194 -0
  40. package/dist/qwen-stop-hook.js +2807 -0
  41. package/dist/status.js +300 -136
  42. package/hooks/hooks.json +37 -0
  43. package/index.js +10 -0
  44. package/package.json +15 -8
  45. package/plugin.json +16 -0
  46. package/skill/SKILL.md +114 -43
@@ -14151,8 +14151,8 @@ function convertBaseSchema(schema, ctx) {
14151
14151
  });
14152
14152
  }
14153
14153
  ctx.processing.add(refPath);
14154
- const resolved = resolveRef(refPath, ctx);
14155
- const zodSchema2 = convertSchema(resolved, ctx);
14154
+ const resolved2 = resolveRef(refPath, ctx);
14155
+ const zodSchema2 = convertSchema(resolved2, ctx);
14156
14156
  ctx.refs.set(refPath, zodSchema2);
14157
14157
  ctx.processing.delete(refPath);
14158
14158
  return zodSchema2;
@@ -14519,9 +14519,9 @@ function date4(params) {
14519
14519
  config(en_default());
14520
14520
 
14521
14521
  // src/core/config.ts
14522
- import { readFileSync } from "fs";
14522
+ import { readFileSync as readFileSync2 } from "fs";
14523
14523
  import { homedir as homedir2 } from "os";
14524
- import { join as join4 } from "path";
14524
+ import { join as join6 } from "path";
14525
14525
 
14526
14526
  // src/core/seed.ts
14527
14527
  import { spawn as realSpawn } from "child_process";
@@ -14557,64 +14557,207 @@ function startBackgroundSeed(repoDir, opts = {}) {
14557
14557
  }
14558
14558
 
14559
14559
  // src/core/bank.ts
14560
- import { execFileSync } from "child_process";
14561
14560
  import { existsSync } from "fs";
14562
14561
  import { homedir } from "os";
14563
- import { basename, dirname as dirname2, join as join2, normalize, sep } from "path";
14562
+ import { basename, dirname as dirname4, join as join4, normalize, sep } from "path";
14563
+
14564
+ // src/core/diag.ts
14565
+ import { appendFileSync as appendFileSync2 } from "fs";
14566
+
14567
+ // src/core/log.ts
14568
+ import { appendFileSync, mkdirSync } from "fs";
14569
+ import { tmpdir } from "os";
14570
+ import { dirname as dirname2, join as join2 } from "path";
14571
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
14572
+ var current = ["debug", "info", "warn", "error"].find(
14573
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
14574
+ ) ?? "info";
14575
+ function setLogLevel(level) {
14576
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
14577
+ }
14578
+ function logFilePath() {
14579
+ return process.env.HINDSIGHT_LOG_FILE || join2(tmpdir(), "hindsight-coding-agent", "plugin.log");
14580
+ }
14581
+ function write(level, scope, msg, extra) {
14582
+ if (WEIGHT[level] < WEIGHT[current]) return;
14583
+ try {
14584
+ const file2 = logFilePath();
14585
+ mkdirSync(dirname2(file2), { recursive: true });
14586
+ appendFileSync(
14587
+ file2,
14588
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
14589
+ );
14590
+ } catch {
14591
+ }
14592
+ }
14593
+ var log = {
14594
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
14595
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
14596
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
14597
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
14598
+ };
14599
+ function describeError(value, maxChars = 200) {
14600
+ const parts = [];
14601
+ const seen = /* @__PURE__ */ new Set();
14602
+ let current2 = value;
14603
+ while (current2 && !seen.has(current2)) {
14604
+ seen.add(current2);
14605
+ const error51 = current2;
14606
+ const text = typeof error51.message === "string" ? error51.message : String(current2);
14607
+ const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
14608
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
14609
+ current2 = error51.cause;
14610
+ }
14611
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
14612
+ }
14613
+
14614
+ // src/core/diag.ts
14615
+ function diagFilePath() {
14616
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
14617
+ }
14618
+ function diag(harness, event, extra = {}) {
14619
+ log.debug(harness, `diag:${event}`, extra);
14620
+ try {
14621
+ appendFileSync2(
14622
+ diagFilePath(),
14623
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
14624
+ );
14625
+ } catch {
14626
+ }
14627
+ }
14628
+
14629
+ // src/core/git-layout.ts
14630
+ import { lstatSync, readFileSync, realpathSync } from "fs";
14631
+ import { dirname as dirname3, isAbsolute, join as join3, resolve } from "path";
14632
+ var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
14633
+ var ATTEMPTS = 3;
14634
+ var BACKOFF_MS = 20;
14635
+ function errorCode(error51) {
14636
+ return error51?.code ?? "";
14637
+ }
14638
+ function sleepSync(ms) {
14639
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
14640
+ }
14641
+ var TransientProbeError = class extends Error {
14642
+ };
14643
+ function entryKind(path) {
14644
+ try {
14645
+ const st = lstatSync(path);
14646
+ return st.isDirectory() ? "dir" : "file";
14647
+ } catch (error51) {
14648
+ if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
14649
+ return "none";
14650
+ }
14651
+ }
14652
+ function readTextOrNull(path) {
14653
+ try {
14654
+ return readFileSync(path, "utf8");
14655
+ } catch (error51) {
14656
+ if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
14657
+ return null;
14658
+ }
14659
+ }
14660
+ function gitDirFromPointer(text, holder) {
14661
+ const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
14662
+ if (!match) return null;
14663
+ const target = match[1];
14664
+ return isAbsolute(target) ? target : resolve(holder, target);
14665
+ }
14666
+ function commonDirOf(gitDir) {
14667
+ const pointer = entryKind(join3(gitDir, "commondir")) === "file" ? readTextOrNull(join3(gitDir, "commondir"))?.trim() : null;
14668
+ if (!pointer) return gitDir;
14669
+ return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
14670
+ }
14671
+ function isBare(commonDir) {
14672
+ const config2 = readTextOrNull(join3(commonDir, "config"));
14673
+ return config2 !== null && /^\s*bare\s*=\s*true\s*$/im.test(config2);
14674
+ }
14675
+ function looksLikeBareRepository(directory) {
14676
+ return entryKind(join3(directory, "HEAD")) === "file" && entryKind(join3(directory, "objects")) === "dir" && entryKind(join3(directory, "refs")) === "dir";
14677
+ }
14678
+ function canonical(path) {
14679
+ try {
14680
+ return realpathSync(path);
14681
+ } catch {
14682
+ return path;
14683
+ }
14684
+ }
14685
+ function resolved(commonDir) {
14686
+ if (entryKind(commonDir) !== "dir") return null;
14687
+ const canonicalDir = canonical(commonDir);
14688
+ return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
14689
+ }
14690
+ function probeOnce(directory) {
14691
+ let current2 = resolve(directory);
14692
+ for (; ; ) {
14693
+ const dotGit = join3(current2, ".git");
14694
+ const kind = entryKind(dotGit);
14695
+ if (kind === "dir") {
14696
+ const layout = resolved(commonDirOf(dotGit));
14697
+ if (layout) return layout;
14698
+ } else if (kind === "file") {
14699
+ const text = readTextOrNull(dotGit);
14700
+ const gitDir = text ? gitDirFromPointer(text, current2) : null;
14701
+ const layout = gitDir ? resolved(commonDirOf(gitDir)) : null;
14702
+ if (layout) return layout;
14703
+ }
14704
+ if (looksLikeBareRepository(current2)) {
14705
+ const layout = resolved(current2);
14706
+ if (layout) return layout;
14707
+ }
14708
+ const parent = dirname3(current2);
14709
+ if (parent === current2) return { status: "absent" };
14710
+ current2 = parent;
14711
+ }
14712
+ }
14713
+ function probeGitLayout(directory) {
14714
+ if (!directory) return { status: "absent" };
14715
+ let last = "";
14716
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
14717
+ if (attempt) sleepSync(BACKOFF_MS * attempt);
14718
+ try {
14719
+ return probeOnce(directory);
14720
+ } catch (error51) {
14721
+ last = error51 instanceof TransientProbeError ? error51.message : errorCode(error51) || "unknown";
14722
+ }
14723
+ }
14724
+ return { status: "failed", reason: last };
14725
+ }
14564
14726
 
14565
14727
  // src/core/template.ts
14566
14728
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
14567
14729
  function applyTemplate(template, resolvers, what) {
14568
14730
  return template.replace(PLACEHOLDER, (_, name) => {
14569
- const resolve2 = resolvers[name];
14570
- if (!resolve2) {
14731
+ const resolve3 = resolvers[name];
14732
+ if (!resolve3) {
14571
14733
  console.error(
14572
14734
  `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
14573
14735
  );
14574
14736
  return "unknown";
14575
14737
  }
14576
- return resolve2();
14738
+ return resolve3();
14577
14739
  });
14578
14740
  }
14579
14741
 
14580
14742
  // src/core/bank.ts
14581
14743
  var DEFAULT_BANK_NAME = "coding";
14582
14744
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
14583
- function getProjectRootFromGit(directory) {
14584
- if (!directory) return null;
14585
- try {
14586
- const commonDir = execFileSync(
14587
- "git",
14588
- ["rev-parse", "--path-format=absolute", "--git-common-dir"],
14589
- {
14590
- cwd: directory,
14591
- encoding: "utf-8",
14592
- stdio: ["ignore", "pipe", "ignore"],
14593
- timeout: 1e3,
14594
- windowsHide: true
14595
- }
14596
- ).trim();
14597
- if (!commonDir) return null;
14598
- if (basename(commonDir) === ".git") return dirname2(commonDir);
14599
- if (basename(commonDir).startsWith(".") && isBareRepository(commonDir)) {
14600
- return dirname2(commonDir);
14601
- }
14602
- return commonDir;
14603
- } catch {
14604
- return null;
14745
+ var BankResolutionError = class extends Error {
14746
+ constructor(message) {
14747
+ super(message);
14748
+ this.name = "BankResolutionError";
14605
14749
  }
14606
- }
14607
- function isBareRepository(commonDir) {
14608
- try {
14609
- return execFileSync("git", ["-C", commonDir, "rev-parse", "--is-bare-repository"], {
14610
- encoding: "utf-8",
14611
- stdio: ["ignore", "pipe", "ignore"],
14612
- timeout: 1e3,
14613
- env: { ...process.env, GIT_DIR: void 0, GIT_WORK_TREE: void 0 }
14614
- }).trim() === "true";
14615
- } catch {
14616
- return false;
14750
+ };
14751
+ function resolveProjectRoot(directory) {
14752
+ if (!directory) return { status: "absent" };
14753
+ const layout = probeGitLayout(directory);
14754
+ if (layout.status !== "resolved") return layout;
14755
+ const commonDir = layout.commonDir;
14756
+ if (basename(commonDir) === ".git") return { status: "resolved", root: dirname4(commonDir) };
14757
+ if (basename(commonDir).startsWith(".") && layout.bare) {
14758
+ return { status: "resolved", root: dirname4(commonDir) };
14617
14759
  }
14760
+ return { status: "resolved", root: commonDir };
14618
14761
  }
14619
14762
  function projectNameOf(directory, sessionRoot) {
14620
14763
  return gitProjectName(directory, true, sessionRoot);
@@ -14624,7 +14767,7 @@ function nearestExistingDir(directory) {
14624
14767
  let current2 = directory;
14625
14768
  while (current2) {
14626
14769
  if (existsSync(current2)) return current2;
14627
- const parent = dirname2(current2);
14770
+ const parent = dirname4(current2);
14628
14771
  if (parent === current2) return "";
14629
14772
  current2 = parent;
14630
14773
  }
@@ -14639,21 +14782,29 @@ function mainWorktreeRoot(directory, sessionRoot = "") {
14639
14782
  sessionRoot,
14640
14783
  ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
14641
14784
  ];
14785
+ let failure = null;
14642
14786
  for (const candidate of candidates) {
14643
- const root = candidate ? getProjectRootFromGit(candidate) : null;
14644
- if (root) return root;
14787
+ if (!candidate) continue;
14788
+ const projectRoot = resolveProjectRoot(candidate);
14789
+ if (projectRoot.status === "resolved") return projectRoot;
14790
+ if (projectRoot.status === "failed") failure = projectRoot;
14645
14791
  }
14646
- return null;
14792
+ return failure ?? { status: "absent" };
14647
14793
  }
14648
14794
  function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
14649
14795
  if (resolveWorktrees) {
14650
- const root = mainWorktreeRoot(directory, sessionRoot);
14651
- if (root) return basename(root);
14796
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
14797
+ if (projectRoot.status === "resolved") return basename(projectRoot.root);
14798
+ if (projectRoot.status === "failed") {
14799
+ throw new BankResolutionError(
14800
+ `git probe failed for ${directory} (${projectRoot.reason}) \u2014 refusing to guess a bank id`
14801
+ );
14802
+ }
14652
14803
  }
14653
14804
  return dirName(sessionRoot || directory);
14654
14805
  }
14655
14806
  function configuredDir(dir) {
14656
- const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
14807
+ const expanded = dir === "~" || dir.startsWith("~/") ? join4(homedir(), dir.slice(1)) : dir;
14657
14808
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
14658
14809
  }
14659
14810
  function isWithin(directory, configured) {
@@ -14673,8 +14824,8 @@ function mapLookup(map2, directory) {
14673
14824
  function lookupDirectories(config2, directory, sessionRoot = "") {
14674
14825
  const directories = [normalize(directory)];
14675
14826
  if (config2.resolveWorktrees ?? true) {
14676
- const root = mainWorktreeRoot(directory, sessionRoot);
14677
- const normalizedRoot = root ? normalize(root) : "";
14827
+ const projectRoot = mainWorktreeRoot(directory, sessionRoot);
14828
+ const normalizedRoot = projectRoot.status === "resolved" ? normalize(projectRoot.root) : "";
14678
14829
  if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
14679
14830
  }
14680
14831
  return directories;
@@ -14707,52 +14858,18 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
14707
14858
  };
14708
14859
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
14709
14860
  }
14710
-
14711
- // src/core/log.ts
14712
- import { appendFileSync, mkdirSync } from "fs";
14713
- import { tmpdir } from "os";
14714
- import { dirname as dirname3, join as join3 } from "path";
14715
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
14716
- var current = ["debug", "info", "warn", "error"].find(
14717
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
14718
- ) ?? "info";
14719
- function setLogLevel(level) {
14720
- if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
14721
- }
14722
- function logFilePath() {
14723
- return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
14724
- }
14725
- function write(level, scope, msg, extra) {
14726
- if (WEIGHT[level] < WEIGHT[current]) return;
14861
+ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
14727
14862
  try {
14728
- const file2 = logFilePath();
14729
- mkdirSync(dirname3(file2), { recursive: true });
14730
- appendFileSync(
14731
- file2,
14732
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
14733
- );
14734
- } catch {
14735
- }
14736
- }
14737
- var log = {
14738
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
14739
- info: (scope, msg, extra) => write("info", scope, msg, extra),
14740
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
14741
- error: (scope, msg, extra) => write("error", scope, msg, extra)
14742
- };
14743
- function describeError(value, maxChars = 200) {
14744
- const parts = [];
14745
- const seen = /* @__PURE__ */ new Set();
14746
- let current2 = value;
14747
- while (current2 && !seen.has(current2)) {
14748
- seen.add(current2);
14749
- const error51 = current2;
14750
- const text = typeof error51.message === "string" ? error51.message : String(current2);
14751
- const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
14752
- if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
14753
- current2 = error51.cause;
14863
+ return deriveBankId(config2, directory, harness, sessionRoot);
14864
+ } catch (error51) {
14865
+ if (!(error51 instanceof BankResolutionError)) throw error51;
14866
+ log.warn(harness, "bank unresolved: skipping (repository could not be identified)", {
14867
+ directory,
14868
+ error: error51.message
14869
+ });
14870
+ diag(harness, "bank_unresolved", { directory, error: error51.message });
14871
+ return null;
14754
14872
  }
14755
- return (parts.join(": ") || String(value)).slice(0, maxChars);
14756
14873
  }
14757
14874
 
14758
14875
  // src/core/missions.ts
@@ -14892,15 +15009,60 @@ var CODING_BANK_TEMPLATE = {
14892
15009
  entities_allow_free_form: true
14893
15010
  }
14894
15011
  };
14895
- var CODING_BANK_STRUCTURE = {
14896
- version: "1",
14897
- bank: {
14898
- retain_strategies: RETAIN_STRATEGIES,
14899
- entity_labels: [KNOWLEDGE_LABELS]
14900
- }
14901
- };
15012
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
15013
+ function isSet(v) {
15014
+ if (v === null || v === void 0) return false;
15015
+ if (typeof v === "string") return v.trim() !== "";
15016
+ return true;
15017
+ }
15018
+ function codingBankManifest(overrides) {
15019
+ const current2 = overrides ?? {};
15020
+ const template = CODING_BANK_TEMPLATE.bank;
15021
+ const bank = {};
15022
+ if (!MISSION_FIELDS.some((f) => isSet(current2[f]))) {
15023
+ bank.reflect_mission = template.reflect_mission;
15024
+ bank.enable_observations = template.enable_observations;
15025
+ bank.observations_mission = template.observations_mission;
15026
+ bank.retain_mission = template.retain_mission;
15027
+ bank.retain_extraction_mode = template.retain_extraction_mode;
15028
+ }
15029
+ if (!isSet(current2.retain_default_strategy))
15030
+ bank.retain_default_strategy = template.retain_default_strategy;
15031
+ if (!isSet(current2.entities_allow_free_form))
15032
+ bank.entities_allow_free_form = template.entities_allow_free_form;
15033
+ const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
15034
+ const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
15035
+ if (missing.length > 0)
15036
+ bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
15037
+ const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
15038
+ const [knowledgeGroup] = template.entity_labels;
15039
+ if (!labels.some((g) => g?.key === knowledgeGroup.key))
15040
+ bank.entity_labels = [...labels, knowledgeGroup];
15041
+ return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
15042
+ }
14902
15043
 
14903
15044
  // src/core/util.ts
15045
+ import { accessSync, constants } from "fs";
15046
+ import { delimiter, join as join5 } from "path";
15047
+ function binOnPath(bin) {
15048
+ try {
15049
+ if (bin.includes("/")) {
15050
+ accessSync(bin, constants.X_OK);
15051
+ return true;
15052
+ }
15053
+ for (const dir of (process.env.PATH || "").split(delimiter)) {
15054
+ if (!dir) continue;
15055
+ try {
15056
+ accessSync(join5(dir, bin), constants.X_OK);
15057
+ return true;
15058
+ } catch {
15059
+ }
15060
+ }
15061
+ return false;
15062
+ } catch {
15063
+ return false;
15064
+ }
15065
+ }
14904
15066
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
14905
15067
  function semverGte(version2, min) {
14906
15068
  const parts = (v) => {
@@ -14932,6 +15094,11 @@ async function pool(items, n, fn, onError, onProgress) {
14932
15094
  }
14933
15095
 
14934
15096
  // src/core/hindsight.ts
15097
+ function resolveRetainScopes(tags, configured) {
15098
+ if (configured !== "per_source") return configured;
15099
+ const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
15100
+ return [[], ...sources.map((s) => [s])];
15101
+ }
14935
15102
  var DEFAULT_OBSERVATION_SCOPES = "shared";
14936
15103
  var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
14937
15104
  var RateLimitedError = class extends Error {
@@ -14962,7 +15129,6 @@ var DEFAULT_MAX_PARALLEL_RETAINS = 10;
14962
15129
  var POLL_CYCLE_MS = 5e3;
14963
15130
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
14964
15131
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
14965
- var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
14966
15132
  var HindsightClient = class {
14967
15133
  apiUrl;
14968
15134
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -15068,7 +15234,7 @@ var HindsightClient = class {
15068
15234
  // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
15069
15235
  // observations were built under is a property of the write rather than of whichever server
15070
15236
  // version happened to process it. Servers older than 0.4.15 ignore the field.
15071
- observation_scopes: this.observationScopes
15237
+ observation_scopes: resolveRetainScopes(tags, this.observationScopes)
15072
15238
  };
15073
15239
  if (opts.timestamp) item.timestamp = opts.timestamp;
15074
15240
  if (opts.metadata) item.metadata = opts.metadata;
@@ -15109,11 +15275,11 @@ var HindsightClient = class {
15109
15275
  * Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
15110
15276
  * with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
15111
15277
  */
15112
- async listDocumentIds(tag) {
15278
+ async listDocumentIds(tag, tagsMatch = "all") {
15113
15279
  const ids = /* @__PURE__ */ new Set();
15114
15280
  const limit = 500;
15115
15281
  for (let offset = 0; ; offset += limit) {
15116
- const q = `?tags=${encodeURIComponent(tag)}&tags_match=all&limit=${limit}&offset=${offset}`;
15282
+ const q = `?tags=${encodeURIComponent(tag)}&tags_match=${tagsMatch}&limit=${limit}&offset=${offset}`;
15117
15283
  const r = await this.req("GET", this.bankUrl(`/documents${q}`));
15118
15284
  let items = [];
15119
15285
  let total = 0;
@@ -15129,49 +15295,54 @@ var HindsightClient = class {
15129
15295
  }
15130
15296
  return ids;
15131
15297
  }
15132
- /** Configure the bank: POST the coding bank template manifest to /import (missions, retain
15133
- * strategies, entity labels), then seed knowledge pages when the server supports them. Both
15134
- * halves are idempotent, so the deepen engine can re-run this every pass. Creates the bank if
15135
- * missing; legacy servers continue with the template-only path. */
15298
+ /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
15299
+ * entity labels), then seed knowledge pages when the server supports them. Both halves are
15300
+ * idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
15301
+ * the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
15302
+ * continue with the template-only path.
15303
+ *
15304
+ * `manage: false` skips the config half entirely, for a bank whose owner shapes it themselves.
15305
+ * That bank should then define the strategies this plugin writes under (`git`, `gitlog`,
15306
+ * `conversation`, `document`, `survey`): an unknown strategy name is not an error server-side,
15307
+ * it just falls back to the bank's own config, so the miss is silent. */
15136
15308
  async configureBank(opts = {}) {
15137
15309
  if (opts.reset) {
15138
15310
  await this.req("DELETE", this.bankUrl());
15139
15311
  this.log(`[bank] reset ${this.bank}`);
15140
15312
  }
15141
- const seeded = opts.reset ? false : await this.hasBankMissions();
15142
- await this.req(
15143
- "POST",
15144
- this.bankUrl("/import"),
15145
- seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
15146
- );
15147
- this.log(
15148
- seeded ? `[bank] structure applied to ${this.bank}: entity_labels {knowledge}, strategies {git, gitlog, conversation, document} \u2014 missions left as configured` : `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
15149
- );
15313
+ if (opts.manage === false) {
15314
+ this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
15315
+ } else {
15316
+ const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
15317
+ if (!manifest) {
15318
+ this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
15319
+ } else {
15320
+ await this.req("POST", this.bankUrl("/import"), manifest);
15321
+ this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
15322
+ }
15323
+ }
15150
15324
  await this.seedPages(opts.pageTrigger);
15151
15325
  }
15152
15326
  /**
15153
- * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
15154
- * the user's own edit. Either way they are not ours to overwrite.
15327
+ * This bank's own config OVERRIDES, or undefined when there are none to read.
15155
15328
  *
15156
- * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
15157
- * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
15158
- * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
15159
- * missions in the first place.
15329
+ * Deliberately the overrides and not the resolved config: an inherited global default is not
15330
+ * something this bank's owner chose, so it must not read as "already set". `undefined` means the
15331
+ * bank does not exist yet, or the deployment has the bank-config API switched off — in neither
15332
+ * case can anything have been customised, so the caller seeds the full template.
15160
15333
  */
15161
- async hasBankMissions() {
15334
+ async readBankOverrides() {
15162
15335
  try {
15163
15336
  const r = await this.req("GET", this.bankUrl("/config"));
15164
- if (!r.ok) return false;
15337
+ if (!r.ok) return void 0;
15165
15338
  const j = await r.json();
15166
- return MISSION_FIELDS.some((f) => {
15167
- const v = j.overrides?.[f];
15168
- return typeof v === "string" && v.trim() !== "";
15169
- });
15339
+ return j.overrides ?? {};
15170
15340
  } catch {
15171
- return false;
15341
+ return void 0;
15172
15342
  }
15173
15343
  }
15174
- /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
15344
+ /** Explicitly delete one document (and its cascaded memory units/links). Background sync must
15345
+ * never use this as a cleanup primitive: a document id alone does not prove repository ownership. */
15175
15346
  async deleteDocument(documentId) {
15176
15347
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
15177
15348
  }
@@ -15472,7 +15643,7 @@ var HindsightClient = class {
15472
15643
  };
15473
15644
 
15474
15645
  // src/core/config.ts
15475
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
15646
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
15476
15647
  var DEFAULT_DAEMON_PORT = 9077;
15477
15648
  var DEFAULT_DAEMON_PROFILE = "coding-agent";
15478
15649
  function resolvePageTriggerType(raw) {
@@ -15496,7 +15667,13 @@ function resolveReflectBudget(raw) {
15496
15667
  log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
15497
15668
  return "high";
15498
15669
  }
15499
- var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
15670
+ var OBSERVATION_SCOPE_MODES = [
15671
+ "shared",
15672
+ "combined",
15673
+ "per_tag",
15674
+ "all_combinations",
15675
+ "per_source"
15676
+ ];
15500
15677
  function resolveObservationScopes(raw) {
15501
15678
  const value = raw;
15502
15679
  if (typeof value === "string")
@@ -15534,6 +15711,7 @@ function resolveConfig(raw = {}) {
15534
15711
  disabled: raw.disabled ?? false,
15535
15712
  retainSessions: raw.retainSessions ?? true,
15536
15713
  // write sessions back by default, every harness
15714
+ manageBankConfig: raw.manageBankConfig ?? true,
15537
15715
  maxParallelRetains: raw.maxParallelRetains || 10,
15538
15716
  reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
15539
15717
  // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
@@ -15560,12 +15738,13 @@ function resolveConfig(raw = {}) {
15560
15738
  ) : {},
15561
15739
  observationScopes: resolveObservationScopes(raw.observationScopes),
15562
15740
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
15563
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
15741
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
15742
+ autoUpdate: raw.autoUpdate ?? true
15564
15743
  };
15565
15744
  }
15566
15745
  function readRaw(path) {
15567
15746
  try {
15568
- return JSON.parse(readFileSync(path, "utf8"));
15747
+ return JSON.parse(readFileSync2(path, "utf8"));
15569
15748
  } catch (e) {
15570
15749
  if (e?.code !== "ENOENT") {
15571
15750
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -15618,13 +15797,15 @@ var ENV_KEYS = {
15618
15797
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
15619
15798
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
15620
15799
  logLevel: "HINDSIGHT_LOG_LEVEL",
15800
+ autoUpdate: "HINDSIGHT_AUTO_UPDATE",
15621
15801
  gitIngest: "HINDSIGHT_GIT_INGEST",
15622
15802
  // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
15623
15803
  // list is a list OF lists, which does not survive flattening into one variable — file-only.
15624
15804
  observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
15625
15805
  // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
15626
15806
  // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
15627
- retainTags: "HINDSIGHT_RETAIN_TAGS"
15807
+ retainTags: "HINDSIGHT_RETAIN_TAGS",
15808
+ manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
15628
15809
  };
15629
15810
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
15630
15811
  "dynamicBankId",
@@ -15634,7 +15815,9 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
15634
15815
  "retainSessions",
15635
15816
  "autoReflect",
15636
15817
  "autoSeed",
15637
- "codebaseSurvey"
15818
+ "codebaseSurvey",
15819
+ "autoUpdate",
15820
+ "manageBankConfig"
15638
15821
  ]);
15639
15822
  var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
15640
15823
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
@@ -15713,7 +15896,9 @@ function resolvePartial(cfg, patch) {
15713
15896
  function resolveHostConfig(harness, directory) {
15714
15897
  const cfg0 = loadConfig({ harness });
15715
15898
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
15716
- return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
15899
+ const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
15900
+ if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
15901
+ return applyBankConfig(cfg0, bankId, directory);
15717
15902
  }
15718
15903
  function resolveHostMemory(harness, directory) {
15719
15904
  const { cfg, bankId } = resolveHostConfig(harness, directory);
@@ -15735,26 +15920,203 @@ function resolveHostMemory(harness, directory) {
15735
15920
  };
15736
15921
  }
15737
15922
 
15738
- // src/core/diag.ts
15739
- import { appendFileSync as appendFileSync2 } from "fs";
15740
- function diagFilePath() {
15741
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
15923
+ // src/core/auto-update.ts
15924
+ import { spawn as realSpawn2 } from "child_process";
15925
+ import {
15926
+ existsSync as existsSync2,
15927
+ mkdirSync as mkdirSync2,
15928
+ readFileSync as readFileSync3,
15929
+ realpathSync as realpathSync2,
15930
+ unlinkSync,
15931
+ writeFileSync
15932
+ } from "fs";
15933
+ import { homedir as homedir3, tmpdir as tmpdir2 } from "os";
15934
+ import { dirname as dirname5, join as join7 } from "path";
15935
+ import { fileURLToPath as fileURLToPath2 } from "url";
15936
+ var PACKAGE_NAME = "@vectorize-io/hindsight-coding-agents";
15937
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
15938
+ var FETCH_TIMEOUT_MS = 5e3;
15939
+ function stateFile(runtimeDir) {
15940
+ return join7(runtimeDir, ".update-check.json");
15742
15941
  }
15743
- function diag(harness, event, extra = {}) {
15744
- log.debug(harness, `diag:${event}`, extra);
15942
+ function packageRoot() {
15943
+ return join7(dirname5(fileURLToPath2(import.meta.url)), "..");
15944
+ }
15945
+ function stagedRuntimeDir() {
15946
+ return join7(homedir3(), ".hindsight", "coding-agents");
15947
+ }
15948
+ function sameDir(a, b) {
15745
15949
  try {
15746
- appendFileSync2(
15747
- diagFilePath(),
15748
- JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
15749
- );
15950
+ return realpathSync2(a) === realpathSync2(b);
15951
+ } catch {
15952
+ return a === b;
15953
+ }
15954
+ }
15955
+ function stagedVersion(pkgRoot) {
15956
+ try {
15957
+ const pkg = JSON.parse(readFileSync3(join7(pkgRoot, "package.json"), "utf8"));
15958
+ return typeof pkg.version === "string" ? pkg.version : "";
15959
+ } catch {
15960
+ return "";
15961
+ }
15962
+ }
15963
+ function isNewer(candidate, current2) {
15964
+ const parse3 = (v) => {
15965
+ const [core = "", ...rest] = v.trim().split("-");
15966
+ return {
15967
+ nums: core.split(".").map((n) => Number.parseInt(n, 10)),
15968
+ pre: rest.length > 0
15969
+ };
15970
+ };
15971
+ const a = parse3(candidate);
15972
+ const b = parse3(current2);
15973
+ if (a.nums.length !== 3 || b.nums.length !== 3) return false;
15974
+ if (a.nums.some(Number.isNaN) || b.nums.some(Number.isNaN)) return false;
15975
+ for (let i = 0; i < 3; i++) {
15976
+ if (a.nums[i] !== b.nums[i]) return a.nums[i] > b.nums[i];
15977
+ }
15978
+ return b.pre && !a.pre;
15979
+ }
15980
+ function dueForCheck(file2, now) {
15981
+ try {
15982
+ const state = JSON.parse(readFileSync3(file2, "utf8"));
15983
+ return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
15984
+ } catch {
15985
+ return true;
15986
+ }
15987
+ }
15988
+ var ORIGIN_FILE = ".install-origin.json";
15989
+ function selfUpdatable(runtimeDir) {
15990
+ try {
15991
+ const origin = JSON.parse(readFileSync3(join7(runtimeDir, ORIGIN_FILE), "utf8"));
15992
+ if (typeof origin.source !== "string" || !origin.source) return false;
15993
+ return origin.source.split(/[\\/]/).includes("_npx");
15994
+ } catch {
15995
+ return false;
15996
+ }
15997
+ }
15998
+ var LOCK_STALE_MS = 10 * 60 * 1e3;
15999
+ function lockFile() {
16000
+ return join7(tmpdir2(), "hindsight-coding-agent", "auto-update.lock");
16001
+ }
16002
+ function acquireUpdateLock(file2, now) {
16003
+ try {
16004
+ const held = JSON.parse(readFileSync3(file2, "utf8"));
16005
+ if (held.ts && now - held.ts < LOCK_STALE_MS) {
16006
+ let holderAlive = false;
16007
+ if (held.pid) {
16008
+ try {
16009
+ process.kill(held.pid, 0);
16010
+ holderAlive = true;
16011
+ } catch {
16012
+ }
16013
+ }
16014
+ if (holderAlive) return false;
16015
+ }
16016
+ } catch {
16017
+ }
16018
+ try {
16019
+ mkdirSync2(dirname5(file2), { recursive: true });
16020
+ writeFileSync(file2, JSON.stringify({ pid: process.pid, ts: now }));
16021
+ return true;
16022
+ } catch {
16023
+ return false;
16024
+ }
16025
+ }
16026
+ function holdLockFor(file2, pid, now) {
16027
+ try {
16028
+ if (pid === void 0) return releaseUpdateLock(file2);
16029
+ writeFileSync(file2, JSON.stringify({ pid, ts: now }));
16030
+ } catch {
16031
+ }
16032
+ }
16033
+ function releaseUpdateLock(file2) {
16034
+ try {
16035
+ unlinkSync(file2);
16036
+ } catch {
16037
+ }
16038
+ }
16039
+ function stampCheck(file2, now, latest) {
16040
+ try {
16041
+ writeFileSync(file2, JSON.stringify({ lastCheck: now, latest }));
16042
+ } catch {
16043
+ }
16044
+ }
16045
+ async function latestVersion(fetchImpl) {
16046
+ try {
16047
+ const r = await fetchImpl(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, {
16048
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
16049
+ headers: { accept: "application/vnd.npm.install-v1+json" }
16050
+ });
16051
+ if (!r.ok) return "";
16052
+ const body = await r.json();
16053
+ return typeof body.version === "string" ? body.version : "";
15750
16054
  } catch {
16055
+ return "";
16056
+ }
16057
+ }
16058
+ async function maybeAutoUpdate(cfg, opts = {}) {
16059
+ try {
16060
+ if (!cfg.autoUpdate) return "";
16061
+ if (process.env.HINDSIGHT_DISABLE_HOOKS) return "";
16062
+ const pkgRoot = opts.pkgRoot ?? packageRoot();
16063
+ const runtime = opts.runtimeDir ?? stagedRuntimeDir();
16064
+ if (!existsSync2(runtime)) return "";
16065
+ if (!sameDir(pkgRoot, runtime)) return "";
16066
+ const now = opts.now ?? Date.now();
16067
+ const file2 = stateFile(runtime);
16068
+ if (!dueForCheck(file2, now)) return "";
16069
+ const current2 = stagedVersion(pkgRoot);
16070
+ if (!current2) return "";
16071
+ if (!(opts.selfUpdatable ?? selfUpdatable)(runtime)) {
16072
+ log.info("auto-update", "runtime is managed outside npx \u2014 leaving its version alone");
16073
+ stampCheck(file2, now, "");
16074
+ return "";
16075
+ }
16076
+ if (!(opts.binOnPath ?? binOnPath)("npx")) {
16077
+ log.info("auto-update", "npx is not on PATH \u2014 skipping the update check");
16078
+ stampCheck(file2, now, "");
16079
+ return "";
16080
+ }
16081
+ const lock = opts.lockFile ?? lockFile();
16082
+ if (!acquireUpdateLock(lock, now)) return "";
16083
+ try {
16084
+ const latest = await latestVersion(opts.fetch ?? fetch);
16085
+ stampCheck(file2, now, latest);
16086
+ if (!latest || !isNewer(latest, current2)) {
16087
+ releaseUpdateLock(lock);
16088
+ return "";
16089
+ }
16090
+ log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
16091
+ const child = (opts.spawn ?? realSpawn2)(
16092
+ "npx",
16093
+ ["-y", `${PACKAGE_NAME}@${latest}`, "update"],
16094
+ {
16095
+ detached: true,
16096
+ stdio: "ignore",
16097
+ windowsHide: true
16098
+ }
16099
+ );
16100
+ child.on("error", (e) => {
16101
+ log.warn("auto-update", `update spawn failed: ${e.message}`);
16102
+ releaseUpdateLock(lock);
16103
+ });
16104
+ child.unref();
16105
+ holdLockFor(lock, child.pid, now);
16106
+ return latest;
16107
+ } catch (e) {
16108
+ releaseUpdateLock(lock);
16109
+ throw e;
16110
+ }
16111
+ } catch {
16112
+ return "";
15751
16113
  }
15752
16114
  }
15753
16115
 
15754
16116
  // src/core/daemon.ts
15755
- import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
15756
- import { dirname as dirname4, join as join5 } from "path";
15757
- import { fileURLToPath as fileURLToPath2 } from "url";
16117
+ import { execFileSync, spawn as realSpawn3 } from "child_process";
16118
+ import { dirname as dirname6, join as join8 } from "path";
16119
+ import { fileURLToPath as fileURLToPath3 } from "url";
15758
16120
  var DAEMON_WAIT_SESSION_START_MS = 12e3;
15759
16121
  var DAEMON_WAIT_RETAIN_MS = 4e4;
15760
16122
  async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
@@ -15768,7 +16130,7 @@ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
15768
16130
  function hasRustToolchain() {
15769
16131
  if (process.platform !== "darwin") return true;
15770
16132
  try {
15771
- execFileSync2("cargo", ["--version"], {
16133
+ execFileSync("cargo", ["--version"], {
15772
16134
  stdio: "pipe",
15773
16135
  timeout: 1e4,
15774
16136
  windowsHide: true
@@ -15780,7 +16142,7 @@ function hasRustToolchain() {
15780
16142
  }
15781
16143
  function hasUvx() {
15782
16144
  try {
15783
- execFileSync2("uvx", ["--version"], {
16145
+ execFileSync("uvx", ["--version"], {
15784
16146
  stdio: "pipe",
15785
16147
  timeout: 1e4,
15786
16148
  windowsHide: true
@@ -15816,7 +16178,7 @@ function detectLlm(env = process.env) {
15816
16178
  }
15817
16179
  function onPath(bin) {
15818
16180
  try {
15819
- execFileSync2("which", [bin], {
16181
+ execFileSync("which", [bin], {
15820
16182
  stdio: "pipe",
15821
16183
  timeout: 5e3,
15822
16184
  windowsHide: true
@@ -15826,9 +16188,9 @@ function onPath(bin) {
15826
16188
  return false;
15827
16189
  }
15828
16190
  }
15829
- function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
16191
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn3) {
15830
16192
  try {
15831
- const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
16193
+ const starter = join8(dirname6(fileURLToPath3(import.meta.url)), "daemon-start.js");
15832
16194
  const child = spawnFn("node", [starter, "--harness", harness], {
15833
16195
  detached: true,
15834
16196
  stdio: "ignore",
@@ -15882,25 +16244,25 @@ function preflightDaemon(cfg, harness) {
15882
16244
  }
15883
16245
 
15884
16246
  // src/core/knowledge-tools.ts
15885
- import { existsSync as existsSync3 } from "fs";
15886
- import { homedir as homedir4 } from "os";
15887
- import { join as join7 } from "path";
16247
+ import { existsSync as existsSync4 } from "fs";
16248
+ import { homedir as homedir5 } from "os";
16249
+ import { join as join10 } from "path";
15888
16250
 
15889
16251
  // src/core/status.ts
15890
- import { execFileSync as execFileSync4 } from "child_process";
16252
+ import { execFileSync as execFileSync3 } from "child_process";
15891
16253
 
15892
16254
  // src/core/git.ts
15893
- import { execFileSync as execFileSync3 } from "child_process";
15894
- import { resolve } from "path";
16255
+ import { execFileSync as execFileSync2 } from "child_process";
16256
+ import { resolve as resolve2 } from "path";
15895
16257
  function git(repo, ...args) {
15896
- return execFileSync3("git", ["-C", repo, ...args], {
16258
+ return execFileSync2("git", ["-C", repo, ...args], {
15897
16259
  encoding: "utf8",
15898
16260
  maxBuffer: 1 << 28,
15899
16261
  windowsHide: true
15900
16262
  });
15901
16263
  }
15902
16264
  function repoNameOf(repo) {
15903
- return projectNameOf(resolve(repo));
16265
+ return projectNameOf(resolve2(repo));
15904
16266
  }
15905
16267
  function gitHeadSha(dir) {
15906
16268
  try {
@@ -15970,11 +16332,11 @@ ${toolGuide(opts)}
15970
16332
  }
15971
16333
 
15972
16334
  // src/core/survey.ts
15973
- import { spawn as realSpawn3 } from "child_process";
15974
- import { accessSync, constants, existsSync as existsSync2 } from "fs";
15975
- import { homedir as homedir3 } from "os";
15976
- import { delimiter, dirname as dirname5, join as join6 } from "path";
15977
- import { fileURLToPath as fileURLToPath3 } from "url";
16335
+ import { spawn as realSpawn4 } from "child_process";
16336
+ import { existsSync as existsSync3 } from "fs";
16337
+ import { homedir as homedir4 } from "os";
16338
+ import { dirname as dirname7, join as join9 } from "path";
16339
+ import { fileURLToPath as fileURLToPath4 } from "url";
15978
16340
  var SURVEY_DOC_IDS = [
15979
16341
  "repository-component-map",
15980
16342
  "repository-core-concepts",
@@ -15984,9 +16346,9 @@ var SURVEY_DOC_IDS = [
15984
16346
  function resolveClaudeBin(explicit) {
15985
16347
  if (explicit) return explicit;
15986
16348
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
15987
- const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
16349
+ const nativeInstallPath = join9(homedir4(), ".claude", "local", "claude");
15988
16350
  try {
15989
- if (existsSync2(nativeInstallPath)) return nativeInstallPath;
16351
+ if (existsSync3(nativeInstallPath)) return nativeInstallPath;
15990
16352
  } catch {
15991
16353
  }
15992
16354
  return "claude";
@@ -16004,33 +16366,7 @@ function resolveAgentBin(harness, claudeBin) {
16004
16366
  return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
16005
16367
  }
16006
16368
  }
16007
- function binExists(bin) {
16008
- try {
16009
- if (bin.includes("/")) {
16010
- accessSync(bin, constants.X_OK);
16011
- return true;
16012
- }
16013
- for (const dir of (process.env.PATH || "").split(delimiter)) {
16014
- if (!dir) continue;
16015
- try {
16016
- accessSync(join6(dir, bin), constants.X_OK);
16017
- return true;
16018
- } catch {
16019
- }
16020
- }
16021
- return false;
16022
- } catch {
16023
- return false;
16024
- }
16025
- }
16026
- var SURVEY_PROMPT = `You are performing a one-time structural survey of THIS repository to seed its Hindsight memory. Work efficiently \u2014 DO NOT read every file; sample enough to understand the architecture: the directory layout, entry points, package manifests (package.json / pyproject.toml / Cargo.toml / go.mod), the README, and a few representative source files per major area.
16027
- IMPORTANT \u2014 DO NOT read, quote, summarize, or ingest agent-instruction files: CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*, or .github/copilot-instructions.md. These are live, user-controlled instructions (not repository knowledge); capturing them as memory would let a stale copy override the user's current instructions. Exclude them entirely from your survey and from every ingested document.
16028
- Then use the hindsight_ingest_document tool to save what you learned as separate documents (one call each), with these titles and factual, developer-oriented content grounded in what you actually saw:
16029
- - "Repository component map": the top-level modules/directories, each one's responsibility, and how they connect (data flow / dependencies).
16030
- - "Repository core concepts": the domain model and key abstractions a new contributor must understand.
16031
- - "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.
16032
- - "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.
16033
- Keep each a few hundred words. When done, stop.`;
16369
+ var SURVEY_PROMPT = 'You are performing a one-time structural survey of THIS repository to seed its Hindsight memory. Work efficiently \u2014 DO NOT read every file; sample enough to understand the architecture: the directory layout, entry points, package manifests (package.json / pyproject.toml / Cargo.toml / go.mod), the README, and a few representative source files per major area. Use Glob (e.g. `**/*`) to see the directory layout \u2014 Read takes a FILE path only and errors on a directory; never call Read on a bare directory path.\nIMPORTANT \u2014 DO NOT read, quote, summarize, or ingest agent-instruction files: CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*, or .github/copilot-instructions.md. These are live, user-controlled instructions (not repository knowledge); capturing them as memory would let a stale copy override the user\'s current instructions. Exclude them entirely from your survey and from every ingested document.\nThen use the hindsight_ingest_document tool to save what you learned as separate documents (one call each), with these titles and factual, developer-oriented content grounded in what you actually saw:\n- "Repository component map": the top-level modules/directories, each one\'s responsibility, and how they connect (data flow / dependencies).\n- "Repository core concepts": the domain model and key abstractions a new contributor must understand.\n- "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.\n- "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.\nKeep each a few hundred words. When done, stop.';
16034
16370
  var SURVEY_DISALLOWED_TOOLS = [
16035
16371
  "Bash",
16036
16372
  "Write",
@@ -16126,9 +16462,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
16126
16462
  }
16127
16463
  function startCodebaseSurvey(repoDir, opts = {}) {
16128
16464
  try {
16129
- const spawnFn = opts.spawn ?? realSpawn3;
16130
- const exists = opts.exists ?? binExists;
16131
- const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
16465
+ const spawnFn = opts.spawn ?? realSpawn4;
16466
+ const exists = opts.exists ?? binOnPath;
16467
+ const mcpServerPath = opts.mcpServerPath ?? join9(dirname7(fileURLToPath4(import.meta.url)), "mcp-server.js");
16132
16468
  const preferred = opts.harness ?? "claude-code";
16133
16469
  const order = [
16134
16470
  preferred,
@@ -16168,7 +16504,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
16168
16504
  var DEEPEN_DIFF_TARGET = 300;
16169
16505
  function commitCount(repoDir) {
16170
16506
  try {
16171
- const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16507
+ const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16172
16508
  encoding: "utf8",
16173
16509
  windowsHide: true
16174
16510
  });
@@ -16178,17 +16514,17 @@ function commitCount(repoDir) {
16178
16514
  }
16179
16515
  }
16180
16516
  async function syncStatus(client, bank, repoDir) {
16181
- const gitIds = await client.listDocumentIds("source:git");
16182
- const chatIds = await client.listDocumentIds("source:chat").catch(() => /* @__PURE__ */ new Set());
16517
+ const gitIds = await client.listDocumentIds("source:git", "all_strict");
16518
+ const chatIds = await client.listDocumentIds("source:chat", "all_strict").catch(() => /* @__PURE__ */ new Set());
16183
16519
  const pages = parsePageList(await client.listPages().catch(() => null));
16184
16520
  const activeOps = await client.activeOperations().catch(() => null);
16185
- const uploads = await client.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
16521
+ const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
16186
16522
  const surveyDocs = SURVEY_DOC_IDS.filter((id) => uploads.has(id)).length;
16187
16523
  let surveyBaseline = null;
16188
16524
  let surveyCommitsBehind = null;
16189
16525
  if (repoDir) {
16190
16526
  try {
16191
- const markers = await client.listDocumentIds("source:survey-baseline");
16527
+ const markers = await client.listDocumentIds("source:survey-baseline", "all_strict");
16192
16528
  let best;
16193
16529
  for (const id of markers) {
16194
16530
  const sha = id.replace(/^survey-baseline:/, "");
@@ -16225,6 +16561,18 @@ async function syncStatus(client, bank, repoDir) {
16225
16561
  }
16226
16562
 
16227
16563
  // src/core/knowledge-tools.ts
16564
+ var READ_ONLY_ANNOTATIONS = {
16565
+ readOnlyHint: true,
16566
+ destructiveHint: false,
16567
+ idempotentHint: true,
16568
+ openWorldHint: false
16569
+ };
16570
+ var NON_DESTRUCTIVE_WRITE_ANNOTATIONS = {
16571
+ readOnlyHint: false,
16572
+ destructiveHint: false,
16573
+ idempotentHint: false,
16574
+ openWorldHint: false
16575
+ };
16228
16576
  function ok(value) {
16229
16577
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
16230
16578
  }
@@ -16247,6 +16595,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16247
16595
  name: "hindsight_sync_status",
16248
16596
  description: "Report whether this repo's memory bank is in sync: gitlog seed present, how much recent history has been deepened with full diffs, conversations ingested, knowledge pages created, and extractions still running. `synced: true` means the seeded memory is fully queryable. Ingestion is automatic and background \u2014 if not synced, it is in progress; nothing to run.",
16249
16597
  inputSchema: {},
16598
+ annotations: READ_ONLY_ANNOTATIONS,
16250
16599
  handler: async () => {
16251
16600
  try {
16252
16601
  return ok(await syncStatus(client, bankId, opts.repoDir ?? process.cwd()));
@@ -16259,8 +16608,9 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16259
16608
  name: "hindsight_diagnose",
16260
16609
  description: "Report safe Hindsight runtime diagnostics for this coding-agent session: resolved bank, workspace, harness, config location, API endpoint, and non-secret environment overrides. Use this when memory, hooks, MCP tools, or configuration appear not to work. Tokens and other secret values are never returned.",
16261
16610
  inputSchema: {},
16611
+ annotations: READ_ONLY_ANNOTATIONS,
16262
16612
  handler: async (_args) => {
16263
- const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
16613
+ const configPath = process.env.HINDSIGHT_CONFIG || join10(homedir5(), ".hindsight", "coding-agent.json");
16264
16614
  const harness = opts.harness ?? "unknown";
16265
16615
  const cfg = applyBankConfig(
16266
16616
  loadConfig({ harness: opts.harness }),
@@ -16273,7 +16623,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16273
16623
  workspace: opts.repoDir ?? process.cwd(),
16274
16624
  config: {
16275
16625
  path: configPath,
16276
- exists: existsSync3(configPath),
16626
+ exists: existsSync4(configPath),
16277
16627
  api_url: cfg.apiUrl,
16278
16628
  api_token_configured: Boolean(cfg.apiToken),
16279
16629
  disabled: cfg.disabled
@@ -16301,6 +16651,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16301
16651
  name: "hindsight_search_knowledge_pages",
16302
16652
  description: `Search this repository's Hindsight knowledge pages for content relevant to a query \u2014 hybrid full-text + semantic search, server-side. Call this when the user's question may be answered by the project's accumulated knowledge (architecture, conventions, decisions, initiatives) rather than by reading code. Returns ranked pages with a relevance snippet; read a full page with hindsight_read_knowledge_page. When a result informs your answer, credit it visibly: start that part with a markdown blockquote header "> \u{1F9E0} **From Hindsight memory (<page name>)** \u2014 <the facts you drew on>".`,
16303
16653
  inputSchema: { query: external_exports.string().describe("what to look for") },
16654
+ annotations: READ_ONLY_ANNOTATIONS,
16304
16655
  handler: async (args) => {
16305
16656
  try {
16306
16657
  const hits = await client.searchKnowledgePages(args.query, 3);
@@ -16321,18 +16672,21 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16321
16672
  name: "hindsight_list_knowledge_pages",
16322
16673
  description: "List this repository's Hindsight knowledge pages \u2014 curated, continuously-updated summaries of the project's durable knowledge (architecture, components, conventions, key decisions, and in-flight initiatives). Returns each page's id, title, and a one-line description of what it covers. Call this at the start of any non-trivial task, and again periodically in long sessions, to see what the project already knows before you read code or ask the user. The list changes as work is captured, so re-check it occasionally.",
16323
16674
  inputSchema: {},
16675
+ annotations: READ_ONLY_ANNOTATIONS,
16324
16676
  handler: guarded(async () => client.listPages())
16325
16677
  },
16326
16678
  {
16327
16679
  name: "hindsight_read_knowledge_page",
16328
16680
  description: "Read the full content of one knowledge page by its id (from hindsight_list_knowledge_pages). Call this whenever a listed page is relevant to what you're about to do \u2014 e.g. read Conventions before writing new code, Component map before changing a subsystem, or an initiative's page before continuing that feature. A page may contain [[page:<id>]] links to related pages; follow one by calling this tool again with that id. Prefer reading a page over re-deriving the same understanding from source.",
16329
16681
  inputSchema: { page_id: external_exports.string() },
16682
+ annotations: READ_ONLY_ANNOTATIONS,
16330
16683
  handler: guarded(async ({ page_id }) => client.getPage(page_id))
16331
16684
  },
16332
16685
  {
16333
16686
  name: "hindsight_reflect",
16334
16687
  description: `Deep memory reasoning: an agentic synthesis over this repository's FULL memory (git decisions, past sessions, ingested knowledge) that answers WHY questions \u2014 the past decision and exact rule/values that explain a behavior, bug, or convention. Slower than hindsight_search_knowledge_pages (several seconds): reach for it when pages are too shallow and you need the root cause or the decided literals. When the answer informs your reply, credit it visibly with a blockquote header: "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>".`,
16335
16688
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
16689
+ annotations: READ_ONLY_ANNOTATIONS,
16336
16690
  handler: guarded(
16337
16691
  async ({ query }) => client.reflect(query, {
16338
16692
  budget: opts.reflectBudget ?? "high",
@@ -16348,6 +16702,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16348
16702
  summary: external_exports.string(),
16349
16703
  relates_to_page_id: external_exports.string().optional()
16350
16704
  },
16705
+ annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
16351
16706
  handler: guarded(
16352
16707
  async ({ title, summary, relates_to_page_id }) => client.captureInitiative({
16353
16708
  title,
@@ -16362,6 +16717,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16362
16717
  name: "hindsight_ingest_document",
16363
16718
  description: "Save an external document or a block of durable notes/findings into this repository's memory so it informs future recall and pages. Use for design notes, research, or reference material you want remembered \u2014 not for the conversation you're already in (that's captured automatically at session end). This is ALSO the correction mechanism: when you verify that a retrieved memory is wrong or outdated, ingest a document titled 'Correction: <topic>' stating what memory claimed, what is actually true, and the evidence \u2014 the newer fact supersedes the stale one in future retrieval.",
16364
16719
  inputSchema: { title: external_exports.string(), content: external_exports.string() },
16720
+ annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
16365
16721
  handler: guarded(async ({ title, content }) => {
16366
16722
  const docId = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "doc";
16367
16723
  const stamp = opts.stampFor?.();
@@ -16578,12 +16934,12 @@ function buildRetainStamp(cfg, ctx) {
16578
16934
  const base = resolversFor(ctx);
16579
16935
  const cache = /* @__PURE__ */ new Map();
16580
16936
  const resolvers = Object.fromEntries(
16581
- Object.entries(base).map(([name, resolve2]) => [
16937
+ Object.entries(base).map(([name, resolve3]) => [
16582
16938
  name,
16583
16939
  () => {
16584
16940
  const hit = cache.get(name);
16585
16941
  if (hit !== void 0) return hit;
16586
- const value = resolve2();
16942
+ const value = resolve3();
16587
16943
  cache.set(name, value);
16588
16944
  return value;
16589
16945
  }
@@ -16602,13 +16958,13 @@ function buildRetainStamp(cfg, ctx) {
16602
16958
  }
16603
16959
 
16604
16960
  // src/core/session-start.ts
16605
- import { readFileSync as readFileSync4 } from "fs";
16961
+ import { readFileSync as readFileSync6 } from "fs";
16606
16962
 
16607
16963
  // src/core/skill-sync.ts
16608
- import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
16609
- import { homedir as homedir5 } from "os";
16610
- import { dirname as dirname6, join as join8 } from "path";
16611
- import { fileURLToPath as fileURLToPath4 } from "url";
16964
+ import { cpSync, existsSync as existsSync5, readFileSync as readFileSync4 } from "fs";
16965
+ import { homedir as homedir6 } from "os";
16966
+ import { dirname as dirname8, join as join11 } from "path";
16967
+ import { fileURLToPath as fileURLToPath5 } from "url";
16612
16968
 
16613
16969
  // src/core/brand.ts
16614
16970
  function brandWord() {
@@ -16625,24 +16981,24 @@ function brandWord() {
16625
16981
  }
16626
16982
 
16627
16983
  // src/core/session-cache.ts
16628
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync } from "fs";
16629
- import { tmpdir as tmpdir2 } from "os";
16630
- import { dirname as dirname7, join as join9 } from "path";
16984
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync5, renameSync, rmSync, writeFileSync as writeFileSync2 } from "fs";
16985
+ import { tmpdir as tmpdir3 } from "os";
16986
+ import { dirname as dirname9, join as join12 } from "path";
16631
16987
  function sessionCacheFile(harness, sessionId) {
16632
- return join9(tmpdir2(), `hindsight-${harness}`, `${sessionId}.json`);
16988
+ return join12(tmpdir3(), `hindsight-${harness}`, `${sessionId}.json`);
16633
16989
  }
16634
16990
  function readSessionCache(cacheFile) {
16635
16991
  try {
16636
- return JSON.parse(readFileSync3(cacheFile, "utf8"));
16992
+ return JSON.parse(readFileSync5(cacheFile, "utf8"));
16637
16993
  } catch {
16638
16994
  return {};
16639
16995
  }
16640
16996
  }
16641
16997
  function writeFileAtomic(path, body) {
16642
- mkdirSync2(dirname7(path), { recursive: true });
16998
+ mkdirSync3(dirname9(path), { recursive: true });
16643
16999
  const tmp = `${path}.${process.pid}.tmp`;
16644
17000
  try {
16645
- writeFileSync(tmp, body);
17001
+ writeFileSync2(tmp, body);
16646
17002
  renameSync(tmp, path);
16647
17003
  } catch (e) {
16648
17004
  try {
@@ -16671,15 +17027,15 @@ async function gitSyncNote(args) {
16671
17027
  if (mode === "none" || cold) return void 0;
16672
17028
  const head = gitHeadSha(cwd);
16673
17029
  if (!head) return void 0;
16674
- const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`).then((s) => s.size > 0).catch(() => void 0);
17030
+ const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
16675
17031
  if (gitlogCurrent === void 0) return void 0;
16676
17032
  if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
16677
17033
  const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
16678
17034
  let target = DEEPEN_DIFF_TARGET;
16679
17035
  try {
16680
- const { execFileSync: execFileSync5 } = await import("child_process");
17036
+ const { execFileSync: execFileSync4 } = await import("child_process");
16681
17037
  const n = Number(
16682
- execFileSync5("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
17038
+ execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
16683
17039
  encoding: "utf8",
16684
17040
  windowsHide: true
16685
17041
  }).trim()
@@ -16729,7 +17085,7 @@ async function buildSessionStartContext(args) {
16729
17085
  {
16730
17086
  let docIds;
16731
17087
  try {
16732
- docIds = await client.listDocumentIds("source:git");
17088
+ docIds = await client.listDocumentIds("source:git", "all_strict");
16733
17089
  } catch {
16734
17090
  docIds = void 0;
16735
17091
  }
@@ -16751,7 +17107,7 @@ async function buildSessionStartContext(args) {
16751
17107
  } else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
16752
17108
  const sha = resolveHeadSha(cwd);
16753
17109
  if (sha) {
16754
- const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG).catch(() => /* @__PURE__ */ new Set());
17110
+ const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
16755
17111
  const counts = [];
16756
17112
  for (const id of markers) {
16757
17113
  if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
@@ -16759,7 +17115,7 @@ async function buildSessionStartContext(args) {
16759
17115
  if (n !== null) counts.push(n);
16760
17116
  }
16761
17117
  const sinceLast = counts.length ? Math.min(...counts) : null;
16762
- const uploads = await client.listDocumentIds("source:upload").catch(() => /* @__PURE__ */ new Set());
17118
+ const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
16763
17119
  const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
16764
17120
  if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
16765
17121
  startSurvey(cwd, {
@@ -16810,7 +17166,7 @@ async function buildSessionStartContext(args) {
16810
17166
  }
16811
17167
 
16812
17168
  // src/core/hook.ts
16813
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
17169
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
16814
17170
 
16815
17171
  // src/core/inject.ts
16816
17172
  function buildReflectQuery(prompt) {
@@ -16998,6 +17354,7 @@ var RuntimeCore = class {
16998
17354
  async seedIfCold(repoPath) {
16999
17355
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
17000
17356
  await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
17357
+ void maybeAutoUpdate(this.cfg);
17001
17358
  try {
17002
17359
  const out = await buildSessionStartContext({
17003
17360
  cwd: repoPath || process.cwd(),
@@ -17149,6 +17506,12 @@ var RuntimeCore = class {
17149
17506
  }
17150
17507
  };
17151
17508
 
17509
+ // src/core/jsonl.ts
17510
+ import { closeSync, openSync, readSync, statSync } from "fs";
17511
+ import { StringDecoder } from "string_decoder";
17512
+ var CHUNK_BYTES = 64 * 1024;
17513
+ var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
17514
+
17152
17515
  // src/core/transcript-util.ts
17153
17516
  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;
17154
17517
  function stripInjectedMemory(s) {
@@ -17184,7 +17547,7 @@ function actionLine(tool, input) {
17184
17547
  return target ? `${tool} ${target}` : tool;
17185
17548
  }
17186
17549
 
17187
- // src/core/transcript-prime-agent.ts
17550
+ // src/core/transcript-pi.ts
17188
17551
  function renderMessage(m) {
17189
17552
  if (!m || typeof m !== "object") return [];
17190
17553
  const role = m.role;
@@ -17212,13 +17575,12 @@ function renderMessage(m) {
17212
17575
  out.push(...actions);
17213
17576
  return out;
17214
17577
  }
17215
- function readPrimeAgentMessages(messages) {
17578
+ function readPiMessages(messages) {
17216
17579
  return (messages || []).flatMap((m) => renderMessage(m));
17217
17580
  }
17218
17581
 
17219
- // src/prime-agent.ts
17220
- var HARNESS2 = "prime-agent";
17221
- function toPrimeAgentTool(spec) {
17582
+ // src/harness/pi-extension.ts
17583
+ function toPiTool(spec) {
17222
17584
  const parameters = external_exports.toJSONSchema(external_exports.object(spec.inputSchema));
17223
17585
  return {
17224
17586
  name: spec.name,
@@ -17232,7 +17594,7 @@ function toPrimeAgentTool(spec) {
17232
17594
  }
17233
17595
  };
17234
17596
  }
17235
- function createPrimeAgentHooks(core, sessionStart) {
17597
+ function createPiHooks(core, harness, sessionStart) {
17236
17598
  let sessionStartAwaited = false;
17237
17599
  return {
17238
17600
  async beforeAgentStart(event, sessionId) {
@@ -17244,42 +17606,45 @@ function createPrimeAgentHooks(core, sessionStart) {
17244
17606
  if (prompt) await core.onPrompt(sessionId, prompt);
17245
17607
  const injection = core.getInjection(sessionId);
17246
17608
  if (!injection) {
17247
- diag(HARNESS2, "inject_empty", { session: sessionId });
17609
+ diag(harness, "inject_empty", { session: sessionId });
17248
17610
  return void 0;
17249
17611
  }
17250
- diag(HARNESS2, "inject_ok", { session: sessionId, chars: injection.length });
17612
+ diag(harness, "inject_ok", { session: sessionId, chars: injection.length });
17251
17613
  return { systemPrompt: `${event.systemPrompt}
17252
17614
 
17253
17615
  ${injection}` };
17254
17616
  },
17255
17617
  async agentEnd(event, sessionId) {
17256
- const turns = readPrimeAgentMessages(event.messages);
17618
+ const turns = readPiMessages(event.messages);
17257
17619
  if (turns.length) await core.onTranscript(sessionId, turns);
17258
17620
  }
17259
17621
  };
17260
17622
  }
17261
- function createRuntime(repoPath) {
17262
- const { cfg, bankId, client } = resolveHostMemory(HARNESS2, repoPath);
17623
+ function createRuntime(harness, repoPath) {
17624
+ const { cfg, bankId, client } = resolveHostMemory(harness, repoPath);
17263
17625
  if (cfg.disabled) return void 0;
17264
- return new RuntimeCore(client, bankId, cfg, HARNESS2, repoPath);
17265
- }
17266
- var extension = (pi) => {
17267
- const repoPath = process.cwd();
17268
- const core = createRuntime(repoPath);
17269
- if (!core) return;
17270
- for (const spec of core.toolSpecs()) pi.registerTool(toPrimeAgentTool(spec));
17271
- const sessionStart = core.seedIfCold(repoPath);
17272
- const hooks = createPrimeAgentHooks(core, sessionStart);
17273
- pi.on(
17274
- "before_agent_start",
17275
- (event, ctx) => hooks.beforeAgentStart(event, ctx.sessionManager.getSessionId())
17276
- );
17277
- pi.on("agent_end", (event, ctx) => hooks.agentEnd(event, ctx.sessionManager.getSessionId()));
17278
- };
17626
+ return new RuntimeCore(client, bankId, cfg, harness, repoPath);
17627
+ }
17628
+ function createPiExtension(harness) {
17629
+ return (pi) => {
17630
+ const repoPath = process.cwd();
17631
+ const core = createRuntime(harness, repoPath);
17632
+ if (!core) return;
17633
+ for (const spec of core.toolSpecs()) pi.registerTool(toPiTool(spec));
17634
+ const sessionStart = core.seedIfCold(repoPath);
17635
+ const hooks = createPiHooks(core, harness, sessionStart);
17636
+ pi.on(
17637
+ "before_agent_start",
17638
+ (event, ctx) => hooks.beforeAgentStart(event, ctx.sessionManager.getSessionId())
17639
+ );
17640
+ pi.on("agent_end", (event, ctx) => hooks.agentEnd(event, ctx.sessionManager.getSessionId()));
17641
+ };
17642
+ }
17643
+
17644
+ // src/prime-agent.ts
17645
+ var extension = createPiExtension("prime-agent");
17279
17646
  var prime_agent_default = extension;
17280
17647
  export {
17281
- createPrimeAgentHooks,
17282
17648
  prime_agent_default as default,
17283
- extension,
17284
- toPrimeAgentTool
17649
+ extension
17285
17650
  };