@vectorize-io/hindsight-coding-agents 0.3.3 → 0.4.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.
@@ -14518,11 +14518,48 @@ function date4(params) {
14518
14518
  // node_modules/zod/v4/classic/external.js
14519
14519
  config(en_default());
14520
14520
 
14521
+ // src/core/config.ts
14522
+ import { readFileSync } from "fs";
14523
+ import { homedir as homedir2 } from "os";
14524
+ import { join as join4 } from "path";
14525
+
14526
+ // src/core/seed.ts
14527
+ import { spawn as realSpawn } from "child_process";
14528
+ import { dirname, join } from "path";
14529
+ import { fileURLToPath } from "url";
14530
+ var DEFAULT_SEED_LIMIT = 300;
14531
+ function startBackgroundSeed(repoDir, opts = {}) {
14532
+ try {
14533
+ const spawnFn = opts.spawn ?? realSpawn;
14534
+ const enginePath = opts.enginePath ?? join(dirname(fileURLToPath(import.meta.url)), "deepen.js");
14535
+ const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
14536
+ const child = spawnFn(
14537
+ "node",
14538
+ [
14539
+ enginePath,
14540
+ "--repo",
14541
+ repoDir,
14542
+ "--gitlog-limit",
14543
+ String(limit),
14544
+ ...opts.harness ? ["--harness", opts.harness] : []
14545
+ ],
14546
+ {
14547
+ detached: true,
14548
+ stdio: "ignore"
14549
+ }
14550
+ );
14551
+ child.on("error", () => {
14552
+ });
14553
+ child.unref();
14554
+ } catch {
14555
+ }
14556
+ }
14557
+
14521
14558
  // src/core/bank.ts
14522
14559
  import { execFileSync } from "child_process";
14523
14560
  import { existsSync } from "fs";
14524
14561
  import { homedir } from "os";
14525
- import { basename, dirname, join, normalize, sep } from "path";
14562
+ import { basename, dirname as dirname2, join as join2, normalize, sep } from "path";
14526
14563
 
14527
14564
  // src/core/template.ts
14528
14565
  var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
@@ -14551,20 +14588,20 @@ function getProjectRootFromGit(directory) {
14551
14588
  { cwd: directory, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1e3 }
14552
14589
  ).trim();
14553
14590
  if (!commonDir) return null;
14554
- return basename(commonDir) === ".git" ? dirname(commonDir) : commonDir;
14591
+ return basename(commonDir) === ".git" ? dirname2(commonDir) : commonDir;
14555
14592
  } catch {
14556
14593
  return null;
14557
14594
  }
14558
14595
  }
