@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/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.",
|
|
@@ -511,11 +326,23 @@ var PAGES = [
|
|
|
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_FACT_TYPES = ["world", "experience", "observation"];
|
|
335
|
+
function buildPageTrigger(cfg = {}) {
|
|
336
|
+
const base = { fact_types: PAGE_FACT_TYPES };
|
|
337
|
+
switch (cfg.pageTriggerType) {
|
|
338
|
+
case "cron":
|
|
339
|
+
return { ...base, refresh_cron: cfg.pageTriggerCron };
|
|
340
|
+
case "manual":
|
|
341
|
+
return { ...base, refresh_after_consolidation: false };
|
|
342
|
+
default:
|
|
343
|
+
return { ...base, refresh_after_consolidation: true };
|
|
344
|
+
}
|
|
345
|
+
}
|
|
519
346
|
var CODING_BANK_TEMPLATE = {
|
|
520
347
|
version: "1",
|
|
521
348
|
bank: {
|
|
@@ -570,6 +397,7 @@ async function pool(items, n, fn, onError, onProgress) {
|
|
|
570
397
|
}
|
|
571
398
|
|
|
572
399
|
// src/core/hindsight.ts
|
|
400
|
+
var DEFAULT_OBSERVATION_SCOPES = "shared";
|
|
573
401
|
var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
|
|
574
402
|
var RateLimitedError = class extends Error {
|
|
575
403
|
constructor(retryAfterMs2) {
|
|
@@ -602,8 +430,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
|
|
|
602
430
|
var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
|
|
603
431
|
var HindsightClient = class {
|
|
604
432
|
apiUrl;
|
|
605
|
-
|
|
433
|
+
/** The credential the NEXT request will sign with — NOT the one the config file holds. The two
|
|
434
|
+
* diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
|
|
435
|
+
token;
|
|
436
|
+
tokenProvider;
|
|
606
437
|
bank;
|
|
438
|
+
project;
|
|
607
439
|
opIds = [];
|
|
608
440
|
// async operation ids collected by retain(), for drain()
|
|
609
441
|
/** Tri-state capability probe: unknown until the first page request, then cached. */
|
|
@@ -612,34 +444,81 @@ var HindsightClient = class {
|
|
|
612
444
|
idempotentRetain;
|
|
613
445
|
log;
|
|
614
446
|
maxParallelRetains;
|
|
447
|
+
observationScopes;
|
|
615
448
|
constructor(o) {
|
|
616
449
|
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
617
|
-
this.
|
|
450
|
+
this.token = o.apiToken;
|
|
451
|
+
this.tokenProvider = o.tokenProvider;
|
|
618
452
|
this.bank = o.bank;
|
|
453
|
+
this.project = o.project;
|
|
619
454
|
this.log = o.log ?? (() => {
|
|
620
455
|
});
|
|
621
456
|
this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
|
|
457
|
+
this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
|
|
458
|
+
}
|
|
459
|
+
/** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
|
|
460
|
+
get apiToken() {
|
|
461
|
+
return this.token;
|
|
622
462
|
}
|
|
623
463
|
headers() {
|
|
624
464
|
const h = { "Content-Type": "application/json" };
|
|
625
|
-
if (this.
|
|
465
|
+
if (this.token) h["Authorization"] = `Bearer ${this.token}`;
|
|
626
466
|
return h;
|
|
627
467
|
}
|
|
468
|
+
/** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
|
|
469
|
+
* only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
|
|
470
|
+
* doubling every failing request. */
|
|
471
|
+
refreshToken() {
|
|
472
|
+
if (!this.tokenProvider) return false;
|
|
473
|
+
let next;
|
|
474
|
+
try {
|
|
475
|
+
next = this.tokenProvider();
|
|
476
|
+
} catch {
|
|
477
|
+
return false;
|
|
478
|
+
}
|
|
479
|
+
if (next === this.token) return false;
|
|
480
|
+
this.token = next;
|
|
481
|
+
return true;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
|
|
485
|
+
* poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
|
|
486
|
+
* failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
|
|
487
|
+
* not.
|
|
488
|
+
*
|
|
489
|
+
* On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
|
|
490
|
+
* string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
|
|
491
|
+
* free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
|
|
492
|
+
* bounds the whole call.
|
|
493
|
+
*/
|
|
494
|
+
async fetchWithAuth(url2, init) {
|
|
495
|
+
const send = () => fetch(url2, { ...init, headers: this.headers() });
|
|
496
|
+
const r = await send();
|
|
497
|
+
if (r.status !== 401 || !this.refreshToken()) return r;
|
|
498
|
+
return send();
|
|
499
|
+
}
|
|
500
|
+
/** A 401 with no `Authorization` header is a different failure from a rejected key, and the
|
|
501
|
+
* server answers identically for both — only the client knows which it sent. */
|
|
502
|
+
authHint(status) {
|
|
503
|
+
if (status !== 401) return "";
|
|
504
|
+
return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
|
|
505
|
+
}
|
|
628
506
|
bankUrl(suffix = "") {
|
|
629
507
|
return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
|
|
630
508
|
}
|
|
631
509
|
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
632
510
|
async req(method, url2, body, tolerate = []) {
|
|
633
|
-
const r = await
|
|
511
|
+
const r = await this.fetchWithAuth(url2, {
|
|
634
512
|
method,
|
|
635
|
-
headers: this.headers(),
|
|
636
513
|
body: body ? JSON.stringify(body) : void 0,
|
|
637
514
|
signal: AbortSignal.timeout(15e3)
|
|
638
515
|
});
|
|
639
516
|
if (r.status === 429 && !tolerate.includes(429))
|
|
640
517
|
throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
|
|
641
518
|
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
642
|
-
throw new Error(
|
|
519
|
+
throw new Error(
|
|
520
|
+
`${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
|
|
521
|
+
);
|
|
643
522
|
return r;
|
|
644
523
|
}
|
|
645
524
|
/** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
|
|
@@ -650,7 +529,11 @@ var HindsightClient = class {
|
|
|
650
529
|
context,
|
|
651
530
|
document_id: documentId,
|
|
652
531
|
tags,
|
|
653
|
-
strategy
|
|
532
|
+
strategy,
|
|
533
|
+
// Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
|
|
534
|
+
// observations were built under is a property of the write rather than of whichever server
|
|
535
|
+
// version happened to process it. Servers older than 0.4.15 ignore the field.
|
|
536
|
+
observation_scopes: this.observationScopes
|
|
654
537
|
};
|
|
655
538
|
if (opts.timestamp) item.timestamp = opts.timestamp;
|
|
656
539
|
if (opts.metadata) item.metadata = opts.metadata;
|
|
@@ -729,7 +612,7 @@ var HindsightClient = class {
|
|
|
729
612
|
this.log(
|
|
730
613
|
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
614
|
);
|
|
732
|
-
await this.seedPages();
|
|
615
|
+
await this.seedPages(opts.pageTrigger);
|
|
733
616
|
}
|
|
734
617
|
/**
|
|
735
618
|
* Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
|
|
@@ -787,7 +670,7 @@ var HindsightClient = class {
|
|
|
787
670
|
let backoffMs = POLL_CYCLE_MS;
|
|
788
671
|
await pool([...pending], this.maxParallelRetains, async (id) => {
|
|
789
672
|
try {
|
|
790
|
-
const r = await
|
|
673
|
+
const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
|
|
791
674
|
if (r.status === 429) {
|
|
792
675
|
backoffMs = Math.min(
|
|
793
676
|
RETRY_AFTER_CEILING_MS,
|
|
@@ -813,233 +696,635 @@ var HindsightClient = class {
|
|
|
813
696
|
`[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
|
|
814
697
|
);
|
|
815
698
|
}
|
|
816
|
-
/**
|
|
817
|
-
|
|
699
|
+
/**
|
|
700
|
+
* Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
|
|
701
|
+
* caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
|
|
702
|
+
* magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
|
|
703
|
+
* tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
|
|
704
|
+
* tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
|
|
705
|
+
*/
|
|
706
|
+
async reflect(query, opts) {
|
|
818
707
|
const ctrl = new AbortController();
|
|
819
|
-
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs
|
|
708
|
+
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
|
|
820
709
|
try {
|
|
821
|
-
const resp = await
|
|
710
|
+
const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
|
|
822
711
|
method: "POST",
|
|
823
|
-
headers: this.headers(),
|
|
824
712
|
body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
|
|
825
713
|
signal: ctrl.signal
|
|
826
714
|
});
|
|
827
|
-
if (!resp.ok) throw new Error(`reflect ${resp.status}`);
|
|
715
|
+
if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
|
|
828
716
|
const data = await resp.json();
|
|
829
717
|
return (data.text || "").trim();
|
|
830
718
|
} finally {
|
|
831
719
|
clearTimeout(timer);
|
|
832
720
|
}
|
|
833
721
|
}
|
|
834
|
-
/**
|
|
835
|
-
* The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
|
|
836
|
-
* queries and staleness but NOT synthesized content, so it is cheap enough to poll.
|
|
837
|
-
*/
|
|
838
|
-
async tree() {
|
|
839
|
-
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
840
|
-
const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
|
|
841
|
-
if ([404, 405, 501].includes(r.status)) {
|
|
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
|
-
}
|
|
722
|
+
/**
|
|
723
|
+
* The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
|
|
724
|
+
* queries and staleness but NOT synthesized content, so it is cheap enough to poll.
|
|
725
|
+
*/
|
|
726
|
+
async tree() {
|
|
727
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
728
|
+
const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
|
|
729
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
730
|
+
this.knowledgePagesSupported = false;
|
|
731
|
+
throw new KnowledgePagesUnavailableError();
|
|
732
|
+
}
|
|
733
|
+
this.knowledgePagesSupported = true;
|
|
734
|
+
try {
|
|
735
|
+
return (await r.json()).roots ?? [];
|
|
736
|
+
} catch {
|
|
737
|
+
return [];
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
|
|
742
|
+
* and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
|
|
743
|
+
* to read, and a caller enumerating pages wants leaves, not structure.
|
|
744
|
+
*
|
|
745
|
+
* NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
|
|
746
|
+
* page read/update in this client goes through the same knowledge-base ids, so a page id from
|
|
747
|
+
* here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
|
|
748
|
+
*/
|
|
749
|
+
async listPages() {
|
|
750
|
+
const items = [];
|
|
751
|
+
const walk = (nodes, folder) => {
|
|
752
|
+
for (const n of nodes) {
|
|
753
|
+
if (!n?.id || !n?.name) continue;
|
|
754
|
+
if (n.kind === "page") {
|
|
755
|
+
items.push({
|
|
756
|
+
id: n.id,
|
|
757
|
+
name: n.name,
|
|
758
|
+
...n.description ? { description: n.description } : {},
|
|
759
|
+
...folder ? { folder } : {}
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
|
|
763
|
+
}
|
|
764
|
+
};
|
|
765
|
+
walk(await this.tree());
|
|
766
|
+
return { items };
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
|
|
770
|
+
* (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
|
|
771
|
+
* the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
|
|
772
|
+
* token cap.
|
|
773
|
+
*/
|
|
774
|
+
async getPage(pageId) {
|
|
775
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
776
|
+
const r = await this.req(
|
|
777
|
+
"GET",
|
|
778
|
+
this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
|
|
779
|
+
);
|
|
780
|
+
if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
|
|
781
|
+
return await r.json();
|
|
782
|
+
}
|
|
783
|
+
/** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
|
|
784
|
+
* Returns page-level hits with a relevance snippet — the real search behind
|
|
785
|
+
* hindsight_search_knowledge_pages. */
|
|
786
|
+
async searchKnowledgePages(query, limit = 3) {
|
|
787
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
788
|
+
const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
|
|
789
|
+
const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
|
|
790
|
+
const j = await r.json();
|
|
791
|
+
return (j.results ?? []).map((x) => ({
|
|
792
|
+
id: x.id,
|
|
793
|
+
name: x.name,
|
|
794
|
+
snippet: x.snippet ?? "",
|
|
795
|
+
score: x.score ?? 0
|
|
796
|
+
}));
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
|
|
800
|
+
*
|
|
801
|
+
* Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
|
|
802
|
+
* client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
|
|
803
|
+
* off a slug). Names are unique per folder server-side, which makes them a sound key.
|
|
804
|
+
*
|
|
805
|
+
* An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
|
|
806
|
+
* `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
|
|
807
|
+
* which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
|
|
808
|
+
*/
|
|
809
|
+
async seedPages(pageTrigger = buildPageTrigger()) {
|
|
810
|
+
const pages = pagesFor(this.project ?? this.bank);
|
|
811
|
+
const existing = /* @__PURE__ */ new Map();
|
|
812
|
+
let roots;
|
|
813
|
+
try {
|
|
814
|
+
roots = await this.tree();
|
|
815
|
+
} catch (e) {
|
|
816
|
+
if (e instanceof KnowledgePagesUnavailableError) {
|
|
817
|
+
this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
throw e;
|
|
821
|
+
}
|
|
822
|
+
for (const n of roots) {
|
|
823
|
+
if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
|
|
824
|
+
}
|
|
825
|
+
let created = 0;
|
|
826
|
+
let updated = 0;
|
|
827
|
+
for (const page of pages) {
|
|
828
|
+
const hit = existing.get(page.name.toLowerCase());
|
|
829
|
+
const body = {
|
|
830
|
+
name: page.name,
|
|
831
|
+
source_query: page.source_query,
|
|
832
|
+
tags: page.tags,
|
|
833
|
+
max_tokens: PAGE_MAX_TOKENS,
|
|
834
|
+
trigger: pageTrigger
|
|
835
|
+
};
|
|
836
|
+
if (!hit) {
|
|
837
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
|
|
838
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
839
|
+
this.knowledgePagesSupported = false;
|
|
840
|
+
this.log(
|
|
841
|
+
`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
|
|
842
|
+
);
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
if (r.status !== 409) created++;
|
|
846
|
+
} else if (hit.description !== page.source_query) {
|
|
847
|
+
const r = await this.req(
|
|
848
|
+
"PATCH",
|
|
849
|
+
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
|
|
850
|
+
{ source_query: page.source_query, tags: page.tags }
|
|
851
|
+
);
|
|
852
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
853
|
+
this.knowledgePagesSupported = false;
|
|
854
|
+
this.log(
|
|
855
|
+
`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
|
|
856
|
+
);
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
updated++;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
this.log(
|
|
863
|
+
`[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
/** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
|
|
867
|
+
slugify(s) {
|
|
868
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* Active-path capture: register a major feature as a per-initiative page + a tagged marker memory.
|
|
872
|
+
* New initiative → creates a page under the Initiatives folder tagged `relatedPageId:<pageId>`.
|
|
873
|
+
* Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
|
|
874
|
+
* enhancement or a mid-work plan change lands on the initiative it belongs to.
|
|
875
|
+
*/
|
|
876
|
+
async captureInitiative(args) {
|
|
877
|
+
let pageId = args.relatesToPageId;
|
|
878
|
+
if (!pageId) {
|
|
879
|
+
const folderId = await this.ensureFolder("Initiatives");
|
|
880
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
|
|
881
|
+
name: args.title,
|
|
882
|
+
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.`,
|
|
883
|
+
parent_id: folderId,
|
|
884
|
+
tags: ["knowledge:feature-work"],
|
|
885
|
+
trigger: args.pageTrigger ?? buildPageTrigger()
|
|
886
|
+
});
|
|
887
|
+
try {
|
|
888
|
+
const j = await r.json();
|
|
889
|
+
pageId = j.page_id ?? j.id;
|
|
890
|
+
} catch {
|
|
891
|
+
}
|
|
892
|
+
pageId ||= `initiative-${this.slugify(args.title)}`;
|
|
893
|
+
}
|
|
894
|
+
const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
|
|
895
|
+
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
896
|
+
const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
|
|
897
|
+
const tags = [
|
|
898
|
+
.../* @__PURE__ */ new Set([
|
|
899
|
+
...args.stamp?.tags ?? [],
|
|
900
|
+
"knowledge:feature-work",
|
|
901
|
+
`relatedPageId:${pageId}`
|
|
902
|
+
])
|
|
903
|
+
];
|
|
904
|
+
if (Object.keys(args.stamp?.metadata ?? {}).length) {
|
|
905
|
+
await this.retain(content, "initiative marker", markerId, tags, "document", {
|
|
906
|
+
metadata: args.stamp?.metadata
|
|
907
|
+
});
|
|
908
|
+
} else {
|
|
909
|
+
await this.retain(content, "initiative marker", markerId, tags, "document");
|
|
910
|
+
}
|
|
911
|
+
return { page_id: pageId };
|
|
912
|
+
}
|
|
913
|
+
/** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
|
|
914
|
+
async ensureFolder(name2) {
|
|
915
|
+
try {
|
|
916
|
+
const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
|
|
917
|
+
const hit = (tree.roots || []).find(
|
|
918
|
+
(n) => n.kind === "folder" && (n.name || "").toLowerCase() === name2.toLowerCase()
|
|
919
|
+
);
|
|
920
|
+
if (hit?.id) return hit.id;
|
|
921
|
+
} catch {
|
|
922
|
+
}
|
|
923
|
+
try {
|
|
924
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name: name2 });
|
|
925
|
+
return (await r.json()).id;
|
|
926
|
+
} catch {
|
|
927
|
+
return void 0;
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
|
|
932
|
+
// src/core/config.ts
|
|
933
|
+
var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
|
|
934
|
+
var DEFAULT_DAEMON_PORT = 9077;
|
|
935
|
+
var DEFAULT_DAEMON_PROFILE = "coding-agent";
|
|
936
|
+
function resolvePageTriggerType(raw) {
|
|
937
|
+
if (raw.pageTriggerType === "manual") return "manual";
|
|
938
|
+
if (raw.pageTriggerType === "cron") {
|
|
939
|
+
if (raw.pageTriggerCron?.trim()) return "cron";
|
|
940
|
+
log.warn(
|
|
941
|
+
"config",
|
|
942
|
+
'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
|
|
943
|
+
);
|
|
944
|
+
}
|
|
945
|
+
return "auto-refresh";
|
|
946
|
+
}
|
|
947
|
+
var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
|
|
948
|
+
var REFLECT_BUDGETS = ["low", "mid", "high"];
|
|
949
|
+
function resolveReflectBudget(raw) {
|
|
950
|
+
const value = raw.reflectBudget;
|
|
951
|
+
if (value === void 0) return "high";
|
|
952
|
+
if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
|
|
953
|
+
return value;
|
|
954
|
+
log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
|
|
955
|
+
return "high";
|
|
956
|
+
}
|
|
957
|
+
var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
|
|
958
|
+
function resolveObservationScopes(raw) {
|
|
959
|
+
const value = raw;
|
|
960
|
+
if (typeof value === "string")
|
|
961
|
+
return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
|
|
962
|
+
if (Array.isArray(value)) {
|
|
963
|
+
const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
|
|
964
|
+
if (scopes.length) return scopes;
|
|
965
|
+
}
|
|
966
|
+
return DEFAULT_OBSERVATION_SCOPES;
|
|
967
|
+
}
|
|
968
|
+
function resolveConfig(raw = {}) {
|
|
969
|
+
const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
|
|
970
|
+
const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
|
|
971
|
+
return {
|
|
972
|
+
serverMode,
|
|
973
|
+
// Daemon mode resolves the URL HERE rather than at each call site: every entry point already
|
|
974
|
+
// builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
|
|
975
|
+
// daemon needs no plumbing through eight separate constructors.
|
|
976
|
+
apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
|
|
977
|
+
apiToken: raw.apiToken || void 0,
|
|
978
|
+
apiPort,
|
|
979
|
+
daemonIdleTimeout: raw.daemonIdleTimeout,
|
|
980
|
+
daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
|
|
981
|
+
embedVersion: raw.embedVersion || void 0,
|
|
982
|
+
embedPackagePath: raw.embedPackagePath || void 0,
|
|
983
|
+
bankId: raw.bankId,
|
|
984
|
+
dynamicBankId: raw.dynamicBankId,
|
|
985
|
+
bankIdTemplate: raw.bankIdTemplate,
|
|
986
|
+
mapPathToBank: raw.mapPathToBank,
|
|
987
|
+
resolveWorktrees: raw.resolveWorktrees,
|
|
988
|
+
optInOnly: raw.optInOnly ?? false,
|
|
989
|
+
// Same shape as retainTags: a config typo must not become a path that silently approves nothing.
|
|
990
|
+
optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
|
|
991
|
+
harness: raw.harness ?? "opencode",
|
|
992
|
+
disabled: raw.disabled ?? false,
|
|
993
|
+
retainSessions: raw.retainSessions ?? true,
|
|
994
|
+
// write sessions back by default, every harness
|
|
995
|
+
maxParallelRetains: raw.maxParallelRetains || 10,
|
|
996
|
+
reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
|
|
997
|
+
// Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
|
|
998
|
+
// reflect already set), but never let it LOWER the tool below the default — a short window is
|
|
999
|
+
// set to bound the automatic hook, not to cut off a call the agent is waiting on.
|
|
1000
|
+
reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
|
|
1001
|
+
reflectBudget: resolveReflectBudget(raw),
|
|
1002
|
+
autoReflect: raw.autoReflect ?? true,
|
|
1003
|
+
pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
|
|
1004
|
+
pageTriggerType: resolvePageTriggerType(raw),
|
|
1005
|
+
pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
|
|
1006
|
+
autoSeed: raw.autoSeed ?? true,
|
|
1007
|
+
seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
|
|
1008
|
+
codebaseSurvey: raw.codebaseSurvey ?? true,
|
|
1009
|
+
surveyModel: raw.surveyModel || "haiku",
|
|
1010
|
+
surveyBudgetUsd: raw.surveyBudgetUsd || 2,
|
|
1011
|
+
surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
|
|
1012
|
+
gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
|
|
1013
|
+
// Hostile input is a config typo, not an attack: keep only string entries so a stray number or
|
|
1014
|
+
// nested object cannot reach the API as a tag and fail the whole retain.
|
|
1015
|
+
retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
|
|
1016
|
+
retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
|
|
1017
|
+
Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
|
|
1018
|
+
) : {},
|
|
1019
|
+
observationScopes: resolveObservationScopes(raw.observationScopes),
|
|
1020
|
+
banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
|
|
1021
|
+
logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
|
|
1022
|
+
};
|
|
1023
|
+
}
|
|
1024
|
+
function readRaw(path) {
|
|
1025
|
+
try {
|
|
1026
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
1027
|
+
} catch (e) {
|
|
1028
|
+
if (e?.code !== "ENOENT") {
|
|
1029
|
+
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
1030
|
+
}
|
|
1031
|
+
return {};
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
function mergeRaw(a, b) {
|
|
1035
|
+
const { harnesses: _drop, ...flat } = b;
|
|
1036
|
+
return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
|
|
1037
|
+
}
|
|
1038
|
+
function applyLayer(raw, layer, harness) {
|
|
1039
|
+
let out = mergeRaw(raw, layer);
|
|
1040
|
+
const perHarness = harness ? layer.harnesses?.[harness] : void 0;
|
|
1041
|
+
if (perHarness) out = mergeRaw(out, perHarness);
|
|
1042
|
+
return out;
|
|
1043
|
+
}
|
|
1044
|
+
var ENV_KEYS = {
|
|
1045
|
+
serverMode: "HINDSIGHT_SERVER_MODE",
|
|
1046
|
+
apiUrl: "HINDSIGHT_API_URL",
|
|
1047
|
+
apiToken: "HINDSIGHT_API_TOKEN",
|
|
1048
|
+
// These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
|
|
1049
|
+
// it can carry their existing environment over unchanged.
|
|
1050
|
+
apiPort: "HINDSIGHT_API_PORT",
|
|
1051
|
+
daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
|
|
1052
|
+
embedVersion: "HINDSIGHT_EMBED_VERSION",
|
|
1053
|
+
embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
|
|
1054
|
+
daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
|
|
1055
|
+
bankId: "HINDSIGHT_BANK_ID",
|
|
1056
|
+
dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
|
|
1057
|
+
bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
|
|
1058
|
+
resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
|
|
1059
|
+
optInOnly: "HINDSIGHT_OPT_IN_ONLY",
|
|
1060
|
+
optInPaths: "HINDSIGHT_OPT_IN_PATHS",
|
|
1061
|
+
harness: "HINDSIGHT_HARNESS",
|
|
1062
|
+
disabled: "HINDSIGHT_DISABLED",
|
|
1063
|
+
retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
|
|
1064
|
+
maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
|
|
1065
|
+
reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
|
|
1066
|
+
reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
|
|
1067
|
+
reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
|
|
1068
|
+
autoReflect: "HINDSIGHT_AUTO_REFLECT",
|
|
1069
|
+
pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
|
|
1070
|
+
pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
|
|
1071
|
+
pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
|
|
1072
|
+
autoSeed: "HINDSIGHT_AUTO_SEED",
|
|
1073
|
+
seedLimit: "HINDSIGHT_SEED_LIMIT",
|
|
1074
|
+
codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
|
|
1075
|
+
surveyModel: "HINDSIGHT_SURVEY_MODEL",
|
|
1076
|
+
surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
|
|
1077
|
+
surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
|
|
1078
|
+
logLevel: "HINDSIGHT_LOG_LEVEL",
|
|
1079
|
+
gitIngest: "HINDSIGHT_GIT_INGEST",
|
|
1080
|
+
// Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
|
|
1081
|
+
// list is a list OF lists, which does not survive flattening into one variable — file-only.
|
|
1082
|
+
observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
|
|
1083
|
+
// Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
|
|
1084
|
+
// a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
|
|
1085
|
+
retainTags: "HINDSIGHT_RETAIN_TAGS"
|
|
1086
|
+
};
|
|
1087
|
+
var ENV_BOOLEANS = /* @__PURE__ */ new Set([
|
|
1088
|
+
"dynamicBankId",
|
|
1089
|
+
"resolveWorktrees",
|
|
1090
|
+
"optInOnly",
|
|
1091
|
+
"disabled",
|
|
1092
|
+
"retainSessions",
|
|
1093
|
+
"autoReflect",
|
|
1094
|
+
"autoSeed",
|
|
1095
|
+
"codebaseSurvey"
|
|
1096
|
+
]);
|
|
1097
|
+
var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
|
|
1098
|
+
var ENV_NUMBERS = /* @__PURE__ */ new Set([
|
|
1099
|
+
"apiPort",
|
|
1100
|
+
"daemonIdleTimeout",
|
|
1101
|
+
"maxParallelRetains",
|
|
1102
|
+
"reflectTimeoutMs",
|
|
1103
|
+
"reflectToolTimeoutMs",
|
|
1104
|
+
"pageRefreshEveryTurns",
|
|
1105
|
+
"seedLimit",
|
|
1106
|
+
"surveyBudgetUsd",
|
|
1107
|
+
"surveyRefreshCommits"
|
|
1108
|
+
]);
|
|
1109
|
+
function readEnvConfig(env = process.env) {
|
|
1110
|
+
const out = {};
|
|
1111
|
+
for (const [key, name2] of Object.entries(ENV_KEYS)) {
|
|
1112
|
+
const value = env[name2];
|
|
1113
|
+
if (value === void 0 || value.trim() === "") continue;
|
|
1114
|
+
if (ENV_BOOLEANS.has(key)) {
|
|
1115
|
+
out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
|
|
1116
|
+
} else if (ENV_LISTS.has(key)) {
|
|
1117
|
+
const items = value.split(",").map((v) => v.trim()).filter(Boolean);
|
|
1118
|
+
if (items.length) out[key] = items;
|
|
1119
|
+
} else if (ENV_NUMBERS.has(key)) {
|
|
1120
|
+
const n = Number(value);
|
|
1121
|
+
if (Number.isFinite(n)) out[key] = n;
|
|
1122
|
+
else console.error(`hindsight: ignoring ${name2}=${value} \u2014 not a number`);
|
|
1123
|
+
} else {
|
|
1124
|
+
out[key] = value;
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
return out;
|
|
1128
|
+
}
|
|
1129
|
+
function loadConfig(opts = {}) {
|
|
1130
|
+
const o = typeof opts === "string" ? { path: opts } : opts;
|
|
1131
|
+
const withEnv = applyLayer({}, readEnvConfig(), o.harness);
|
|
1132
|
+
const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
|
|
1133
|
+
if (!raw.harness && o.harness) raw.harness = o.harness;
|
|
1134
|
+
return resolveConfig(raw);
|
|
1135
|
+
}
|
|
1136
|
+
var BANK_OVERRIDE_EXCLUDED = [
|
|
1137
|
+
"bankId",
|
|
1138
|
+
"bankIdTemplate",
|
|
1139
|
+
"mapPathToBank",
|
|
1140
|
+
"dynamicBankId",
|
|
1141
|
+
"resolveWorktrees",
|
|
1142
|
+
// Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
|
|
1143
|
+
// only ever arrive too late to matter — strip them rather than let them read as effective.
|
|
1144
|
+
"optInOnly",
|
|
1145
|
+
"optInPaths",
|
|
1146
|
+
"harness"
|
|
1147
|
+
];
|
|
1148
|
+
function applyBankConfig(cfg, resolvedId, directory) {
|
|
1149
|
+
if (directory !== void 0 && !isOptedIn(cfg, directory))
|
|
1150
|
+
return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
|
|
1151
|
+
const section = cfg.banks[resolvedId];
|
|
1152
|
+
if (!section) return { cfg, bankId: resolvedId };
|
|
1153
|
+
const safe = { ...section };
|
|
1154
|
+
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
1155
|
+
delete safe.banks;
|
|
1156
|
+
const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
|
|
1157
|
+
delete safe.bank;
|
|
1158
|
+
return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
|
|
1159
|
+
}
|
|
1160
|
+
function resolvePartial(cfg, patch) {
|
|
1161
|
+
const full = resolveConfig(patch);
|
|
1162
|
+
const out = {};
|
|
1163
|
+
for (const key of Object.keys(patch)) {
|
|
1164
|
+
if (key in full)
|
|
1165
|
+
out[key] = full[key];
|
|
1166
|
+
}
|
|
1167
|
+
return out;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
// src/core/host-client.ts
|
|
1171
|
+
function resolveHostConfig(harness, directory) {
|
|
1172
|
+
const cfg0 = loadConfig({ harness });
|
|
1173
|
+
if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
|
|
1174
|
+
return applyBankConfig(cfg0, deriveBankId(cfg0, directory, harness), directory);
|
|
1175
|
+
}
|
|
1176
|
+
function resolveHostMemory(harness, directory) {
|
|
1177
|
+
const { cfg, bankId } = resolveHostConfig(harness, directory);
|
|
1178
|
+
return {
|
|
1179
|
+
cfg,
|
|
1180
|
+
bankId,
|
|
1181
|
+
client: new HindsightClient({
|
|
1182
|
+
apiUrl: cfg.apiUrl,
|
|
1183
|
+
apiToken: cfg.apiToken,
|
|
1184
|
+
bank: bankId,
|
|
1185
|
+
maxParallelRetains: cfg.maxParallelRetains,
|
|
1186
|
+
observationScopes: cfg.observationScopes,
|
|
1187
|
+
// The credential a host STARTED with is not the one it must keep using: enable auth or
|
|
1188
|
+
// rotate the key mid-session and the snapshot 401s every call until restart (#3600). Read
|
|
1189
|
+
// through the same pipeline the constructor used, so a per-bank `banks.<id>.apiToken` is
|
|
1190
|
+
// honoured on re-resolution exactly as it was on the first one.
|
|
1191
|
+
tokenProvider: () => resolveHostConfig(harness, directory).cfg.apiToken
|
|
1192
|
+
})
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
// src/core/diag.ts
|
|
1197
|
+
import { appendFileSync as appendFileSync2 } from "fs";
|
|
1198
|
+
function diagFilePath() {
|
|
1199
|
+
return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
|
|
1200
|
+
}
|
|
1201
|
+
function diag(harness, event, extra = {}) {
|
|
1202
|
+
log.debug(harness, `diag:${event}`, extra);
|
|
1203
|
+
try {
|
|
1204
|
+
appendFileSync2(
|
|
1205
|
+
diagFilePath(),
|
|
1206
|
+
JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
|
|
1207
|
+
);
|
|
1208
|
+
} catch {
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
// src/core/daemon.ts
|
|
1213
|
+
import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
|
|
1214
|
+
import { dirname as dirname4, join as join5 } from "path";
|
|
1215
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
1216
|
+
var DAEMON_WAIT_SESSION_START_MS = 12e3;
|
|
1217
|
+
var DAEMON_WAIT_RETAIN_MS = 4e4;
|
|
1218
|
+
async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
|
|
1219
|
+
try {
|
|
1220
|
+
const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
|
|
1221
|
+
return res.ok;
|
|
1222
|
+
} catch {
|
|
1223
|
+
return false;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
function hasRustToolchain() {
|
|
1227
|
+
if (process.platform !== "darwin") return true;
|
|
1228
|
+
try {
|
|
1229
|
+
execFileSync2("cargo", ["--version"], { stdio: "pipe", timeout: 1e4 });
|
|
1230
|
+
return true;
|
|
1231
|
+
} catch {
|
|
1232
|
+
return false;
|
|
851
1233
|
}
|
|
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
|
-
}
|
|
1234
|
+
}
|
|
1235
|
+
function hasUvx() {
|
|
1236
|
+
try {
|
|
1237
|
+
execFileSync2("uvx", ["--version"], { stdio: "pipe", timeout: 1e4 });
|
|
1238
|
+
return true;
|
|
1239
|
+
} catch {
|
|
1240
|
+
return false;
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
var PROVIDER_PROBES = [
|
|
1244
|
+
{ provider: "openai", keyEnv: "OPENAI_API_KEY" },
|
|
1245
|
+
{ provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
|
|
1246
|
+
{ provider: "gemini", keyEnv: "GEMINI_API_KEY" },
|
|
1247
|
+
{ provider: "groq", keyEnv: "GROQ_API_KEY" }
|
|
1248
|
+
];
|
|
1249
|
+
function detectLlm(env = process.env) {
|
|
1250
|
+
const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
|
|
1251
|
+
if (explicit) {
|
|
1252
|
+
return {
|
|
1253
|
+
provider: explicit,
|
|
1254
|
+
apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
|
|
1255
|
+
source: "HINDSIGHT_API_LLM_PROVIDER"
|
|
876
1256
|
};
|
|
877
|
-
walk(await this.tree());
|
|
878
|
-
return { items };
|
|
879
1257
|
}
|
|
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();
|
|
1258
|
+
for (const probe of PROVIDER_PROBES) {
|
|
1259
|
+
const key = env[probe.keyEnv]?.trim();
|
|
1260
|
+
if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
|
|
894
1261
|
}
|
|
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
|
-
}));
|
|
1262
|
+
if (onPath("claude")) {
|
|
1263
|
+
return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
|
|
909
1264
|
}
|
|
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
|
-
);
|
|
1265
|
+
return void 0;
|
|
1266
|
+
}
|
|
1267
|
+
function onPath(bin) {
|
|
1268
|
+
try {
|
|
1269
|
+
execFileSync2("which", [bin], { stdio: "pipe", timeout: 5e3 });
|
|
1270
|
+
return true;
|
|
1271
|
+
} catch {
|
|
1272
|
+
return false;
|
|
975
1273
|
}
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
1274
|
+
}
|
|
1275
|
+
function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
|
|
1276
|
+
try {
|
|
1277
|
+
const starter = join5(dirname4(fileURLToPath2(import.meta.url)), "daemon-start.js");
|
|
1278
|
+
const child = spawnFn("node", [starter, "--harness", harness], {
|
|
1279
|
+
detached: true,
|
|
1280
|
+
stdio: "ignore"
|
|
1281
|
+
});
|
|
1282
|
+
child.on("error", () => {
|
|
1283
|
+
});
|
|
1284
|
+
child.unref();
|
|
1285
|
+
diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
|
|
1286
|
+
} catch {
|
|
979
1287
|
}
|
|
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 };
|
|
1288
|
+
}
|
|
1289
|
+
async function ensureDaemon(cfg, harness, opts = {}) {
|
|
1290
|
+
if (cfg.serverMode !== "daemon") return;
|
|
1291
|
+
if (await isServerHealthy(cfg.apiUrl)) return;
|
|
1292
|
+
if (!preflightDaemon(cfg, harness)) return;
|
|
1293
|
+
startDaemonDetached(cfg, harness, opts.spawnFn);
|
|
1294
|
+
await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
|
|
1295
|
+
}
|
|
1296
|
+
async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
|
|
1297
|
+
const deadline = Date.now() + budgetMs;
|
|
1298
|
+
while (Date.now() < deadline) {
|
|
1299
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
1300
|
+
if (await isServerHealthy(baseUrl)) return true;
|
|
1024
1301
|
}
|
|
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
|
-
}
|
|
1302
|
+
return false;
|
|
1303
|
+
}
|
|
1304
|
+
function preflightDaemon(cfg, harness) {
|
|
1305
|
+
if (!hasUvx()) {
|
|
1306
|
+
diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
|
|
1307
|
+
log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
|
|
1308
|
+
return false;
|
|
1041
1309
|
}
|
|
1042
|
-
|
|
1310
|
+
if (!hasRustToolchain()) {
|
|
1311
|
+
diag(harness, "daemon_rust_missing", { platform: process.platform });
|
|
1312
|
+
log.warn(
|
|
1313
|
+
harness,
|
|
1314
|
+
"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`"
|
|
1315
|
+
);
|
|
1316
|
+
return false;
|
|
1317
|
+
}
|
|
1318
|
+
if (!detectLlm()) {
|
|
1319
|
+
diag(harness, "daemon_no_llm", {});
|
|
1320
|
+
log.warn(
|
|
1321
|
+
harness,
|
|
1322
|
+
"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"
|
|
1323
|
+
);
|
|
1324
|
+
return false;
|
|
1325
|
+
}
|
|
1326
|
+
return true;
|
|
1327
|
+
}
|
|
1043
1328
|
|
|
1044
1329
|
// node_modules/zod/v4/classic/external.js
|
|
1045
1330
|
var external_exports = {};
|
|
@@ -15558,16 +15843,16 @@ config(en_default());
|
|
|
15558
15843
|
// src/core/knowledge-tools.ts
|
|
15559
15844
|
import { existsSync as existsSync3 } from "fs";
|
|
15560
15845
|
import { homedir as homedir4 } from "os";
|
|
15561
|
-
import { join as
|
|
15846
|
+
import { join as join7 } from "path";
|
|
15562
15847
|
|
|
15563
15848
|
// src/core/status.ts
|
|
15564
|
-
import { execFileSync as
|
|
15849
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
15565
15850
|
|
|
15566
15851
|
// src/core/git.ts
|
|
15567
|
-
import { execFileSync as
|
|
15852
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
15568
15853
|
import { resolve } from "path";
|
|
15569
15854
|
function git(repo, ...args) {
|
|
15570
|
-
return
|
|
15855
|
+
return execFileSync3("git", ["-C", repo, ...args], { encoding: "utf8", maxBuffer: 1 << 28 });
|
|
15571
15856
|
}
|
|
15572
15857
|
function repoNameOf(repo) {
|
|
15573
15858
|
return projectNameOf(resolve(repo));
|
|
@@ -15613,7 +15898,7 @@ function roster(pages) {
|
|
|
15613
15898
|
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
15899
|
- 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
15900
|
- 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
|
|
15901
|
+
- 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
15902
|
- 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
15903
|
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
15904
|
function toolGuide(opts) {
|
|
@@ -15640,11 +15925,11 @@ ${toolGuide(opts)}
|
|
|
15640
15925
|
}
|
|
15641
15926
|
|
|
15642
15927
|
// src/core/survey.ts
|
|
15643
|
-
import { spawn as
|
|
15928
|
+
import { spawn as realSpawn3 } from "child_process";
|
|
15644
15929
|
import { accessSync, constants, existsSync as existsSync2 } from "fs";
|
|
15645
15930
|
import { homedir as homedir3 } from "os";
|
|
15646
|
-
import { delimiter, dirname as
|
|
15647
|
-
import { fileURLToPath as
|
|
15931
|
+
import { delimiter, dirname as dirname5, join as join6 } from "path";
|
|
15932
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
15648
15933
|
var SURVEY_DOC_IDS = [
|
|
15649
15934
|
"repository-component-map",
|
|
15650
15935
|
"repository-core-concepts",
|
|
@@ -15654,7 +15939,7 @@ var SURVEY_DOC_IDS = [
|
|
|
15654
15939
|
function resolveClaudeBin(explicit) {
|
|
15655
15940
|
if (explicit) return explicit;
|
|
15656
15941
|
if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
|
|
15657
|
-
const nativeInstallPath =
|
|
15942
|
+
const nativeInstallPath = join6(homedir3(), ".claude", "local", "claude");
|
|
15658
15943
|
try {
|
|
15659
15944
|
if (existsSync2(nativeInstallPath)) return nativeInstallPath;
|
|
15660
15945
|
} catch {
|
|
@@ -15683,7 +15968,7 @@ function binExists(bin) {
|
|
|
15683
15968
|
for (const dir of (process.env.PATH || "").split(delimiter)) {
|
|
15684
15969
|
if (!dir) continue;
|
|
15685
15970
|
try {
|
|
15686
|
-
accessSync(
|
|
15971
|
+
accessSync(join6(dir, bin), constants.X_OK);
|
|
15687
15972
|
return true;
|
|
15688
15973
|
} catch {
|
|
15689
15974
|
}
|
|
@@ -15727,7 +16012,11 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
|
|
|
15727
16012
|
hindsight: {
|
|
15728
16013
|
command: "node",
|
|
15729
16014
|
args: [opts.mcpServerPath],
|
|
15730
|
-
|
|
16015
|
+
// HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
|
|
16016
|
+
// ingests are its writes. mcp-server.js REQUIRES it (it used to default to
|
|
16017
|
+
// "claude-code", which is how the codex recipe below silently stamped its findings
|
|
16018
|
+
// harness:claude-code and wrote them to Claude Code's bank — #3603).
|
|
16019
|
+
env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir, HINDSIGHT_MCP_HARNESS: "claude-code" }
|
|
15731
16020
|
}
|
|
15732
16021
|
}
|
|
15733
16022
|
});
|
|
@@ -15767,6 +16056,8 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
|
|
|
15767
16056
|
`mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
|
|
15768
16057
|
"-c",
|
|
15769
16058
|
`mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
|
|
16059
|
+
"-c",
|
|
16060
|
+
`mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
|
|
15770
16061
|
SURVEY_PROMPT
|
|
15771
16062
|
],
|
|
15772
16063
|
env
|
|
@@ -15790,9 +16081,9 @@ function buildSurveyPlan(harness, bin, repoDir, opts) {
|
|
|
15790
16081
|
}
|
|
15791
16082
|
function startCodebaseSurvey(repoDir, opts = {}) {
|
|
15792
16083
|
try {
|
|
15793
|
-
const spawnFn = opts.spawn ??
|
|
16084
|
+
const spawnFn = opts.spawn ?? realSpawn3;
|
|
15794
16085
|
const exists = opts.exists ?? binExists;
|
|
15795
|
-
const mcpServerPath = opts.mcpServerPath ??
|
|
16086
|
+
const mcpServerPath = opts.mcpServerPath ?? join6(dirname5(fileURLToPath3(import.meta.url)), "mcp-server.js");
|
|
15796
16087
|
const preferred = opts.harness ?? "claude-code";
|
|
15797
16088
|
const order = [
|
|
15798
16089
|
preferred,
|
|
@@ -15831,7 +16122,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
|
|
|
15831
16122
|
var DEEPEN_DIFF_TARGET = 300;
|
|
15832
16123
|
function commitCount(repoDir) {
|
|
15833
16124
|
try {
|
|
15834
|
-
const out =
|
|
16125
|
+
const out = execFileSync4("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
|
|
15835
16126
|
encoding: "utf8"
|
|
15836
16127
|
});
|
|
15837
16128
|
return Number(out.trim()) || 0;
|
|
@@ -15922,9 +16213,13 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
15922
16213
|
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
16214
|
inputSchema: {},
|
|
15924
16215
|
handler: async (_args) => {
|
|
15925
|
-
const configPath = process.env.HINDSIGHT_CONFIG ||
|
|
16216
|
+
const configPath = process.env.HINDSIGHT_CONFIG || join7(homedir4(), ".hindsight", "coding-agent.json");
|
|
15926
16217
|
const harness = opts.harness ?? "unknown";
|
|
15927
|
-
const cfg =
|
|
16218
|
+
const cfg = applyBankConfig(
|
|
16219
|
+
loadConfig({ harness: opts.harness }),
|
|
16220
|
+
bankId,
|
|
16221
|
+
opts.repoDir
|
|
16222
|
+
).cfg;
|
|
15928
16223
|
return ok({
|
|
15929
16224
|
bank_id: bankId,
|
|
15930
16225
|
harness,
|
|
@@ -15936,6 +16231,14 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
15936
16231
|
api_token_configured: Boolean(cfg.apiToken),
|
|
15937
16232
|
disabled: cfg.disabled
|
|
15938
16233
|
},
|
|
16234
|
+
// What the LIVE client is signing with, which is not the same question as what the file
|
|
16235
|
+
// says. A long-lived host used to keep a credential the config had already replaced, and
|
|
16236
|
+
// this tool reported that state as perfectly healthy (#3600). Booleans only — the token
|
|
16237
|
+
// value is never returned.
|
|
16238
|
+
credential: {
|
|
16239
|
+
api_token_in_use: Boolean(client.apiToken),
|
|
16240
|
+
api_token_matches_config: client.apiToken === cfg.apiToken
|
|
16241
|
+
},
|
|
15939
16242
|
environment: {
|
|
15940
16243
|
config_override: Boolean(process.env.HINDSIGHT_CONFIG),
|
|
15941
16244
|
hooks_disabled: Boolean(process.env.HINDSIGHT_DISABLE_HOOKS),
|
|
@@ -15984,12 +16287,15 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
15984
16287
|
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
16288
|
inputSchema: { query: external_exports.string().describe("the question to reason over memory about") },
|
|
15986
16289
|
handler: guarded(
|
|
15987
|
-
async ({ query }) => client.reflect(query, {
|
|
16290
|
+
async ({ query }) => client.reflect(query, {
|
|
16291
|
+
budget: opts.reflectBudget ?? "high",
|
|
16292
|
+
timeoutMs: opts.reflectTimeoutMs ?? DEFAULT_REFLECT_TOOL_TIMEOUT_MS
|
|
16293
|
+
})
|
|
15988
16294
|
)
|
|
15989
16295
|
},
|
|
15990
16296
|
{
|
|
15991
16297
|
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.
|
|
16298
|
+
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
16299
|
inputSchema: {
|
|
15994
16300
|
title: external_exports.string(),
|
|
15995
16301
|
summary: external_exports.string(),
|
|
@@ -16000,7 +16306,8 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
|
|
|
16000
16306
|
title,
|
|
16001
16307
|
summary,
|
|
16002
16308
|
relatesToPageId: relates_to_page_id,
|
|
16003
|
-
...opts.stampFor ? { stamp: opts.stampFor() } : {}
|
|
16309
|
+
...opts.stampFor ? { stamp: opts.stampFor() } : {},
|
|
16310
|
+
...opts.pageTrigger ? { pageTrigger: opts.pageTrigger } : {}
|
|
16004
16311
|
})
|
|
16005
16312
|
)
|
|
16006
16313
|
},
|
|
@@ -16207,7 +16514,7 @@ function resolversFor(ctx) {
|
|
|
16207
16514
|
return {
|
|
16208
16515
|
// Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
|
|
16209
16516
|
// otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
|
|
16210
|
-
gitProject: () => projectNameOf(ctx.directory),
|
|
16517
|
+
gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
|
|
16211
16518
|
project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
|
|
16212
16519
|
harness: () => ctx.harness,
|
|
16213
16520
|
bankId: () => ctx.bankId,
|
|
@@ -16253,11 +16560,6 @@ import { readFileSync as readFileSync4 } from "fs";
|
|
|
16253
16560
|
// src/core/skill-sync.ts
|
|
16254
16561
|
import { cpSync, existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
|
|
16255
16562
|
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
16563
|
import { dirname as dirname6, join as join8 } from "path";
|
|
16262
16564
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
16263
16565
|
|
|
@@ -16348,7 +16650,7 @@ async function buildSessionStartContext(args) {
|
|
|
16348
16650
|
const startSurvey = args.startSurvey ?? startCodebaseSurvey;
|
|
16349
16651
|
const resolveHeadSha = args.headSha ?? gitHeadSha;
|
|
16350
16652
|
const countCommitsSince = args.commitsSince ?? commitsSince;
|
|
16351
|
-
const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, harness, bankId });
|
|
16653
|
+
const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
|
|
16352
16654
|
const SURVEY_BASELINE_TAG = "source:survey-baseline";
|
|
16353
16655
|
const SURVEY_BASELINE_PREFIX = "survey-baseline:";
|
|
16354
16656
|
const recordSurveyBaseline = (sha) => {
|
|
@@ -16624,6 +16926,9 @@ var RuntimeCore = class {
|
|
|
16624
16926
|
return buildKnowledgeTools(this.client, this.bankId, {
|
|
16625
16927
|
repoDir: this.projectDir,
|
|
16626
16928
|
harness: this.harness,
|
|
16929
|
+
pageTrigger: buildPageTrigger(this.cfg),
|
|
16930
|
+
reflectTimeoutMs: this.cfg.reflectToolTimeoutMs,
|
|
16931
|
+
reflectBudget: this.cfg.reflectBudget,
|
|
16627
16932
|
stampFor: () => buildRetainStamp(this.cfg, {
|
|
16628
16933
|
directory: this.projectDir,
|
|
16629
16934
|
harness: this.harness,
|
|
@@ -16642,6 +16947,7 @@ var RuntimeCore = class {
|
|
|
16642
16947
|
*/
|
|
16643
16948
|
async seedIfCold(repoPath) {
|
|
16644
16949
|
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
16950
|
+
await ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
|
|
16645
16951
|
try {
|
|
16646
16952
|
const out = await buildSessionStartContext({
|
|
16647
16953
|
cwd: repoPath || process.cwd(),
|
|
@@ -16765,15 +17071,17 @@ var RuntimeCore = class {
|
|
|
16765
17071
|
/** Fire-and-forget upsert of the session transcript; never throws into the host. */
|
|
16766
17072
|
retain(sessionId, turns, startTs, trigger = "turn") {
|
|
16767
17073
|
const t0 = Date.now();
|
|
16768
|
-
void
|
|
16769
|
-
|
|
16770
|
-
|
|
16771
|
-
|
|
16772
|
-
|
|
16773
|
-
|
|
16774
|
-
|
|
17074
|
+
void ensureDaemon(this.cfg, this.harness, { waitMs: DAEMON_WAIT_RETAIN_MS }).then(
|
|
17075
|
+
() => retainLiveSession(this.client, sessionId, turns, startTs, this.harness, {
|
|
17076
|
+
cursors: this.cursors,
|
|
17077
|
+
stamp: buildRetainStamp(this.cfg, {
|
|
17078
|
+
directory: this.projectDir,
|
|
17079
|
+
harness: this.harness,
|
|
17080
|
+
bankId: this.bankId,
|
|
17081
|
+
sessionId
|
|
17082
|
+
})
|
|
16775
17083
|
})
|
|
16776
|
-
|
|
17084
|
+
).then(
|
|
16777
17085
|
() => diag(this.harness, "retain_ok", {
|
|
16778
17086
|
ms: Date.now() - t0,
|
|
16779
17087
|
turns: turns.length,
|
|
@@ -16882,23 +17190,12 @@ function workspaceRoot(agent) {
|
|
|
16882
17190
|
function workspaceFor(root) {
|
|
16883
17191
|
const cached2 = workspaces.get(root);
|
|
16884
17192
|
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;
|
|
17193
|
+
const { cfg, bankId, client } = resolveHostMemory(HARNESS2, root);
|
|
16892
17194
|
if (cfg.disabled) {
|
|
16893
17195
|
workspaces.set(root, null);
|
|
16894
17196
|
return void 0;
|
|
16895
17197
|
}
|
|
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);
|
|
17198
|
+
const core = new RuntimeCore(client, bankId, cfg, HARNESS2, root);
|
|
16902
17199
|
core.setTranscriptSource(async (sessionId) => {
|
|
16903
17200
|
const agent = liveAgents.get(sessionId);
|
|
16904
17201
|
return agent ? readDshEvents(agent.session.events) : [];
|