@vectorize-io/hindsight-coding-agents 0.3.4 → 0.4.1
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 +449 -282
- package/dist/antigravity-statusline.js +130 -27
- package/dist/antigravity-stop-hook.js +456 -284
- package/dist/claude-hook.js +449 -282
- package/dist/claude-sessionstart-hook.js +461 -288
- package/dist/claude-stop-hook.js +456 -284
- package/dist/cline.js +652 -348
- package/dist/codex-hook.js +449 -282
- package/dist/codex-sessionstart-hook.js +461 -288
- package/dist/codex-stop-hook.js +456 -284
- package/dist/copilot-hook.js +449 -282
- package/dist/copilot-sessionstart-hook.js +461 -288
- package/dist/copilot-stop-hook.js +456 -284
- package/dist/cursor-hook.js +449 -282
- package/dist/cursor-sessionstart-hook.js +461 -288
- package/dist/cursor-stop-hook.js +456 -284
- package/dist/daemon-start.js +101 -45
- package/dist/deepen.js +314 -149
- package/dist/devin-hook.js +449 -282
- package/dist/devin-sessionstart-hook.js +461 -288
- package/dist/devin-stop-hook.js +456 -284
- package/dist/dsh.js +888 -585
- package/dist/grok-hook.js +449 -282
- package/dist/grok-sessionstart-hook.js +461 -288
- package/dist/grok-stop-hook.js +456 -284
- package/dist/hindsight-seed.js +122 -24
- package/dist/index.js +676 -371
- package/dist/installer.js +40 -48
- package/dist/kilo.js +676 -371
- package/dist/mcp-server.js +550 -318
- package/dist/prime-agent.js +888 -582
- package/dist/status.js +444 -263
- package/package.json +10 -2
- package/skill/SKILL.md +20 -4
package/dist/dsh.js
CHANGED
|
@@ -7,11 +7,48 @@ var __export = (target, all) => {
|
|
|
7
7
|
// src/dsh.ts
|
|
8
8
|
import { randomUUID } from "crypto";
|
|
9
9
|
|
|
10
|
+
// src/core/config.ts
|
|
11
|
+
import { readFileSync } from "fs";
|
|
12
|
+
import { homedir as homedir2 } from "os";
|
|
13
|
+
import { join as join4 } from "path";
|
|
14
|
+
|
|
15
|
+
// src/core/seed.ts
|
|
16
|
+
import { spawn as realSpawn } from "child_process";
|
|
17
|
+
import { dirname, join } from "path";
|
|
18
|
+
import { fileURLToPath } from "url";
|
|
19
|
+
var DEFAULT_SEED_LIMIT = 300;
|
|
20
|
+
function startBackgroundSeed(repoDir, opts = {}) {
|
|
21
|
+
try {
|
|
22
|
+
const spawnFn = opts.spawn ?? realSpawn;
|
|
23
|
+
const enginePath = opts.enginePath ?? join(dirname(fileURLToPath(import.meta.url)), "deepen.js");
|
|
24
|
+
const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
|
|
25
|
+
const child = spawnFn(
|
|
26
|
+
"node",
|
|
27
|
+
[
|
|
28
|
+
enginePath,
|
|
29
|
+
"--repo",
|
|
30
|
+
repoDir,
|
|
31
|
+
"--gitlog-limit",
|
|
32
|
+
String(limit),
|
|
33
|
+
...opts.harness ? ["--harness", opts.harness] : []
|
|
34
|
+
],
|
|
35
|
+
{
|
|
36
|
+
detached: true,
|
|
37
|
+
stdio: "ignore"
|
|
38
|
+
}
|
|
39
|
+
);
|
|
40
|
+
child.on("error", () => {
|
|
41
|
+
});
|
|
42
|
+
child.unref();
|
|
43
|
+
} catch {
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
10
47
|
// src/core/bank.ts
|
|
11
48
|
import { execFileSync } from "child_process";
|
|
12
49
|
import { existsSync } from "fs";
|
|
13
50
|
import { homedir } from "os";
|
|
14
|
-
import { basename, dirname, join, normalize, sep } from "path";
|
|
51
|
+
import { basename, dirname as dirname2, join as join2, normalize, sep } from "path";
|
|
15
52
|
|
|
16
53
|
// src/core/template.ts
|
|
17
54
|
var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
|
|
@@ -40,20 +77,20 @@ function getProjectRootFromGit(directory) {
|
|
|
40
77
|
{ cwd: directory, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], timeout: 1e3 }
|
|
41
78
|
).trim();
|
|
42
79
|
if (!commonDir) return null;
|
|
43
|
-
return basename(commonDir) === ".git" ?
|
|
80
|
+
return basename(commonDir) === ".git" ? dirname2(commonDir) : commonDir;
|
|
44
81
|
} catch {
|
|
45
82
|
return null;
|
|
46
83
|
}
|
|
47
84
|
}
|
|
48
|
-
function projectNameOf(directory) {
|
|
49
|
-
return gitProjectName(directory, true);
|
|
85
|
+
function projectNameOf(directory, sessionRoot) {
|
|
86
|
+
return gitProjectName(directory, true, sessionRoot);
|
|
50
87
|
}
|
|
51
88
|
var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
|
|
52
89
|
function nearestExistingDir(directory) {
|
|
53
90
|
let current2 = directory;
|
|
54
91
|
while (current2) {
|
|
55
92
|
if (existsSync(current2)) return current2;
|
|
56
|
-
const parent =
|
|
93
|
+
const parent = dirname2(current2);
|
|
57
94
|
if (parent === current2) return "";
|
|
58
95
|
current2 = parent;
|
|
59
96
|
}
|
|
@@ -62,21 +99,27 @@ function nearestExistingDir(directory) {
|
|
|
62
99
|
function dirName(directory) {
|
|
63
100
|
return directory && basename(directory) || "unknown";
|
|
64
101
|
}
|
|
65
|
-
function
|
|
102
|
+
function mainWorktreeRoot(directory, sessionRoot = "") {
|
|
103
|
+
const candidates = [
|
|
104
|
+
nearestExistingDir(directory),
|
|
105
|
+
sessionRoot,
|
|
106
|
+
...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
|
|
107
|
+
];
|
|
108
|
+
for (const candidate of candidates) {
|
|
109
|
+
const root = candidate ? getProjectRootFromGit(candidate) : null;
|
|
110
|
+
if (root) return root;
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
|
|
66
115
|
if (resolveWorktrees) {
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
|
|
70
|
-
];
|
|
71
|
-
for (const candidate of candidates) {
|
|
72
|
-
const root = candidate ? getProjectRootFromGit(candidate) : null;
|
|
73
|
-
if (root) return basename(root);
|
|
74
|
-
}
|
|
116
|
+
const root = mainWorktreeRoot(directory, sessionRoot);
|
|
117
|
+
if (root) return basename(root);
|
|
75
118
|
}
|
|
76
|
-
return dirName(directory);
|
|
119
|
+
return dirName(sessionRoot || directory);
|
|
77
120
|
}
|
|
78
121
|
function configuredDir(dir) {
|
|
79
|
-
const expanded = dir === "~" || dir.startsWith("~/") ?
|
|
122
|
+
const expanded = dir === "~" || dir.startsWith("~/") ? join2(homedir(), dir.slice(1)) : dir;
|
|
80
123
|
return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
|
|
81
124
|
}
|
|
82
125
|
function isWithin(directory, configured) {
|
|
@@ -93,320 +136,89 @@ function mapLookup(map2, directory) {
|
|
|
93
136
|
}
|
|
94
137
|
return best?.bank;
|
|
95
138
|
}
|
|
139
|
+
function lookupDirectories(config2, directory, sessionRoot = "") {
|
|
140
|
+
const directories = [normalize(directory)];
|
|
141
|
+
if (config2.resolveWorktrees ?? true) {
|
|
142
|
+
const root = mainWorktreeRoot(directory, sessionRoot);
|
|
143
|
+
const normalizedRoot = root ? normalize(root) : "";
|
|
144
|
+
if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
|
|
145
|
+
}
|
|
146
|
+
return directories;
|
|
147
|
+
}
|
|
96
148
|
function isOptedIn(config2, directory) {
|
|
97
149
|
if (!config2.optInOnly) return true;
|
|
98
150
|
if (!directory) return false;
|
|
99
|
-
const
|
|
100
|
-
if (
|
|
151
|
+
const directories = lookupDirectories(config2, directory);
|
|
152
|
+
if (directories.some(
|
|
153
|
+
(candidate) => (config2.optInPaths ?? []).some(
|
|
154
|
+
(configured) => configured && isWithin(candidate, configuredDir(configured))
|
|
155
|
+
)
|
|
156
|
+
))
|
|
101
157
|
return true;
|
|
102
|
-
|
|
158
|
+
const pathMap = config2.mapPathToBank;
|
|
159
|
+
return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
|
|
103
160
|
}
|
|
104
|
-
function deriveBankId(config2, directory, harness = "coding") {
|
|
105
|
-
const
|
|
161
|
+
function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
|
|
162
|
+
const pathMap = config2.mapPathToBank;
|
|
163
|
+
const mapped = directory && pathMap ? lookupDirectories(config2, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
|
|
106
164
|
if (mapped) return mapped;
|
|
107
165
|
const dynamic = config2.dynamicBankId ?? !config2.bankId;
|
|
108
166
|
if (!dynamic) return config2.bankId || DEFAULT_BANK_NAME;
|
|
109
167
|
const resolvers = {
|
|
110
168
|
harness: () => harness,
|
|
111
169
|
project: () => dirName(directory),
|
|
112
|
-
gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true),
|
|
170
|
+
gitProject: () => gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot),
|
|
113
171
|
channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
|
|
114
172
|
user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
|
|
115
173
|
};
|
|
116
174
|
return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
|
|
117
175
|
}
|
|
118
176
|
|
|
119
|
-
// src/core/
|
|
120
|
-
import {
|
|
121
|
-
import {
|
|
122
|
-
import { join as join3 } from "path";
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
function startBackgroundSeed(repoDir, opts = {}) {
|
|
130
|
-
try {
|
|
131
|
-
const spawnFn = opts.spawn ?? realSpawn;
|
|
132
|
-
const enginePath = opts.enginePath ?? join2(dirname2(fileURLToPath(import.meta.url)), "deepen.js");
|
|
133
|
-
const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
|
|
134
|
-
const child = spawnFn(
|
|
135
|
-
"node",
|
|
136
|
-
[
|
|
137
|
-
enginePath,
|
|
138
|
-
"--repo",
|
|
139
|
-
repoDir,
|
|
140
|
-
"--gitlog-limit",
|
|
141
|
-
String(limit),
|
|
142
|
-
...opts.harness ? ["--harness", opts.harness] : []
|
|
143
|
-
],
|
|
144
|
-
{
|
|
145
|
-
detached: true,
|
|
146
|
-
stdio: "ignore"
|
|
147
|
-
}
|
|
148
|
-
);
|
|
149
|
-
child.on("error", () => {
|
|
150
|
-
});
|
|
151
|
-
child.unref();
|
|
152
|
-
} catch {
|
|
153
|
-
}
|
|
177
|
+
// src/core/log.ts
|
|
178
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
179
|
+
import { tmpdir } from "os";
|
|
180
|
+
import { dirname as dirname3, join as join3 } from "path";
|
|
181
|
+
var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
182
|
+
var current = ["debug", "info", "warn", "error"].find(
|
|
183
|
+
(l) => l === process.env.HINDSIGHT_LOG_LEVEL
|
|
184
|
+
) ?? "info";
|
|
185
|
+
function setLogLevel(level) {
|
|
186
|
+
if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
|
|
154
187
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
|
|
158
|
-
var DEFAULT_DAEMON_PORT = 9077;
|
|
159
|
-
var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
|
|
160
|
-
var DEFAULT_DAEMON_PROFILE = "coding-agent";
|
|
161
|
-
function resolveConfig(raw = {}) {
|
|
162
|
-
const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
|
|
163
|
-
const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
|
|
164
|
-
return {
|
|
165
|
-
serverMode,
|
|
166
|
-
// Daemon mode resolves the URL HERE rather than at each call site: every entry point already
|
|
167
|
-
// builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
|
|
168
|
-
// daemon needs no plumbing through eight separate constructors.
|
|
169
|
-
apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
|
|
170
|
-
apiToken: raw.apiToken || void 0,
|
|
171
|
-
apiPort,
|
|
172
|
-
daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
|
|
173
|
-
daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
|
|
174
|
-
embedVersion: raw.embedVersion || void 0,
|
|
175
|
-
embedPackagePath: raw.embedPackagePath || void 0,
|
|
176
|
-
bankId: raw.bankId,
|
|
177
|
-
dynamicBankId: raw.dynamicBankId,
|
|
178
|
-
bankIdTemplate: raw.bankIdTemplate,
|
|
179
|
-
mapPathToBank: raw.mapPathToBank,
|
|
180
|
-
resolveWorktrees: raw.resolveWorktrees,
|
|
181
|
-
optInOnly: raw.optInOnly ?? false,
|
|
182
|
-
// Same shape as retainTags: a config typo must not become a path that silently approves nothing.
|
|
183
|
-
optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
|
|
184
|
-
harness: raw.harness ?? "opencode",
|
|
185
|
-
disabled: raw.disabled ?? false,
|
|
186
|
-
retainSessions: raw.retainSessions ?? true,
|
|
187
|
-
// opencode: write back by default (parity with hook-harness Stop)
|
|
188
|
-
maxParallelRetains: raw.maxParallelRetains || 10,
|
|
189
|
-
reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
|
|
190
|
-
autoReflect: raw.autoReflect ?? true,
|
|
191
|
-
pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
|
|
192
|
-
autoSeed: raw.autoSeed ?? true,
|
|
193
|
-
seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
|
|
194
|
-
codebaseSurvey: raw.codebaseSurvey ?? true,
|
|
195
|
-
surveyModel: raw.surveyModel || "haiku",
|
|
196
|
-
surveyBudgetUsd: raw.surveyBudgetUsd || 2,
|
|
197
|
-
surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
|
|
198
|
-
gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
|
|
199
|
-
// Hostile input is a config typo, not an attack: keep only string entries so a stray number or
|
|
200
|
-
// nested object cannot reach the API as a tag and fail the whole retain.
|
|
201
|
-
retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
|
|
202
|
-
retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
|
|
203
|
-
Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
|
|
204
|
-
) : {},
|
|
205
|
-
banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
|
|
206
|
-
logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
|
|
207
|
-
};
|
|
188
|
+
function logFilePath() {
|
|
189
|
+
return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
|
|
208
190
|
}
|
|
209
|
-
function
|
|
191
|
+
function write(level, scope, msg, extra) {
|
|
192
|
+
if (WEIGHT[level] < WEIGHT[current]) return;
|
|
210
193
|
try {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
194
|
+
const file2 = logFilePath();
|
|
195
|
+
mkdirSync(dirname3(file2), { recursive: true });
|
|
196
|
+
appendFileSync(
|
|
197
|
+
file2,
|
|
198
|
+
`${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
|
|
199
|
+
);
|
|
200
|
+
} catch {
|
|
217
201
|
}
|
|
218
202
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
let out = mergeRaw(raw, layer);
|
|
225
|
-
const perHarness = harness ? layer.harnesses?.[harness] : void 0;
|
|
226
|
-
if (perHarness) out = mergeRaw(out, perHarness);
|
|
227
|
-
return out;
|
|
228
|
-
}
|
|
229
|
-
var ENV_KEYS = {
|
|
230
|
-
serverMode: "HINDSIGHT_SERVER_MODE",
|
|
231
|
-
apiUrl: "HINDSIGHT_API_URL",
|
|
232
|
-
apiToken: "HINDSIGHT_API_TOKEN",
|
|
233
|
-
// These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
|
|
234
|
-
// it can carry their existing environment over unchanged.
|
|
235
|
-
apiPort: "HINDSIGHT_API_PORT",
|
|
236
|
-
daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
|
|
237
|
-
embedVersion: "HINDSIGHT_EMBED_VERSION",
|
|
238
|
-
embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
|
|
239
|
-
daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
|
|
240
|
-
bankId: "HINDSIGHT_BANK_ID",
|
|
241
|
-
dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
|
|
242
|
-
bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
|
|
243
|
-
resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
|
|
244
|
-
optInOnly: "HINDSIGHT_OPT_IN_ONLY",
|
|
245
|
-
optInPaths: "HINDSIGHT_OPT_IN_PATHS",
|
|
246
|
-
harness: "HINDSIGHT_HARNESS",
|
|
247
|
-
disabled: "HINDSIGHT_DISABLED",
|
|
248
|
-
retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
|
|
249
|
-
maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
|
|
250
|
-
reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
|
|
251
|
-
autoReflect: "HINDSIGHT_AUTO_REFLECT",
|
|
252
|
-
pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
|
|
253
|
-
autoSeed: "HINDSIGHT_AUTO_SEED",
|
|
254
|
-
seedLimit: "HINDSIGHT_SEED_LIMIT",
|
|
255
|
-
codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
|
|
256
|
-
surveyModel: "HINDSIGHT_SURVEY_MODEL",
|
|
257
|
-
surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
|
|
258
|
-
surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
|
|
259
|
-
logLevel: "HINDSIGHT_LOG_LEVEL",
|
|
260
|
-
gitIngest: "HINDSIGHT_GIT_INGEST",
|
|
261
|
-
// Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
|
|
262
|
-
// a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
|
|
263
|
-
retainTags: "HINDSIGHT_RETAIN_TAGS"
|
|
203
|
+
var log = {
|
|
204
|
+
debug: (scope, msg, extra) => write("debug", scope, msg, extra),
|
|
205
|
+
info: (scope, msg, extra) => write("info", scope, msg, extra),
|
|
206
|
+
warn: (scope, msg, extra) => write("warn", scope, msg, extra),
|
|
207
|
+
error: (scope, msg, extra) => write("error", scope, msg, extra)
|
|
264
208
|
};
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
var ENV_NUMBERS = /* @__PURE__ */ new Set([
|
|
277
|
-
"apiPort",
|
|
278
|
-
"daemonIdleTimeout",
|
|
279
|
-
"maxParallelRetains",
|
|
280
|
-
"reflectTimeoutMs",
|
|
281
|
-
"pageRefreshEveryTurns",
|
|
282
|
-
"seedLimit",
|
|
283
|
-
"surveyBudgetUsd",
|
|
284
|
-
"surveyRefreshCommits"
|
|
285
|
-
]);
|
|
286
|
-
function readEnvConfig(env = process.env) {
|
|
287
|
-
const out = {};
|
|
288
|
-
for (const [key, name2] of Object.entries(ENV_KEYS)) {
|
|
289
|
-
const value = env[name2];
|
|
290
|
-
if (value === void 0 || value.trim() === "") continue;
|
|
291
|
-
if (ENV_BOOLEANS.has(key)) {
|
|
292
|
-
out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
|
|
293
|
-
} else if (ENV_LISTS.has(key)) {
|
|
294
|
-
const items = value.split(",").map((v) => v.trim()).filter(Boolean);
|
|
295
|
-
if (items.length) out[key] = items;
|
|
296
|
-
} else if (ENV_NUMBERS.has(key)) {
|
|
297
|
-
const n = Number(value);
|
|
298
|
-
if (Number.isFinite(n)) out[key] = n;
|
|
299
|
-
else console.error(`hindsight: ignoring ${name2}=${value} \u2014 not a number`);
|
|
300
|
-
} else {
|
|
301
|
-
out[key] = value;
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
return out;
|
|
305
|
-
}
|
|
306
|
-
function loadConfig(opts = {}) {
|
|
307
|
-
const o = typeof opts === "string" ? { path: opts } : opts;
|
|
308
|
-
const withEnv = applyLayer({}, readEnvConfig(), o.harness);
|
|
309
|
-
const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
|
|
310
|
-
if (!raw.harness && o.harness) raw.harness = o.harness;
|
|
311
|
-
return resolveConfig(raw);
|
|
312
|
-
}
|
|
313
|
-
var BANK_OVERRIDE_EXCLUDED = [
|
|
314
|
-
"bankId",
|
|
315
|
-
"bankIdTemplate",
|
|
316
|
-
"mapPathToBank",
|
|
317
|
-
"dynamicBankId",
|
|
318
|
-
"resolveWorktrees",
|
|
319
|
-
// Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
|
|
320
|
-
// only ever arrive too late to matter — strip them rather than let them read as effective.
|
|
321
|
-
"optInOnly",
|
|
322
|
-
"optInPaths",
|
|
323
|
-
"harness"
|
|
324
|
-
];
|
|
325
|
-
function applyBankConfig(cfg, resolvedId, directory) {
|
|
326
|
-
if (directory !== void 0 && !isOptedIn(cfg, directory))
|
|
327
|
-
return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
|
|
328
|
-
const section = cfg.banks[resolvedId];
|
|
329
|
-
if (!section) return { cfg, bankId: resolvedId };
|
|
330
|
-
const safe = { ...section };
|
|
331
|
-
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
332
|
-
delete safe.banks;
|
|
333
|
-
const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
|
|
334
|
-
delete safe.bank;
|
|
335
|
-
return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
|
|
336
|
-
}
|
|
337
|
-
function resolvePartial(cfg, patch) {
|
|
338
|
-
const full = resolveConfig(patch);
|
|
339
|
-
const out = {};
|
|
340
|
-
for (const key of Object.keys(patch)) {
|
|
341
|
-
if (key in full)
|
|
342
|
-
out[key] = full[key];
|
|
343
|
-
}
|
|
344
|
-
return out;
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
// src/core/diag.ts
|
|
348
|
-
import { appendFileSync as appendFileSync2 } from "fs";
|
|
349
|
-
|
|
350
|
-
// src/core/log.ts
|
|
351
|
-
import { appendFileSync, mkdirSync } from "fs";
|
|
352
|
-
import { tmpdir } from "os";
|
|
353
|
-
import { dirname as dirname3, join as join4 } from "path";
|
|
354
|
-
var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
355
|
-
var current = ["debug", "info", "warn", "error"].find(
|
|
356
|
-
(l) => l === process.env.HINDSIGHT_LOG_LEVEL
|
|
357
|
-
) ?? "info";
|
|
358
|
-
function setLogLevel(level) {
|
|
359
|
-
if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
|
|
360
|
-
}
|
|
361
|
-
function logFilePath() {
|
|
362
|
-
return process.env.HINDSIGHT_LOG_FILE || join4(tmpdir(), "hindsight-coding-agent", "plugin.log");
|
|
363
|
-
}
|
|
364
|
-
function write(level, scope, msg, extra) {
|
|
365
|
-
if (WEIGHT[level] < WEIGHT[current]) return;
|
|
366
|
-
try {
|
|
367
|
-
const file2 = logFilePath();
|
|
368
|
-
mkdirSync(dirname3(file2), { recursive: true });
|
|
369
|
-
appendFileSync(
|
|
370
|
-
file2,
|
|
371
|
-
`${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
|
|
372
|
-
);
|
|
373
|
-
} catch {
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
var log = {
|
|
377
|
-
debug: (scope, msg, extra) => write("debug", scope, msg, extra),
|
|
378
|
-
info: (scope, msg, extra) => write("info", scope, msg, extra),
|
|
379
|
-
warn: (scope, msg, extra) => write("warn", scope, msg, extra),
|
|
380
|
-
error: (scope, msg, extra) => write("error", scope, msg, extra)
|
|
381
|
-
};
|
|
382
|
-
function describeError(value, maxChars = 200) {
|
|
383
|
-
const parts = [];
|
|
384
|
-
const seen = /* @__PURE__ */ new Set();
|
|
385
|
-
let current2 = value;
|
|
386
|
-
while (current2 && !seen.has(current2)) {
|
|
387
|
-
seen.add(current2);
|
|
388
|
-
const error51 = current2;
|
|
389
|
-
const text = typeof error51.message === "string" ? error51.message : String(current2);
|
|
390
|
-
const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
|
|
391
|
-
if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
|
|
392
|
-
current2 = error51.cause;
|
|
393
|
-
}
|
|
394
|
-
return (parts.join(": ") || String(value)).slice(0, maxChars);
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
// src/core/diag.ts
|
|
398
|
-
function diagFilePath() {
|
|
399
|
-
return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
|
|
400
|
-
}
|
|
401
|
-
function diag(harness, event, extra = {}) {
|
|
402
|
-
log.debug(harness, `diag:${event}`, extra);
|
|
403
|
-
try {
|
|
404
|
-
appendFileSync2(
|
|
405
|
-
diagFilePath(),
|
|
406
|
-
JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
|
|
407
|
-
);
|
|
408
|
-
} catch {
|
|
209
|
+
function describeError(value, maxChars = 200) {
|
|
210
|
+
const parts = [];
|
|
211
|
+
const seen = /* @__PURE__ */ new Set();
|
|
212
|
+
let current2 = value;
|
|
213
|
+
while (current2 && !seen.has(current2)) {
|
|
214
|
+
seen.add(current2);
|
|
215
|
+
const error51 = current2;
|
|
216
|
+
const text = typeof error51.message === "string" ? error51.message : String(current2);
|
|
217
|
+
const withCode = error51.code ? `${text} (${String(error51.code)})` : text;
|
|
218
|
+
if (withCode && parts.at(-1) !== withCode) parts.push(withCode);
|
|
219
|
+
current2 = error51.cause;
|
|
409
220
|
}
|
|
221
|
+
return (parts.join(": ") || String(value)).slice(0, maxChars);
|
|
410
222
|
}
|
|
411
223
|
|
|
412
224
|
// src/core/missions.ts
|
|
@@ -484,7 +296,10 @@ var KNOWLEDGE_LABELS = {
|
|
|
484
296
|
}
|
|
485
297
|
]
|
|
486
298
|
};
|
|
487
|
-
|
|
299
|
+
function pageScopeRule(project) {
|
|
300
|
+
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.`;
|
|
301
|
+
}
|
|
302
|
+
var PAGE_TAXONOMY = [
|
|
488
303
|
{
|
|
489
304
|
name: "Component map",
|
|
490
305
|
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.",
|
|
@@ -507,15 +322,28 @@ var PAGES = [
|
|
|
507
322
|
},
|
|
508
323
|
{
|
|
509
324
|
name: "Initiatives and enhancements",
|
|
510
|
-
source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory carries a
|
|
325
|
+
source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory's context carries a `[[page:<id>]]` link, repeat that link in the summary of what it describes, so each initiative links to its detailed page.",
|
|
511
326
|
tags: ["knowledge:feature-work"]
|
|
512
327
|
}
|
|
513
328
|
];
|
|
329
|
+
function pagesFor(project) {
|
|
330
|
+
const scope = pageScopeRule(project);
|
|
331
|
+
return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
|
|
332
|
+
}
|
|
514
333
|
var PAGE_MAX_TOKENS = 4096;
|
|
515
|
-
var
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
};
|
|
334
|
+
var PAGE_TAGS_MATCH = "all";
|
|
335
|
+
var PAGE_FACT_TYPES = ["world", "experience", "observation"];
|
|
336
|
+
function buildPageTrigger(cfg = {}) {
|
|
337
|
+
const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
|
|
338
|
+
switch (cfg.pageTriggerType) {
|
|
339
|
+
case "cron":
|
|
340
|
+
return { ...base, refresh_cron: cfg.pageTriggerCron };
|
|
341
|
+
case "manual":
|
|
342
|
+
return { ...base, refresh_after_consolidation: false };
|
|
343
|
+
default:
|
|
344
|
+
return { ...base, refresh_after_consolidation: true };
|
|
345
|
+
}
|
|
346
|
+
}
|
|
519
347
|
var CODING_BANK_TEMPLATE = {
|
|
520
348
|
version: "1",
|
|
521
349
|
bank: {
|
|
@@ -570,6 +398,7 @@ async function pool(items, n, fn, onError, onProgress) {
|
|
|
570
398
|
}
|
|
571
399
|
|
|
572
400
|
// src/core/hindsight.ts
|
|
401
|
+
var DEFAULT_OBSERVATION_SCOPES = "shared";
|
|
573
402
|
var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
|
|
574
403
|
var RateLimitedError = class extends Error {
|
|
575
404
|
constructor(retryAfterMs2) {
|
|
@@ -602,8 +431,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
|
|
|
602
431
|
var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
|
|
603
432
|
var HindsightClient = class {
|
|
604
433
|
apiUrl;
|
|
605
|
-
|
|
434
|
+
/** The credential the NEXT request will sign with — NOT the one the config file holds. The two
|
|
435
|
+
* diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
|
|
436
|
+
token;
|
|
437
|
+
tokenProvider;
|
|
606
438
|
bank;
|
|
439
|
+
project;
|
|
607
440
|
opIds = [];
|
|
608
441
|
// async operation ids collected by retain(), for drain()
|
|
609
442
|
/** Tri-state capability probe: unknown until the first page request, then cached. */
|
|
@@ -612,34 +445,81 @@ var HindsightClient = class {
|
|
|
612
445
|
idempotentRetain;
|
|
613
446
|
log;
|
|
614
447
|
maxParallelRetains;
|
|
448
|
+
observationScopes;
|
|
615
449
|
constructor(o) {
|
|
616
450
|
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
617
|
-
this.
|
|
451
|
+
this.token = o.apiToken;
|
|
452
|
+
this.tokenProvider = o.tokenProvider;
|
|
618
453
|
this.bank = o.bank;
|
|
454
|
+
this.project = o.project;
|
|
619
455
|
this.log = o.log ?? (() => {
|
|
620
456
|
});
|
|
621
457
|
this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
|
|
458
|
+
this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
|
|
459
|
+
}
|
|
460
|
+
/** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
|
|
461
|
+
get apiToken() {
|
|
462
|
+
return this.token;
|
|
622
463
|
}
|
|
623
464
|
headers() {
|
|
624
465
|
const h = { "Content-Type": "application/json" };
|
|
625
|
-
if (this.
|
|
466
|
+
if (this.token) h["Authorization"] = `Bearer ${this.token}`;
|
|
626
467
|
return h;
|
|
627
468
|
}
|
|
469
|
+
/** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
|
|
470
|
+
* only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
|
|
471
|
+
* doubling every failing request. */
|
|
472
|
+
refreshToken() {
|
|
473
|
+
if (!this.tokenProvider) return false;
|
|
474
|
+
let next;
|
|
475
|
+
try {
|
|
476
|
+
next = this.tokenProvider();
|
|
477
|
+
} catch {
|
|
478
|
+
return false;
|
|
479
|
+
}
|
|
480
|
+
if (next === this.token) return false;
|
|
481
|
+
this.token = next;
|
|
482
|
+
return true;
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
|
|
486
|
+
* poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
|
|
487
|
+
* failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
|
|
488
|
+
* not.
|
|
489
|
+
*
|
|
490
|
+
* On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
|
|
491
|
+
* string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
|
|
492
|
+
* free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
|
|
493
|
+
* bounds the whole call.
|
|
494
|
+
*/
|
|
495
|
+
async fetchWithAuth(url2, init) {
|
|
496
|
+
const send = () => fetch(url2, { ...init, headers: this.headers() });
|
|
497
|
+
const r = await send();
|
|
498
|
+
if (r.status !== 401 || !this.refreshToken()) return r;
|
|
499
|
+
return send();
|
|
500
|
+
}
|
|
501
|
+
/** A 401 with no `Authorization` header is a different failure from a rejected key, and the
|
|
502
|
+
* server answers identically for both — only the client knows which it sent. */
|
|
503
|
+
authHint(status) {
|
|
504
|
+
if (status !== 401) return "";
|
|
505
|
+
return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
|
|
506
|
+
}
|
|
628
507
|
bankUrl(suffix = "") {
|
|
629
508
|
return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
|
|
630
509
|
}
|
|
631
510
|
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
632
511
|
async req(method, url2, body, tolerate = []) {
|
|
633
|
-
const r = await
|
|
512
|
+
const r = await this.fetchWithAuth(url2, {
|
|
634
513
|
method,
|
|
635
|
-
headers: this.headers(),
|
|
636
514
|
body: body ? JSON.stringify(body) : void 0,
|
|
637
515
|
signal: AbortSignal.timeout(15e3)
|
|
638
516
|
});
|
|
639
517
|
if (r.status === 429 && !tolerate.includes(429))
|
|
640
518
|
throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
|
|
641
519
|
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
642
|
-
throw new Error(
|
|
520
|
+
throw new Error(
|
|
521
|
+
`${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
|
|
522
|
+
);
|
|
643
523
|
return r;
|
|
644
524
|
}
|
|
645
525
|
/** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
|
|
@@ -650,7 +530,11 @@ var HindsightClient = class {
|
|
|
650
530
|
context,
|
|
651
531
|
document_id: documentId,
|
|
652
532
|
tags,
|
|
653
|
-
strategy
|
|
533
|
+
strategy,
|
|
534
|
+
// Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
|
|
535
|
+
// observations were built under is a property of the write rather than of whichever server
|
|
536
|
+
// version happened to process it. Servers older than 0.4.15 ignore the field.
|
|
537
|
+
observation_scopes: this.observationScopes
|
|
654
538
|
};
|
|
655
539
|
if (opts.timestamp) item.timestamp = opts.timestamp;
|
|
656
540
|
if (opts.metadata) item.metadata = opts.metadata;
|
|
@@ -729,7 +613,7 @@ var HindsightClient = class {
|
|
|
729
613
|
this.log(
|
|
730
614
|
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}`
|
|
731
615
|
);
|
|
732
|
-
await this.seedPages();
|
|
616
|
+
await this.seedPages(opts.pageTrigger);
|
|
733
617
|
}
|
|
734
618
|
/**
|
|
735
619
|
* Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
|
|
@@ -787,7 +671,7 @@ var HindsightClient = class {
|
|
|
787
671
|
let backoffMs = POLL_CYCLE_MS;
|
|
788
672
|
await pool([...pending], this.maxParallelRetains, async (id) => {
|
|
789
673
|
try {
|
|
790
|
-
const r = await
|
|
674
|
+
const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
|
|
791
675
|
if (r.status === 429) {
|
|
792
676
|
backoffMs = Math.min(
|
|
793
677
|
RETRY_AFTER_CEILING_MS,
|
|
@@ -813,233 +697,640 @@ var HindsightClient = class {
|
|
|
813
697
|
`[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
|
|
814
698
|
);
|
|
815
699
|
}
|
|
816
|
-
/**
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
700
|
+
/**
|
|
701
|
+
* Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
|
|
702
|
+
* caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
|
|
703
|
+
* magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
|
|
704
|
+
* tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
|
|
705
|
+
* tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
|
|
706
|
+
*/
|
|
707
|
+
async reflect(query, opts) {
|
|
708
|
+
const ctrl = new AbortController();
|
|
709
|
+
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
|
|
710
|
+
try {
|
|
711
|
+
const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
|
|
712
|
+
method: "POST",
|
|
713
|
+
body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
|
|
714
|
+
signal: ctrl.signal
|
|
715
|
+
});
|
|
716
|
+
if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
|
|
717
|
+
const data = await resp.json();
|
|
718
|
+
return (data.text || "").trim();
|
|
719
|
+
} finally {
|
|
720
|
+
clearTimeout(timer);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
|
|
725
|
+
* queries and staleness but NOT synthesized content, so it is cheap enough to poll.
|
|
726
|
+
*/
|
|
727
|
+
async tree() {
|
|
728
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
729
|
+
const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
|
|
730
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
731
|
+
this.knowledgePagesSupported = false;
|
|
732
|
+
throw new KnowledgePagesUnavailableError();
|
|
733
|
+
}
|
|
734
|
+
this.knowledgePagesSupported = true;
|
|
735
|
+
try {
|
|
736
|
+
return (await r.json()).roots ?? [];
|
|
737
|
+
} catch {
|
|
738
|
+
return [];
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
|
|
743
|
+
* and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
|
|
744
|
+
* to read, and a caller enumerating pages wants leaves, not structure.
|
|
745
|
+
*
|
|
746
|
+
* NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
|
|
747
|
+
* page read/update in this client goes through the same knowledge-base ids, so a page id from
|
|
748
|
+
* here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
|
|
749
|
+
*/
|
|
750
|
+
async listPages() {
|
|
751
|
+
const items = [];
|
|
752
|
+
const walk = (nodes, folder) => {
|
|
753
|
+
for (const n of nodes) {
|
|
754
|
+
if (!n?.id || !n?.name) continue;
|
|
755
|
+
if (n.kind === "page") {
|
|
756
|
+
items.push({
|
|
757
|
+
id: n.id,
|
|
758
|
+
name: n.name,
|
|
759
|
+
...n.description ? { description: n.description } : {},
|
|
760
|
+
...folder ? { folder } : {}
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
walk(await this.tree());
|
|
767
|
+
return { items };
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
|
|
771
|
+
* (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
|
|
772
|
+
* the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
|
|
773
|
+
* token cap.
|
|
774
|
+
*/
|
|
775
|
+
async getPage(pageId) {
|
|
776
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
777
|
+
const r = await this.req(
|
|
778
|
+
"GET",
|
|
779
|
+
this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
|
|
780
|
+
);
|
|
781
|
+
if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
|
|
782
|
+
return await r.json();
|
|
783
|
+
}
|
|
784
|
+
/** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
|
|
785
|
+
* Returns page-level hits with a relevance snippet — the real search behind
|
|
786
|
+
* hindsight_search_knowledge_pages. */
|
|
787
|
+
async searchKnowledgePages(query, limit = 3) {
|
|
788
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
789
|
+
const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
|
|
790
|
+
const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
|
|
791
|
+
const j = await r.json();
|
|
792
|
+
return (j.results ?? []).map((x) => ({
|
|
793
|
+
id: x.id,
|
|
794
|
+
name: x.name,
|
|
795
|
+
snippet: x.snippet ?? "",
|
|
796
|
+
score: x.score ?? 0
|
|
797
|
+
}));
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
|
|
801
|
+
*
|
|
802
|
+
* Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
|
|
803
|
+
* client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
|
|
804
|
+
* off a slug). Names are unique per folder server-side, which makes them a sound key.
|
|
805
|
+
*
|
|
806
|
+
* An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
|
|
807
|
+
* `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
|
|
808
|
+
* which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
|
|
809
|
+
*/
|
|
810
|
+
async seedPages(pageTrigger = buildPageTrigger()) {
|
|
811
|
+
const pages = pagesFor(this.project ?? this.bank);
|
|
812
|
+
const existing = /* @__PURE__ */ new Map();
|
|
813
|
+
let roots;
|
|
814
|
+
try {
|
|
815
|
+
roots = await this.tree();
|
|
816
|
+
} catch (e) {
|
|
817
|
+
if (e instanceof KnowledgePagesUnavailableError) {
|
|
818
|
+
this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
throw e;
|
|
822
|
+
}
|
|
823
|
+
for (const n of roots) {
|
|
824
|
+
if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
|
|
825
|
+
}
|
|
826
|
+
let created = 0;
|
|
827
|
+
let updated = 0;
|
|
828
|
+
for (const page of pages) {
|
|
829
|
+
const hit = existing.get(page.name.toLowerCase());
|
|
830
|
+
const body = {
|
|
831
|
+
name: page.name,
|
|
832
|
+
source_query: page.source_query,
|
|
833
|
+
tags: page.tags,
|
|
834
|
+
max_tokens: PAGE_MAX_TOKENS,
|
|
835
|
+
trigger: pageTrigger
|
|
836
|
+
};
|
|
837
|
+
if (!hit) {
|
|
838
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
|
|
839
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
840
|
+
this.knowledgePagesSupported = false;
|
|
841
|
+
this.log(
|
|
842
|
+
`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
|
|
843
|
+
);
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
if (r.status !== 409) created++;
|
|
847
|
+
} else if (hit.description !== page.source_query || hit.trigger?.tags_match !== pageTrigger.tags_match) {
|
|
848
|
+
const patch = {
|
|
849
|
+
trigger: pageTrigger
|
|
850
|
+
};
|
|
851
|
+
if (hit.description !== page.source_query) {
|
|
852
|
+
patch.source_query = page.source_query;
|
|
853
|
+
patch.tags = page.tags;
|
|
854
|
+
}
|
|
855
|
+
const r = await this.req(
|
|
856
|
+
"PATCH",
|
|
857
|
+
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
|
|
858
|
+
patch
|
|
859
|
+
);
|
|
860
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
861
|
+
this.knowledgePagesSupported = false;
|
|
862
|
+
this.log(
|
|
863
|
+
`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
|
|
864
|
+
);
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
updated++;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
this.log(
|
|
871
|
+
`[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
|
|
872
|
+
);
|
|
873
|
+
}
|
|
874
|
+
/** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
|
|
875
|
+
slugify(s) {
|
|
876
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
|
|
877
|
+
}
|
|
878
|
+
/**
|
|
879
|
+
* Active-path capture: register a major feature as a per-initiative page + a marker memory.
|
|
880
|
+
* New initiative → creates a page under the Initiatives folder.
|
|
881
|
+
* Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
|
|
882
|
+
* enhancement or a mid-work plan change lands on the initiative it belongs to.
|
|
883
|
+
*
|
|
884
|
+
* The marker carries its page id in two places, neither of them a tag (#3641):
|
|
885
|
+
* `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
|
|
886
|
+
* expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
|
|
887
|
+
* three channels a page synthesis actually reads — reflect's search results keep `context` and
|
|
888
|
+
* `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
|
|
889
|
+
* vocabulary that exists to be matched with exact set-ops.
|
|
890
|
+
*/
|
|
891
|
+
async captureInitiative(args) {
|
|
892
|
+
let pageId = args.relatesToPageId;
|
|
893
|
+
if (!pageId) {
|
|
894
|
+
const folderId = await this.ensureFolder("Initiatives");
|
|
895
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
|
|
896
|
+
name: args.title,
|
|
897
|
+
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.`,
|
|
898
|
+
parent_id: folderId,
|
|
899
|
+
tags: ["knowledge:feature-work"],
|
|
900
|
+
trigger: args.pageTrigger ?? buildPageTrigger()
|
|
901
|
+
});
|
|
902
|
+
try {
|
|
903
|
+
const j = await r.json();
|
|
904
|
+
pageId = j.page_id ?? j.id;
|
|
905
|
+
} catch {
|
|
906
|
+
}
|
|
907
|
+
pageId ||= `initiative-${this.slugify(args.title)}`;
|
|
908
|
+
}
|
|
909
|
+
const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
|
|
910
|
+
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
911
|
+
const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
|
|
912
|
+
const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
|
|
913
|
+
const context = `initiative marker for [[page:${pageId}]]`;
|
|
914
|
+
await this.retain(content, context, markerId, tags, "document", {
|
|
915
|
+
metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
|
|
916
|
+
});
|
|
917
|
+
return { page_id: pageId };
|
|
918
|
+
}
|
|
919
|
+
/** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
|
|
920
|
+
async ensureFolder(name2) {
|
|
921
|
+
try {
|
|
922
|
+
const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
|
|
923
|
+
const hit = (tree.roots || []).find(
|
|
924
|
+
(n) => n.kind === "folder" && (n.name || "").toLowerCase() === name2.toLowerCase()
|
|
925
|
+
);
|
|
926
|
+
if (hit?.id) return hit.id;
|
|
927
|
+
} catch {
|
|
928
|
+
}
|
|
929
|
+
try {
|
|
930
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name: name2 });
|
|
931
|
+
return (await r.json()).id;
|
|
932
|
+
} catch {
|
|
933
|
+
return void 0;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
|
|
938
|
+
// src/core/config.ts
|
|
939
|
+
var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
|
|
940
|
+
var DEFAULT_DAEMON_PORT = 9077;
|
|
941
|
+
var DEFAULT_DAEMON_PROFILE = "coding-agent";
|
|
942
|
+
function resolvePageTriggerType(raw) {
|
|
943
|
+
if (raw.pageTriggerType === "manual") return "manual";
|
|
944
|
+
if (raw.pageTriggerType === "cron") {
|
|
945
|
+
if (raw.pageTriggerCron?.trim()) return "cron";
|
|
946
|
+
log.warn(
|
|
947
|
+
"config",
|
|
948
|
+
'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
|
|
949
|
+
);
|
|
950
|
+
}
|
|
951
|
+
return "auto-refresh";
|
|
952
|
+
}
|
|
953
|
+
var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
|
|
954
|
+
var REFLECT_BUDGETS = ["low", "mid", "high"];
|
|
955
|
+
function resolveReflectBudget(raw) {
|
|
956
|
+
const value = raw.reflectBudget;
|
|
957
|
+
if (value === void 0) return "high";
|
|
958
|
+
if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
|
|
959
|
+
return value;
|
|
960
|
+
log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
|
|
961
|
+
return "high";
|
|
962
|
+
}
|
|
963
|
+
var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
|
|
964
|
+
function resolveObservationScopes(raw) {
|
|
965
|
+
const value = raw;
|
|
966
|
+
if (typeof value === "string")
|
|
967
|
+
return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
|
|
968
|
+
if (Array.isArray(value)) {
|
|
969
|
+
const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
|
|
970
|
+
if (scopes.length) return scopes;
|
|
971
|
+
}
|
|
972
|
+
return DEFAULT_OBSERVATION_SCOPES;
|
|
973
|
+
}
|
|
974
|
+
function resolveConfig(raw = {}) {
|
|
975
|
+
const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
|
|
976
|
+
const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
|
|
977
|
+
return {
|
|
978
|
+
serverMode,
|
|
979
|
+
// Daemon mode resolves the URL HERE rather than at each call site: every entry point already
|
|
980
|
+
// builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
|
|
981
|
+
// daemon needs no plumbing through eight separate constructors.
|
|
982
|
+
apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
|
|
983
|
+
apiToken: raw.apiToken || void 0,
|
|
984
|
+
apiPort,
|
|
985
|
+
daemonIdleTimeout: raw.daemonIdleTimeout,
|
|
986
|
+
daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
|
|
987
|
+
embedVersion: raw.embedVersion || void 0,
|
|
988
|
+
embedPackagePath: raw.embedPackagePath || void 0,
|
|
989
|
+
bankId: raw.bankId,
|
|
990
|
+
dynamicBankId: raw.dynamicBankId,
|
|
991
|
+
bankIdTemplate: raw.bankIdTemplate,
|
|
992
|
+
mapPathToBank: raw.mapPathToBank,
|
|
993
|
+
resolveWorktrees: raw.resolveWorktrees,
|
|
994
|
+
optInOnly: raw.optInOnly ?? false,
|
|
995
|
+
// Same shape as retainTags: a config typo must not become a path that silently approves nothing.
|
|
996
|
+
optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
|
|
997
|
+
harness: raw.harness ?? "opencode",
|
|
998
|
+
disabled: raw.disabled ?? false,
|
|
999
|
+
retainSessions: raw.retainSessions ?? true,
|
|
1000
|
+
// write sessions back by default, every harness
|
|
1001
|
+
maxParallelRetains: raw.maxParallelRetains || 10,
|
|
1002
|
+
reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
|
|
1003
|
+
// Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
|
|
1004
|
+
// reflect already set), but never let it LOWER the tool below the default — a short window is
|
|
1005
|
+
// set to bound the automatic hook, not to cut off a call the agent is waiting on.
|
|
1006
|
+
reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
|
|
1007
|
+
reflectBudget: resolveReflectBudget(raw),
|
|
1008
|
+
autoReflect: raw.autoReflect ?? true,
|
|
1009
|
+
pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
|
|
1010
|
+
pageTriggerType: resolvePageTriggerType(raw),
|
|
1011
|
+
pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
|
|
1012
|
+
autoSeed: raw.autoSeed ?? true,
|
|
1013
|
+
seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
|
|
1014
|
+
codebaseSurvey: raw.codebaseSurvey ?? true,
|
|
1015
|
+
surveyModel: raw.surveyModel || "haiku",
|
|
1016
|
+
surveyBudgetUsd: raw.surveyBudgetUsd || 2,
|
|
1017
|
+
surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
|
|
1018
|
+
gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
|
|
1019
|
+
// Hostile input is a config typo, not an attack: keep only string entries so a stray number or
|
|
1020
|
+
// nested object cannot reach the API as a tag and fail the whole retain.
|
|
1021
|
+
retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
|
|
1022
|
+
retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
|
|
1023
|
+
Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
|
|
1024
|
+
) : {},
|
|
1025
|
+
observationScopes: resolveObservationScopes(raw.observationScopes),
|
|
1026
|
+
banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
|
|
1027
|
+
logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
function readRaw(path) {
|
|
1031
|
+
try {
|
|
1032
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
1033
|
+
} catch (e) {
|
|
1034
|
+
if (e?.code !== "ENOENT") {
|
|
1035
|
+
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
1036
|
+
}
|
|
1037
|
+
return {};
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
function mergeRaw(a, b) {
|
|
1041
|
+
const { harnesses: _drop, ...flat } = b;
|
|
1042
|
+
return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
|
|
1043
|
+
}
|
|
1044
|
+
function applyLayer(raw, layer, harness) {
|
|
1045
|
+
let out = mergeRaw(raw, layer);
|
|
1046
|
+
const perHarness = harness ? layer.harnesses?.[harness] : void 0;
|
|
1047
|
+
if (perHarness) out = mergeRaw(out, perHarness);
|
|
1048
|
+
return out;
|
|
1049
|
+
}
|
|
1050
|
+
var ENV_KEYS = {
|
|
1051
|
+
serverMode: "HINDSIGHT_SERVER_MODE",
|
|
1052
|
+
apiUrl: "HINDSIGHT_API_URL",
|
|
1053
|
+
apiToken: "HINDSIGHT_API_TOKEN",
|
|
1054
|
+
// These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
|
|
1055
|
+
// it can carry their existing environment over unchanged.
|
|
1056
|
+
apiPort: "HINDSIGHT_API_PORT",
|
|
1057
|
+
daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
|
|
1058
|
+
embedVersion: "HINDSIGHT_EMBED_VERSION",
|
|
1059
|
+
embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
|
|
1060
|
+
daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
|
|
1061
|
+
bankId: "HINDSIGHT_BANK_ID",
|
|
1062
|
+
dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
|
|
1063
|
+
bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
|
|
1064
|
+
resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
|
|
1065
|
+
optInOnly: "HINDSIGHT_OPT_IN_ONLY",
|
|
1066
|
+
optInPaths: "HINDSIGHT_OPT_IN_PATHS",
|
|
1067
|
+
harness: "HINDSIGHT_HARNESS",
|
|
1068
|
+
disabled: "HINDSIGHT_DISABLED",
|
|
1069
|
+
retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
|
|
1070
|
+
maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
|
|
1071
|
+
reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
|
|
1072
|
+
reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
|
|
1073
|
+
reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
|
|
1074
|
+
autoReflect: "HINDSIGHT_AUTO_REFLECT",
|
|
1075
|
+
pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
|
|
1076
|
+
pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
|
|
1077
|
+
pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
|
|
1078
|
+
autoSeed: "HINDSIGHT_AUTO_SEED",
|
|
1079
|
+
seedLimit: "HINDSIGHT_SEED_LIMIT",
|
|
1080
|
+
codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
|
|
1081
|
+
surveyModel: "HINDSIGHT_SURVEY_MODEL",
|
|
1082
|
+
surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
|
|
1083
|
+
surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
|
|
1084
|
+
logLevel: "HINDSIGHT_LOG_LEVEL",
|
|
1085
|
+
gitIngest: "HINDSIGHT_GIT_INGEST",
|
|
1086
|
+
// Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
|
|
1087
|
+
// list is a list OF lists, which does not survive flattening into one variable — file-only.
|
|
1088
|
+
observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
|
|
1089
|
+
// Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
|
|
1090
|
+
// a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
|
|
1091
|
+
retainTags: "HINDSIGHT_RETAIN_TAGS"
|
|
1092
|
+
};
|
|
1093
|
+
var ENV_BOOLEANS = /* @__PURE__ */ new Set([
|
|
1094
|
+
"dynamicBankId",
|
|
1095
|
+
"resolveWorktrees",
|
|
1096
|
+
"optInOnly",
|
|
1097
|
+
"disabled",
|
|
1098
|
+
"retainSessions",
|
|
1099
|
+
"autoReflect",
|
|
1100
|
+
"autoSeed",
|
|
1101
|
+
"codebaseSurvey"
|
|
1102
|
+
]);
|
|
1103
|
+
var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
|
|
1104
|
+
var ENV_NUMBERS = /* @__PURE__ */ new Set([
|
|
1105
|
+
"apiPort",
|
|
1106
|
+
"daemonIdleTimeout",
|
|
1107
|
+
"maxParallelRetains",
|
|
1108
|
+
"reflectTimeoutMs",
|
|
1109
|
+
"reflectToolTimeoutMs",
|
|
1110
|
+
"pageRefreshEveryTurns",
|
|
1111
|
+
"seedLimit",
|
|
1112
|
+
"surveyBudgetUsd",
|
|
1113
|
+
"surveyRefreshCommits"
|
|
1114
|
+
]);
|
|
1115
|
+
function readEnvConfig(env = process.env) {
|
|
1116
|
+
const out = {};
|
|
1117
|
+
for (const [key, name2] of Object.entries(ENV_KEYS)) {
|
|
1118
|
+
const value = env[name2];
|
|
1119
|
+
if (value === void 0 || value.trim() === "") continue;
|
|
1120
|
+
if (ENV_BOOLEANS.has(key)) {
|
|
1121
|
+
out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
|
|
1122
|
+
} else if (ENV_LISTS.has(key)) {
|
|
1123
|
+
const items = value.split(",").map((v) => v.trim()).filter(Boolean);
|
|
1124
|
+
if (items.length) out[key] = items;
|
|
1125
|
+
} else if (ENV_NUMBERS.has(key)) {
|
|
1126
|
+
const n = Number(value);
|
|
1127
|
+
if (Number.isFinite(n)) out[key] = n;
|
|
1128
|
+
else console.error(`hindsight: ignoring ${name2}=${value} \u2014 not a number`);
|
|
1129
|
+
} else {
|
|
1130
|
+
out[key] = value;
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
return out;
|
|
1134
|
+
}
|
|
1135
|
+
function loadConfig(opts = {}) {
|
|
1136
|
+
const o = typeof opts === "string" ? { path: opts } : opts;
|
|
1137
|
+
const withEnv = applyLayer({}, readEnvConfig(), o.harness);
|
|
1138
|
+
const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
|
|
1139
|
+
if (!raw.harness && o.harness) raw.harness = o.harness;
|
|
1140
|
+
return resolveConfig(raw);
|
|
1141
|
+
}
|
|
1142
|
+
var BANK_OVERRIDE_EXCLUDED = [
|
|
1143
|
+
"bankId",
|
|
1144
|
+
"bankIdTemplate",
|
|
1145
|
+
"mapPathToBank",
|
|
1146
|
+
"dynamicBankId",
|
|
1147
|
+
"resolveWorktrees",
|
|
1148
|
+
// Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
|
|
1149
|
+
// only ever arrive too late to matter — strip them rather than let them read as effective.
|
|
1150
|
+
"optInOnly",
|
|
1151
|
+
"optInPaths",
|
|
1152
|
+
"harness"
|
|
1153
|
+
];
|
|
1154
|
+
function applyBankConfig(cfg, resolvedId, directory) {
|
|
1155
|
+
if (directory !== void 0 && !isOptedIn(cfg, directory))
|
|
1156
|
+
return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
|
|
1157
|
+
const section = cfg.banks[resolvedId];
|
|
1158
|
+
if (!section) return { cfg, bankId: resolvedId };
|
|
1159
|
+
const safe = { ...section };
|
|
1160
|
+
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
1161
|
+
delete safe.banks;
|
|
1162
|
+
const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
|
|
1163
|
+
delete safe.bank;
|
|
1164
|
+
return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
|
|
1165
|
+
}
|
|
1166
|
+
function resolvePartial(cfg, patch) {
|
|
1167
|
+
const full = resolveConfig(patch);
|
|
1168
|
+
const out = {};
|
|
1169
|
+
for (const key of Object.keys(patch)) {
|
|
1170
|
+
if (key in full)
|
|
1171
|
+
out[key] = full[key];
|
|
1172
|
+
}
|
|
1173
|
+
return out;
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
// src/core/host-client.ts
|
|
1177
|
+
function resolveHostConfig(harness, directory) {
|
|
1178
|
+
const cfg0 = loadConfig({ harness });
|
|
1179
|
+
if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
|
|
1180
|
+
return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
|
|
1181
|
+
}
|
|
1182
|
+
function resolveHostMemory(harness, directory) {
|
|
1183
|
+
const { cfg, bankId } = resolveHostConfig(harness, directory);
|
|
1184
|
+
return {
|
|
1185
|
+
cfg,
|
|
1186
|
+
bankId,
|
|
1187
|
+
client: new HindsightClient({
|
|
1188
|
+
apiUrl: cfg.apiUrl,
|
|
1189
|
+
apiToken: cfg.apiToken,
|
|
1190
|
+
bank: bankId,
|
|
1191
|
+
maxParallelRetains: cfg.maxParallelRetains,
|
|
1192
|
+
observationScopes: cfg.observationScopes,
|
|
1193
|
+
// The credential a host STARTED with is not the one it must keep using: enable auth or
|
|
1194
|
+
// rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
|
|
1195
|
+
// through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
|
|
1196
|
+
// honoured on re-resolution exactly as it was on the first one.
|
|
1197
|
+
tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
|
|
1198
|
+
})
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
// src/core/diag.ts
|
|
1203
|
+
import { appendFileSync as appendFileSync2 } from "fs";
|
|
1204
|
+
function diagFilePath() {
|
|
1205
|
+
return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
|
|
1206
|
+
}
|
|
1207
|
+
function diag(harness, event, extra = {}) {
|
|
1208
|
+
log.debug(harness, `diag:${event}`, extra);
|
|
1209
|
+
try {
|
|
1210
|
+
appendFileSync2(
|
|
1211
|
+
diagFilePath(),
|
|
1212
|
+
JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
|
|
1213
|
+
);
|
|
1214
|
+
} catch {
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// src/core/daemon.ts
|
|
1219
|
+
import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
|
|
1220
|
+
import { dirname as dirname4, join as join5 } from "path";
|
|
1221
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
1222
|
+
var DAEMON_WAIT_SESSION_START_MS = 12e3;
|
|
1223
|
+
var DAEMON_WAIT_RETAIN_MS = 4e4;
|
|
1224
|
+
async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
|
|
1225
|
+
try {
|
|
1226
|
+
const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
|
|
1227
|
+
return res.ok;
|
|
1228
|
+
} catch {
|
|
1229
|
+
return false;
|
|
833
1230
|
}
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
this.knowledgePagesSupported = false;
|
|
843
|
-
throw new KnowledgePagesUnavailableError();
|
|
844
|
-
}
|
|
845
|
-
this.knowledgePagesSupported = true;
|
|
846
|
-
try {
|
|
847
|
-
return (await r.json()).roots ?? [];
|
|
848
|
-
} catch {
|
|
849
|
-
return [];
|
|
850
|
-
}
|
|
1231
|
+
}
|
|
1232
|
+
function hasRustToolchain() {
|
|
1233
|
+
if (process.platform !== "darwin") return true;
|
|
1234
|
+
try {
|
|
1235
|
+
execFileSync2("cargo", ["--version"], { stdio: "pipe", timeout: 1e4 });
|
|
1236
|
+
return true;
|
|
1237
|
+
} catch {
|
|
1238
|
+
return false;
|
|
851
1239
|
}
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
|
|
875
|
-
}
|
|
1240
|
+
}
|
|
1241
|
+
function hasUvx() {
|
|
1242
|
+
try {
|
|
1243
|
+
execFileSync2("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
|
|
1244
|
+
return true;
|
|
1245
|
+
} catch {
|
|
1246
|
+
return false;
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
var PROVIDER_PROBES = [
|
|
1250
|
+
{ provider: "openai", keyEnv: "OPENAI_API_KEY" },
|
|
1251
|
+
{ provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
|
|
1252
|
+
{ provider: "gemini", keyEnv: "GEMINI_API_KEY" },
|
|
1253
|
+
{ provider: "groq", keyEnv: "GROQ_API_KEY" }
|
|
1254
|
+
];
|
|
1255
|
+
function detectLlm(env = process.env) {
|
|
1256
|
+
const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
|
|
1257
|
+
if (explicit) {
|
|
1258
|
+
return {
|
|
1259
|
+
provider: explicit,
|
|
1260
|
+
apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
|
|
1261
|
+
source: "HINDSIGHT_API_LLM_PROVIDER"
|
|
876
1262
|
};
|
|
877
|
-
walk(await this.tree());
|
|
878
|
-
return { items };
|
|
879
1263
|
}
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
* the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
|
|
884
|
-
* token cap.
|
|
885
|
-
*/
|
|
886
|
-
async getPage(pageId) {
|
|
887
|
-
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
888
|
-
const r = await this.req(
|
|
889
|
-
"GET",
|
|
890
|
-
this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
|
|
891
|
-
);
|
|
892
|
-
if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
|
|
893
|
-
return await r.json();
|
|
1264
|
+
for (const probe of PROVIDER_PROBES) {
|
|
1265
|
+
const key = env[probe.keyEnv]?.trim();
|
|
1266
|
+
if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
|
|
894
1267
|
}
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
* hindsight_search_knowledge_pages. */
|
|
898
|
-
async searchKnowledgePages(query, limit = 3) {
|
|
899
|
-
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
900
|
-
const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
|
|
901
|
-
const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
|
|
902
|
-
const j = await r.json();
|
|
903
|
-
return (j.results ?? []).map((x) => ({
|
|
904
|
-
id: x.id,
|
|
905
|
-
name: x.name,
|
|
906
|
-
snippet: x.snippet ?? "",
|
|
907
|
-
score: x.score ?? 0
|
|
908
|
-
}));
|
|
1268
|
+
if (onPath("claude")) {
|
|
1269
|
+
return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
|
|
909
1270
|
}
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
* `source_query` re-syncs onto the live page instead of orphaning its synthesized content.
|
|
919
|
-
*/
|
|
920
|
-
async seedPages() {
|
|
921
|
-
const existing = /* @__PURE__ */ new Map();
|
|
922
|
-
let roots;
|
|
923
|
-
try {
|
|
924
|
-
roots = await this.tree();
|
|
925
|
-
} catch (e) {
|
|
926
|
-
if (e instanceof KnowledgePagesUnavailableError) {
|
|
927
|
-
this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
|
|
928
|
-
return;
|
|
929
|
-
}
|
|
930
|
-
throw e;
|
|
931
|
-
}
|
|
932
|
-
for (const n of roots) {
|
|
933
|
-
if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
|
|
934
|
-
}
|
|
935
|
-
let created = 0;
|
|
936
|
-
let updated = 0;
|
|
937
|
-
for (const page of PAGES) {
|
|
938
|
-
const hit = existing.get(page.name.toLowerCase());
|
|
939
|
-
const body = {
|
|
940
|
-
name: page.name,
|
|
941
|
-
source_query: page.source_query,
|
|
942
|
-
tags: page.tags,
|
|
943
|
-
max_tokens: PAGE_MAX_TOKENS,
|
|
944
|
-
trigger: PAGE_TRIGGER
|
|
945
|
-
};
|
|
946
|
-
if (!hit) {
|
|
947
|
-
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
|
|
948
|
-
if ([404, 405, 501].includes(r.status)) {
|
|
949
|
-
this.knowledgePagesSupported = false;
|
|
950
|
-
this.log(
|
|
951
|
-
`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
|
|
952
|
-
);
|
|
953
|
-
return;
|
|
954
|
-
}
|
|
955
|
-
if (r.status !== 409) created++;
|
|
956
|
-
} else if (hit.description !== page.source_query) {
|
|
957
|
-
const r = await this.req(
|
|
958
|
-
"PATCH",
|
|
959
|
-
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
|
|
960
|
-
{ source_query: page.source_query, tags: page.tags }
|
|
961
|
-
);
|
|
962
|
-
if ([404, 405, 501].includes(r.status)) {
|
|
963
|
-
this.knowledgePagesSupported = false;
|
|
964
|
-
this.log(
|
|
965
|
-
`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
|
|
966
|
-
);
|
|
967
|
-
return;
|
|
968
|
-
}
|
|
969
|
-
updated++;
|
|
970
|
-
}
|
|
971
|
-
}
|
|
972
|
-
this.log(
|
|
973
|
-
`[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${PAGES.length - created - updated} unchanged`
|
|
974
|
-
);
|
|
1271
|
+
return void 0;
|
|
1272
|
+
}
|
|
1273
|
+
function onPath(bin) {
|
|
1274
|
+
try {
|
|
1275
|
+
execFileSync2("which", [bin], { stdio: "pipe", timeout: 5e3 });
|
|
1276
|
+
return true;
|
|
1277
|
+
} catch {
|
|
1278
|
+
return false;
|
|
975
1279
|
}
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
1280
|
+
}
|
|
1281
|
+
function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
|
|
1282
|
+
try {
|
|
1283
|
+
const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
|
|
1284
|
+
const child = spawnFn("node", [starter, "--harness", harness], {
|
|
1285
|
+
detached: true,
|
|
1286
|
+
stdio: "ignore"
|
|
1287
|
+
});
|
|
1288
|
+
child.on("error", () => {
|
|
1289
|
+
});
|
|
1290
|
+
child.unref();
|
|
1291
|
+
diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
|
|
1292
|
+
} catch {
|
|
979
1293
|
}
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
tags: ["knowledge:feature-work"],
|
|
994
|
-
trigger: {
|
|
995
|
-
fact_types: ["world", "experience", "observation"],
|
|
996
|
-
refresh_after_consolidation: true
|
|
997
|
-
}
|
|
998
|
-
});
|
|
999
|
-
try {
|
|
1000
|
-
const j = await r.json();
|
|
1001
|
-
pageId = j.page_id ?? j.id;
|
|
1002
|
-
} catch {
|
|
1003
|
-
}
|
|
1004
|
-
pageId ||= `initiative-${this.slugify(args.title)}`;
|
|
1005
|
-
}
|
|
1006
|
-
const verb = args.relatesToPageId ? "Enhancement to an existing initiative" : "New initiative";
|
|
1007
|
-
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
1008
|
-
const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
|
|
1009
|
-
const tags = [
|
|
1010
|
-
.../* @__PURE__ */ new Set([
|
|
1011
|
-
...args.stamp?.tags ?? [],
|
|
1012
|
-
"knowledge:feature-work",
|
|
1013
|
-
`relatedPageId:${pageId}`
|
|
1014
|
-
])
|
|
1015
|
-
];
|
|
1016
|
-
if (Object.keys(args.stamp?.metadata ?? {}).length) {
|
|
1017
|
-
await this.retain(content, "initiative marker", markerId, tags, "document", {
|
|
1018
|
-
metadata: args.stamp?.metadata
|
|
1019
|
-
});
|
|
1020
|
-
} else {
|
|
1021
|
-
await this.retain(content, "initiative marker", markerId, tags, "document");
|
|
1022
|
-
}
|
|
1023
|
-
return { page_id: pageId };
|
|
1294
|
+
}
|
|
1295
|
+
async function ensureDaemon(cfg, harness, opts = {}) {
|
|
1296
|
+
if (cfg.serverMode !== "daemon") return;
|
|
1297
|
+
if (await isServerHealthy(cfg.apiUrl)) return;
|
|
1298
|
+
if (!preflightDaemon(cfg, harness)) return;
|
|
1299
|
+
startDaemonDetached(cfg, harness, opts.spawnFn);
|
|
1300
|
+
await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
|
|
1301
|
+
}
|
|
1302
|
+
async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
|
|
1303
|
+
const deadline = Date.now() + budgetMs;
|
|
1304
|
+
while (Date.now() < deadline) {
|
|
1305
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
1306
|
+
if (await isServerHealthy(baseUrl)) return true;
|
|
1024
1307
|
}
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
if (hit?.id) return hit.id;
|
|
1033
|
-
} catch {
|
|
1034
|
-
}
|
|
1035
|
-
try {
|
|
1036
|
-
const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name: name2 });
|
|
1037
|
-
return (await r.json()).id;
|
|
1038
|
-
} catch {
|
|
1039
|
-
return void 0;
|
|
1040
|
-
}
|
|
1308
|
+
return false;
|
|
1309
|
+
}
|
|
1310
|
+
function preflightDaemon(cfg, harness) {
|
|
1311
|
+
if (!hasUvx()) {
|
|
1312
|
+
diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
|
|
1313
|
+
log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
|
|
1314
|
+
return false;
|
|
1041
1315
|
}
|
|
1042
|
-
|
|
1316
|
+
if (!hasRustToolchain()) {
|
|
1317
|
+
diag(harness, "daemon_rust_missing", { platform: process.platform });
|
|
1318
|
+
log.warn(
|
|
1319
|
+
harness,
|
|
1320
|
+
"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`"
|
|
1321
|
+
);
|
|
1322
|
+
return false;
|
|
1323
|
+
}
|
|
1324
|
+
if (!detectLlm()) {
|
|
1325
|
+
diag(harness, "daemon_no_llm", {});
|
|
1326
|
+
log.warn(
|
|
1327
|
+
harness,
|
|
1328
|
+
"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"
|
|
1329
|
+
);
|
|
1330
|
+
return false;
|
|
1331
|
+
}
|
|
1332
|
+
return true;
|
|
1333
|
+
}
|
|
1043
1334
|
|
|
1044
1335
|
// node_modules/zod/v4/classic/external.js
|
|
1045
1336
|
var external_exports = {};
|
|
@@ -15558,16 +15849,16 @@ config(en_default());
|
|
|
15558
15849
|
// src/core/knowledge-tools.ts
|
|
15559
15850
|
import { existsSync as existsSync3 } from "fs";
|
|
15560
15851
|
import { homedir as homedir4 } from "os";
|
|
15561
|
-
import { join as
|
|
15852
|
+
import { join as join7 } from "path";
|
|
15562
15853
|
|
|
15563
15854
|
// src/core/status.ts
|
|
15564
|
-
import { execFileSync as
|
|
15855
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
15565
15856
|
|
|
15566
15857
|
// src/core/git.ts
|
|
15567
|
-
import { execFileSync as
|
|
15858
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
15568
15859
|
import { resolve } from "path";
|
|
15569
15860
|
function git(repo, ...args) {
|
|
15570
|
-
return
|
|
15861
|
+
return execFileSync3("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
|
|
15571
15862
|
}
|
|
15572
15863
|
function repoNameOf(repo) {
|
|
15573
15864
|
return projectNameOf(resolve(repo));
|
|
@@ -15613,7 +15904,7 @@ function roster(pages) {
|
|
|
15613
15904
|
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>".
|
|
15614
15905
|
- 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.
|
|
15615
15906
|
- 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>").
|
|
15616
|
-
- 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
|
|
15907
|
+
- 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.
|
|
15617
15908
|
- 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).`;
|
|
15618
15909
|
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";
|
|
15619
15910
|
function toolGuide(opts) {
|
|
@@ -15640,11 +15931,11 @@ ${toolGuide(opts)}
|
|
|
15640
15931
|
}
|
|
15641
15932
|
|
|
15642
15933
|
// src/core/survey.ts
|
|
15643
|
-
import { spawn as
|
|
15934
|
+
import { spawn as realSpawn3 } from "child_process";
|
|
15644
15935
|
import { accessSync, constants, existsSync as existsSync2 } from "fs";
|
|
15645
15936
|
import { homedir as homedir3 } from "os";
|
|
15646
|
-
import { delimiter, dirname as
|
|
15647
|
-
import { fileURLToPath as
|
|
15937
|
+
import { delimiter, dirname as dirname5, join as join6 } from "path";
|
|
15938
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
15648
15939
|
var SURVEY_DOC_IDS = [
|
|
15649
15940
|
"repository-component-map",
|
|
15650
15941
|
"repository-core-concepts",
|
|
@@ -15654,7 +15945,7 @@ var SURVEY_DOC_IDS = [
|
|
|
15654
15945
|
function resolveClaudeBin(explicit) {
|
|
15655
15946
|
if (explicit) return explicit;
|
|
15656
15947
|
if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
|
|
15657
|
-
const nativeInstallPath =
|
|
15948
|
+
const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
|
|
15658
15949
|
try {
|
|
15659
15950
|
if (existsSync2(nativeInstallPath)) return nativeInstallPath;
|
|
15660
15951
|
} catch {
|
|
@@ -15683,7 +15974,7 @@ function binExists(bin) {
|
|
|
15683
15974
|
for (const dir of (process.env.PATH || "").split(delimiter)) {
|
|
15684
15975
|
if (!dir) continue;
|
|
15685
15976
|
try {
|
|
15686
|
-
accessSync(
|
|
15977
|
+
accessSync(join6(dir, bin), constants.X_OK);
|
|
15687
15978
|
return true;
|
|
15688
15979
|
} catch {
|
|
15689
15980
|
}
|
|
@@ -15727,7 +16018,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
|
|
|
15727
16018
|
hindsight: {
|
|
15728
16019
|
command: "node",
|
|
15729
16020
|
args: [opts.mcpServerPath],
|
|
15730
|
-
|
|
16021
|
+
// HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
|
|
16022
|
+
// ingests are its writes. mcp-server.js REQUIRES it (it used to default to
|
|
16023
|
+
// "claude-code", which is how the codex recipe below silently stamped its findings
|
|
16024
|
+
// harness:claude-code and wrote them to Claude Code's bank — #3603).
|
|
16025
|
+
env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir, HINDSIGHT_MCP_HARNESS: "claude-code" }
|
|
15731
16026
|
}
|
|
15732
16027
|
}
|
|
15733
16028
|
});
|
|
@@ -15767,6 +16062,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
|
|
|
15767
16062
|
`mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
|
|
15768
16063
|
"-c",
|
|
15769
16064
|
`mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
|
|
16065
|
+
"-c",
|
|
16066
|
+
`mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
|
|
15770
16067
|
SURVEY_PROMPT
|
|
15771
16068
|
],
|
|
15772
16069
|
env
|
|
@@ -15790,9 +16087,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
|
|
|
15790
16087
|
}
|
|
15791
16088
|
function startCodebaseSurvey(repoDir, opts = {}) {
|
|
15792
16089
|
try {
|
|
15793
|
-
const spawnFn = opts.spawn ??
|
|
16090
|
+
const spawnFn = opts.spawn ?? realSpawn3;
|
|
15794
16091
|
const exists = opts.exists ?? binExists;
|
|
15795
|
-
const mcpServerPath = opts.mcpServerPath ??
|
|
16092
|
+
const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
|
|
15796
16093
|
const preferred = opts.harness ?? "claude-code";
|
|
15797
16094
|
const order = [
|
|
15798
16095
|
preferred,
|
|
@@ -15831,7 +16128,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
15831
16128
|
var DEEPEN_DIFF_TARGET = 300;
|
|
15832
16129
|
function commitCount(repoDir) {
|
|
15833
16130
|
try {
|
|
15834
|
-
const out =
|
|
16131
|
+
const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
|
|
15835
16132
|
encoding: "utf8"
|
|
15836
16133
|
});
|
|
15837
16134
|
return Number(out.trim()) || 0;
|
|
@@ -15922,9 +16219,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
15922
16219
|
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.",
|
|
15923
16220
|
inputSchema: {},
|
|
15924
16221
|
handler: async (_args) => {
|
|
15925
|
-
const configPath = process.env.HINDSIGHT_CONFIG ||
|
|
16222
|
+
const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
|
|
15926
16223
|
const harness = opts.harness ?? "unknown";
|
|
15927
|
-
const cfg =
|
|
16224
|
+
const cfg = applyBankConfig(
|
|
16225
|
+
loadConfig({ harness: opts.harness }),
|
|
16226
|
+
bankId,
|
|
16227
|
+
opts.repoDir
|
|
16228
|
+
).cfg;
|
|
15928
16229
|
return ok({
|
|
15929
16230
|
bank_id: bankId,
|
|
15930
16231
|
harness,
|
|
@@ -15936,6 +16237,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
15936
16237
|
api_token_configured: Boolean(cfg.apiToken),
|
|
15937
16238
|
disabled: cfg.disabled
|
|
15938
16239
|
},
|
|
16240
|
+
// What the LIVE client is signing with, which is not the same question as what the file
|
|
16241
|
+
// says. A long-lived host used to keep a credential the config had already replaced, and
|
|
16242
|
+
// this tool reported that state as perfectly healthy (#3600). Booleans only — the token
|
|
16243
|
+
// value is never returned.
|
|
16244
|
+
credential: {
|
|
16245
|
+
api_token_in_use: Boolean(client.apiToken),
|
|
16246
|
+
api_token_matches_config: client.apiToken === cfg.apiToken
|
|
16247
|
+
},
|
|
15939
16248
|
environment: {
|
|
15940
16249
|
config_override: Boolean(process.env.HINDSIGHT_CONFIG),
|
|
15941
16250
|
hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
|
|
@@ -15984,12 +16293,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
15984
16293
|
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>".`,
|
|
15985
16294
|
inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
|
|
15986
16295
|
handler: guarded(
|
|
15987
|
-
async ({ query }) => client.reflect(query, {
|
|
16296
|
+
async ({ query }) => client.reflect(query, {
|
|
16297
|
+
budget: opts.reflectBudget ?? "high",
|
|
16298
|
+
timeoutMs: opts.reflectTimeoutMs ?? DEFAULT_REFLECT_TOOL_TIMEOUT_MS
|
|
16299
|
+
})
|
|
15988
16300
|
)
|
|
15989
16301
|
},
|
|
15990
16302
|
{
|
|
15991
16303
|
name: "hindsight_capture_initiative",
|
|
15992
|
-
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.
|
|
16304
|
+
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.",
|
|
15993
16305
|
inputSchema: {
|
|
15994
16306
|
title: external_exports.string(),
|
|
15995
16307
|
summary: external_exports.string(),
|
|
@@ -16000,7 +16312,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
16000
16312
|
title,
|
|
16001
16313
|
summary,
|
|
16002
16314
|
relatesToPageId: relates_to_page_id,
|
|
16003
|
-
...opts.stampFor ? { stamp: opts.stampFor() } : {}
|
|
16315
|
+
...opts.stampFor ? { stamp: opts.stampFor() } : {},
|
|
16316
|
+
...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
|
|
16004
16317
|
})
|
|
16005
16318
|
)
|
|
16006
16319
|
},
|
|
@@ -16207,7 +16520,7 @@ function resolversFor(ctx) {
|
|
|
16207
16520
|
return {
|
|
16208
16521
|
// Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
|
|
16209
16522
|
// otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
|
|
16210
|
-
gitProject: () => projectNameOf(ctx.directory),
|
|
16523
|
+
gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
|
|
16211
16524
|
project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
|
|
16212
16525
|
harness: () => ctx.harness,
|
|
16213
16526
|
bankId: () => ctx.bankId,
|
|
@@ -16253,11 +16566,6 @@ import { readFileSync as readFileSync4 } from "fs";
|
|
|
16253
16566
|
// src/core/skill-sync.ts
|
|
16254
16567
|
import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
|
|
16255
16568
|
import { homedir as homedir5 } from "os";
|
|
16256
|
-
import { dirname as dirname5, join as join7 } from "path";
|
|
16257
|
-
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
16258
|
-
|
|
16259
|
-
// src/core/daemon.ts
|
|
16260
|
-
import { execFileSync as execFileSync4, spawn as realSpawn3 } from "child_process";
|
|
16261
16569
|
import { dirname as dirname6, join as join8 } from "path";
|
|
16262
16570
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
16263
16571
|
|
|
@@ -16348,7 +16656,7 @@ async function buildSessionStartContext(args) {
|
|
|
16348
16656
|
const startSurvey = args.startSurvey ?? startCodebaseSurvey;
|
|
16349
16657
|
const resolveHeadSha = args.headSha ?? gitHeadSha;
|
|
16350
16658
|
const countCommitsSince = args.commitsSince ?? commitsSince;
|
|
16351
|
-
const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
|
|
16659
|
+
const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
|
|
16352
16660
|
const SURVEY_BASELINE_TAG = "source:survey-baseline";
|
|
16353
16661
|
const SURVEY_BASELINE_PREFIX = "survey-baseline:";
|
|
16354
16662
|
const recordSurveyBaseline = (sha) => {
|
|
@@ -16624,6 +16932,9 @@ var RuntimeCore = class {
|
|
|
16624
16932
|
return buildKnowledgeTools(this.client, this.bankId, {
|
|
16625
16933
|
repoDir: this.projectDir,
|
|
16626
16934
|
harness: this.harness,
|
|
16935
|
+
pageTrigger: buildPageTrigger(this.cfg),
|
|
16936
|
+
reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
|
|
16937
|
+
reflectBudget: this.cfg.reflectBudget,
|
|
16627
16938
|
stampFor: () => buildRetainStamp(this.cfg, {
|
|
16628
16939
|
directory: this.projectDir,
|
|
16629
16940
|
harness: this.harness,
|
|
@@ -16642,6 +16953,7 @@ var RuntimeCore = class {
|
|
|
16642
16953
|
*/
|
|
16643
16954
|
async seedIfCold(repoPath) {
|
|
16644
16955
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
16956
|
+
await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
|
|
16645
16957
|
try {
|
|
16646
16958
|
const out = await buildSessionStartContext({
|
|
16647
16959
|
cwd: repoPath || process.cwd(),
|
|
@@ -16765,15 +17077,17 @@ var RuntimeCore = class {
|
|
|
16765
17077
|
/** Fire-and-forget upsert of the session transcript; never throws into the host. */
|
|
16766
17078
|
retain(sessionId, turns, startTs, trigger = "turn") {
|
|
16767
17079
|
const t0 = Date.now();
|
|
16768
|
-
void
|
|
16769
|
-
|
|
16770
|
-
|
|
16771
|
-
|
|
16772
|
-
|
|
16773
|
-
|
|
16774
|
-
|
|
17080
|
+
void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
|
|
17081
|
+
() => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
|
|
17082
|
+
cursors: this.cursors,
|
|
17083
|
+
stamp: buildRetainStamp(this.cfg, {
|
|
17084
|
+
directory: this.projectDir,
|
|
17085
|
+
harness: this.harness,
|
|
17086
|
+
bankId: this.bankId,
|
|
17087
|
+
sessionId
|
|
17088
|
+
})
|
|
16775
17089
|
})
|
|
16776
|
-
|
|
17090
|
+
).then(
|
|
16777
17091
|
() => diag(this.harness, "retain_ok", {
|
|
16778
17092
|
ms: Date.now() - t0,
|
|
16779
17093
|
turns: turns.length,
|
|
@@ -16882,23 +17196,12 @@ function workspaceRoot(agent) {
|
|
|
16882
17196
|
function workspaceFor(root) {
|
|
16883
17197
|
const cached2 = workspaces.get(root);
|
|
16884
17198
|
if (cached2 !== void 0) return cached2 ?? void 0;
|
|
16885
|
-
|
|
16886
|
-
if (cfg.disabled) {
|
|
16887
|
-
workspaces.set(root, null);
|
|
16888
|
-
return void 0;
|
|
16889
|
-
}
|
|
16890
|
-
const resolved = applyBankConfig(cfg, deriveBankId(cfg, root, HARNESS2));
|
|
16891
|
-
cfg = resolved.cfg;
|
|
17199
|
+
const { cfg, bankId, client } = resolveHostMemory(HARNESS2, root);
|
|
16892
17200
|
if (cfg.disabled) {
|
|
16893
17201
|
workspaces.set(root, null);
|
|
16894
17202
|
return void 0;
|
|
16895
17203
|
}
|
|
16896
|
-
const
|
|
16897
|
-
apiUrl: cfg.apiUrl,
|
|
16898
|
-
apiToken: cfg.apiToken,
|
|
16899
|
-
bank: resolved.bankId
|
|
16900
|
-
});
|
|
16901
|
-
const core = new RuntimeCore(client, resolved.bankId, cfg, HARNESS2, root);
|
|
17204
|
+
const core = new RuntimeCore(client, bankId, cfg, HARNESS2, root);
|
|
16902
17205
|
core.setTranscriptSource(async (sessionId) => {
|
|
16903
17206
|
const agent = liveAgents.get(sessionId);
|
|
16904
17207
|
return agent ? readDshEvents(agent.session.events) : [];
|