@vectorize-io/hindsight-coding-agents 0.3.4 → 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.
- package/README.md +101 -32
- package/dist/antigravity-hook.js +424 -263
- package/dist/antigravity-statusline.js +130 -27
- package/dist/antigravity-stop-hook.js +431 -265
- package/dist/claude-hook.js +424 -263
- package/dist/claude-sessionstart-hook.js +436 -269
- package/dist/claude-stop-hook.js +431 -265
- package/dist/cline.js +627 -329
- package/dist/codex-hook.js +424 -263
- package/dist/codex-sessionstart-hook.js +436 -269
- package/dist/codex-stop-hook.js +431 -265
- package/dist/copilot-hook.js +424 -263
- package/dist/copilot-sessionstart-hook.js +436 -269
- package/dist/copilot-stop-hook.js +431 -265
- package/dist/cursor-hook.js +424 -263
- package/dist/cursor-sessionstart-hook.js +436 -269
- package/dist/cursor-stop-hook.js +431 -265
- package/dist/daemon-start.js +101 -45
- package/dist/deepen.js +289 -130
- package/dist/devin-hook.js +424 -263
- package/dist/devin-sessionstart-hook.js +436 -269
- package/dist/devin-stop-hook.js +431 -265
- package/dist/dsh.js +870 -573
- package/dist/grok-hook.js +424 -263
- package/dist/grok-sessionstart-hook.js +436 -269
- package/dist/grok-stop-hook.js +431 -265
- package/dist/hindsight-seed.js +122 -24
- package/dist/index.js +665 -366
- package/dist/installer.js +40 -48
- package/dist/kilo.js +665 -366
- package/dist/mcp-server.js +525 -299
- package/dist/prime-agent.js +881 -581
- package/dist/status.js +419 -244
- package/package.json +10 -2
- package/skill/SKILL.md +20 -4
package/dist/prime-agent.js
CHANGED
|
@@ -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" ?
|
|
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 =
|
|
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
|
|
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
|
|
14579
|
-
|
|
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("~/") ?
|
|
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,320 +14647,89 @@ 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
|
|
14611
|
-
if (
|
|
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
|
-
|
|
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
|
|
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/
|
|
14631
|
-
import {
|
|
14632
|
-
import {
|
|
14633
|
-
import { join as join3 } from "path";
|
|
14634
|
-
|
|
14635
|
-
|
|
14636
|
-
|
|
14637
|
-
|
|
14638
|
-
|
|
14639
|
-
|
|
14640
|
-
function startBackgroundSeed(repoDir, opts = {}) {
|
|
14641
|
-
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
|
-
}
|
|
14659
|
-
);
|
|
14660
|
-
child.on("error", () => {
|
|
14661
|
-
});
|
|
14662
|
-
child.unref();
|
|
14663
|
-
} catch {
|
|
14664
|
-
}
|
|
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;
|
|
14665
14698
|
}
|
|
14666
|
-
|
|
14667
|
-
|
|
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
|
-
};
|
|
14699
|
+
function logFilePath() {
|
|
14700
|
+
return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
|
|
14719
14701
|
}
|
|
14720
|
-
function
|
|
14702
|
+
function write(level, scope, msg, extra) {
|
|
14703
|
+
if (WEIGHT[level] < WEIGHT[current]) return;
|
|
14721
14704
|
try {
|
|
14722
|
-
|
|
14723
|
-
|
|
14724
|
-
|
|
14725
|
-
|
|
14726
|
-
|
|
14727
|
-
|
|
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"
|
|
14710
|
+
);
|
|
14711
|
+
} catch {
|
|
14728
14712
|
}
|
|
14729
14713
|
}
|
|
14730
|
-
|
|
14731
|
-
|
|
14732
|
-
|
|
14733
|
-
|
|
14734
|
-
|
|
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;
|
|
14739
|
-
}
|
|
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"
|
|
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)
|
|
14775
14719
|
};
|
|
14776
|
-
|
|
14777
|
-
|
|
14778
|
-
|
|
14779
|
-
|
|
14780
|
-
|
|
14781
|
-
|
|
14782
|
-
|
|
14783
|
-
|
|
14784
|
-
|
|
14785
|
-
|
|
14786
|
-
|
|
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
|
-
}
|
|
14814
|
-
}
|
|
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 };
|
|
14847
|
-
}
|
|
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];
|
|
14854
|
-
}
|
|
14855
|
-
return out;
|
|
14856
|
-
}
|
|
14857
|
-
|
|
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 {
|
|
14885
|
-
}
|
|
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)
|
|
14892
|
-
};
|
|
14893
|
-
function describeError(value, maxChars = 200) {
|
|
14894
|
-
const parts = [];
|
|
14895
|
-
const seen = /* @__PURE__ */ new Set();
|
|
14896
|
-
let current2 = value;
|
|
14897
|
-
while (current2 && !seen.has(current2)) {
|
|
14898
|
-
seen.add(current2);
|
|
14899
|
-
const error51 = current2;
|
|
14900
|
-
const text = typeof error51.message === "string" ? error51.message : String(current2);
|
|
14901
|
-
const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
|
|
14902
|
-
if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
|
|
14903
|
-
current2 = error51.cause;
|
|
14904
|
-
}
|
|
14905
|
-
return (parts.join(": ") || String(value)).slice(0, maxChars);
|
|
14906
|
-
}
|
|
14907
|
-
|
|
14908
|
-
// src/core/diag.ts
|
|
14909
|
-
function diagFilePath() {
|
|
14910
|
-
return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
|
|
14911
|
-
}
|
|
14912
|
-
function diag(harness, event, extra = {}) {
|
|
14913
|
-
log.debug(harness, `diag:${event}`, extra);
|
|
14914
|
-
try {
|
|
14915
|
-
appendFileSync2(
|
|
14916
|
-
diagFilePath(),
|
|
14917
|
-
JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
|
|
14918
|
-
);
|
|
14919
|
-
} catch {
|
|
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;
|
|
14920
14731
|
}
|
|
14732
|
+
return (parts.join(": ") || String(value)).slice(0, maxChars);
|
|
14921
14733
|
}
|
|
14922
14734
|
|
|
14923
14735
|
// src/core/missions.ts
|
|
@@ -14995,7 +14807,10 @@ var KNOWLEDGE_LABELS = {
|
|
|
14995
14807
|
}
|
|
14996
14808
|
]
|
|
14997
14809
|
};
|
|
14998
|
-
|
|
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.`;
|
|
14812
|
+
}
|
|
14813
|
+
var PAGE_TAXONOMY = [
|
|
14999
14814
|
{
|
|
15000
14815
|
name: "Component map",
|
|
15001
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.",
|
|
@@ -15022,11 +14837,23 @@ var PAGES = [
|
|
|
15022
14837
|
tags: ["knowledge:feature-work"]
|
|
15023
14838
|
}
|
|
15024
14839
|
];
|
|
14840
|
+
function pagesFor(project) {
|
|
14841
|
+
const scope = pageScopeRule(project);
|
|
14842
|
+
return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
|
|
14843
|
+
}
|
|
15025
14844
|
var PAGE_MAX_TOKENS = 4096;
|
|
15026
|
-
var
|
|
15027
|
-
|
|
15028
|
-
|
|
15029
|
-
|
|
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
|
+
}
|
|
14856
|
+
}
|
|
15030
14857
|
var CODING_BANK_TEMPLATE = {
|
|
15031
14858
|
version: "1",
|
|
15032
14859
|
bank: {
|
|
@@ -15081,6 +14908,7 @@ async function pool(items, n, fn, onError, onProgress) {
|
|
|
15081
14908
|
}
|
|
15082
14909
|
|
|
15083
14910
|
// src/core/hindsight.ts
|
|
14911
|
+
var DEFAULT_OBSERVATION_SCOPES = "shared";
|
|
15084
14912
|
var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
|
|
15085
14913
|
var RateLimitedError = class extends Error {
|
|
15086
14914
|
constructor(retryAfterMs2) {
|
|
@@ -15113,8 +14941,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
|
|
|
15113
14941
|
var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
|
|
15114
14942
|
var HindsightClient = class {
|
|
15115
14943
|
apiUrl;
|
|
15116
|
-
|
|
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;
|
|
15117
14948
|
bank;
|
|
14949
|
+
project;
|
|
15118
14950
|
opIds = [];
|
|
15119
14951
|
// async operation ids collected by retain(), for drain()
|
|
15120
14952
|
/** Tri-state capability probe: unknown until the first page request, then cached. */
|
|
@@ -15123,34 +14955,81 @@ var HindsightClient = class {
|
|
|
15123
14955
|
idempotentRetain;
|
|
15124
14956
|
log;
|
|
15125
14957
|
maxParallelRetains;
|
|
14958
|
+
observationScopes;
|
|
15126
14959
|
constructor(o) {
|
|
15127
14960
|
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
15128
|
-
this.
|
|
14961
|
+
this.token = o.apiToken;
|
|
14962
|
+
this.tokenProvider = o.tokenProvider;
|
|
15129
14963
|
this.bank = o.bank;
|
|
14964
|
+
this.project = o.project;
|
|
15130
14965
|
this.log = o.log ?? (() => {
|
|
15131
14966
|
});
|
|
15132
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;
|
|
15133
14973
|
}
|
|
15134
14974
|
headers() {
|
|
15135
14975
|
const h = { "Content-Type": "application/json" };
|
|
15136
|
-
if (this.
|
|
14976
|
+
if (this.token) h["Authorization"] = `Bearer ${this.token}`;
|
|
15137
14977
|
return h;
|
|
15138
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
|
+
}
|
|
15139
15017
|
bankUrl(suffix = "") {
|
|
15140
15018
|
return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
|
|
15141
15019
|
}
|
|
15142
15020
|
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
15143
15021
|
async req(method, url2, body, tolerate = []) {
|
|
15144
|
-
const r = await
|
|
15022
|
+
const r = await this.fetchWithAuth(url2, {
|
|
15145
15023
|
method,
|
|
15146
|
-
headers: this.headers(),
|
|
15147
15024
|
body: body ? JSON.stringify(body) : void 0,
|
|
15148
15025
|
signal: AbortSignal.timeout(15e3)
|
|
15149
15026
|
});
|
|
15150
15027
|
if (r.status === 429 && !tolerate.includes(429))
|
|
15151
15028
|
throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
|
|
15152
15029
|
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
15153
|
-
throw new Error(
|
|
15030
|
+
throw new Error(
|
|
15031
|
+
`${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
|
|
15032
|
+
);
|
|
15154
15033
|
return r;
|
|
15155
15034
|
}
|
|
15156
15035
|
/** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
|
|
@@ -15161,7 +15040,11 @@ var HindsightClient = class {
|
|
|
15161
15040
|
context,
|
|
15162
15041
|
document_id: documentId,
|
|
15163
15042
|
tags,
|
|
15164
|
-
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
|
|
15165
15048
|
};
|
|
15166
15049
|
if (opts.timestamp) item.timestamp = opts.timestamp;
|
|
15167
15050
|
if (opts.metadata) item.metadata = opts.metadata;
|
|
@@ -15240,7 +15123,7 @@ var HindsightClient = class {
|
|
|
15240
15123
|
this.log(
|
|
15241
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}`
|
|
15242
15125
|
);
|
|
15243
|
-
await this.seedPages();
|
|
15126
|
+
await this.seedPages(opts.pageTrigger);
|
|
15244
15127
|
}
|
|
15245
15128
|
/**
|
|
15246
15129
|
* Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
|
|
@@ -15298,7 +15181,7 @@ var HindsightClient = class {
|
|
|
15298
15181
|
let backoffMs = POLL_CYCLE_MS;
|
|
15299
15182
|
await pool([...pending], this.maxParallelRetains, async (id) => {
|
|
15300
15183
|
try {
|
|
15301
|
-
const r = await
|
|
15184
|
+
const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
|
|
15302
15185
|
if (r.status === 429) {
|
|
15303
15186
|
backoffMs = Math.min(
|
|
15304
15187
|
RETRY_AFTER_CEILING_MS,
|
|
@@ -15324,247 +15207,649 @@ var HindsightClient = class {
|
|
|
15324
15207
|
`[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
|
|
15325
15208
|
);
|
|
15326
15209
|
}
|
|
15327
|
-
/**
|
|
15328
|
-
|
|
15329
|
-
|
|
15330
|
-
|
|
15331
|
-
|
|
15332
|
-
|
|
15333
|
-
|
|
15334
|
-
|
|
15335
|
-
|
|
15336
|
-
|
|
15337
|
-
|
|
15338
|
-
|
|
15339
|
-
|
|
15340
|
-
|
|
15341
|
-
|
|
15342
|
-
|
|
15343
|
-
|
|
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;
|
|
15344
15744
|
}
|
|
15345
|
-
|
|
15346
|
-
|
|
15347
|
-
|
|
15348
|
-
|
|
15349
|
-
|
|
15350
|
-
|
|
15351
|
-
|
|
15352
|
-
if ([404, 405, 501].includes(r.status)) {
|
|
15353
|
-
this.knowledgePagesSupported = false;
|
|
15354
|
-
throw new KnowledgePagesUnavailableError();
|
|
15355
|
-
}
|
|
15356
|
-
this.knowledgePagesSupported = true;
|
|
15357
|
-
try {
|
|
15358
|
-
return (await r.json()).roots ?? [];
|
|
15359
|
-
} catch {
|
|
15360
|
-
return [];
|
|
15361
|
-
}
|
|
15745
|
+
}
|
|
15746
|
+
function hasUvx() {
|
|
15747
|
+
try {
|
|
15748
|
+
execFileSync2("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
|
|
15749
|
+
return true;
|
|
15750
|
+
} catch {
|
|
15751
|
+
return false;
|
|
15362
15752
|
}
|
|
15363
|
-
|
|
15364
|
-
|
|
15365
|
-
|
|
15366
|
-
|
|
15367
|
-
|
|
15368
|
-
|
|
15369
|
-
|
|
15370
|
-
|
|
15371
|
-
|
|
15372
|
-
|
|
15373
|
-
|
|
15374
|
-
|
|
15375
|
-
|
|
15376
|
-
|
|
15377
|
-
if (n.kind === "page") {
|
|
15378
|
-
items.push({
|
|
15379
|
-
id: n.id,
|
|
15380
|
-
name: n.name,
|
|
15381
|
-
...n.description ? { description: n.description } : {},
|
|
15382
|
-
...folder ? { folder } : {}
|
|
15383
|
-
});
|
|
15384
|
-
}
|
|
15385
|
-
if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
|
|
15386
|
-
}
|
|
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"
|
|
15387
15767
|
};
|
|
15388
|
-
walk(await this.tree());
|
|
15389
|
-
return { items };
|
|
15390
15768
|
}
|
|
15391
|
-
|
|
15392
|
-
|
|
15393
|
-
|
|
15394
|
-
* the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
|
|
15395
|
-
* token cap.
|
|
15396
|
-
*/
|
|
15397
|
-
async getPage(pageId) {
|
|
15398
|
-
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
15399
|
-
const r = await this.req(
|
|
15400
|
-
"GET",
|
|
15401
|
-
this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
|
|
15402
|
-
);
|
|
15403
|
-
if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
|
|
15404
|
-
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 };
|
|
15405
15772
|
}
|
|
15406
|
-
|
|
15407
|
-
|
|
15408
|
-
* hindsight_search_knowledge_pages. */
|
|
15409
|
-
async searchKnowledgePages(query, limit = 3) {
|
|
15410
|
-
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
15411
|
-
const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
|
|
15412
|
-
const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
|
|
15413
|
-
const j = await r.json();
|
|
15414
|
-
return (j.results ?? []).map((x) => ({
|
|
15415
|
-
id: x.id,
|
|
15416
|
-
name: x.name,
|
|
15417
|
-
snippet: x.snippet ?? "",
|
|
15418
|
-
score: x.score ?? 0
|
|
15419
|
-
}));
|
|
15773
|
+
if (onPath("claude")) {
|
|
15774
|
+
return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
|
|
15420
15775
|
}
|
|
15421
|
-
|
|
15422
|
-
|
|
15423
|
-
|
|
15424
|
-
|
|
15425
|
-
|
|
15426
|
-
|
|
15427
|
-
|
|
15428
|
-
|
|
15429
|
-
* `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
|
|
15430
|
-
*/
|
|
15431
|
-
async seedPages() {
|
|
15432
|
-
const existing = /* @__PURE__ */ new Map();
|
|
15433
|
-
let roots;
|
|
15434
|
-
try {
|
|
15435
|
-
roots = await this.tree();
|
|
15436
|
-
} catch (e) {
|
|
15437
|
-
if (e instanceof KnowledgePagesUnavailableError) {
|
|
15438
|
-
this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
|
|
15439
|
-
return;
|
|
15440
|
-
}
|
|
15441
|
-
throw e;
|
|
15442
|
-
}
|
|
15443
|
-
for (const n of roots) {
|
|
15444
|
-
if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
|
|
15445
|
-
}
|
|
15446
|
-
let created = 0;
|
|
15447
|
-
let updated = 0;
|
|
15448
|
-
for (const page of PAGES) {
|
|
15449
|
-
const hit = existing.get(page.name.toLowerCase());
|
|
15450
|
-
const body = {
|
|
15451
|
-
name: page.name,
|
|
15452
|
-
source_query: page.source_query,
|
|
15453
|
-
tags: page.tags,
|
|
15454
|
-
max_tokens: PAGE_MAX_TOKENS,
|
|
15455
|
-
trigger: PAGE_TRIGGER
|
|
15456
|
-
};
|
|
15457
|
-
if (!hit) {
|
|
15458
|
-
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
|
|
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
|
-
if (r.status !== 409) created++;
|
|
15467
|
-
} else if (hit.description !== page.source_query) {
|
|
15468
|
-
const r = await this.req(
|
|
15469
|
-
"PATCH",
|
|
15470
|
-
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
|
|
15471
|
-
{ source_query: page.source_query, tags: page.tags }
|
|
15472
|
-
);
|
|
15473
|
-
if ([404, 405, 501].includes(r.status)) {
|
|
15474
|
-
this.knowledgePagesSupported = false;
|
|
15475
|
-
this.log(
|
|
15476
|
-
`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
|
|
15477
|
-
);
|
|
15478
|
-
return;
|
|
15479
|
-
}
|
|
15480
|
-
updated++;
|
|
15481
|
-
}
|
|
15482
|
-
}
|
|
15483
|
-
this.log(
|
|
15484
|
-
`[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
|
|
15485
|
-
);
|
|
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;
|
|
15486
15784
|
}
|
|
15487
|
-
|
|
15488
|
-
|
|
15489
|
-
|
|
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 {
|
|
15490
15798
|
}
|
|
15491
|
-
|
|
15492
|
-
|
|
15493
|
-
|
|
15494
|
-
|
|
15495
|
-
|
|
15496
|
-
|
|
15497
|
-
|
|
15498
|
-
|
|
15499
|
-
|
|
15500
|
-
|
|
15501
|
-
|
|
15502
|
-
|
|
15503
|
-
|
|
15504
|
-
tags: ["knowledge:feature-work"],
|
|
15505
|
-
trigger: {
|
|
15506
|
-
fact_types: ["world", "experience", "observation"],
|
|
15507
|
-
refresh_after_consolidation: true
|
|
15508
|
-
}
|
|
15509
|
-
});
|
|
15510
|
-
try {
|
|
15511
|
-
const j = await r.json();
|
|
15512
|
-
pageId = j.page_id ?? j.id;
|
|
15513
|
-
} catch {
|
|
15514
|
-
}
|
|
15515
|
-
pageId ||= `initiative-${this.slugify(args.title)}`;
|
|
15516
|
-
}
|
|
15517
|
-
const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
|
|
15518
|
-
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
15519
|
-
const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
|
|
15520
|
-
const tags = [
|
|
15521
|
-
.../* @__PURE__ */ new Set([
|
|
15522
|
-
...args.stamp?.tags ?? [],
|
|
15523
|
-
"knowledge:feature-work",
|
|
15524
|
-
`relatedPageId:${pageId}`
|
|
15525
|
-
])
|
|
15526
|
-
];
|
|
15527
|
-
if (Object.keys(args.stamp?.metadata ?? {}).length) {
|
|
15528
|
-
await this.retain(content, "initiative marker", markerId, tags, "document", {
|
|
15529
|
-
metadata: args.stamp?.metadata
|
|
15530
|
-
});
|
|
15531
|
-
} else {
|
|
15532
|
-
await this.retain(content, "initiative marker", markerId, tags, "document");
|
|
15533
|
-
}
|
|
15534
|
-
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;
|
|
15535
15812
|
}
|
|
15536
|
-
|
|
15537
|
-
|
|
15538
|
-
|
|
15539
|
-
|
|
15540
|
-
|
|
15541
|
-
|
|
15542
|
-
|
|
15543
|
-
if (hit?.id) return hit.id;
|
|
15544
|
-
} catch {
|
|
15545
|
-
}
|
|
15546
|
-
try {
|
|
15547
|
-
const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
|
|
15548
|
-
return (await r.json()).id;
|
|
15549
|
-
} catch {
|
|
15550
|
-
return void 0;
|
|
15551
|
-
}
|
|
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;
|
|
15552
15820
|
}
|
|
15553
|
-
|
|
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
|
+
}
|
|
15554
15839
|
|
|
15555
15840
|
// src/core/knowledge-tools.ts
|
|
15556
15841
|
import { existsSync as existsSync3 } from "fs";
|
|
15557
15842
|
import { homedir as homedir4 } from "os";
|
|
15558
|
-
import { join as
|
|
15843
|
+
import { join as join7 } from "path";
|
|
15559
15844
|
|
|
15560
15845
|
// src/core/status.ts
|
|
15561
|
-
import { execFileSync as
|
|
15846
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
15562
15847
|
|
|
15563
15848
|
// src/core/git.ts
|
|
15564
|
-
import { execFileSync as
|
|
15849
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
15565
15850
|
import { resolve } from "path";
|
|
15566
15851
|
function git(repo, ...args) {
|
|
15567
|
-
return
|
|
15852
|
+
return execFileSync3("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
|
|
15568
15853
|
}
|
|
15569
15854
|
function repoNameOf(repo) {
|
|
15570
15855
|
return projectNameOf(resolve(repo));
|
|
@@ -15610,7 +15895,7 @@ function roster(pages) {
|
|
|
15610
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>".
|
|
15611
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.
|
|
15612
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>").
|
|
15613
|
-
- 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
|
|
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.
|
|
15614
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).`;
|
|
15615
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";
|
|
15616
15901
|
function toolGuide(opts) {
|
|
@@ -15637,11 +15922,11 @@ ${toolGuide(opts)}
|
|
|
15637
15922
|
}
|
|
15638
15923
|
|
|
15639
15924
|
// src/core/survey.ts
|
|
15640
|
-
import { spawn as
|
|
15925
|
+
import { spawn as realSpawn3 } from "child_process";
|
|
15641
15926
|
import { accessSync, constants, existsSync as existsSync2 } from "fs";
|
|
15642
15927
|
import { homedir as homedir3 } from "os";
|
|
15643
|
-
import { delimiter, dirname as
|
|
15644
|
-
import { fileURLToPath as
|
|
15928
|
+
import { delimiter, dirname as dirname5, join as join6 } from "path";
|
|
15929
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
15645
15930
|
var SURVEY_DOC_IDS = [
|
|
15646
15931
|
"repository-component-map",
|
|
15647
15932
|
"repository-core-concepts",
|
|
@@ -15651,7 +15936,7 @@ var SURVEY_DOC_IDS = [
|
|
|
15651
15936
|
function resolveClaudeBin(explicit) {
|
|
15652
15937
|
if (explicit) return explicit;
|
|
15653
15938
|
if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
|
|
15654
|
-
const nativeInstallPath =
|
|
15939
|
+
const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
|
|
15655
15940
|
try {
|
|
15656
15941
|
if (existsSync2(nativeInstallPath)) return nativeInstallPath;
|
|
15657
15942
|
} catch {
|
|
@@ -15680,7 +15965,7 @@ function binExists(bin) {
|
|
|
15680
15965
|
for (const dir of (process.env.PATH || "").split(delimiter)) {
|
|
15681
15966
|
if (!dir) continue;
|
|
15682
15967
|
try {
|
|
15683
|
-
accessSync(
|
|
15968
|
+
accessSync(join6(dir, bin), constants.X_OK);
|
|
15684
15969
|
return true;
|
|
15685
15970
|
} catch {
|
|
15686
15971
|
}
|
|
@@ -15724,7 +16009,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
|
|
|
15724
16009
|
hindsight: {
|
|
15725
16010
|
command: "node",
|
|
15726
16011
|
args: [opts.mcpServerPath],
|
|
15727
|
-
|
|
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" }
|
|
15728
16017
|
}
|
|
15729
16018
|
}
|
|
15730
16019
|
});
|
|
@@ -15764,6 +16053,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
|
|
|
15764
16053
|
`mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
|
|
15765
16054
|
"-c",
|
|
15766
16055
|
`mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
|
|
16056
|
+
"-c",
|
|
16057
|
+
`mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
|
|
15767
16058
|
SURVEY_PROMPT
|
|
15768
16059
|
],
|
|
15769
16060
|
env
|
|
@@ -15787,9 +16078,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
|
|
|
15787
16078
|
}
|
|
15788
16079
|
function startCodebaseSurvey(repoDir, opts = {}) {
|
|
15789
16080
|
try {
|
|
15790
|
-
const spawnFn = opts.spawn ??
|
|
16081
|
+
const spawnFn = opts.spawn ?? realSpawn3;
|
|
15791
16082
|
const exists = opts.exists ?? binExists;
|
|
15792
|
-
const mcpServerPath = opts.mcpServerPath ??
|
|
16083
|
+
const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
|
|
15793
16084
|
const preferred = opts.harness ?? "claude-code";
|
|
15794
16085
|
const order = [
|
|
15795
16086
|
preferred,
|
|
@@ -15828,7 +16119,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
15828
16119
|
var DEEPEN_DIFF_TARGET = 300;
|
|
15829
16120
|
function commitCount(repoDir) {
|
|
15830
16121
|
try {
|
|
15831
|
-
const out =
|
|
16122
|
+
const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
|
|
15832
16123
|
encoding: "utf8"
|
|
15833
16124
|
});
|
|
15834
16125
|
return Number(out.trim()) || 0;
|
|
@@ -15919,9 +16210,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
15919
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.",
|
|
15920
16211
|
inputSchema: {},
|
|
15921
16212
|
handler: async (_args) => {
|
|
15922
|
-
const configPath = process.env.HINDSIGHT_CONFIG ||
|
|
16213
|
+
const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
|
|
15923
16214
|
const harness = opts.harness ?? "unknown";
|
|
15924
|
-
const cfg =
|
|
16215
|
+
const cfg = applyBankConfig(
|
|
16216
|
+
loadConfig({ harness: opts.harness }),
|
|
16217
|
+
bankId,
|
|
16218
|
+
opts.repoDir
|
|
16219
|
+
).cfg;
|
|
15925
16220
|
return ok({
|
|
15926
16221
|
bank_id: bankId,
|
|
15927
16222
|
harness,
|
|
@@ -15933,6 +16228,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
15933
16228
|
api_token_configured: Boolean(cfg.apiToken),
|
|
15934
16229
|
disabled: cfg.disabled
|
|
15935
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
|
+
},
|
|
15936
16239
|
environment: {
|
|
15937
16240
|
config_override: Boolean(process.env.HINDSIGHT_CONFIG),
|
|
15938
16241
|
hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
|
|
@@ -15981,12 +16284,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
15981
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>".`,
|
|
15982
16285
|
inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
|
|
15983
16286
|
handler: guarded(
|
|
15984
|
-
async ({ query }) => client.reflect(query, {
|
|
16287
|
+
async ({ query }) => client.reflect(query, {
|
|
16288
|
+
budget: opts.reflectBudget ?? "high",
|
|
16289
|
+
timeoutMs: opts.reflectTimeoutMs ?? DEFAULT_REFLECT_TOOL_TIMEOUT_MS
|
|
16290
|
+
})
|
|
15985
16291
|
)
|
|
15986
16292
|
},
|
|
15987
16293
|
{
|
|
15988
16294
|
name: "hindsight_capture_initiative",
|
|
15989
|
-
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.
|
|
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.",
|
|
15990
16296
|
inputSchema: {
|
|
15991
16297
|
title: external_exports.string(),
|
|
15992
16298
|
summary: external_exports.string(),
|
|
@@ -15997,7 +16303,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
15997
16303
|
title,
|
|
15998
16304
|
summary,
|
|
15999
16305
|
relatesToPageId: relates_to_page_id,
|
|
16000
|
-
...opts.stampFor ? { stamp: opts.stampFor() } : {}
|
|
16306
|
+
...opts.stampFor ? { stamp: opts.stampFor() } : {},
|
|
16307
|
+
...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
|
|
16001
16308
|
})
|
|
16002
16309
|
)
|
|
16003
16310
|
},
|
|
@@ -16204,7 +16511,7 @@ function resolversFor(ctx) {
|
|
|
16204
16511
|
return {
|
|
16205
16512
|
// Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
|
|
16206
16513
|
// otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
|
|
16207
|
-
gitProject: () => projectNameOf(ctx.directory),
|
|
16514
|
+
gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
|
|
16208
16515
|
project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
|
|
16209
16516
|
harness: () => ctx.harness,
|
|
16210
16517
|
bankId: () => ctx.bankId,
|
|
@@ -16250,11 +16557,6 @@ import { readFileSync as readFileSync4 } from "fs";
|
|
|
16250
16557
|
// src/core/skill-sync.ts
|
|
16251
16558
|
import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
|
|
16252
16559
|
import { homedir as homedir5 } from "os";
|
|
16253
|
-
import { dirname as dirname5, join as join7 } from "path";
|
|
16254
|
-
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
16255
|
-
|
|
16256
|
-
// src/core/daemon.ts
|
|
16257
|
-
import { execFileSync as execFileSync4, spawn as realSpawn3 } from "child_process";
|
|
16258
16560
|
import { dirname as dirname6, join as join8 } from "path";
|
|
16259
16561
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
16260
16562
|
|
|
@@ -16345,7 +16647,7 @@ async function buildSessionStartContext(args) {
|
|
|
16345
16647
|
const startSurvey = args.startSurvey ?? startCodebaseSurvey;
|
|
16346
16648
|
const resolveHeadSha = args.headSha ?? gitHeadSha;
|
|
16347
16649
|
const countCommitsSince = args.commitsSince ?? commitsSince;
|
|
16348
|
-
const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
|
|
16650
|
+
const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
|
|
16349
16651
|
const SURVEY_BASELINE_TAG = "source:survey-baseline";
|
|
16350
16652
|
const SURVEY_BASELINE_PREFIX = "survey-baseline:";
|
|
16351
16653
|
const recordSurveyBaseline = (sha) => {
|
|
@@ -16621,6 +16923,9 @@ var RuntimeCore = class {
|
|
|
16621
16923
|
return buildKnowledgeTools(this.client, this.bankId, {
|
|
16622
16924
|
repoDir: this.projectDir,
|
|
16623
16925
|
harness: this.harness,
|
|
16926
|
+
pageTrigger: buildPageTrigger(this.cfg),
|
|
16927
|
+
reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
|
|
16928
|
+
reflectBudget: this.cfg.reflectBudget,
|
|
16624
16929
|
stampFor: () => buildRetainStamp(this.cfg, {
|
|
16625
16930
|
directory: this.projectDir,
|
|
16626
16931
|
harness: this.harness,
|
|
@@ -16639,6 +16944,7 @@ var RuntimeCore = class {
|
|
|
16639
16944
|
*/
|
|
16640
16945
|
async seedIfCold(repoPath) {
|
|
16641
16946
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
16947
|
+
await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
|
|
16642
16948
|
try {
|
|
16643
16949
|
const out = await buildSessionStartContext({
|
|
16644
16950
|
cwd: repoPath || process.cwd(),
|
|
@@ -16762,15 +17068,17 @@ var RuntimeCore = class {
|
|
|
16762
17068
|
/** Fire-and-forget upsert of the session transcript; never throws into the host. */
|
|
16763
17069
|
retain(sessionId, turns, startTs, trigger = "turn") {
|
|
16764
17070
|
const t0 = Date.now();
|
|
16765
|
-
void
|
|
16766
|
-
|
|
16767
|
-
|
|
16768
|
-
|
|
16769
|
-
|
|
16770
|
-
|
|
16771
|
-
|
|
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
|
+
})
|
|
16772
17080
|
})
|
|
16773
|
-
|
|
17081
|
+
).then(
|
|
16774
17082
|
() => diag(this.harness, "retain_ok", {
|
|
16775
17083
|
ms: Date.now() - t0,
|
|
16776
17084
|
turns: turns.length,
|
|
@@ -16898,17 +17206,9 @@ ${injection}` };
|
|
|
16898
17206
|
};
|
|
16899
17207
|
}
|
|
16900
17208
|
function createRuntime(repoPath) {
|
|
16901
|
-
|
|
17209
|
+
const { cfg, bankId, client } = resolveHostMemory(HARNESS2, repoPath);
|
|
16902
17210
|
if (cfg.disabled) return void 0;
|
|
16903
|
-
|
|
16904
|
-
cfg = resolved.cfg;
|
|
16905
|
-
if (cfg.disabled) return void 0;
|
|
16906
|
-
const client = new HindsightClient({
|
|
16907
|
-
apiUrl: cfg.apiUrl,
|
|
16908
|
-
apiToken: cfg.apiToken,
|
|
16909
|
-
bank: resolved.bankId
|
|
16910
|
-
});
|
|
16911
|
-
return new RuntimeCore(client, resolved.bankId, cfg, HARNESS2, repoPath);
|
|
17211
|
+
return new RuntimeCore(client, bankId, cfg, HARNESS2, repoPath);
|
|
16912
17212
|
}
|
|
16913
17213
|
var extension = (pi) => {
|
|
16914
17214
|
const repoPath = process.cwd();
|