14559
- function projectNameOf(directory) {
14560
- return gitProjectName(directory, true);
14596
+ function projectNameOf(directory, sessionRoot) {
14597
+ return gitProjectName(directory, true, sessionRoot);
14561
14598
  }
14562
14599
  var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
14563
14600
  function nearestExistingDir(directory) {
14564
14601
  let current2 = directory;
14565
14602
  while (current2) {
14566
14603
  if (existsSync(current2)) return current2;
14567
- const parent = dirname(current2);
14604
+ const parent = dirname2(current2);
14568
14605
  if (parent === current2) return "";
14569
14606
  current2 = parent;
14570
14607
  }
@@ -14573,21 +14610,27 @@ function nearestExistingDir(directory) {
14573
14610
  function dirName(directory) {
14574
14611
  return directory && basename(directory) || "unknown";
14575
14612
  }
14576
- function gitProjectName(directory, resolveWorktrees) {
14613
+ function mainWorktreeRoot(directory, sessionRoot = "") {
14614
+ const candidates = [
14615
+ nearestExistingDir(directory),
14616
+ sessionRoot,
14617
+ ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
14618
+ ];
14619
+ for (const candidate of candidates) {
14620
+ const root = candidate ? getProjectRootFromGit(candidate) : null;
14621
+ if (root) return root;
14622
+ }
14623
+ return null;
14624
+ }
14625
+ function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
14577
14626
  if (resolveWorktrees) {
14578
- const candidates = [
14579
- nearestExistingDir(directory),
14580
- ...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
14581
- ];
14582
- for (const candidate of candidates) {
14583
- const root = candidate ? getProjectRootFromGit(candidate) : null;
14584
- if (root) return basename(root);
14585
- }
14627
+ const root = mainWorktreeRoot(directory, sessionRoot);
14628
+ if (root) return basename(root);
14586
14629
  }
14587
- return dirName(directory);
14630
+ return dirName(sessionRoot || directory);
14588
14631
  }
14589
14632
  function configuredDir(dir) {
14590
- const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
14633
+ const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
14591
14634
  return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
14592
14635
  }
14593
14636
  function isWithin(directory, configured) {
@@ -14604,491 +14647,290 @@ function mapLookup(map2, directory) {
14604
14647
  }
14605
14648
  return best?.bank;
14606
14649
  }
14650
+ function lookupDirectories(config2, directory, sessionRoot = "") {
14651
+ const directories = [normalize(directory)];
14652
+ if (config2.resolveWorktrees ?? true) {
14653
+ const root = mainWorktreeRoot(directory, sessionRoot);
14654
+ const normalizedRoot = root ? normalize(root) : "";
14655
+ if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
14656
+ }
14657
+ return directories;
14658
+ }
14607
14659
  function isOptedIn(config2, directory) {
14608
14660
  if (!config2.optInOnly) return true;
14609
14661
  if (!directory) return false;
14610
- const cwd = normalize(directory);
14611
- if ((config2.optInPaths ?? []).some((dir) => dir && isWithin(cwd, configuredDir(dir))))
14662
+ const directories = lookupDirectories(config2, directory);
14663
+ if (directories.some(
14664
+ (candidate) => (config2.optInPaths ?? []).some(
14665
+ (configured) => configured && isWithin(candidate, configuredDir(configured))
14666
+ )
14667
+ ))
14612
14668
  return true;
14613
- return Boolean(config2.mapPathToBank && mapLookup(config2.mapPathToBank, directory));
14669
+ const pathMap = config2.mapPathToBank;
14670
+ return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
14614
14671
  }
14615
- function deriveBankId(config2, directory, harness = "coding") {
14616
- const mapped = directory && config2.mapPathToBank ? mapLookup(config2.mapPathToBank, directory) : void 0;
14672
+ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
14673
+ const pathMap = config2.mapPathToBank;
14674
+ const mapped = directory && pathMap ? lookupDirectories(config2, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
14617
14675
  if (mapped) return mapped;
14618
14676
  const dynamic = config2.dynamicBankId ?? !config2.bankId;
14619
14677
  if (!dynamic) return config2.bankId || DEFAULT_BANK_NAME;
14620
14678
  const resolvers = {
14621
14679
  harness: () => harness,
14622
14680
  project: () => dirName(directory),
14623
- gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true),
14681
+ gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot),
14624
14682
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
14625
14683
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
14626
14684
  };
14627
14685
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
14628
14686
  }
14629
14687
 
14630
- // src/core/config.ts
14631
- import { readFileSync } from "fs";
14632
- import { homedir as homedir2 } from "os";
14633
- import { join as join3 } from "path";
14634
-
14635
- // src/core/seed.ts
14636
- import { spawn as realSpawn } from "child_process";
14637
- import { dirname as dirname2, join as join2 } from "path";
14638
- import { fileURLToPath } from "url";
14639
- var DEFAULT_SEED_LIMIT = 300;
14640
- function startBackgroundSeed(repoDir, opts = {}) {
14688
+ // src/core/log.ts
14689
+ import { appendFileSync, mkdirSync } from "fs";
14690
+ import { tmpdir } from "os";
14691
+ import { dirname as dirname3, join as join3 } from "path";
14692
+ var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
14693
+ var current = ["debug", "info", "warn", "error"].find(
14694
+ (l) => l === process.env.HINDSIGHT_LOG_LEVEL
14695
+ ) ?? "info";
14696
+ function setLogLevel(level) {
14697
+ if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
14698
+ }
14699
+ function logFilePath() {
14700
+ return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
14701
+ }
14702
+ function write(level, scope, msg, extra) {
14703
+ if (WEIGHT[level] < WEIGHT[current]) return;
14641
14704
  try {
14642
- const spawnFn = opts.spawn ?? realSpawn;
14643
- const enginePath = opts.enginePath ?? join2(dirname2(fileURLToPath(import.meta.url)), "deepen.js");
14644
- const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
14645
- const child = spawnFn(
14646
- "node",
14647
- [
14648
- enginePath,
14649
- "--repo",
14650
- repoDir,
14651
- "--gitlog-limit",
14652
- String(limit),
14653
- ...opts.harness ? ["--harness", opts.harness] : []
14654
- ],
14655
- {
14656
- detached: true,
14657
- stdio: "ignore"
14658
- }
14705
+ const file2 = logFilePath();
14706
+ mkdirSync(dirname3(file2), { recursive: true });
14707
+ appendFileSync(
14708
+ file2,
14709
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
14659
14710
  );
14660
- child.on("error", () => {
14661
- });
14662
- child.unref();
14663
14711
  } catch {
14664
14712
  }
14665
14713
  }
14666
-
14667
- // src/core/config.ts
14668
- var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
14669
- var DEFAULT_DAEMON_PORT = 9077;
14670
- var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
14671
- var DEFAULT_DAEMON_PROFILE = "coding-agent";
14672
- function resolveConfig(raw = {}) {
14673
- const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
14674
- const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
14675
- return {
14676
- serverMode,
14677
- // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
14678
- // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
14679
- // daemon needs no plumbing through eight separate constructors.
14680
- apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
14681
- apiToken: raw.apiToken || void 0,
14682
- apiPort,
14683
- daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
14684
- daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
14685
- embedVersion: raw.embedVersion || void 0,
14686
- embedPackagePath: raw.embedPackagePath || void 0,
14687
- bankId: raw.bankId,
14688
- dynamicBankId: raw.dynamicBankId,
14689
- bankIdTemplate: raw.bankIdTemplate,
14690
- mapPathToBank: raw.mapPathToBank,
14691
- resolveWorktrees: raw.resolveWorktrees,
14692
- optInOnly: raw.optInOnly ?? false,
14693
- // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
14694
- optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
14695
- harness: raw.harness ?? "opencode",
14696
- disabled: raw.disabled ?? false,
14697
- retainSessions: raw.retainSessions ?? true,
14698
- // opencode: write back by default (parity with hook-harness Stop)
14699
- maxParallelRetains: raw.maxParallelRetains || 10,
14700
- reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
14701
- autoReflect: raw.autoReflect ?? true,
14702
- pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
14703
- autoSeed: raw.autoSeed ?? true,
14704
- seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
14705
- codebaseSurvey: raw.codebaseSurvey ?? true,
14706
- surveyModel: raw.surveyModel || "haiku",
14707
- surveyBudgetUsd: raw.surveyBudgetUsd || 2,
14708
- surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
14709
- gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
14710
- // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
14711
- // nested object cannot reach the API as a tag and fail the whole retain.
14712
- retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
14713
- retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
14714
- Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
14715
- ) : {},
14716
- banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
14717
- logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
14718
- };
14714
+ var log = {
14715
+ debug: (scope, msg, extra) => write("debug", scope, msg, extra),
14716
+ info: (scope, msg, extra) => write("info", scope, msg, extra),
14717
+ warn: (scope, msg, extra) => write("warn", scope, msg, extra),
14718
+ error: (scope, msg, extra) => write("error", scope, msg, extra)
14719
+ };
14720
+ function describeError(value, maxChars = 200) {
14721
+ const parts = [];
14722
+ const seen = /* @__PURE__ */ new Set();
14723
+ let current2 = value;
14724
+ while (current2 && !seen.has(current2)) {
14725
+ seen.add(current2);
14726
+ const error51 = current2;
14727
+ const text = typeof error51.message === "string" ? error51.message : String(current2);
14728
+ const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
14729
+ if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
14730
+ current2 = error51.cause;
14731
+ }
14732
+ return (parts.join(": ") || String(value)).slice(0, maxChars);
14719
14733
  }
14720
- function readRaw(path) {
14721
- try {
14722
- return JSON.parse(readFileSync(path, "utf8"));
14723
- } catch (e) {
14724
- if (e?.code !== "ENOENT") {
14725
- console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
14726
- }
14727
- return {};
14734
+
14735
+ // src/core/missions.ts
14736
+ var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
14737
+ var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
14738
+ var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
14739
+ var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
14740
+ var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
14741
+ var OBSERVATIONS_MISSION = "Consolidate durable knowledge about THIS codebase \u2014 recurring patterns, conventions, module responsibilities, and how components relate \u2014 from the ingested commits and conversations. Favor stable structural understanding over one-off details. When a new fact contradicts or supersedes an existing observation, UPDATE that observation to reflect the current state rather than creating a sibling alongside it; note that the rule was revised and when, so the superseded version is visible as history rather than as a competing claim.";
14742
+ var RETAIN_STRATEGIES = {
14743
+ git: { retain_mission: GIT_MISSION, retain_extraction_mode: "verbose" },
14744
+ // ONE big aggregated document (last N commit messages, no diffs) -> a larger chunk size so it stays
14745
+ // in as few chunks as possible and the extractor sees the whole history arc at once.
14746
+ gitlog: {
14747
+ retain_mission: GITLOG_MISSION,
14748
+ retain_extraction_mode: "verbose",
14749
+ retain_chunk_size: 12e3
14750
+ },
14751
+ // ONE strategy for ALL developer conversations — backfilled decision chats and live working
14752
+ // sessions alike (they are the same content type in the same JSON transcript format; the mission
14753
+ // scales extraction to the substance, final-state-wins). Chunk big enough to hold a whole typical
14754
+ // conversation in ONE chunk so the extractor sees the full proposal→revision arc (the 3000
14755
+ // default SPLIT them into per-chunk fragments); very long sessions still split and fall back to
14756
+ // the consolidation layer.
14757
+ conversation: {
14758
+ retain_mission: CONVERSATION_MISSION,
14759
+ retain_extraction_mode: "verbose",
14760
+ retain_chunk_size: 12e3
14761
+ },
14762
+ // Structural documents (e.g. the codebase survey's ingested findings) aren't dialogue — the
14763
+ // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. Verbose mode
14764
+ // with a bigger chunk size (documents can run long) captures the concrete facts/structure instead.
14765
+ document: {
14766
+ retain_mission: DOCUMENT_MISSION,
14767
+ retain_extraction_mode: "verbose",
14768
+ retain_chunk_size: 12e3
14769
+ },
14770
+ // Codebase-SURVEY lifecycle documents, ONE strategy with conditional rules: the survey's
14771
+ // internal status markers ("researching…"/"completed" baselines) must yield ZERO memories,
14772
+ // while any actual survey findings routed here extract as concrete structural facts.
14773
+ survey: {
14774
+ retain_extraction_mode: "custom",
14775
+ retain_custom_instructions: "This document belongs to the Hindsight codebase-survey lifecycle. Apply ONE of two rules: (1) If the content is an internal status marker \u2014 it says it is an internal marker, or merely announces that a survey started/completed at some commit \u2014 extract NOTHING: return an empty list of facts. (2) Otherwise the content is survey FINDINGS about the codebase: extract the concrete structural facts it states (components and their responsibilities, key concepts, conventions, tech stack), preserving identifiers verbatim.",
14776
+ retain_chunk_size: 12e3
14728
14777
  }
14778
+ };
14779
+ var KNOWLEDGE_LABELS = {
14780
+ key: "knowledge",
14781
+ type: "multi-values",
14782
+ // 0, 1, or several — empty is normal
14783
+ optional: true,
14784
+ tag: true,
14785
+ // emits knowledge:<value> onto the fact's tags
14786
+ description: "Routing labels for this project's Hindsight KNOWLEDGE PAGES \u2014 curated, human-readable summaries of the repo's DURABLE engineering knowledge (architecture, key decisions, conventions, ongoing initiatives), each page rebuilt automatically from the facts labeled for it. Mark a fact only when it is durable, reusable knowledge a developer would still want surfaced in future sessions. IMPORTANT: leave this EMPTY for routine, transient, or operational facts \u2014 a passing test, a one-off command, a status update, a debugging dead-end. MOST facts should get no label here. Assign more than one value only when the fact genuinely fits several.",
14787
+ values: [
14788
+ {
14789
+ value: "feature-work",
14790
+ description: "A new feature, initiative, or enhancement being planned or built \u2014 the capability being added and the intent behind it. Not routine bug-fixes or chores."
14791
+ },
14792
+ {
14793
+ value: "decision",
14794
+ description: "A technical decision that will constrain future work, with its rationale \u2014 why this approach was chosen over alternatives, or a rule deliberately adopted."
14795
+ },
14796
+ {
14797
+ value: "convention",
14798
+ description: "An established way this project does things \u2014 naming, structure, testing, error handling, or another recurring pattern a contributor is expected to follow."
14799
+ },
14800
+ {
14801
+ value: "component",
14802
+ description: "What a specific module, file, service, or subsystem is responsible for, or how components depend on and connect to one another."
14803
+ },
14804
+ {
14805
+ value: "concept",
14806
+ description: "A domain concept, key abstraction, or piece of project vocabulary a new contributor must understand to work effectively."
14807
+ }
14808
+ ]
14809
+ };
14810
+ function pageScopeRule(project) {
14811
+ return ` Scope this page to ${project} ITSELF: the bank also holds facts about external tools, libraries and services that ${project} merely uses, configures, deploys or discusses, and those belong to somebody else's codebase. Include something only when its subject is ${project}'s own code, configuration or process; when it is about a dependency, leave it out however well-evidenced it looks \u2014 including any commit SHA or identifier that belongs to that dependency's repository rather than this one.`;
14729
14812
  }
14730
- function mergeRaw(a, b) {
14731
- const { harnesses: _drop, ...flat } = b;
14732
- return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
14813
+ var PAGE_TAXONOMY = [
14814
+ {
14815
+ name: "Component map",
14816
+ source_query: "From this project's commit history and past discussions, what are the main components/modules/subsystems, what is each responsible for, and how do they relate to or depend on one another? Describe the structure and responsibilities.",
14817
+ tags: ["knowledge:component"]
14818
+ },
14819
+ {
14820
+ name: "Core concepts",
14821
+ source_query: "What are the core concepts, domain abstractions, and key entities in this project \u2014 the vocabulary a developer must understand? For each, explain what it represents and its role, drawn from how they are introduced and discussed across the history and conversations.",
14822
+ tags: ["knowledge:concept"]
14823
+ },
14824
+ {
14825
+ name: "Conventions and patterns",
14826
+ source_query: "What conventions, idioms, and recurring patterns does this project follow \u2014 its approach to testing, error handling, naming, structure, and how changes are typically made? Describe how THIS project does things, as evidenced across its history and discussions.",
14827
+ tags: ["knowledge:convention"]
14828
+ },
14829
+ {
14830
+ name: "Key decisions and rationale",
14831
+ source_query: "What are the significant technical decisions made in this project and the rationale behind them \u2014 the durable 'why we do it this way' a developer should know? Summarize the decisions and their reasoning from the commit rationales and past conversations.",
14832
+ tags: ["knowledge:decision"]
14833
+ },
14834
+ {
14835
+ name: "Initiatives and enhancements",
14836
+ source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory carries a tag of the form `relatedPageId:<id>`, include a Markdown link `[[page:<id>]]` to that page in the summary, so each initiative links to its detailed page.",
14837
+ tags: ["knowledge:feature-work"]
14838
+ }
14839
+ ];
14840
+ function pagesFor(project) {
14841
+ const scope = pageScopeRule(project);
14842
+ return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
14733
14843
  }
14734
- function applyLayer(raw, layer, harness) {
14735
- let out = mergeRaw(raw, layer);
14736
- const perHarness = harness ? layer.harnesses?.[harness] : void 0;
14737
- if (perHarness) out = mergeRaw(out, perHarness);
14738
- return out;
14844
+ var PAGE_MAX_TOKENS = 4096;
14845
+ var PAGE_FACT_TYPES = ["world", "experience", "observation"];
14846
+ function buildPageTrigger(cfg = {}) {
14847
+ const base = { fact_types: PAGE_FACT_TYPES };
14848
+ switch (cfg.pageTriggerType) {
14849
+ case "cron":
14850
+ return { ...base, refresh_cron: cfg.pageTriggerCron };
14851
+ case "manual":
14852
+ return { ...base, refresh_after_consolidation: false };
14853
+ default:
14854
+ return { ...base, refresh_after_consolidation: true };
14855
+ }
14739
14856
  }
14740
- var ENV_KEYS = {
14741
- serverMode: "HINDSIGHT_SERVER_MODE",
14742
- apiUrl: "HINDSIGHT_API_URL",
14743
- apiToken: "HINDSIGHT_API_TOKEN",
14744
- // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
14745
- // it can carry their existing environment over unchanged.
14746
- apiPort: "HINDSIGHT_API_PORT",
14747
- daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
14748
- embedVersion: "HINDSIGHT_EMBED_VERSION",
14749
- embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
14750
- daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
14751
- bankId: "HINDSIGHT_BANK_ID",
14752
- dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
14753
- bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
14754
- resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
14755
- optInOnly: "HINDSIGHT_OPT_IN_ONLY",
14756
- optInPaths: "HINDSIGHT_OPT_IN_PATHS",
14757
- harness: "HINDSIGHT_HARNESS",
14758
- disabled: "HINDSIGHT_DISABLED",
14759
- retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
14760
- maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
14761
- reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
14762
- autoReflect: "HINDSIGHT_AUTO_REFLECT",
14763
- pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
14764
- autoSeed: "HINDSIGHT_AUTO_SEED",
14765
- seedLimit: "HINDSIGHT_SEED_LIMIT",
14766
- codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
14767
- surveyModel: "HINDSIGHT_SURVEY_MODEL",
14768
- surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
14769
- surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
14770
- logLevel: "HINDSIGHT_LOG_LEVEL",
14771
- gitIngest: "HINDSIGHT_GIT_INGEST",
14772
- // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
14773
- // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
14774
- retainTags: "HINDSIGHT_RETAIN_TAGS"
14857
+ var CODING_BANK_TEMPLATE = {
14858
+ version: "1",
14859
+ bank: {
14860
+ reflect_mission: REFLECT_MISSION,
14861
+ enable_observations: true,
14862
+ observations_mission: OBSERVATIONS_MISSION,
14863
+ retain_mission: GIT_MISSION,
14864
+ retain_extraction_mode: "verbose",
14865
+ retain_default_strategy: "git",
14866
+ retain_strategies: RETAIN_STRATEGIES,
14867
+ entity_labels: [KNOWLEDGE_LABELS],
14868
+ entities_allow_free_form: true
14869
+ }
14775
14870
  };
14776
- var ENV_BOOLEANS = /* @__PURE__ */ new Set([
14777
- "dynamicBankId",
14778
- "resolveWorktrees",
14779
- "optInOnly",
14780
- "disabled",
14781
- "retainSessions",
14782
- "autoReflect",
14783
- "autoSeed",
14784
- "codebaseSurvey"
14785
- ]);
14786
- var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
14787
- var ENV_NUMBERS = /* @__PURE__ */ new Set([
14788
- "apiPort",
14789
- "daemonIdleTimeout",
14790
- "maxParallelRetains",
14791
- "reflectTimeoutMs",
14792
- "pageRefreshEveryTurns",
14793
- "seedLimit",
14794
- "surveyBudgetUsd",
14795
- "surveyRefreshCommits"
14796
- ]);
14797
- function readEnvConfig(env = process.env) {
14798
- const out = {};
14799
- for (const [key, name] of Object.entries(ENV_KEYS)) {
14800
- const value = env[name];
14801
- if (value === void 0 || value.trim() === "") continue;
14802
- if (ENV_BOOLEANS.has(key)) {
14803
- out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
14804
- } else if (ENV_LISTS.has(key)) {
14805
- const items = value.split(",").map((v) => v.trim()).filter(Boolean);
14806
- if (items.length) out[key] = items;
14807
- } else if (ENV_NUMBERS.has(key)) {
14808
- const n = Number(value);
14809
- if (Number.isFinite(n)) out[key] = n;
14810
- else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
14811
- } else {
14812
- out[key] = value;
14813
- }
14871
+ var CODING_BANK_STRUCTURE = {
14872
+ version: "1",
14873
+ bank: {
14874
+ retain_strategies: RETAIN_STRATEGIES,
14875
+ entity_labels: [KNOWLEDGE_LABELS]
14814
14876
  }
14815
- return out;
14816
- }
14817
- function loadConfig(opts = {}) {
14818
- const o = typeof opts === "string" ? { path: opts } : opts;
14819
- const withEnv = applyLayer({}, readEnvConfig(), o.harness);
14820
- const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
14821
- if (!raw.harness && o.harness) raw.harness = o.harness;
14822
- return resolveConfig(raw);
14823
- }
14824
- var BANK_OVERRIDE_EXCLUDED = [
14825
- "bankId",
14826
- "bankIdTemplate",
14827
- "mapPathToBank",
14828
- "dynamicBankId",
14829
- "resolveWorktrees",
14830
- // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
14831
- // only ever arrive too late to matter — strip them rather than let them read as effective.
14832
- "optInOnly",
14833
- "optInPaths",
14834
- "harness"
14835
- ];
14836
- function applyBankConfig(cfg, resolvedId, directory) {
14837
- if (directory !== void 0 && !isOptedIn(cfg, directory))
14838
- return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
14839
- const section = cfg.banks[resolvedId];
14840
- if (!section) return { cfg, bankId: resolvedId };
14841
- const safe = { ...section };
14842
- for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
14843
- delete safe.banks;
14844
- const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
14845
- delete safe.bank;
14846
- return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
14877
+ };
14878
+
14879
+ // src/core/util.ts
14880
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
14881
+ function semverGte(version2, min) {
14882
+ const parts = (v) => {
14883
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
14884
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
14885
+ };
14886
+ const a = version2 ? parts(version2) : void 0;
14887
+ const b = parts(min);
14888
+ if (!a || !b) return false;
14889
+ for (let i = 0; i < 3; i++) {
14890
+ if (a[i] !== b[i]) return a[i] > b[i];
14891
+ }
14892
+ return true;
14847
14893
  }
14848
- function resolvePartial(cfg, patch) {
14849
- const full = resolveConfig(patch);
14850
- const out = {};
14851
- for (const key of Object.keys(patch)) {
14852
- if (key in full)
14853
- out[key] = full[key];
14894
+ async function pool(items, n, fn, onError, onProgress) {
14895
+ let i = 0, done = 0;
14896
+ async function worker() {
14897
+ while (i < items.length) {
14898
+ const idx = i++;
14899
+ try {
14900
+ await fn(items[idx], idx);
14901
+ } catch (e) {
14902
+ onError?.(idx, e);
14903
+ }
14904
+ onProgress?.(++done, items.length);
14905
+ }
14854
14906
  }
14855
- return out;
14907
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
14856
14908
  }
14857
14909
 
14858
- // src/core/diag.ts
14859
- import { appendFileSync as appendFileSync2 } from "fs";
14860
-
14861
- // src/core/log.ts
14862
- import { appendFileSync, mkdirSync } from "fs";
14863
- import { tmpdir } from "os";
14864
- import { dirname as dirname3, join as join4 } from "path";
14865
- var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
14866
- var current = ["debug", "info", "warn", "error"].find(
14867
- (l) => l === process.env.HINDSIGHT_LOG_LEVEL
14868
- ) ?? "info";
14869
- function setLogLevel(level) {
14870
- if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
14871
- }
14872
- function logFilePath() {
14873
- return process.env.HINDSIGHT_LOG_FILE || join4(tmpdir(), "hindsight-coding-agent", "plugin.log");
14874
- }
14875
- function write(level, scope, msg, extra) {
14876
- if (WEIGHT[level] < WEIGHT[current]) return;
14877
- try {
14878
- const file2 = logFilePath();
14879
- mkdirSync(dirname3(file2), { recursive: true });
14880
- appendFileSync(
14881
- file2,
14882
- `${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
14883
- );
14884
- } catch {
14910
+ // src/core/hindsight.ts
14911
+ var DEFAULT_OBSERVATION_SCOPES = "shared";
14912
+ var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
14913
+ var RateLimitedError = class extends Error {
14914
+ constructor(retryAfterMs2) {
14915
+ super(`rate limited; retry after ${Math.round(retryAfterMs2 / 1e3)}s`);
14916
+ this.retryAfterMs = retryAfterMs2;
14917
+ this.name = "RateLimitedError";
14885
14918
  }
14886
- }
14887
- var log = {
14888
- debug: (scope, msg, extra) => write("debug", scope, msg, extra),
14889
- info: (scope, msg, extra) => write("info", scope, msg, extra),
14890
- warn: (scope, msg, extra) => write("warn", scope, msg, extra),
14891
- error: (scope, msg, extra) => write("error", scope, msg, extra)
14919
+ retryAfterMs;
14920
+ code = "rate_limited";
14892
14921
  };
14893
-
14894
- // src/core/diag.ts
14895
- function diagFilePath() {
14896
- return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
14922
+ function retryAfterMs(header) {
14923
+ if (!header) return 0;
14924
+ const secs = Number(header.trim());
14925
+ if (Number.isFinite(secs) && secs >= 0) return secs * 1e3;
14926
+ const at = Date.parse(header);
14927
+ return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
14897
14928
  }
14898
- function diag(harness, event, extra = {}) {
14899
- log.debug(harness, `diag:${event}`, extra);
14900
- try {
14901
- appendFileSync2(
14902
- diagFilePath(),
14903
- JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
14904
- );
14905
- } catch {
14906
- }
14907
- }
14908
-
14909
- // src/core/missions.ts
14910
- var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
14911
- var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
14912
- var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
14913
- var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
14914
- var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
14915
- var OBSERVATIONS_MISSION = "Consolidate durable knowledge about THIS codebase \u2014 recurring patterns, conventions, module responsibilities, and how components relate \u2014 from the ingested commits and conversations. Favor stable structural understanding over one-off details. When a new fact contradicts or supersedes an existing observation, UPDATE that observation to reflect the current state rather than creating a sibling alongside it; note that the rule was revised and when, so the superseded version is visible as history rather than as a competing claim.";
14916
- var RETAIN_STRATEGIES = {
14917
- git: { retain_mission: GIT_MISSION, retain_extraction_mode: "verbose" },
14918
- // ONE big aggregated document (last N commit messages, no diffs) -> a larger chunk size so it stays
14919
- // in as few chunks as possible and the extractor sees the whole history arc at once.
14920
- gitlog: {
14921
- retain_mission: GITLOG_MISSION,
14922
- retain_extraction_mode: "verbose",
14923
- retain_chunk_size: 12e3
14924
- },
14925
- // ONE strategy for ALL developer conversations — backfilled decision chats and live working
14926
- // sessions alike (they are the same content type in the same JSON transcript format; the mission
14927
- // scales extraction to the substance, final-state-wins). Chunk big enough to hold a whole typical
14928
- // conversation in ONE chunk so the extractor sees the full proposal→revision arc (the 3000
14929
- // default SPLIT them into per-chunk fragments); very long sessions still split and fall back to
14930
- // the consolidation layer.
14931
- conversation: {
14932
- retain_mission: CONVERSATION_MISSION,
14933
- retain_extraction_mode: "verbose",
14934
- retain_chunk_size: 12e3
14935
- },
14936
- // Structural documents (e.g. the codebase survey's ingested findings) aren't dialogue — the
14937
- // chat strategy's "final decision vs rejected proposal" extraction doesn't apply. Verbose mode
14938
- // with a bigger chunk size (documents can run long) captures the concrete facts/structure instead.
14939
- document: {
14940
- retain_mission: DOCUMENT_MISSION,
14941
- retain_extraction_mode: "verbose",
14942
- retain_chunk_size: 12e3
14943
- },
14944
- // Codebase-SURVEY lifecycle documents, ONE strategy with conditional rules: the survey's
14945
- // internal status markers ("researching…"/"completed" baselines) must yield ZERO memories,
14946
- // while any actual survey findings routed here extract as concrete structural facts.
14947
- survey: {
14948
- retain_extraction_mode: "custom",
14949
- retain_custom_instructions: "This document belongs to the Hindsight codebase-survey lifecycle. Apply ONE of two rules: (1) If the content is an internal status marker \u2014 it says it is an internal marker, or merely announces that a survey started/completed at some commit \u2014 extract NOTHING: return an empty list of facts. (2) Otherwise the content is survey FINDINGS about the codebase: extract the concrete structural facts it states (components and their responsibilities, key concepts, conventions, tech stack), preserving identifiers verbatim.",
14950
- retain_chunk_size: 12e3
14951
- }
14952
- };
14953
- var KNOWLEDGE_LABELS = {
14954
- key: "knowledge",
14955
- type: "multi-values",
14956
- // 0, 1, or several — empty is normal
14957
- optional: true,
14958
- tag: true,
14959
- // emits knowledge:<value> onto the fact's tags
14960
- description: "Routing labels for this project's Hindsight KNOWLEDGE PAGES \u2014 curated, human-readable summaries of the repo's DURABLE engineering knowledge (architecture, key decisions, conventions, ongoing initiatives), each page rebuilt automatically from the facts labeled for it. Mark a fact only when it is durable, reusable knowledge a developer would still want surfaced in future sessions. IMPORTANT: leave this EMPTY for routine, transient, or operational facts \u2014 a passing test, a one-off command, a status update, a debugging dead-end. MOST facts should get no label here. Assign more than one value only when the fact genuinely fits several.",
14961
- values: [
14962
- {
14963
- value: "feature-work",
14964
- description: "A new feature, initiative, or enhancement being planned or built \u2014 the capability being added and the intent behind it. Not routine bug-fixes or chores."
14965
- },
14966
- {
14967
- value: "decision",
14968
- description: "A technical decision that will constrain future work, with its rationale \u2014 why this approach was chosen over alternatives, or a rule deliberately adopted."
14969
- },
14970
- {
14971
- value: "convention",
14972
- description: "An established way this project does things \u2014 naming, structure, testing, error handling, or another recurring pattern a contributor is expected to follow."
14973
- },
14974
- {
14975
- value: "component",
14976
- description: "What a specific module, file, service, or subsystem is responsible for, or how components depend on and connect to one another."
14977
- },
14978
- {
14979
- value: "concept",
14980
- description: "A domain concept, key abstraction, or piece of project vocabulary a new contributor must understand to work effectively."
14981
- }
14982
- ]
14983
- };
14984
- var PAGES = [
14985
- {
14986
- name: "Component map",
14987
- source_query: "From this project's commit history and past discussions, what are the main components/modules/subsystems, what is each responsible for, and how do they relate to or depend on one another? Describe the structure and responsibilities.",
14988
- tags: ["knowledge:component"]
14989
- },
14990
- {
14991
- name: "Core concepts",
14992
- source_query: "What are the core concepts, domain abstractions, and key entities in this project \u2014 the vocabulary a developer must understand? For each, explain what it represents and its role, drawn from how they are introduced and discussed across the history and conversations.",
14993
- tags: ["knowledge:concept"]
14994
- },
14995
- {
14996
- name: "Conventions and patterns",
14997
- source_query: "What conventions, idioms, and recurring patterns does this project follow \u2014 its approach to testing, error handling, naming, structure, and how changes are typically made? Describe how THIS project does things, as evidenced across its history and discussions.",
14998
- tags: ["knowledge:convention"]
14999
- },
15000
- {
15001
- name: "Key decisions and rationale",
15002
- source_query: "What are the significant technical decisions made in this project and the rationale behind them \u2014 the durable 'why we do it this way' a developer should know? Summarize the decisions and their reasoning from the commit rationales and past conversations.",
15003
- tags: ["knowledge:decision"]
15004
- },
15005
- {
15006
- name: "Initiatives and enhancements",
15007
- source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory carries a tag of the form `relatedPageId:<id>`, include a Markdown link `[[page:<id>]]` to that page in the summary, so each initiative links to its detailed page.",
15008
- tags: ["knowledge:feature-work"]
15009
- }
15010
- ];
15011
- var PAGE_MAX_TOKENS = 4096;
15012
- var PAGE_TRIGGER = {
15013
- fact_types: ["world", "experience", "observation"],
15014
- refresh_after_consolidation: true
15015
- };
15016
- var CODING_BANK_TEMPLATE = {
15017
- version: "1",
15018
- bank: {
15019
- reflect_mission: REFLECT_MISSION,
15020
- enable_observations: true,
15021
- observations_mission: OBSERVATIONS_MISSION,
15022
- retain_mission: GIT_MISSION,
15023
- retain_extraction_mode: "verbose",
15024
- retain_default_strategy: "git",
15025
- retain_strategies: RETAIN_STRATEGIES,
15026
- entity_labels: [KNOWLEDGE_LABELS],
15027
- entities_allow_free_form: true
15028
- }
15029
- };
15030
- var CODING_BANK_STRUCTURE = {
15031
- version: "1",
15032
- bank: {
15033
- retain_strategies: RETAIN_STRATEGIES,
15034
- entity_labels: [KNOWLEDGE_LABELS]
15035
- }
15036
- };
15037
-
15038
- // src/core/util.ts
15039
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
15040
- function semverGte(version2, min) {
15041
- const parts = (v) => {
15042
- const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
15043
- return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
15044
- };
15045
- const a = version2 ? parts(version2) : void 0;
15046
- const b = parts(min);
15047
- if (!a || !b) return false;
15048
- for (let i = 0; i < 3; i++) {
15049
- if (a[i] !== b[i]) return a[i] > b[i];
15050
- }
15051
- return true;
15052
- }
15053
- async function pool(items, n, fn, onError, onProgress) {
15054
- let i = 0, done = 0;
15055
- async function worker() {
15056
- while (i < items.length) {
15057
- const idx = i++;
15058
- try {
15059
- await fn(items[idx], idx);
15060
- } catch (e) {
15061
- onError?.(idx, e);
15062
- }
15063
- onProgress?.(++done, items.length);
15064
- }
15065
- }
15066
- await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
15067
- }
15068
-
15069
- // src/core/hindsight.ts
15070
- var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
15071
- var RateLimitedError = class extends Error {
15072
- constructor(retryAfterMs2) {
15073
- super(`rate limited; retry after ${Math.round(retryAfterMs2 / 1e3)}s`);
15074
- this.retryAfterMs = retryAfterMs2;
15075
- this.name = "RateLimitedError";
15076
- }
15077
- retryAfterMs;
15078
- code = "rate_limited";
15079
- };
15080
- function retryAfterMs(header) {
15081
- if (!header) return 0;
15082
- const secs = Number(header.trim());
15083
- if (Number.isFinite(secs) && secs >= 0) return secs * 1e3;
15084
- const at = Date.parse(header);
15085
- return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
15086
- }
15087
- var KnowledgePagesUnavailableError = class extends Error {
15088
- code = "knowledge_pages_unavailable";
15089
- constructor() {
15090
- super("Hindsight server does not support knowledge pages");
15091
- this.name = "KnowledgePagesUnavailableError";
14929
+ var KnowledgePagesUnavailableError = class extends Error {
14930
+ code = "knowledge_pages_unavailable";
14931
+ constructor() {
14932
+ super("Hindsight server does not support knowledge pages");
14933
+ this.name = "KnowledgePagesUnavailableError";
15092
14934
  }
15093
14935
  };
15094
14936
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -15099,8 +14941,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
15099
14941
  var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
15100
14942
  var HindsightClient = class {
15101
14943
  apiUrl;
15102
- apiToken;
14944
+ /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
14945
+ * diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
14946
+ token;
14947
+ tokenProvider;
15103
14948
  bank;
14949
+ project;
15104
14950
  opIds = [];
15105
14951
  // async operation ids collected by retain(), for drain()
15106
14952
  /** Tri-state capability probe: unknown until the first page request, then cached. */
@@ -15109,34 +14955,81 @@ var HindsightClient = class {
15109
14955
  idempotentRetain;
15110
14956
  log;
15111
14957
  maxParallelRetains;
14958
+ observationScopes;
15112
14959
  constructor(o) {
15113
14960
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
15114
- this.apiToken = o.apiToken;
14961
+ this.token = o.apiToken;
14962
+ this.tokenProvider = o.tokenProvider;
15115
14963
  this.bank = o.bank;
14964
+ this.project = o.project;
15116
14965
  this.log = o.log ?? (() => {
15117
14966
  });
15118
14967
  this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
14968
+ this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
14969
+ }
14970
+ /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
14971
+ get apiToken() {
14972
+ return this.token;
15119
14973
  }
15120
14974
  headers() {
15121
14975
  const h = { "Content-Type": "application/json" };
15122
- if (this.apiToken) h["Authorization"] = `Bearer ${this.apiToken}`;
14976
+ if (this.token) h["Authorization"] = `Bearer ${this.token}`;
15123
14977
  return h;
15124
14978
  }
14979
+ /** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
14980
+ * only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
14981
+ * doubling every failing request. */
14982
+ refreshToken() {
14983
+ if (!this.tokenProvider) return false;
14984
+ let next;
14985
+ try {
14986
+ next = this.tokenProvider();
14987
+ } catch {
14988
+ return false;
14989
+ }
14990
+ if (next === this.token) return false;
14991
+ this.token = next;
14992
+ return true;
14993
+ }
14994
+ /**
14995
+ * The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
14996
+ * poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
14997
+ * failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
14998
+ * not.
14999
+ *
15000
+ * On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
15001
+ * string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
15002
+ * free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
15003
+ * bounds the whole call.
15004
+ */
15005
+ async fetchWithAuth(url2, init) {
15006
+ const send = () => fetch(url2, { ...init, headers: this.headers() });
15007
+ const r = await send();
15008
+ if (r.status !== 401 || !this.refreshToken()) return r;
15009
+ return send();
15010
+ }
15011
+ /** A 401 with no `Authorization` header is a different failure from a rejected key, and the
15012
+ * server answers identically for both — only the client knows which it sent. */
15013
+ authHint(status) {
15014
+ if (status !== 401) return "";
15015
+ return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
15016
+ }
15125
15017
  bankUrl(suffix = "") {
15126
15018
  return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
15127
15019
  }
15128
15020
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
15129
15021
  async req(method, url2, body, tolerate = []) {
15130
- const r = await fetch(url2, {
15022
+ const r = await this.fetchWithAuth(url2, {
15131
15023
  method,
15132
- headers: this.headers(),
15133
15024
  body: body ? JSON.stringify(body) : void 0,
15134
15025
  signal: AbortSignal.timeout(15e3)
15135
15026
  });
15136
15027
  if (r.status === 429 && !tolerate.includes(429))
15137
15028
  throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
15138
15029
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
15139
- throw new Error(`${method} ${url2} -> ${r.status} ${await r.text()}`);
15030
+ throw new Error(
15031
+ `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
15032
+ );
15140
15033
  return r;
15141
15034
  }
15142
15035
  /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
@@ -15147,7 +15040,11 @@ var HindsightClient = class {
15147
15040
  context,
15148
15041
  document_id: documentId,
15149
15042
  tags,
15150
- strategy
15043
+ strategy,
15044
+ // Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
15045
+ // observations were built under is a property of the write rather than of whichever server
15046
+ // version happened to process it. Servers older than 0.4.15 ignore the field.
15047
+ observation_scopes: this.observationScopes
15151
15048
  };
15152
15049
  if (opts.timestamp) item.timestamp = opts.timestamp;
15153
15050
  if (opts.metadata) item.metadata = opts.metadata;
@@ -15226,7 +15123,7 @@ var HindsightClient = class {
15226
15123
  this.log(
15227
15124
  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}`
15228
15125
  );
15229
- await this.seedPages();
15126
+ await this.seedPages(opts.pageTrigger);
15230
15127
  }
15231
15128
  /**
15232
15129
  * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
@@ -15284,7 +15181,7 @@ var HindsightClient = class {
15284
15181
  let backoffMs = POLL_CYCLE_MS;
15285
15182
  await pool([...pending], this.maxParallelRetains, async (id) => {
15286
15183
  try {
15287
- const r = await fetch(this.bankUrl(`/operations/${id}`), { headers: this.headers() });
15184
+ const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
15288
15185
  if (r.status === 429) {
15289
15186
  backoffMs = Math.min(
15290
15187
  RETRY_AFTER_CEILING_MS,
@@ -15310,247 +15207,649 @@ var HindsightClient = class {
15310
15207
  `[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
15311
15208
  );
15312
15209
  }
15313
- /** Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a caller. */
15314
- async reflect(query, opts = {}) {
15315
- const ctrl = new AbortController();
15316
- const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 12e4);
15317
- try {
15318
- const resp = await fetch(this.bankUrl("/reflect"), {
15319
- method: "POST",
15320
- headers: this.headers(),
15321
- body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
15322
- signal: ctrl.signal
15323
- });
15324
- if (!resp.ok) throw new Error(`reflect ${resp.status}`);
15325
- const data = await resp.json();
15326
- return (data.text || "").trim();
15327
- } finally {
15328
- clearTimeout(timer);
15329
- }
15210
+ /**
15211
+ * Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
15212
+ * caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
15213
+ * magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
15214
+ * tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
15215
+ * tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
15216
+ */
15217
+ async reflect(query, opts) {
15218
+ const ctrl = new AbortController();
15219
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
15220
+ try {
15221
+ const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
15222
+ method: "POST",
15223
+ body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
15224
+ signal: ctrl.signal
15225
+ });
15226
+ if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
15227
+ const data = await resp.json();
15228
+ return (data.text || "").trim();
15229
+ } finally {
15230
+ clearTimeout(timer);
15231
+ }
15232
+ }
15233
+ /**
15234
+ * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
15235
+ * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
15236
+ */
15237
+ async tree() {
15238
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15239
+ const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
15240
+ if ([404, 405, 501].includes(r.status)) {
15241
+ this.knowledgePagesSupported = false;
15242
+ throw new KnowledgePagesUnavailableError();
15243
+ }
15244
+ this.knowledgePagesSupported = true;
15245
+ try {
15246
+ return (await r.json()).roots ?? [];
15247
+ } catch {
15248
+ return [];
15249
+ }
15250
+ }
15251
+ /**
15252
+ * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
15253
+ * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
15254
+ * to read, and a caller enumerating pages wants leaves, not structure.
15255
+ *
15256
+ * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
15257
+ * page read/update in this client goes through the same knowledge-base ids, so a page id from
15258
+ * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
15259
+ */
15260
+ async listPages() {
15261
+ const items = [];
15262
+ const walk = (nodes, folder) => {
15263
+ for (const n of nodes) {
15264
+ if (!n?.id || !n?.name) continue;
15265
+ if (n.kind === "page") {
15266
+ items.push({
15267
+ id: n.id,
15268
+ name: n.name,
15269
+ ...n.description ? { description: n.description } : {},
15270
+ ...folder ? { folder } : {}
15271
+ });
15272
+ }
15273
+ if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
15274
+ }
15275
+ };
15276
+ walk(await this.tree());
15277
+ return { items };
15278
+ }
15279
+ /**
15280
+ * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
15281
+ * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
15282
+ * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
15283
+ * token cap.
15284
+ */
15285
+ async getPage(pageId) {
15286
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15287
+ const r = await this.req(
15288
+ "GET",
15289
+ this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
15290
+ );
15291
+ if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
15292
+ return await r.json();
15293
+ }
15294
+ /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
15295
+ * Returns page-level hits with a relevance snippet — the real search behind
15296
+ * hindsight_search_knowledge_pages. */
15297
+ async searchKnowledgePages(query, limit = 3) {
15298
+ if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15299
+ const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
15300
+ const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
15301
+ const j = await r.json();
15302
+ return (j.results ?? []).map((x) => ({
15303
+ id: x.id,
15304
+ name: x.name,
15305
+ snippet: x.snippet ?? "",
15306
+ score: x.score ?? 0
15307
+ }));
15308
+ }
15309
+ /**
15310
+ * Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
15311
+ *
15312
+ * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
15313
+ * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
15314
+ * off a slug). Names are unique per folder server-side, which makes them a sound key.
15315
+ *
15316
+ * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
15317
+ * `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
15318
+ * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
15319
+ */
15320
+ async seedPages(pageTrigger = buildPageTrigger()) {
15321
+ const pages = pagesFor(this.project ?? this.bank);
15322
+ const existing = /* @__PURE__ */ new Map();
15323
+ let roots;
15324
+ try {
15325
+ roots = await this.tree();
15326
+ } catch (e) {
15327
+ if (e instanceof KnowledgePagesUnavailableError) {
15328
+ this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
15329
+ return;
15330
+ }
15331
+ throw e;
15332
+ }
15333
+ for (const n of roots) {
15334
+ if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
15335
+ }
15336
+ let created = 0;
15337
+ let updated = 0;
15338
+ for (const page of pages) {
15339
+ const hit = existing.get(page.name.toLowerCase());
15340
+ const body = {
15341
+ name: page.name,
15342
+ source_query: page.source_query,
15343
+ tags: page.tags,
15344
+ max_tokens: PAGE_MAX_TOKENS,
15345
+ trigger: pageTrigger
15346
+ };
15347
+ if (!hit) {
15348
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
15349
+ if ([404, 405, 501].includes(r.status)) {
15350
+ this.knowledgePagesSupported = false;
15351
+ this.log(
15352
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
15353
+ );
15354
+ return;
15355
+ }
15356
+ if (r.status !== 409) created++;
15357
+ } else if (hit.description !== page.source_query) {
15358
+ const r = await this.req(
15359
+ "PATCH",
15360
+ this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
15361
+ { source_query: page.source_query, tags: page.tags }
15362
+ );
15363
+ if ([404, 405, 501].includes(r.status)) {
15364
+ this.knowledgePagesSupported = false;
15365
+ this.log(
15366
+ `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
15367
+ );
15368
+ return;
15369
+ }
15370
+ updated++;
15371
+ }
15372
+ }
15373
+ this.log(
15374
+ `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
15375
+ );
15376
+ }
15377
+ /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
15378
+ slugify(s) {
15379
+ return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
15380
+ }
15381
+ /**
15382
+ * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
15383
+ * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
15384
+ * Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
15385
+ * enhancement or a mid-work plan change lands on the initiative it belongs to.
15386
+ */
15387
+ async captureInitiative(args) {
15388
+ let pageId = args.relatesToPageId;
15389
+ if (!pageId) {
15390
+ const folderId = await this.ensureFolder("Initiatives");
15391
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
15392
+ name: args.title,
15393
+ source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.`,
15394
+ parent_id: folderId,
15395
+ tags: ["knowledge:feature-work"],
15396
+ trigger: args.pageTrigger ?? buildPageTrigger()
15397
+ });
15398
+ try {
15399
+ const j = await r.json();
15400
+ pageId = j.page_id ?? j.id;
15401
+ } catch {
15402
+ }
15403
+ pageId ||= `initiative-${this.slugify(args.title)}`;
15404
+ }
15405
+ const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
15406
+ const content = `${verb}: ${args.title}. ${args.summary}`;
15407
+ const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
15408
+ const tags = [
15409
+ .../* @__PURE__ */ new Set([
15410
+ ...args.stamp?.tags ?? [],
15411
+ "knowledge:feature-work",
15412
+ `relatedPageId:${pageId}`
15413
+ ])
15414
+ ];
15415
+ if (Object.keys(args.stamp?.metadata ?? {}).length) {
15416
+ await this.retain(content, "initiative marker", markerId, tags, "document", {
15417
+ metadata: args.stamp?.metadata
15418
+ });
15419
+ } else {
15420
+ await this.retain(content, "initiative marker", markerId, tags, "document");
15421
+ }
15422
+ return { page_id: pageId };
15423
+ }
15424
+ /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
15425
+ async ensureFolder(name) {
15426
+ try {
15427
+ const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
15428
+ const hit = (tree.roots || []).find(
15429
+ (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
15430
+ );
15431
+ if (hit?.id) return hit.id;
15432
+ } catch {
15433
+ }
15434
+ try {
15435
+ const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
15436
+ return (await r.json()).id;
15437
+ } catch {
15438
+ return void 0;
15439
+ }
15440
+ }
15441
+ };
15442
+
15443
+ // src/core/config.ts
15444
+ var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
15445
+ var DEFAULT_DAEMON_PORT = 9077;
15446
+ var DEFAULT_DAEMON_PROFILE = "coding-agent";
15447
+ function resolvePageTriggerType(raw) {
15448
+ if (raw.pageTriggerType === "manual") return "manual";
15449
+ if (raw.pageTriggerType === "cron") {
15450
+ if (raw.pageTriggerCron?.trim()) return "cron";
15451
+ log.warn(
15452
+ "config",
15453
+ 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
15454
+ );
15455
+ }
15456
+ return "auto-refresh";
15457
+ }
15458
+ var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
15459
+ var REFLECT_BUDGETS = ["low", "mid", "high"];
15460
+ function resolveReflectBudget(raw) {
15461
+ const value = raw.reflectBudget;
15462
+ if (value === void 0) return "high";
15463
+ if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
15464
+ return value;
15465
+ log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
15466
+ return "high";
15467
+ }
15468
+ var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
15469
+ function resolveObservationScopes(raw) {
15470
+ const value = raw;
15471
+ if (typeof value === "string")
15472
+ return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
15473
+ if (Array.isArray(value)) {
15474
+ const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
15475
+ if (scopes.length) return scopes;
15476
+ }
15477
+ return DEFAULT_OBSERVATION_SCOPES;
15478
+ }
15479
+ function resolveConfig(raw = {}) {
15480
+ const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
15481
+ const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
15482
+ return {
15483
+ serverMode,
15484
+ // Daemon mode resolves the URL HERE rather than at each call site: every entry point already
15485
+ // builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
15486
+ // daemon needs no plumbing through eight separate constructors.
15487
+ apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
15488
+ apiToken: raw.apiToken || void 0,
15489
+ apiPort,
15490
+ daemonIdleTimeout: raw.daemonIdleTimeout,
15491
+ daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
15492
+ embedVersion: raw.embedVersion || void 0,
15493
+ embedPackagePath: raw.embedPackagePath || void 0,
15494
+ bankId: raw.bankId,
15495
+ dynamicBankId: raw.dynamicBankId,
15496
+ bankIdTemplate: raw.bankIdTemplate,
15497
+ mapPathToBank: raw.mapPathToBank,
15498
+ resolveWorktrees: raw.resolveWorktrees,
15499
+ optInOnly: raw.optInOnly ?? false,
15500
+ // Same shape as retainTags: a config typo must not become a path that silently approves nothing.
15501
+ optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
15502
+ harness: raw.harness ?? "opencode",
15503
+ disabled: raw.disabled ?? false,
15504
+ retainSessions: raw.retainSessions ?? true,
15505
+ // write sessions back by default, every harness
15506
+ maxParallelRetains: raw.maxParallelRetains || 10,
15507
+ reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
15508
+ // Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
15509
+ // reflect already set), but never let it LOWER the tool below the default — a short window is
15510
+ // set to bound the automatic hook, not to cut off a call the agent is waiting on.
15511
+ reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
15512
+ reflectBudget: resolveReflectBudget(raw),
15513
+ autoReflect: raw.autoReflect ?? true,
15514
+ pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
15515
+ pageTriggerType: resolvePageTriggerType(raw),
15516
+ pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
15517
+ autoSeed: raw.autoSeed ?? true,
15518
+ seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
15519
+ codebaseSurvey: raw.codebaseSurvey ?? true,
15520
+ surveyModel: raw.surveyModel || "haiku",
15521
+ surveyBudgetUsd: raw.surveyBudgetUsd || 2,
15522
+ surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
15523
+ gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
15524
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
15525
+ // nested object cannot reach the API as a tag and fail the whole retain.
15526
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
15527
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
15528
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
15529
+ ) : {},
15530
+ observationScopes: resolveObservationScopes(raw.observationScopes),
15531
+ banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
15532
+ logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
15533
+ };
15534
+ }
15535
+ function readRaw(path) {
15536
+ try {
15537
+ return JSON.parse(readFileSync(path, "utf8"));
15538
+ } catch (e) {
15539
+ if (e?.code !== "ENOENT") {
15540
+ console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
15541
+ }
15542
+ return {};
15543
+ }
15544
+ }
15545
+ function mergeRaw(a, b) {
15546
+ const { harnesses: _drop, ...flat } = b;
15547
+ return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
15548
+ }
15549
+ function applyLayer(raw, layer, harness) {
15550
+ let out = mergeRaw(raw, layer);
15551
+ const perHarness = harness ? layer.harnesses?.[harness] : void 0;
15552
+ if (perHarness) out = mergeRaw(out, perHarness);
15553
+ return out;
15554
+ }
15555
+ var ENV_KEYS = {
15556
+ serverMode: "HINDSIGHT_SERVER_MODE",
15557
+ apiUrl: "HINDSIGHT_API_URL",
15558
+ apiToken: "HINDSIGHT_API_TOKEN",
15559
+ // These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
15560
+ // it can carry their existing environment over unchanged.
15561
+ apiPort: "HINDSIGHT_API_PORT",
15562
+ daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
15563
+ embedVersion: "HINDSIGHT_EMBED_VERSION",
15564
+ embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
15565
+ daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
15566
+ bankId: "HINDSIGHT_BANK_ID",
15567
+ dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
15568
+ bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
15569
+ resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
15570
+ optInOnly: "HINDSIGHT_OPT_IN_ONLY",
15571
+ optInPaths: "HINDSIGHT_OPT_IN_PATHS",
15572
+ harness: "HINDSIGHT_HARNESS",
15573
+ disabled: "HINDSIGHT_DISABLED",
15574
+ retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
15575
+ maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
15576
+ reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
15577
+ reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
15578
+ reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
15579
+ autoReflect: "HINDSIGHT_AUTO_REFLECT",
15580
+ pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
15581
+ pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
15582
+ pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
15583
+ autoSeed: "HINDSIGHT_AUTO_SEED",
15584
+ seedLimit: "HINDSIGHT_SEED_LIMIT",
15585
+ codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
15586
+ surveyModel: "HINDSIGHT_SURVEY_MODEL",
15587
+ surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
15588
+ surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
15589
+ logLevel: "HINDSIGHT_LOG_LEVEL",
15590
+ gitIngest: "HINDSIGHT_GIT_INGEST",
15591
+ // Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
15592
+ // list is a list OF lists, which does not survive flattening into one variable — file-only.
15593
+ observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
15594
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
15595
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
15596
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
15597
+ };
15598
+ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
15599
+ "dynamicBankId",
15600
+ "resolveWorktrees",
15601
+ "optInOnly",
15602
+ "disabled",
15603
+ "retainSessions",
15604
+ "autoReflect",
15605
+ "autoSeed",
15606
+ "codebaseSurvey"
15607
+ ]);
15608
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
15609
+ var ENV_NUMBERS = /* @__PURE__ */ new Set([
15610
+ "apiPort",
15611
+ "daemonIdleTimeout",
15612
+ "maxParallelRetains",
15613
+ "reflectTimeoutMs",
15614
+ "reflectToolTimeoutMs",
15615
+ "pageRefreshEveryTurns",
15616
+ "seedLimit",
15617
+ "surveyBudgetUsd",
15618
+ "surveyRefreshCommits"
15619
+ ]);
15620
+ function readEnvConfig(env = process.env) {
15621
+ const out = {};
15622
+ for (const [key, name] of Object.entries(ENV_KEYS)) {
15623
+ const value = env[name];
15624
+ if (value === void 0 || value.trim() === "") continue;
15625
+ if (ENV_BOOLEANS.has(key)) {
15626
+ out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
15627
+ } else if (ENV_LISTS.has(key)) {
15628
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
15629
+ if (items.length) out[key] = items;
15630
+ } else if (ENV_NUMBERS.has(key)) {
15631
+ const n = Number(value);
15632
+ if (Number.isFinite(n)) out[key] = n;
15633
+ else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
15634
+ } else {
15635
+ out[key] = value;
15636
+ }
15637
+ }
15638
+ return out;
15639
+ }
15640
+ function loadConfig(opts = {}) {
15641
+ const o = typeof opts === "string" ? { path: opts } : opts;
15642
+ const withEnv = applyLayer({}, readEnvConfig(), o.harness);
15643
+ const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
15644
+ if (!raw.harness && o.harness) raw.harness = o.harness;
15645
+ return resolveConfig(raw);
15646
+ }
15647
+ var BANK_OVERRIDE_EXCLUDED = [
15648
+ "bankId",
15649
+ "bankIdTemplate",
15650
+ "mapPathToBank",
15651
+ "dynamicBankId",
15652
+ "resolveWorktrees",
15653
+ // Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
15654
+ // only ever arrive too late to matter — strip them rather than let them read as effective.
15655
+ "optInOnly",
15656
+ "optInPaths",
15657
+ "harness"
15658
+ ];
15659
+ function applyBankConfig(cfg, resolvedId, directory) {
15660
+ if (directory !== void 0 && !isOptedIn(cfg, directory))
15661
+ return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
15662
+ const section = cfg.banks[resolvedId];
15663
+ if (!section) return { cfg, bankId: resolvedId };
15664
+ const safe = { ...section };
15665
+ for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
15666
+ delete safe.banks;
15667
+ const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
15668
+ delete safe.bank;
15669
+ return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
15670
+ }
15671
+ function resolvePartial(cfg, patch) {
15672
+ const full = resolveConfig(patch);
15673
+ const out = {};
15674
+ for (const key of Object.keys(patch)) {
15675
+ if (key in full)
15676
+ out[key] = full[key];
15677
+ }
15678
+ return out;
15679
+ }
15680
+
15681
+ // src/core/host-client.ts
15682
+ function resolveHostConfig(harness, directory) {
15683
+ const cfg0 = loadConfig({ harness });
15684
+ if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
15685
+ return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
15686
+ }
15687
+ function resolveHostMemory(harness, directory) {
15688
+ const { cfg, bankId } = resolveHostConfig(harness, directory);
15689
+ return {
15690
+ cfg,
15691
+ bankId,
15692
+ client: new HindsightClient({
15693
+ apiUrl: cfg.apiUrl,
15694
+ apiToken: cfg.apiToken,
15695
+ bank: bankId,
15696
+ maxParallelRetains: cfg.maxParallelRetains,
15697
+ observationScopes: cfg.observationScopes,
15698
+ // The credential a host STARTED with is not the one it must keep using: enable auth or
15699
+ // rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
15700
+ // through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
15701
+ // honoured on re-resolution exactly as it was on the first one.
15702
+ tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
15703
+ })
15704
+ };
15705
+ }
15706
+
15707
+ // src/core/diag.ts
15708
+ import { appendFileSync as appendFileSync2 } from "fs";
15709
+ function diagFilePath() {
15710
+ return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
15711
+ }
15712
+ function diag(harness, event, extra = {}) {
15713
+ log.debug(harness, `diag:${event}`, extra);
15714
+ try {
15715
+ appendFileSync2(
15716
+ diagFilePath(),
15717
+ JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
15718
+ );
15719
+ } catch {
15720
+ }
15721
+ }
15722
+
15723
+ // src/core/daemon.ts
15724
+ import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
15725
+ import { dirname as dirname4, join as join5 } from "path";
15726
+ import { fileURLToPath as fileURLToPath2 } from "url";
15727
+ var DAEMON_WAIT_SESSION_START_MS = 12e3;
15728
+ var DAEMON_WAIT_RETAIN_MS = 4e4;
15729
+ async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
15730
+ try {
15731
+ const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
15732
+ return res.ok;
15733
+ } catch {
15734
+ return false;
15735
+ }
15736
+ }
15737
+ function hasRustToolchain() {
15738
+ if (process.platform !== "darwin") return true;
15739
+ try {
15740
+ execFileSync2("cargo", ["--version"], { stdio: "pipe", timeout: 1e4 });
15741
+ return true;
15742
+ } catch {
15743
+ return false;
15330
15744
  }
15331
- /**
15332
- * The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
15333
- * queries and staleness but NOT synthesized content, so it is cheap enough to poll.
15334
- */
15335
- async tree() {
15336
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15337
- const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
15338
- if ([404, 405, 501].includes(r.status)) {
15339
- this.knowledgePagesSupported = false;
15340
- throw new KnowledgePagesUnavailableError();
15341
- }
15342
- this.knowledgePagesSupported = true;
15343
- try {
15344
- return (await r.json()).roots ?? [];
15345
- } catch {
15346
- return [];
15347
- }
15745
+ }
15746
+ function hasUvx() {
15747
+ try {
15748
+ execFileSync2("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
15749
+ return true;
15750
+ } catch {
15751
+ return false;
15348
15752
  }
15349
- /**
15350
- * List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
15351
- * and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
15352
- * to read, and a caller enumerating pages wants leaves, not structure.
15353
- *
15354
- * NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
15355
- * page read/update in this client goes through the same knowledge-base ids, so a page id from
15356
- * here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
15357
- */
15358
- async listPages() {
15359
- const items = [];
15360
- const walk = (nodes, folder) => {
15361
- for (const n of nodes) {
15362
- if (!n?.id || !n?.name) continue;
15363
- if (n.kind === "page") {
15364
- items.push({
15365
- id: n.id,
15366
- name: n.name,
15367
- ...n.description ? { description: n.description } : {},
15368
- ...folder ? { folder } : {}
15369
- });
15370
- }
15371
- if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
15372
- }
15753
+ }
15754
+ var PROVIDER_PROBES = [
15755
+ { provider: "openai", keyEnv: "OPENAI_API_KEY" },
15756
+ { provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
15757
+ { provider: "gemini", keyEnv: "GEMINI_API_KEY" },
15758
+ { provider: "groq", keyEnv: "GROQ_API_KEY" }
15759
+ ];
15760
+ function detectLlm(env = process.env) {
15761
+ const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
15762
+ if (explicit) {
15763
+ return {
15764
+ provider: explicit,
15765
+ apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
15766
+ source: "HINDSIGHT_API_LLM_PROVIDER"
15373
15767
  };
15374
- walk(await this.tree());
15375
- return { items };
15376
15768
  }
15377
- /**
15378
- * Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
15379
- * (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
15380
- * the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
15381
- * token cap.
15382
- */
15383
- async getPage(pageId) {
15384
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15385
- const r = await this.req(
15386
- "GET",
15387
- this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
15388
- );
15389
- if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
15390
- return await r.json();
15769
+ for (const probe of PROVIDER_PROBES) {
15770
+ const key = env[probe.keyEnv]?.trim();
15771
+ if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
15391
15772
  }
15392
- /** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
15393
- * Returns page-level hits with a relevance snippet — the real search behind
15394
- * hindsight_search_knowledge_pages. */
15395
- async searchKnowledgePages(query, limit = 3) {
15396
- if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
15397
- const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
15398
- const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
15399
- const j = await r.json();
15400
- return (j.results ?? []).map((x) => ({
15401
- id: x.id,
15402
- name: x.name,
15403
- snippet: x.snippet ?? "",
15404
- score: x.score ?? 0
15405
- }));
15773
+ if (onPath("claude")) {
15774
+ return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
15406
15775
  }
15407
- /**
15408
- * Seed the fixed `PAGES` taxonomy as knowledge-base pages at the tree root, idempotently.
15409
- *
15410
- * Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
15411
- * client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
15412
- * off a slug). Names are unique per folder server-side, which makes them a sound key.
15413
- *
15414
- * An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
15415
- * `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
15416
- */
15417
- async seedPages() {
15418
- const existing = /* @__PURE__ */ new Map();
15419
- let roots;
15420
- try {
15421
- roots = await this.tree();
15422
- } catch (e) {
15423
- if (e instanceof KnowledgePagesUnavailableError) {
15424
- this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
15425
- return;
15426
- }
15427
- throw e;
15428
- }
15429
- for (const n of roots) {
15430
- if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
15431
- }
15432
- let created = 0;
15433
- let updated = 0;
15434
- for (const page of PAGES) {
15435
- const hit = existing.get(page.name.toLowerCase());
15436
- const body = {
15437
- name: page.name,
15438
- source_query: page.source_query,
15439
- tags: page.tags,
15440
- max_tokens: PAGE_MAX_TOKENS,
15441
- trigger: PAGE_TRIGGER
15442
- };
15443
- if (!hit) {
15444
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
15445
- if ([404, 405, 501].includes(r.status)) {
15446
- this.knowledgePagesSupported = false;
15447
- this.log(
15448
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
15449
- );
15450
- return;
15451
- }
15452
- if (r.status !== 409) created++;
15453
- } else if (hit.description !== page.source_query) {
15454
- const r = await this.req(
15455
- "PATCH",
15456
- this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
15457
- { source_query: page.source_query, tags: page.tags }
15458
- );
15459
- if ([404, 405, 501].includes(r.status)) {
15460
- this.knowledgePagesSupported = false;
15461
- this.log(
15462
- `[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
15463
- );
15464
- return;
15465
- }
15466
- updated++;
15467
- }
15468
- }
15469
- this.log(
15470
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
15471
- );
15776
+ return void 0;
15777
+ }
15778
+ function onPath(bin) {
15779
+ try {
15780
+ execFileSync2("which", [bin], { stdio: "pipe", timeout: 5e3 });
15781
+ return true;
15782
+ } catch {
15783
+ return false;
15472
15784
  }
15473
- /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
15474
- slugify(s) {
15475
- return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
15785
+ }
15786
+ function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
15787
+ try {
15788
+ const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
15789
+ const child = spawnFn("node", [starter, "--harness", harness], {
15790
+ detached: true,
15791
+ stdio: "ignore"
15792
+ });
15793
+ child.on("error", () => {
15794
+ });
15795
+ child.unref();
15796
+ diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
15797
+ } catch {
15476
15798
  }
15477
- /**
15478
- * Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
15479
- * New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
15480
- * Enhancement (relatesToPageId) → no new page; only a marker accruing to the existing page.
15481
- */
15482
- async captureInitiative(args) {
15483
- let pageId = args.relatesToPageId;
15484
- if (!pageId) {
15485
- const folderId = await this.ensureFolder("Initiatives");
15486
- const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
15487
- name: args.title,
15488
- source_query: `Summarize the "${args.title}" initiative: what is being built or changed and why, and its current state \u2014 drawn from the project's memory.`,
15489
- parent_id: folderId,
15490
- tags: ["knowledge:feature-work"],
15491
- trigger: {
15492
- fact_types: ["world", "experience", "observation"],
15493
- refresh_after_consolidation: true
15494
- }
15495
- });
15496
- try {
15497
- const j = await r.json();
15498
- pageId = j.page_id ?? j.id;
15499
- } catch {
15500
- }
15501
- pageId ||= `initiative-${this.slugify(args.title)}`;
15502
- }
15503
- const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
15504
- const content = `${verb}: ${args.title}. ${args.summary}`;
15505
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
15506
- const tags = [
15507
- .../* @__PURE__ */ new Set([
15508
- ...args.stamp?.tags ?? [],
15509
- "knowledge:feature-work",
15510
- `relatedPageId:${pageId}`
15511
- ])
15512
- ];
15513
- if (Object.keys(args.stamp?.metadata ?? {}).length) {
15514
- await this.retain(content, "initiative marker", markerId, tags, "document", {
15515
- metadata: args.stamp?.metadata
15516
- });
15517
- } else {
15518
- await this.retain(content, "initiative marker", markerId, tags, "document");
15519
- }
15520
- return { page_id: pageId };
15799
+ }
15800
+ async function ensureDaemon(cfg, harness, opts = {}) {
15801
+ if (cfg.serverMode !== "daemon") return;
15802
+ if (await isServerHealthy(cfg.apiUrl)) return;
15803
+ if (!preflightDaemon(cfg, harness)) return;
15804
+ startDaemonDetached(cfg, harness, opts.spawnFn);
15805
+ await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
15806
+ }
15807
+ async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
15808
+ const deadline = Date.now() + budgetMs;
15809
+ while (Date.now() < deadline) {
15810
+ await new Promise((r) => setTimeout(r, pollMs));
15811
+ if (await isServerHealthy(baseUrl)) return true;
15521
15812
  }
15522
- /** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
15523
- async ensureFolder(name) {
15524
- try {
15525
- const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
15526
- const hit = (tree.roots || []).find(
15527
- (n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
15528
- );
15529
- if (hit?.id) return hit.id;
15530
- } catch {
15531
- }
15532
- try {
15533
- const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
15534
- return (await r.json()).id;
15535
- } catch {
15536
- return void 0;
15537
- }
15813
+ return false;
15814
+ }
15815
+ function preflightDaemon(cfg, harness) {
15816
+ if (!hasUvx()) {
15817
+ diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
15818
+ log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
15819
+ return false;
15538
15820
  }
15539
- };
15821
+ if (!hasRustToolchain()) {
15822
+ diag(harness, "daemon_rust_missing", { platform: process.platform });
15823
+ log.warn(
15824
+ harness,
15825
+ "daemon mode on macOS needs a current Rust toolchain (litellm ships no macOS wheel) \u2014 install from https://rustup.rs, then `rustup default stable && rustup update`"
15826
+ );
15827
+ return false;
15828
+ }
15829
+ if (!detectLlm()) {
15830
+ diag(harness, "daemon_no_llm", {});
15831
+ log.warn(
15832
+ harness,
15833
+ "daemon mode needs an LLM for fact extraction \u2014 set OPENAI_API_KEY (or ANTHROPIC_API_KEY / GEMINI_API_KEY / HINDSIGHT_API_LLM_PROVIDER), or install the Claude Code CLI"
15834
+ );
15835
+ return false;
15836
+ }
15837
+ return true;
15838
+ }
15540
15839
 
15541
15840
  // src/core/knowledge-tools.ts
15542
15841
  import { existsSync as existsSync3 } from "fs";
15543
15842
  import { homedir as homedir4 } from "os";
15544
- import { join as join6 } from "path";
15843
+ import { join as join7 } from "path";
15545
15844
 
15546
15845
  // src/core/status.ts
15547
- import { execFileSync as execFileSync3 } from "child_process";
15846
+ import { execFileSync as execFileSync4 } from "child_process";
15548
15847
 
15549
15848
  // src/core/git.ts
15550
- import { execFileSync as execFileSync2 } from "child_process";
15849
+ import { execFileSync as execFileSync3 } from "child_process";
15551
15850
  import { resolve } from "path";
15552
15851
  function git(repo, ...args) {
15553
- return execFileSync2("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15852
+ return execFileSync3("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
15554
15853
  }
15555
15854
  function repoNameOf(repo) {
15556
15855
  return projectNameOf(resolve(repo));
@@ -15596,7 +15895,7 @@ function roster(pages) {
15596
15895
  var TOOL_GUIDE = `- hindsight_search_knowledge_pages(query) \u2014 FIRST STOP for any question the project's accumulated knowledge might answer (components, conventions, past decisions, initiatives): search the knowledge pages and credit results visibly with a markdown blockquote so it renders as a callout, exactly: "> \u{1F9E0} **From Hindsight memory (<page>)** \u2014 <the specific facts you drew on>".
15597
15896
  - hindsight_list_knowledge_pages / hindsight_read_knowledge_page \u2014 BEFORE substantial work, list the pages and read the relevant ones to ground yourself in this repo's architecture, conventions, and past decisions instead of re-deriving them from the code; follow any [[page:<id>]] links you see.
15598
15897
  - hindsight_reflect(query) \u2014 when pages are too shallow and you need the WHY: deep reasoning over the repo's full memory for the past decision and exact values that explain a behavior or bug (slower \u2014 use deliberately, and credit results with a blockquote header "> \u{1F9E0} **From Hindsight memory** \u2014 <summary>").
15599
- - hindsight_capture_initiative(title, summary) \u2014 right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing (BEFORE you write any code), call this ONCE to record it as a tracked page. Skip bug fixes, small tweaks, and chores.
15898
+ - hindsight_capture_initiative(title, summary) \u2014 right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing (BEFORE you write any code), call this to record it as a tracked page; then call it AGAIN with relates_to_page_id set to that page whenever the goal, scope, or rationale materially changes mid-work, so the page tracks the current plan and not the opening one. Skip bug fixes, small tweaks, chores, and trivial course-corrections.
15600
15899
  - hindsight_ingest_document(title, content) \u2014 save an external document or durable notes/findings you want remembered (not the current conversation \u2014 that is captured automatically at session end).`;
15601
15900
  var REFLECT_ON_GOALS = "- The user just set a NEW task or goal \u2192 call hindsight_reflect with that goal FIRST, before planning: no memory is injected automatically in this configuration, so this call is the only way past decisions, constraints, and failed attempts relevant to the goal reach you.\n";
15602
15901
  function toolGuide(opts) {
@@ -15623,11 +15922,11 @@ ${toolGuide(opts)}
15623
15922
  }
15624
15923
 
15625
15924
  // src/core/survey.ts
15626
- import { spawn as realSpawn2 } from "child_process";
15925
+ import { spawn as realSpawn3 } from "child_process";
15627
15926
  import { accessSync, constants, existsSync as existsSync2 } from "fs";
15628
15927
  import { homedir as homedir3 } from "os";
15629
- import { delimiter, dirname as dirname4, join as join5 } from "path";
15630
- import { fileURLToPath as fileURLToPath2 } from "url";
15928
+ import { delimiter, dirname as dirname5, join as join6 } from "path";
15929
+ import { fileURLToPath as fileURLToPath3 } from "url";
15631
15930
  var SURVEY_DOC_IDS = [
15632
15931
  "repository-component-map",
15633
15932
  "repository-core-concepts",
@@ -15637,7 +15936,7 @@ var SURVEY_DOC_IDS = [
15637
15936
  function resolveClaudeBin(explicit) {
15638
15937
  if (explicit) return explicit;
15639
15938
  if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
15640
- const nativeInstallPath = join5(homedir3(), ".claude", "local", "claude");
15939
+ const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
15641
15940
  try {
15642
15941
  if (existsSync2(nativeInstallPath)) return nativeInstallPath;
15643
15942
  } catch {
@@ -15666,7 +15965,7 @@ function binExists(bin) {
15666
15965
  for (const dir of (process.env.PATH || "").split(delimiter)) {
15667
15966
  if (!dir) continue;
15668
15967
  try {
15669
- accessSync(join5(dir, bin), constants.X_OK);
15968
+ accessSync(join6(dir, bin), constants.X_OK);
15670
15969
  return true;
15671
15970
  } catch {
15672
15971
  }
@@ -15710,7 +16009,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15710
16009
  hindsight: {
15711
16010
  command: "node",
15712
16011
  args: [opts.mcpServerPath],
15713
- env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir }
16012
+ // HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
16013
+ // ingests are its writes. mcp-server.js REQUIRES it (it used to default to
16014
+ // "claude-code", which is how the codex recipe below silently stamped its findings
16015
+ // harness:claude-code and wrote them to Claude Code's bank — #3603).
16016
+ env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir, HINDSIGHT_MCP_HARNESS: "claude-code" }
15714
16017
  }
15715
16018
  }
15716
16019
  });
@@ -15750,6 +16053,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15750
16053
  `mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
15751
16054
  "-c",
15752
16055
  `mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
16056
+ "-c",
16057
+ `mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
15753
16058
  SURVEY_PROMPT
15754
16059
  ],
15755
16060
  env
@@ -15773,9 +16078,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
15773
16078
  }
15774
16079
  function startCodebaseSurvey(repoDir, opts = {}) {
15775
16080
  try {
15776
- const spawnFn = opts.spawn ?? realSpawn2;
16081
+ const spawnFn = opts.spawn ?? realSpawn3;
15777
16082
  const exists = opts.exists ?? binExists;
15778
- const mcpServerPath = opts.mcpServerPath ?? join5(dirname4(fileURLToPath2(import.meta.url)), "mcp-server.js");
16083
+ const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
15779
16084
  const preferred = opts.harness ?? "claude-code";
15780
16085
  const order = [
15781
16086
  preferred,
@@ -15814,7 +16119,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
15814
16119
  var DEEPEN_DIFF_TARGET = 300;
15815
16120
  function commitCount(repoDir) {
15816
16121
  try {
15817
- const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
16122
+ const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
15818
16123
  encoding: "utf8"
15819
16124
  });
15820
16125
  return Number(out.trim()) || 0;
@@ -15874,7 +16179,7 @@ function ok(value) {
15874
16179
  return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
15875
16180
  }
15876
16181
  function err(e) {
15877
- const message = String(e?.message ?? e);
16182
+ const message = describeError(e);
15878
16183
  return { content: [{ type: "text", text: JSON.stringify({ error: message }) }], isError: true };
15879
16184
  }
15880
16185
  function guarded(fn) {
@@ -15905,9 +16210,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15905
16210
  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.",
15906
16211
  inputSchema: {},
15907
16212
  handler: async (_args) => {
15908
- const configPath = process.env.HINDSIGHT_CONFIG || join6(homedir4(), ".hindsight", "coding-agent.json");
16213
+ const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
15909
16214
  const harness = opts.harness ?? "unknown";
15910
- const cfg = loadConfig({ harness: opts.harness });
16215
+ const cfg = applyBankConfig(
16216
+ loadConfig({ harness: opts.harness }),
16217
+ bankId,
16218
+ opts.repoDir
16219
+ ).cfg;
15911
16220
  return ok({
15912
16221
  bank_id: bankId,
15913
16222
  harness,
@@ -15919,6 +16228,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15919
16228
  api_token_configured: Boolean(cfg.apiToken),
15920
16229
  disabled: cfg.disabled
15921
16230
  },
16231
+ // What the LIVE client is signing with, which is not the same question as what the file
16232
+ // says. A long-lived host used to keep a credential the config had already replaced, and
16233
+ // this tool reported that state as perfectly healthy (#3600). Booleans only — the token
16234
+ // value is never returned.
16235
+ credential: {
16236
+ api_token_in_use: Boolean(client.apiToken),
16237
+ api_token_matches_config: client.apiToken === cfg.apiToken
16238
+ },
15922
16239
  environment: {
15923
16240
  config_override: Boolean(process.env.HINDSIGHT_CONFIG),
15924
16241
  hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
@@ -15967,12 +16284,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15967
16284
  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>".`,
15968
16285
  inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
15969
16286
  handler: guarded(
15970
- async ({ query }) => client.reflect(query, { budget: "high" })
16287
+ async ({ query }) => client.reflect(query, {
16288
+ budget: opts.reflectBudget ?? "high",
16289
+ timeoutMs: opts.reflectTimeoutMs ?? DEFAULT_REFLECT_TOOL_TIMEOUT_MS
16290
+ })
15971
16291
  )
15972
16292
  },
15973
16293
  {
15974
16294
  name: "hindsight_capture_initiative",
15975
- description: "Record a new feature or initiative as a tracked knowledge page, so future sessions know it exists and can build on it.\n\nWHEN TO CALL: right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing \u2014 BEFORE you write any code. Call it ONCE, EARLY.\n\nWHEN TO SKIP: bug fixes, small tweaks, refactors, and chores are not initiatives \u2014 skip them.\n\n- title: short, specific name (e.g. 'Newsletter refinement chat').\n- summary: 2-3 sentences on what you're building and why (the intent, not a code diff).\n- relates_to_page_id: leave empty for a new initiative. Set it only to attach to an initiative that already has a page \u2014 pass that page's id from hindsight_list_knowledge_pages.\n\nReturns the page id. The page is generated for you \u2014 you never format one yourself.",
16295
+ description: "Record a new feature or initiative as a tracked knowledge page, so future sessions know it exists and can build on it \u2014 and keep that page tracking the plan as it moves.\n\nWHEN TO CALL:\n- Starting one: right after the user approves a plan or finishes brainstorming a new feature/capability and you are about to start implementing \u2014 BEFORE you write any code. Leave relates_to_page_id empty.\n- Plan changed: call it AGAIN \u2014 mid-implementation is fine and expected \u2014 whenever the goal, scope, or rationale of an initiative you already captured materially changes (an approach is dropped, scope grows or shrinks, the why is rewritten). Pass relates_to_page_id = that initiative's page id so the change lands on the existing page. Never mint a second page for the same initiative.\n\nWHEN TO SKIP: bug fixes, small tweaks, refactors, chores, and trivial course-corrections that leave the goal intact are not initiatives \u2014 skip them.\n\n- title: short, specific name (e.g. 'Newsletter refinement chat'). On a recapture, reuse the initiative's existing title.\n- summary: 2-3 sentences on what you're building and why \u2014 the CURRENT intent, not the originally approved plan (on a recapture, say what changed and why).\n- relates_to_page_id: leave empty for a new initiative. Set it to an existing initiative's page id \u2014 from hindsight_list_knowledge_pages, or the id this tool returned earlier \u2014 to record a plan change or an enhancement to it.\n\nReturns the page id. The page is generated for you \u2014 you never format one yourself.",
15976
16296
  inputSchema: {
15977
16297
  title: external_exports.string(),
15978
16298
  summary: external_exports.string(),
@@ -15983,7 +16303,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
15983
16303
  title,
15984
16304
  summary,
15985
16305
  relatesToPageId: relates_to_page_id,
15986
- ...opts.stampFor ? { stamp: opts.stampFor() } : {}
16306
+ ...opts.stampFor ? { stamp: opts.stampFor() } : {},
16307
+ ...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
15987
16308
  })
15988
16309
  )
15989
16310
  },
@@ -16190,7 +16511,7 @@ function resolversFor(ctx) {
16190
16511
  return {
16191
16512
  // Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
16192
16513
  // otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
16193
- gitProject: () => projectNameOf(ctx.directory),
16514
+ gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
16194
16515
  project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
16195
16516
  harness: () => ctx.harness,
16196
16517
  bankId: () => ctx.bankId,
@@ -16236,11 +16557,6 @@ import { readFileSync as readFileSync4 } from "fs";
16236
16557
  // src/core/skill-sync.ts
16237
16558
  import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
16238
16559
  import { homedir as homedir5 } from "os";
16239
- import { dirname as dirname5, join as join7 } from "path";
16240
- import { fileURLToPath as fileURLToPath3 } from "url";
16241
-
16242
- // src/core/daemon.ts
16243
- import { execFileSync as execFileSync4, spawn as realSpawn3 } from "child_process";
16244
16560
  import { dirname as dirname6, join as join8 } from "path";
16245
16561
  import { fileURLToPath as fileURLToPath4 } from "url";
16246
16562
 
@@ -16331,7 +16647,7 @@ async function buildSessionStartContext(args) {
16331
16647
  const startSurvey = args.startSurvey ?? startCodebaseSurvey;
16332
16648
  const resolveHeadSha = args.headSha ?? gitHeadSha;
16333
16649
  const countCommitsSince = args.commitsSince ?? commitsSince;
16334
- const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
16650
+ const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
16335
16651
  const SURVEY_BASELINE_TAG = "source:survey-baseline";
16336
16652
  const SURVEY_BASELINE_PREFIX = "survey-baseline:";
16337
16653
  const recordSurveyBaseline = (sha) => {
@@ -16507,11 +16823,11 @@ async function buildHookOutput(args) {
16507
16823
  reflectAnswer = "";
16508
16824
  reflectFailed = true;
16509
16825
  log.warn(harness, "reflect failed \u2014 session runs without memory", {
16510
- error: String(e?.message || e).slice(0, 200)
16826
+ error: describeError(e)
16511
16827
  });
16512
16828
  diag(harness, "reflect_failed", {
16513
16829
  ms: Date.now() - t0,
16514
- error: String(e?.message || e).slice(0, 200),
16830
+ error: describeError(e),
16515
16831
  query: prompt.slice(0, 80)
16516
16832
  });
16517
16833
  }
@@ -16530,7 +16846,7 @@ async function buildHookOutput(args) {
16530
16846
  client.knowledgePagesSupported === false ? "knowledge_pages_unavailable" : "pages_failed",
16531
16847
  {
16532
16848
  ms: Date.now() - t0,
16533
- error: String(e?.message || e).slice(0, 200)
16849
+ error: describeError(e)
16534
16850
  }
16535
16851
  );
16536
16852
  }
@@ -16607,6 +16923,9 @@ var RuntimeCore = class {
16607
16923
  return buildKnowledgeTools(this.client, this.bankId, {
16608
16924
  repoDir: this.projectDir,
16609
16925
  harness: this.harness,
16926
+ pageTrigger: buildPageTrigger(this.cfg),
16927
+ reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
16928
+ reflectBudget: this.cfg.reflectBudget,
16610
16929
  stampFor: () => buildRetainStamp(this.cfg, {
16611
16930
  directory: this.projectDir,
16612
16931
  harness: this.harness,
@@ -16625,6 +16944,7 @@ var RuntimeCore = class {
16625
16944
  */
16626
16945
  async seedIfCold(repoPath) {
16627
16946
  if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
16947
+ await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
16628
16948
  try {
16629
16949
  const out = await buildSessionStartContext({
16630
16950
  cwd: repoPath || process.cwd(),
@@ -16726,7 +17046,7 @@ var RuntimeCore = class {
16726
17046
  turns = await this.fetchTranscript(sessionId);
16727
17047
  } catch (e) {
16728
17048
  diag(this.harness, "idle_fetch_failed", {
16729
- error: String(e?.message || e).slice(0, 200),
17049
+ error: describeError(e),
16730
17050
  session: sessionId
16731
17051
  });
16732
17052
  return;
@@ -16748,15 +17068,17 @@ var RuntimeCore = class {
16748
17068
  /** Fire-and-forget upsert of the session transcript; never throws into the host. */
16749
17069
  retain(sessionId, turns, startTs, trigger = "turn") {
16750
17070
  const t0 = Date.now();
16751
- void retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
16752
- cursors: this.cursors,
16753
- stamp: buildRetainStamp(this.cfg, {
16754
- directory: this.projectDir,
16755
- harness: this.harness,
16756
- bankId: this.bankId,
16757
- sessionId
17071
+ void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
17072
+ () => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
17073
+ cursors: this.cursors,
17074
+ stamp: buildRetainStamp(this.cfg, {
17075
+ directory: this.projectDir,
17076
+ harness: this.harness,
17077
+ bankId: this.bankId,
17078
+ sessionId
17079
+ })
16758
17080
  })
16759
- }).then(
17081
+ ).then(
16760
17082
  () => diag(this.harness, "retain_ok", {
16761
17083
  ms: Date.now() - t0,
16762
17084
  turns: turns.length,
@@ -16766,7 +17088,7 @@ var RuntimeCore = class {
16766
17088
  ).catch(
16767
17089
  (e) => diag(this.harness, "retain_failed", {
16768
17090
  ms: Date.now() - t0,
16769
- error: String(e?.message || e).slice(0, 200),
17091
+ error: describeError(e),
16770
17092
  session: sessionId,
16771
17093
  trigger
16772
17094
  })
@@ -16884,17 +17206,9 @@ ${injection}` };
16884
17206
  };
16885
17207
  }
16886
17208
  function createRuntime(repoPath) {
16887
- let cfg = loadConfig({ harness: HARNESS2 });
17209
+ const { cfg, bankId, client } = resolveHostMemory(HARNESS2, repoPath);
16888
17210
  if (cfg.disabled) return void 0;
16889
- const resolved = applyBankConfig(cfg, deriveBankId(cfg, repoPath, HARNESS2), repoPath);
16890
- cfg = resolved.cfg;
16891
- if (cfg.disabled) return void 0;
16892
- const client = new HindsightClient({
16893
- apiUrl: cfg.apiUrl,
16894
- apiToken: cfg.apiToken,
16895
- bank: resolved.bankId
16896
- });
16897
- return new RuntimeCore(client, resolved.bankId, cfg, HARNESS2, repoPath);
17211
+ return new RuntimeCore(client, bankId, cfg, HARNESS2, repoPath);
16898
17212
  }
16899
17213
  var extension = (pi) => {
16900
17214
  const repoPath = process.cwd();