@vectorize-io/hindsight-coding-agents 0.5.0 → 0.5.2
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 +44 -3
- package/dist/antigravity-hook.js +142 -9
- package/dist/antigravity-statusline.js +42 -4
- package/dist/antigravity-stop-hook.js +222 -59
- package/dist/claude-hook.js +142 -9
- package/dist/claude-sessionstart-hook.js +145 -11
- package/dist/claude-stop-hook.js +222 -59
- package/dist/cline.js +149 -61
- package/dist/codex-hook.js +142 -9
- package/dist/codex-sessionstart-hook.js +145 -11
- package/dist/codex-stop-hook.js +222 -59
- package/dist/copilot-hook.js +142 -9
- package/dist/copilot-sessionstart-hook.js +145 -11
- package/dist/copilot-stop-hook.js +222 -59
- package/dist/cursor-hook.js +142 -9
- package/dist/cursor-sessionstart-hook.js +145 -11
- package/dist/cursor-stop-hook.js +222 -59
- package/dist/daemon-start.js +36 -2
- package/dist/dcode-hook.js +142 -9
- package/dist/dcode-sessionstart-hook.js +145 -11
- package/dist/dcode-stop-hook.js +222 -59
- package/dist/deepen.js +97 -14
- package/dist/devin-hook.js +142 -9
- package/dist/devin-sessionstart-hook.js +145 -11
- package/dist/devin-stop-hook.js +222 -59
- package/dist/droid-hook.js +2710 -0
- package/dist/droid-sessionstart-hook.js +3328 -0
- package/dist/droid-stop-hook.js +2970 -0
- package/dist/dsh.js +154 -62
- package/dist/grok-hook.js +142 -9
- package/dist/grok-sessionstart-hook.js +145 -11
- package/dist/grok-stop-hook.js +222 -59
- package/dist/hindsight-seed.js +42 -4
- package/dist/index.js +149 -61
- package/dist/installer.js +155 -13
- package/dist/kilo.js +149 -61
- package/dist/mcp-server.js +474 -133
- package/dist/opencode2.js +149 -61
- package/dist/pi.js +149 -61
- package/dist/prime-agent.js +149 -61
- package/dist/qwen-hook.js +142 -9
- package/dist/qwen-sessionstart-hook.js +145 -11
- package/dist/qwen-stop-hook.js +222 -59
- package/dist/status.js +65 -7
- package/package.json +6 -3
- package/plugin.json +1 -1
- package/skill/SKILL.md +26 -2
|
@@ -0,0 +1,3328 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/core/hook.ts
|
|
4
|
+
import { existsSync as existsSync2, readFileSync as readFileSync4 } from "fs";
|
|
5
|
+
|
|
6
|
+
// src/core/bank.ts
|
|
7
|
+
import { existsSync } from "fs";
|
|
8
|
+
import { homedir } from "os";
|
|
9
|
+
import { basename, dirname as dirname3, join as join3, normalize, sep } from "path";
|
|
10
|
+
|
|
11
|
+
// src/core/diag.ts
|
|
12
|
+
import { appendFileSync as appendFileSync2 } from "fs";
|
|
13
|
+
|
|
14
|
+
// src/core/log.ts
|
|
15
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
16
|
+
import { tmpdir } from "os";
|
|
17
|
+
import { dirname, join } from "path";
|
|
18
|
+
var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
19
|
+
var current = ["debug", "info", "warn", "error"].find(
|
|
20
|
+
(l) => l === process.env.HINDSIGHT_LOG_LEVEL
|
|
21
|
+
) ?? "info";
|
|
22
|
+
function setLogLevel(level) {
|
|
23
|
+
if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
|
|
24
|
+
}
|
|
25
|
+
function logFilePath() {
|
|
26
|
+
return process.env.HINDSIGHT_LOG_FILE || join(tmpdir(), "hindsight-coding-agent", "plugin.log");
|
|
27
|
+
}
|
|
28
|
+
function write(level, scope, msg, extra) {
|
|
29
|
+
if (WEIGHT[level] < WEIGHT[current]) return;
|
|
30
|
+
try {
|
|
31
|
+
const file = logFilePath();
|
|
32
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
33
|
+
appendFileSync(
|
|
34
|
+
file,
|
|
35
|
+
`${(/* @__PURE__ */ new Date()).toISOString()} ${level.toUpperCase().padEnd(5)} [${scope}] ${msg}` + (extra && Object.keys(extra).length ? ` ${JSON.stringify(extra)}` : "") + "\n"
|
|
36
|
+
);
|
|
37
|
+
} catch {
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
var log = {
|
|
41
|
+
debug: (scope, msg, extra) => write("debug", scope, msg, extra),
|
|
42
|
+
info: (scope, msg, extra) => write("info", scope, msg, extra),
|
|
43
|
+
warn: (scope, msg, extra) => write("warn", scope, msg, extra),
|
|
44
|
+
error: (scope, msg, extra) => write("error", scope, msg, extra)
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// src/core/diag.ts
|
|
48
|
+
function diagFilePath() {
|
|
49
|
+
return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
|
|
50
|
+
}
|
|
51
|
+
function diag(harness, event, extra = {}) {
|
|
52
|
+
log.debug(harness, `diag:${event}`, extra);
|
|
53
|
+
try {
|
|
54
|
+
appendFileSync2(
|
|
55
|
+
diagFilePath(),
|
|
56
|
+
JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
|
|
57
|
+
);
|
|
58
|
+
} catch {
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/core/git-layout.ts
|
|
63
|
+
import { lstatSync, readFileSync, realpathSync } from "fs";
|
|
64
|
+
import { dirname as dirname2, isAbsolute, join as join2, resolve } from "path";
|
|
65
|
+
var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
|
|
66
|
+
var ATTEMPTS = 3;
|
|
67
|
+
var BACKOFF_MS = 20;
|
|
68
|
+
function errorCode(error) {
|
|
69
|
+
return error?.code ?? "";
|
|
70
|
+
}
|
|
71
|
+
function sleepSync(ms) {
|
|
72
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
73
|
+
}
|
|
74
|
+
var TransientProbeError = class extends Error {
|
|
75
|
+
};
|
|
76
|
+
function entryKind(path) {
|
|
77
|
+
try {
|
|
78
|
+
const st = lstatSync(path);
|
|
79
|
+
return st.isDirectory() ? "dir" : "file";
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
|
|
82
|
+
return "none";
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function readTextOrNull(path) {
|
|
86
|
+
try {
|
|
87
|
+
return readFileSync(path, "utf8");
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (TRANSIENT.has(errorCode(error))) throw new TransientProbeError(errorCode(error));
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function gitDirFromPointer(text, holder) {
|
|
94
|
+
const match = /^\s*gitdir:\s*(.+?)\s*$/m.exec(text);
|
|
95
|
+
if (!match) return null;
|
|
96
|
+
const target = match[1];
|
|
97
|
+
return isAbsolute(target) ? target : resolve(holder, target);
|
|
98
|
+
}
|
|
99
|
+
function commonDirOf(gitDir) {
|
|
100
|
+
const pointer = entryKind(join2(gitDir, "commondir")) === "file" ? readTextOrNull(join2(gitDir, "commondir"))?.trim() : null;
|
|
101
|
+
if (!pointer) return gitDir;
|
|
102
|
+
return isAbsolute(pointer) ? pointer : resolve(gitDir, pointer);
|
|
103
|
+
}
|
|
104
|
+
function isBare(commonDir) {
|
|
105
|
+
const config = readTextOrNull(join2(commonDir, "config"));
|
|
106
|
+
return config !== null && /^\s*bare\s*=\s*true\s*$/im.test(config);
|
|
107
|
+
}
|
|
108
|
+
function looksLikeBareRepository(directory) {
|
|
109
|
+
return entryKind(join2(directory, "HEAD")) === "file" && entryKind(join2(directory, "objects")) === "dir" && entryKind(join2(directory, "refs")) === "dir";
|
|
110
|
+
}
|
|
111
|
+
function canonical(path) {
|
|
112
|
+
try {
|
|
113
|
+
return realpathSync(path);
|
|
114
|
+
} catch {
|
|
115
|
+
return path;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function resolved(commonDir) {
|
|
119
|
+
if (entryKind(commonDir) !== "dir") return null;
|
|
120
|
+
const canonicalDir = canonical(commonDir);
|
|
121
|
+
return { status: "resolved", commonDir: canonicalDir, bare: isBare(canonicalDir) };
|
|
122
|
+
}
|
|
123
|
+
function probeOnce(directory) {
|
|
124
|
+
let current2 = resolve(directory);
|
|
125
|
+
for (; ; ) {
|
|
126
|
+
const dotGit = join2(current2, ".git");
|
|
127
|
+
const kind = entryKind(dotGit);
|
|
128
|
+
if (kind === "dir") {
|
|
129
|
+
const layout = resolved(commonDirOf(dotGit));
|
|
130
|
+
if (layout) return layout;
|
|
131
|
+
} else if (kind === "file") {
|
|
132
|
+
const text = readTextOrNull(dotGit);
|
|
133
|
+
const gitDir = text ? gitDirFromPointer(text, current2) : null;
|
|
134
|
+
const layout = gitDir ? resolved(commonDirOf(gitDir)) : null;
|
|
135
|
+
if (layout) return layout;
|
|
136
|
+
}
|
|
137
|
+
if (looksLikeBareRepository(current2)) {
|
|
138
|
+
const layout = resolved(current2);
|
|
139
|
+
if (layout) return layout;
|
|
140
|
+
}
|
|
141
|
+
const parent = dirname2(current2);
|
|
142
|
+
if (parent === current2) return { status: "absent" };
|
|
143
|
+
current2 = parent;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function probeGitLayout(directory) {
|
|
147
|
+
if (!directory) return { status: "absent" };
|
|
148
|
+
let last = "";
|
|
149
|
+
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
|
|
150
|
+
if (attempt) sleepSync(BACKOFF_MS * attempt);
|
|
151
|
+
try {
|
|
152
|
+
return probeOnce(directory);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
last = error instanceof TransientProbeError ? error.message : errorCode(error) || "unknown";
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return { status: "failed", reason: last };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// src/core/template.ts
|
|
161
|
+
var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
|
|
162
|
+
function applyTemplate(template, resolvers, what) {
|
|
163
|
+
return template.replace(PLACEHOLDER, (_, name) => {
|
|
164
|
+
const resolve3 = resolvers[name];
|
|
165
|
+
if (!resolve3) {
|
|
166
|
+
console.error(
|
|
167
|
+
`hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
|
|
168
|
+
);
|
|
169
|
+
return "unknown";
|
|
170
|
+
}
|
|
171
|
+
return resolve3();
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// src/core/bank.ts
|
|
176
|
+
var DEFAULT_BANK_NAME = "coding";
|
|
177
|
+
var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
|
|
178
|
+
var BankResolutionError = class extends Error {
|
|
179
|
+
constructor(message) {
|
|
180
|
+
super(message);
|
|
181
|
+
this.name = "BankResolutionError";
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
function resolveProjectRoot(directory) {
|
|
185
|
+
if (!directory) return { status: "absent" };
|
|
186
|
+
const layout = probeGitLayout(directory);
|
|
187
|
+
if (layout.status !== "resolved") return layout;
|
|
188
|
+
const commonDir = layout.commonDir;
|
|
189
|
+
if (basename(commonDir) === ".git") return { status: "resolved", root: dirname3(commonDir) };
|
|
190
|
+
if (basename(commonDir).startsWith(".") && layout.bare) {
|
|
191
|
+
return { status: "resolved", root: dirname3(commonDir) };
|
|
192
|
+
}
|
|
193
|
+
return { status: "resolved", root: commonDir };
|
|
194
|
+
}
|
|
195
|
+
function projectNameOf(directory, sessionRoot) {
|
|
196
|
+
return gitProjectName(directory, true, sessionRoot);
|
|
197
|
+
}
|
|
198
|
+
var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
|
|
199
|
+
function nearestExistingDir(directory) {
|
|
200
|
+
let current2 = directory;
|
|
201
|
+
while (current2) {
|
|
202
|
+
if (existsSync(current2)) return current2;
|
|
203
|
+
const parent = dirname3(current2);
|
|
204
|
+
if (parent === current2) return "";
|
|
205
|
+
current2 = parent;
|
|
206
|
+
}
|
|
207
|
+
return "";
|
|
208
|
+
}
|
|
209
|
+
function dirName(directory) {
|
|
210
|
+
return directory && basename(directory) || "unknown";
|
|
211
|
+
}
|
|
212
|
+
function mainWorktreeRoot(directory, sessionRoot = "") {
|
|
213
|
+
const candidates = [
|
|
214
|
+
nearestExistingDir(directory),
|
|
215
|
+
sessionRoot,
|
|
216
|
+
...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
|
|
217
|
+
];
|
|
218
|
+
let failure = null;
|
|
219
|
+
for (const candidate of candidates) {
|
|
220
|
+
if (!candidate) continue;
|
|
221
|
+
const projectRoot = resolveProjectRoot(candidate);
|
|
222
|
+
if (projectRoot.status === "resolved") return projectRoot;
|
|
223
|
+
if (projectRoot.status === "failed") failure = projectRoot;
|
|
224
|
+
}
|
|
225
|
+
return failure ?? { status: "absent" };
|
|
226
|
+
}
|
|
227
|
+
function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
|
|
228
|
+
if (resolveWorktrees) {
|
|
229
|
+
const projectRoot = mainWorktreeRoot(directory, sessionRoot);
|
|
230
|
+
if (projectRoot.status === "resolved") return basename(projectRoot.root);
|
|
231
|
+
if (projectRoot.status === "failed") {
|
|
232
|
+
throw new BankResolutionError(
|
|
233
|
+
`git probe failed for ${directory} (${projectRoot.reason}) \u2014 refusing to guess a bank id`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return dirName(sessionRoot || directory);
|
|
238
|
+
}
|
|
239
|
+
function configuredDir(dir) {
|
|
240
|
+
const expanded = dir === "~" || dir.startsWith("~/") ? join3(homedir(), dir.slice(1)) : dir;
|
|
241
|
+
return normalize(expanded).replace(new RegExp(`\\${sep}+$`), "");
|
|
242
|
+
}
|
|
243
|
+
function isWithin(directory, configured) {
|
|
244
|
+
return directory === configured || directory.startsWith(configured + sep);
|
|
245
|
+
}
|
|
246
|
+
function mapLookup(map, directory) {
|
|
247
|
+
const cwd = normalize(directory);
|
|
248
|
+
let best;
|
|
249
|
+
for (const [dir, bank] of Object.entries(map)) {
|
|
250
|
+
const p = configuredDir(dir);
|
|
251
|
+
if (isWithin(cwd, p)) {
|
|
252
|
+
if (!best || p.length > best.len) best = { len: p.length, bank };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return best?.bank;
|
|
256
|
+
}
|
|
257
|
+
function lookupDirectories(config, directory, sessionRoot = "") {
|
|
258
|
+
const directories = [normalize(directory)];
|
|
259
|
+
if (config.resolveWorktrees ?? true) {
|
|
260
|
+
const projectRoot = mainWorktreeRoot(directory, sessionRoot);
|
|
261
|
+
const normalizedRoot = projectRoot.status === "resolved" ? normalize(projectRoot.root) : "";
|
|
262
|
+
if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
|
|
263
|
+
}
|
|
264
|
+
return directories;
|
|
265
|
+
}
|
|
266
|
+
function isOptedIn(config, directory) {
|
|
267
|
+
if (!config.optInOnly) return true;
|
|
268
|
+
if (!directory) return false;
|
|
269
|
+
const directories = lookupDirectories(config, directory);
|
|
270
|
+
if (directories.some(
|
|
271
|
+
(candidate) => (config.optInPaths ?? []).some(
|
|
272
|
+
(configured) => configured && isWithin(candidate, configuredDir(configured))
|
|
273
|
+
)
|
|
274
|
+
))
|
|
275
|
+
return true;
|
|
276
|
+
const pathMap = config.mapPathToBank;
|
|
277
|
+
return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
|
|
278
|
+
}
|
|
279
|
+
function mappedBank(config, directory, sessionRoot) {
|
|
280
|
+
const pathMap = config.mapPathToBank;
|
|
281
|
+
if (!directory || !pathMap) return void 0;
|
|
282
|
+
return lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0);
|
|
283
|
+
}
|
|
284
|
+
function deriveBankId(config, directory, harness = "coding", sessionRoot) {
|
|
285
|
+
const mapped = mappedBank(config, directory, sessionRoot);
|
|
286
|
+
if (mapped) return mapped;
|
|
287
|
+
const dynamic = config.dynamicBankId ?? !config.bankId;
|
|
288
|
+
if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
|
|
289
|
+
const resolvers = {
|
|
290
|
+
harness: () => harness,
|
|
291
|
+
project: () => dirName(directory),
|
|
292
|
+
gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot),
|
|
293
|
+
channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
|
|
294
|
+
user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
|
|
295
|
+
};
|
|
296
|
+
return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
|
|
297
|
+
}
|
|
298
|
+
function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot) {
|
|
299
|
+
try {
|
|
300
|
+
return deriveBankId(config, directory, harness, sessionRoot);
|
|
301
|
+
} catch (error) {
|
|
302
|
+
if (!(error instanceof BankResolutionError)) throw error;
|
|
303
|
+
log.warn(harness, "bank unresolved: skipping (repository could not be identified)", {
|
|
304
|
+
directory,
|
|
305
|
+
error: error.message
|
|
306
|
+
});
|
|
307
|
+
diag(harness, "bank_unresolved", { directory, error: error.message });
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// src/core/config.ts
|
|
313
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
314
|
+
import { homedir as homedir2 } from "os";
|
|
315
|
+
import { join as join6 } from "path";
|
|
316
|
+
|
|
317
|
+
// src/core/seed.ts
|
|
318
|
+
import { spawn as realSpawn } from "child_process";
|
|
319
|
+
import { dirname as dirname4, join as join4 } from "path";
|
|
320
|
+
import { fileURLToPath } from "url";
|
|
321
|
+
var DEFAULT_SEED_LIMIT = 300;
|
|
322
|
+
function startBackgroundSeed(repoDir, opts = {}) {
|
|
323
|
+
try {
|
|
324
|
+
const spawnFn = opts.spawn ?? realSpawn;
|
|
325
|
+
const enginePath = opts.enginePath ?? join4(dirname4(fileURLToPath(import.meta.url)), "deepen.js");
|
|
326
|
+
const limit = opts.limit ?? DEFAULT_SEED_LIMIT;
|
|
327
|
+
const child = spawnFn(
|
|
328
|
+
"node",
|
|
329
|
+
[
|
|
330
|
+
enginePath,
|
|
331
|
+
"--repo",
|
|
332
|
+
repoDir,
|
|
333
|
+
"--gitlog-limit",
|
|
334
|
+
String(limit),
|
|
335
|
+
...opts.harness ? ["--harness", opts.harness] : []
|
|
336
|
+
],
|
|
337
|
+
{
|
|
338
|
+
detached: true,
|
|
339
|
+
stdio: "ignore",
|
|
340
|
+
windowsHide: true
|
|
341
|
+
}
|
|
342
|
+
);
|
|
343
|
+
child.on("error", () => {
|
|
344
|
+
});
|
|
345
|
+
child.unref();
|
|
346
|
+
} catch {
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// src/core/missions.ts
|
|
351
|
+
import { createHash } from "crypto";
|
|
352
|
+
var GIT_MISSION = "You are ingesting a single git commit: its message and its full diff. Extract the concrete technical DECISION and the CAUSE/INVARIANT it encodes, bound to the specific code entities (functions, methods, files) and behaviors it changes. Preserve exact identifiers, paths, and literal values verbatim. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Capture both WHAT changed and WHY. Issue/PR references (#123, GH-123, PROJ-123) are load-bearing: keep them VERBATIM in the fact text and emit each as an ENTITY, so a later question about that issue or PR retrieves this decision.";
|
|
353
|
+
var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, newest first. Extract the project's INITIATIVES, FEATURES, ENHANCEMENTS, and notable changes or THEMES over time \u2014 what the project has been working on and how it has evolved. Do NOT extract per-line code detail (there is no diff to draw it from). Group related commits into a coherent initiative/theme where the messages make that clear; preserve exact identifiers and literal values verbatim when quoting a subject line. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY \u2014 they are how future sessions will ask about this work.";
|
|
354
|
+
var CONVERSATION_MISSION = `You are ingesting a developer conversation as a JSONL transcript (one {role, content} turn per line): the user's requests, the assistant's narration, and compact 'action' turns naming each tool use and its target (e.g. "Edit boltons/strutils.py") with no arguments or outputs. It may be a SHORT decision chat or a LONG working session \u2014 scale the facts to the substance, never to the message count. Extract the FEWEST facts that capture the OUTCOME: the settled DECISIONS and their exact rules/values (quote literals VERBATIM); concrete CHANGES to specific code entities; problems and how they were resolved; conventions or invariants established; at most one fact for a notable REJECTED alternative ('initially proposed X, changed to Y because Z'). A short decision chat usually yields 1-2 facts; a substantial working session several. CRITICAL: a conversation REVISES itself \u2014 record ONLY the FINAL state as what is in effect; a superseded proposal appears ONLY inside the rejected fact, NEVER as its own 'decided' fact; if the same setting changes several times keep only the LAST, and make unmistakably clear which choice WON. Do NOT emit one fact per message, per intermediate proposal, or per action turn. Keep issue/PR references (#123, GH-123) VERBATIM and emit each as an ENTITY. Preserve the 'REF-ID: <token>' marker verbatim in every fact. Do not invent; capture only what was actually settled.`;
|
|
355
|
+
var REFLECT_MISSION = "You are a debugging assistant with the project's past decisions in memory (git rationale and developer chats). Given a bug's SYMPTOM, find the past decision whose rationale explains the ROOT CAUSE \u2014 not one that merely shares vocabulary. Answer with the PRECISE fix: state the EXACT rule and the LITERAL values, identifiers, strings, numbers, or set members that were decided \u2014 quote them VERBATIM, never paraphrase, generalize, or omit them (give the actual decided value, not 'the project standard'). If memories CONFLICT on the same rule, the LATEST decision wins \u2014 prefer facts that explicitly amend or supersede an earlier one, state the superseded rule as no longer in effect, and never present it as the fix. Name the function/file to change and cite the REF-ID(s). If NOTHING in memory genuinely explains THIS symptom, say exactly that in one short sentence \u2014 a wrong-but-confident nearest match is worse than an honest miss; never stretch an unrelated decision to fit.";
|
|
356
|
+
var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
|
|
357
|
+
var OBSERVATIONS_MISSION = "Consolidate durable knowledge about THIS codebase \u2014 recurring patterns, conventions, module responsibilities, and how components relate \u2014 from the ingested commits and conversations. Favor stable structural understanding over one-off details. When a new fact contradicts or supersedes an existing observation, UPDATE that observation to reflect the current state rather than creating a sibling alongside it; note that the rule was revised and when, so the superseded version is visible as history rather than as a competing claim.";
|
|
358
|
+
var RETAIN_STRATEGIES = {
|
|
359
|
+
git: { retain_mission: GIT_MISSION, retain_extraction_mode: "verbose" },
|
|
360
|
+
// ONE big aggregated document (last N commit messages, no diffs) -> a larger chunk size so it stays
|
|
361
|
+
// in as few chunks as possible and the extractor sees the whole history arc at once.
|
|
362
|
+
gitlog: {
|
|
363
|
+
retain_mission: GITLOG_MISSION,
|
|
364
|
+
retain_extraction_mode: "verbose",
|
|
365
|
+
retain_chunk_size: 12e3
|
|
366
|
+
},
|
|
367
|
+
// ONE strategy for ALL developer conversations — backfilled decision chats and live working
|
|
368
|
+
// sessions alike (they are the same content type in the same JSON transcript format; the mission
|
|
369
|
+
// scales extraction to the substance, final-state-wins). Chunk big enough to hold a whole typical
|
|
370
|
+
// conversation in ONE chunk so the extractor sees the full proposal→revision arc (the 3000
|
|
371
|
+
// default SPLIT them into per-chunk fragments); very long sessions still split and fall back to
|
|
372
|
+
// the consolidation layer.
|
|
373
|
+
conversation: {
|
|
374
|
+
retain_mission: CONVERSATION_MISSION,
|
|
375
|
+
retain_extraction_mode: "verbose",
|
|
376
|
+
retain_chunk_size: 12e3
|
|
377
|
+
},
|
|
378
|
+
// Structural documents (e.g. the codebase survey's ingested findings) aren't dialogue — the
|
|
379
|
+
// chat strategy's "final decision vs rejected proposal" extraction doesn't apply. Verbose mode
|
|
380
|
+
// with a bigger chunk size (documents can run long) captures the concrete facts/structure instead.
|
|
381
|
+
document: {
|
|
382
|
+
retain_mission: DOCUMENT_MISSION,
|
|
383
|
+
retain_extraction_mode: "verbose",
|
|
384
|
+
retain_chunk_size: 12e3
|
|
385
|
+
},
|
|
386
|
+
// Codebase-SURVEY lifecycle documents, ONE strategy with conditional rules: the survey's
|
|
387
|
+
// internal status markers ("researching…"/"completed" baselines) must yield ZERO memories,
|
|
388
|
+
// while any actual survey findings routed here extract as concrete structural facts.
|
|
389
|
+
survey: {
|
|
390
|
+
retain_extraction_mode: "custom",
|
|
391
|
+
retain_custom_instructions: "This document belongs to the Hindsight codebase-survey lifecycle. Apply ONE of two rules: (1) If the content is an internal status marker \u2014 it says it is an internal marker, or merely announces that a survey started/completed at some commit \u2014 extract NOTHING: return an empty list of facts. (2) Otherwise the content is survey FINDINGS about the codebase: extract the concrete structural facts it states (components and their responsibilities, key concepts, conventions, tech stack), preserving identifiers verbatim.",
|
|
392
|
+
retain_chunk_size: 12e3
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
var KNOWLEDGE_LABELS = {
|
|
396
|
+
key: "knowledge",
|
|
397
|
+
type: "multi-values",
|
|
398
|
+
// 0, 1, or several — empty is normal
|
|
399
|
+
optional: true,
|
|
400
|
+
tag: true,
|
|
401
|
+
// emits knowledge:<value> onto the fact's tags
|
|
402
|
+
description: "Routing labels for this project's Hindsight KNOWLEDGE PAGES \u2014 curated, human-readable summaries of the repo's DURABLE engineering knowledge (architecture, key decisions, conventions, ongoing initiatives), each page rebuilt automatically from the facts labeled for it. Mark a fact only when it is durable, reusable knowledge a developer would still want surfaced in future sessions. IMPORTANT: leave this EMPTY for routine, transient, or operational facts \u2014 a passing test, a one-off command, a status update, a debugging dead-end. MOST facts should get no label here. Assign more than one value only when the fact genuinely fits several.",
|
|
403
|
+
values: [
|
|
404
|
+
{
|
|
405
|
+
value: "feature-work",
|
|
406
|
+
description: "A new feature, initiative, or enhancement being planned or built \u2014 the capability being added and the intent behind it. Not routine bug-fixes or chores."
|
|
407
|
+
},
|
|
408
|
+
{
|
|
409
|
+
value: "decision",
|
|
410
|
+
description: "A technical decision that will constrain future work, with its rationale \u2014 why this approach was chosen over alternatives, or a rule deliberately adopted."
|
|
411
|
+
},
|
|
412
|
+
{
|
|
413
|
+
value: "convention",
|
|
414
|
+
description: "An established way this project does things \u2014 naming, structure, testing, error handling, or another recurring pattern a contributor is expected to follow."
|
|
415
|
+
},
|
|
416
|
+
{
|
|
417
|
+
value: "component",
|
|
418
|
+
description: "What a specific module, file, service, or subsystem is responsible for, or how components depend on and connect to one another."
|
|
419
|
+
},
|
|
420
|
+
{
|
|
421
|
+
value: "concept",
|
|
422
|
+
description: "A domain concept, key abstraction, or piece of project vocabulary a new contributor must understand to work effectively."
|
|
423
|
+
}
|
|
424
|
+
]
|
|
425
|
+
};
|
|
426
|
+
function pageScopeRule(project) {
|
|
427
|
+
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.`;
|
|
428
|
+
}
|
|
429
|
+
var PAGE_TAXONOMY = [
|
|
430
|
+
{
|
|
431
|
+
name: "Component map",
|
|
432
|
+
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.",
|
|
433
|
+
tags: ["knowledge:component"]
|
|
434
|
+
},
|
|
435
|
+
{
|
|
436
|
+
name: "Core concepts",
|
|
437
|
+
source_query: "What are the core concepts, domain abstractions, and key entities in this project \u2014 the vocabulary a developer must understand? For each, explain what it represents and its role, drawn from how they are introduced and discussed across the history and conversations.",
|
|
438
|
+
tags: ["knowledge:concept"]
|
|
439
|
+
},
|
|
440
|
+
{
|
|
441
|
+
name: "Conventions and patterns",
|
|
442
|
+
source_query: "What conventions, idioms, and recurring patterns does this project follow \u2014 its approach to testing, error handling, naming, structure, and how changes are typically made? Describe how THIS project does things, as evidenced across its history and discussions.",
|
|
443
|
+
tags: ["knowledge:convention"]
|
|
444
|
+
},
|
|
445
|
+
{
|
|
446
|
+
name: "Key decisions and rationale",
|
|
447
|
+
source_query: "What are the significant technical decisions made in this project and the rationale behind them \u2014 the durable 'why we do it this way' a developer should know? Summarize the decisions and their reasoning from the commit rationales and past conversations.",
|
|
448
|
+
tags: ["knowledge:decision"]
|
|
449
|
+
},
|
|
450
|
+
{
|
|
451
|
+
name: "Initiatives and enhancements",
|
|
452
|
+
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.",
|
|
453
|
+
tags: ["knowledge:feature-work"]
|
|
454
|
+
}
|
|
455
|
+
];
|
|
456
|
+
function pagesFor(project) {
|
|
457
|
+
const scope = pageScopeRule(project);
|
|
458
|
+
return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
|
|
459
|
+
}
|
|
460
|
+
var PAGE_MAX_TOKENS = 4096;
|
|
461
|
+
var PAGE_TAGS_MATCH = "all";
|
|
462
|
+
var PAGE_FACT_TYPES = ["world", "experience", "observation"];
|
|
463
|
+
var CRON_FIELD_RANGES = [
|
|
464
|
+
[0, 59],
|
|
465
|
+
// minute
|
|
466
|
+
[0, 23],
|
|
467
|
+
// hour
|
|
468
|
+
[1, 31],
|
|
469
|
+
// day of month
|
|
470
|
+
[1, 12],
|
|
471
|
+
// month
|
|
472
|
+
[0, 6]
|
|
473
|
+
// day of week
|
|
474
|
+
];
|
|
475
|
+
var HASHED_FIELD = /^H(?:\((\d+)-(\d+)\))?$/;
|
|
476
|
+
function isHashedCron(cron) {
|
|
477
|
+
return /(^|\s)H/.test(cron);
|
|
478
|
+
}
|
|
479
|
+
function parseHashedCron(cron) {
|
|
480
|
+
const fields = cron.trim().split(/\s+/);
|
|
481
|
+
if (fields.length !== CRON_FIELD_RANGES.length) return void 0;
|
|
482
|
+
for (const [i, field] of fields.entries()) {
|
|
483
|
+
if (!field.startsWith("H")) continue;
|
|
484
|
+
const m = HASHED_FIELD.exec(field);
|
|
485
|
+
if (!m) return void 0;
|
|
486
|
+
if (m[1] === void 0) continue;
|
|
487
|
+
const [lo, hi] = [Number(m[1]), Number(m[2])];
|
|
488
|
+
const [min, max] = CRON_FIELD_RANGES[i];
|
|
489
|
+
if (lo > hi || lo < min || hi > max) return void 0;
|
|
490
|
+
}
|
|
491
|
+
return fields;
|
|
492
|
+
}
|
|
493
|
+
function hashedValue(seed, field, lo, hi) {
|
|
494
|
+
const digest = createHash("sha256").update(`${seed}\0${field}`).digest();
|
|
495
|
+
return lo + digest.readUInt32BE(0) % (hi - lo + 1);
|
|
496
|
+
}
|
|
497
|
+
function expandCronHash(cron, seed) {
|
|
498
|
+
if (!isHashedCron(cron)) return cron;
|
|
499
|
+
const fields = parseHashedCron(cron);
|
|
500
|
+
if (!fields) return cron;
|
|
501
|
+
return fields.map((field, i) => {
|
|
502
|
+
const m = HASHED_FIELD.exec(field);
|
|
503
|
+
if (!m) return field;
|
|
504
|
+
const [lo, hi] = m[1] === void 0 ? CRON_FIELD_RANGES[i] : [Number(m[1]), Number(m[2])];
|
|
505
|
+
return String(hashedValue(seed, i, lo, hi));
|
|
506
|
+
}).join(" ");
|
|
507
|
+
}
|
|
508
|
+
function pageTriggerFor(trigger, bank, page) {
|
|
509
|
+
const cron = trigger.refresh_cron;
|
|
510
|
+
if (!cron || !isHashedCron(cron)) return trigger;
|
|
511
|
+
return { ...trigger, refresh_cron: expandCronHash(cron, `${bank}\0${page}`) };
|
|
512
|
+
}
|
|
513
|
+
function buildPageTrigger(cfg = {}) {
|
|
514
|
+
const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
|
|
515
|
+
switch (cfg.pageTriggerType) {
|
|
516
|
+
case "cron":
|
|
517
|
+
return { ...base, refresh_cron: cfg.pageTriggerCron };
|
|
518
|
+
case "manual":
|
|
519
|
+
return { ...base, refresh_after_consolidation: false };
|
|
520
|
+
default:
|
|
521
|
+
return { ...base, refresh_after_consolidation: true };
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
var CODING_BANK_TEMPLATE = {
|
|
525
|
+
version: "1",
|
|
526
|
+
bank: {
|
|
527
|
+
reflect_mission: REFLECT_MISSION,
|
|
528
|
+
enable_observations: true,
|
|
529
|
+
observations_mission: OBSERVATIONS_MISSION,
|
|
530
|
+
retain_mission: GIT_MISSION,
|
|
531
|
+
retain_extraction_mode: "verbose",
|
|
532
|
+
retain_default_strategy: "git",
|
|
533
|
+
retain_strategies: RETAIN_STRATEGIES,
|
|
534
|
+
entity_labels: [KNOWLEDGE_LABELS],
|
|
535
|
+
entities_allow_free_form: true
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
|
|
539
|
+
function isSet(v) {
|
|
540
|
+
if (v === null || v === void 0) return false;
|
|
541
|
+
if (typeof v === "string") return v.trim() !== "";
|
|
542
|
+
return true;
|
|
543
|
+
}
|
|
544
|
+
function codingBankManifest(overrides) {
|
|
545
|
+
const current2 = overrides ?? {};
|
|
546
|
+
const template = CODING_BANK_TEMPLATE.bank;
|
|
547
|
+
const bank = {};
|
|
548
|
+
if (!MISSION_FIELDS.some((f) => isSet(current2[f]))) {
|
|
549
|
+
bank.reflect_mission = template.reflect_mission;
|
|
550
|
+
bank.enable_observations = template.enable_observations;
|
|
551
|
+
bank.observations_mission = template.observations_mission;
|
|
552
|
+
bank.retain_mission = template.retain_mission;
|
|
553
|
+
bank.retain_extraction_mode = template.retain_extraction_mode;
|
|
554
|
+
}
|
|
555
|
+
if (!isSet(current2.retain_default_strategy))
|
|
556
|
+
bank.retain_default_strategy = template.retain_default_strategy;
|
|
557
|
+
if (!isSet(current2.entities_allow_free_form))
|
|
558
|
+
bank.entities_allow_free_form = template.entities_allow_free_form;
|
|
559
|
+
const strategies = current2.retain_strategies && typeof current2.retain_strategies === "object" ? current2.retain_strategies : {};
|
|
560
|
+
const missing = Object.entries(template.retain_strategies).filter(([n]) => !(n in strategies));
|
|
561
|
+
if (missing.length > 0)
|
|
562
|
+
bank.retain_strategies = { ...strategies, ...Object.fromEntries(missing) };
|
|
563
|
+
const labels = Array.isArray(current2.entity_labels) ? current2.entity_labels : [];
|
|
564
|
+
const [knowledgeGroup] = template.entity_labels;
|
|
565
|
+
if (!labels.some((g) => g?.key === knowledgeGroup.key))
|
|
566
|
+
bank.entity_labels = [...labels, knowledgeGroup];
|
|
567
|
+
return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// src/core/util.ts
|
|
571
|
+
import { accessSync, constants } from "fs";
|
|
572
|
+
import { delimiter, join as join5 } from "path";
|
|
573
|
+
function binOnPath(bin) {
|
|
574
|
+
try {
|
|
575
|
+
if (bin.includes("/")) {
|
|
576
|
+
accessSync(bin, constants.X_OK);
|
|
577
|
+
return true;
|
|
578
|
+
}
|
|
579
|
+
for (const dir of (process.env.PATH || "").split(delimiter)) {
|
|
580
|
+
if (!dir) continue;
|
|
581
|
+
try {
|
|
582
|
+
accessSync(join5(dir, bin), constants.X_OK);
|
|
583
|
+
return true;
|
|
584
|
+
} catch {
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
return false;
|
|
588
|
+
} catch {
|
|
589
|
+
return false;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
593
|
+
function semverGte(version, min) {
|
|
594
|
+
const parts = (v) => {
|
|
595
|
+
const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
|
|
596
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
|
|
597
|
+
};
|
|
598
|
+
const a = version ? parts(version) : void 0;
|
|
599
|
+
const b = parts(min);
|
|
600
|
+
if (!a || !b) return false;
|
|
601
|
+
for (let i = 0; i < 3; i++) {
|
|
602
|
+
if (a[i] !== b[i]) return a[i] > b[i];
|
|
603
|
+
}
|
|
604
|
+
return true;
|
|
605
|
+
}
|
|
606
|
+
async function pool(items, n, fn, onError, onProgress) {
|
|
607
|
+
let i = 0, done = 0;
|
|
608
|
+
async function worker() {
|
|
609
|
+
while (i < items.length) {
|
|
610
|
+
const idx = i++;
|
|
611
|
+
try {
|
|
612
|
+
await fn(items[idx], idx);
|
|
613
|
+
} catch (e) {
|
|
614
|
+
onError?.(idx, e);
|
|
615
|
+
}
|
|
616
|
+
onProgress?.(++done, items.length);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// src/core/hindsight.ts
|
|
623
|
+
function resolveRetainScopes(tags, configured) {
|
|
624
|
+
if (configured !== "per_source") return configured;
|
|
625
|
+
const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
|
|
626
|
+
return [[], ...sources.map((s) => [s])];
|
|
627
|
+
}
|
|
628
|
+
var DEFAULT_OBSERVATION_SCOPES = "shared";
|
|
629
|
+
var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
|
|
630
|
+
var RateLimitedError = class extends Error {
|
|
631
|
+
constructor(retryAfterMs2) {
|
|
632
|
+
super(`rate limited; retry after ${Math.round(retryAfterMs2 / 1e3)}s`);
|
|
633
|
+
this.retryAfterMs = retryAfterMs2;
|
|
634
|
+
this.name = "RateLimitedError";
|
|
635
|
+
}
|
|
636
|
+
retryAfterMs;
|
|
637
|
+
code = "rate_limited";
|
|
638
|
+
};
|
|
639
|
+
function retryAfterMs(header) {
|
|
640
|
+
if (!header) return 0;
|
|
641
|
+
const secs = Number(header.trim());
|
|
642
|
+
if (Number.isFinite(secs) && secs >= 0) return secs * 1e3;
|
|
643
|
+
const at = Date.parse(header);
|
|
644
|
+
return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
|
|
645
|
+
}
|
|
646
|
+
var KnowledgePagesUnavailableError = class extends Error {
|
|
647
|
+
code = "knowledge_pages_unavailable";
|
|
648
|
+
constructor() {
|
|
649
|
+
super("Hindsight server does not support knowledge pages");
|
|
650
|
+
this.name = "KnowledgePagesUnavailableError";
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
|
|
654
|
+
var DEFAULT_MAX_PARALLEL_RETAINS = 10;
|
|
655
|
+
var POLL_CYCLE_MS = 5e3;
|
|
656
|
+
var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
|
|
657
|
+
var RETRY_AFTER_CEILING_MS = 60 * 1e3;
|
|
658
|
+
var HindsightClient = class {
|
|
659
|
+
apiUrl;
|
|
660
|
+
/** The credential the NEXT request will sign with — NOT the one the config file holds. The two
|
|
661
|
+
* diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
|
|
662
|
+
token;
|
|
663
|
+
tokenProvider;
|
|
664
|
+
bank;
|
|
665
|
+
project;
|
|
666
|
+
opIds = [];
|
|
667
|
+
// async operation ids collected by retain(), for drain()
|
|
668
|
+
/** Tri-state capability probe: unknown until the first page request, then cached. */
|
|
669
|
+
knowledgePagesSupported;
|
|
670
|
+
/** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
|
|
671
|
+
idempotentRetain;
|
|
672
|
+
log;
|
|
673
|
+
maxParallelRetains;
|
|
674
|
+
observationScopes;
|
|
675
|
+
constructor(o) {
|
|
676
|
+
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
677
|
+
this.token = o.apiToken;
|
|
678
|
+
this.tokenProvider = o.tokenProvider;
|
|
679
|
+
this.bank = o.bank;
|
|
680
|
+
this.project = o.project;
|
|
681
|
+
this.log = o.log ?? (() => {
|
|
682
|
+
});
|
|
683
|
+
this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
|
|
684
|
+
this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
|
|
685
|
+
}
|
|
686
|
+
/** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
|
|
687
|
+
get apiToken() {
|
|
688
|
+
return this.token;
|
|
689
|
+
}
|
|
690
|
+
headers() {
|
|
691
|
+
const h = { "Content-Type": "application/json" };
|
|
692
|
+
if (this.token) h["Authorization"] = `Bearer ${this.token}`;
|
|
693
|
+
return h;
|
|
694
|
+
}
|
|
695
|
+
/** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
|
|
696
|
+
* only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
|
|
697
|
+
* doubling every failing request. */
|
|
698
|
+
refreshToken() {
|
|
699
|
+
if (!this.tokenProvider) return false;
|
|
700
|
+
let next;
|
|
701
|
+
try {
|
|
702
|
+
next = this.tokenProvider();
|
|
703
|
+
} catch {
|
|
704
|
+
return false;
|
|
705
|
+
}
|
|
706
|
+
if (next === this.token) return false;
|
|
707
|
+
this.token = next;
|
|
708
|
+
return true;
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
|
|
712
|
+
* poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
|
|
713
|
+
* failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
|
|
714
|
+
* not.
|
|
715
|
+
*
|
|
716
|
+
* On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
|
|
717
|
+
* string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
|
|
718
|
+
* free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
|
|
719
|
+
* bounds the whole call.
|
|
720
|
+
*/
|
|
721
|
+
async fetchWithAuth(url, init) {
|
|
722
|
+
const send = () => fetch(url, { ...init, headers: this.headers() });
|
|
723
|
+
const r = await send();
|
|
724
|
+
if (r.status !== 401 || !this.refreshToken()) return r;
|
|
725
|
+
return send();
|
|
726
|
+
}
|
|
727
|
+
/** A 401 with no `Authorization` header is a different failure from a rejected key, and the
|
|
728
|
+
* server answers identically for both — only the client knows which it sent. */
|
|
729
|
+
authHint(status) {
|
|
730
|
+
if (status !== 401) return "";
|
|
731
|
+
return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
|
|
732
|
+
}
|
|
733
|
+
bankUrl(suffix = "") {
|
|
734
|
+
return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
|
|
735
|
+
}
|
|
736
|
+
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
737
|
+
async req(method, url, body, tolerate = []) {
|
|
738
|
+
const r = await this.fetchWithAuth(url, {
|
|
739
|
+
method,
|
|
740
|
+
body: body ? JSON.stringify(body) : void 0,
|
|
741
|
+
signal: AbortSignal.timeout(15e3)
|
|
742
|
+
});
|
|
743
|
+
if (r.status === 429 && !tolerate.includes(429))
|
|
744
|
+
throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
|
|
745
|
+
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
746
|
+
throw new Error(
|
|
747
|
+
`${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
|
|
748
|
+
);
|
|
749
|
+
return r;
|
|
750
|
+
}
|
|
751
|
+
/** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
|
|
752
|
+
* drain(). Nothing in this plugin can afford to block a coding agent's hook on extraction. */
|
|
753
|
+
async retain(content, context, documentId, tags, strategy, opts = {}) {
|
|
754
|
+
const item = {
|
|
755
|
+
content,
|
|
756
|
+
context,
|
|
757
|
+
document_id: documentId,
|
|
758
|
+
tags,
|
|
759
|
+
strategy,
|
|
760
|
+
// Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
|
|
761
|
+
// observations were built under is a property of the write rather than of whichever server
|
|
762
|
+
// version happened to process it. Servers older than 0.4.15 ignore the field.
|
|
763
|
+
observation_scopes: resolveRetainScopes(tags, this.observationScopes)
|
|
764
|
+
};
|
|
765
|
+
if (opts.timestamp) item.timestamp = opts.timestamp;
|
|
766
|
+
if (opts.metadata) item.metadata = opts.metadata;
|
|
767
|
+
if (opts.updateMode) item.update_mode = opts.updateMode;
|
|
768
|
+
const body = { items: [item], async: true };
|
|
769
|
+
if (opts.operationId) body.operation_id = opts.operationId;
|
|
770
|
+
const r = await this.req("POST", this.bankUrl("/memories"), body);
|
|
771
|
+
try {
|
|
772
|
+
const j = await r.json();
|
|
773
|
+
if (j.operation_id) this.opIds.push(j.operation_id);
|
|
774
|
+
} catch {
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Whether this server honours `operation_id` on an async retain, and can therefore be appended to
|
|
779
|
+
* safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
|
|
780
|
+
* unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
|
|
781
|
+
*/
|
|
782
|
+
async supportsIdempotentRetain() {
|
|
783
|
+
if (this.idempotentRetain === void 0) {
|
|
784
|
+
this.idempotentRetain = await this.probeIdempotentRetain();
|
|
785
|
+
this.log(`server retain idempotency: ${this.idempotentRetain ? "supported" : "unavailable"}`);
|
|
786
|
+
}
|
|
787
|
+
return this.idempotentRetain;
|
|
788
|
+
}
|
|
789
|
+
async probeIdempotentRetain() {
|
|
790
|
+
try {
|
|
791
|
+
const r = await this.req("GET", `${this.apiUrl}/version`);
|
|
792
|
+
if (!r.ok) return false;
|
|
793
|
+
const j = await r.json();
|
|
794
|
+
return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
|
|
795
|
+
} catch {
|
|
796
|
+
return false;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Every document_id currently in the bank under a strategy tag (e.g. `source:git`), paginated into a
|
|
801
|
+
* Set. Powers the incremental git-sync's "what's already ingested?" check — since git commits are stored
|
|
802
|
+
* with document_id `git:<sha>`, the returned Set lets a caller diff a ref's commits against memory.
|
|
803
|
+
*/
|
|
804
|
+
async listDocumentIds(tag, tagsMatch = "all") {
|
|
805
|
+
const ids = /* @__PURE__ */ new Set();
|
|
806
|
+
const limit = 500;
|
|
807
|
+
for (let offset = 0; ; offset += limit) {
|
|
808
|
+
const q = `?tags=${encodeURIComponent(tag)}&tags_match=${tagsMatch}&limit=${limit}&offset=${offset}`;
|
|
809
|
+
const r = await this.req("GET", this.bankUrl(`/documents${q}`));
|
|
810
|
+
let items = [];
|
|
811
|
+
let total = 0;
|
|
812
|
+
try {
|
|
813
|
+
const j = await r.json();
|
|
814
|
+
items = j.items || [];
|
|
815
|
+
total = j.total ?? 0;
|
|
816
|
+
} catch {
|
|
817
|
+
break;
|
|
818
|
+
}
|
|
819
|
+
for (const it of items) if (it.id) ids.add(it.id);
|
|
820
|
+
if (items.length < limit || ids.size >= total) break;
|
|
821
|
+
}
|
|
822
|
+
return ids;
|
|
823
|
+
}
|
|
824
|
+
/** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
|
|
825
|
+
* entity labels), then seed knowledge pages when the server supports them. Both halves are
|
|
826
|
+
* idempotent and strictly ADDITIVE — nothing the bank already says is overwritten (#3927) — so
|
|
827
|
+
* the deepen engine can re-run this every pass. Creates the bank if missing; legacy servers
|
|
828
|
+
* continue with the template-only path.
|
|
829
|
+
*
|
|
830
|
+
* `manage: false` skips the config half entirely, for a bank whose owner shapes it themselves.
|
|
831
|
+
* That bank should then define the strategies this plugin writes under (`git`, `gitlog`,
|
|
832
|
+
* `conversation`, `document`, `survey`): an unknown strategy name is not an error server-side,
|
|
833
|
+
* it just falls back to the bank's own config, so the miss is silent. */
|
|
834
|
+
async configureBank(opts = {}) {
|
|
835
|
+
if (opts.reset) {
|
|
836
|
+
await this.req("DELETE", this.bankUrl());
|
|
837
|
+
this.log(`[bank] reset ${this.bank}`);
|
|
838
|
+
}
|
|
839
|
+
if (opts.manage === false) {
|
|
840
|
+
this.log(`[bank] manageBankConfig: false \u2014 leaving ${this.bank}'s configuration alone`);
|
|
841
|
+
} else {
|
|
842
|
+
const manifest = codingBankManifest(opts.reset ? void 0 : await this.readBankOverrides());
|
|
843
|
+
if (!manifest) {
|
|
844
|
+
this.log(`[bank] ${this.bank} already carries the coding structure \u2014 nothing to apply`);
|
|
845
|
+
} else {
|
|
846
|
+
await this.req("POST", this.bankUrl("/import"), manifest);
|
|
847
|
+
this.log(`[bank] applied to ${this.bank}: ${Object.keys(manifest.bank).sort().join(", ")}`);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
await this.seedPages(opts.pageTrigger);
|
|
851
|
+
}
|
|
852
|
+
/**
|
|
853
|
+
* This bank's own config OVERRIDES, or undefined when there are none to read.
|
|
854
|
+
*
|
|
855
|
+
* Deliberately the overrides and not the resolved config: an inherited global default is not
|
|
856
|
+
* something this bank's owner chose, so it must not read as "already set". `undefined` means the
|
|
857
|
+
* bank does not exist yet, or the deployment has the bank-config API switched off — in neither
|
|
858
|
+
* case can anything have been customised, so the caller seeds the full template.
|
|
859
|
+
*/
|
|
860
|
+
async readBankOverrides() {
|
|
861
|
+
try {
|
|
862
|
+
const r = await this.req("GET", this.bankUrl("/config"));
|
|
863
|
+
if (!r.ok) return void 0;
|
|
864
|
+
const j = await r.json();
|
|
865
|
+
return j.overrides ?? {};
|
|
866
|
+
} catch {
|
|
867
|
+
return void 0;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
/** Explicitly delete one document (and its cascaded memory units/links). Background sync must
|
|
871
|
+
* never use this as a cleanup primitive: a document id alone does not prove repository ownership. */
|
|
872
|
+
async deleteDocument(documentId) {
|
|
873
|
+
await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
|
|
874
|
+
}
|
|
875
|
+
/** Count of operations still ACTIVE on this bank — the list includes terminal ops (completed/
|
|
876
|
+
* failed/cancelled), so filter by status. Powers syncStatus's "extractions drained" check. */
|
|
877
|
+
async activeOperations() {
|
|
878
|
+
const r = await this.req("GET", this.bankUrl("/operations"));
|
|
879
|
+
try {
|
|
880
|
+
const j = await r.json();
|
|
881
|
+
const ops = j.operations ?? j.items ?? [];
|
|
882
|
+
return ops.filter((o) => !TERMINAL.has((o?.status || "").toLowerCase())).length;
|
|
883
|
+
} catch {
|
|
884
|
+
return 0;
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
/**
|
|
888
|
+
* Poll each enqueued operation by id until terminal. LIST only shows active ops, so per-id GET is reliable.
|
|
889
|
+
*
|
|
890
|
+
* Concurrency is capped at `maxParallelRetains` (the API rate-limits bursts, not single
|
|
891
|
+
* requests — a 200 to a lone GET with 429s under `Promise.all` over every pending op). A 429
|
|
892
|
+
* leaves the op pending and backs the next cycle off by its `Retry-After` (10s floor) instead
|
|
893
|
+
* of hammering the next cycle 5s later.
|
|
894
|
+
*/
|
|
895
|
+
async drain(ids, label, maxMs = 60 * 60 * 1e3) {
|
|
896
|
+
if (!ids.length) return;
|
|
897
|
+
this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
|
|
898
|
+
const start = Date.now();
|
|
899
|
+
const pending = new Set(ids);
|
|
900
|
+
let failed = 0;
|
|
901
|
+
while (pending.size && Date.now() - start < maxMs) {
|
|
902
|
+
let backoffMs = POLL_CYCLE_MS;
|
|
903
|
+
await pool([...pending], this.maxParallelRetains, async (id) => {
|
|
904
|
+
try {
|
|
905
|
+
const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
|
|
906
|
+
if (r.status === 429) {
|
|
907
|
+
backoffMs = Math.min(
|
|
908
|
+
RETRY_AFTER_CEILING_MS,
|
|
909
|
+
Math.max(backoffMs, RETRY_AFTER_FLOOR_MS, retryAfterMs(r.headers.get("retry-after")))
|
|
910
|
+
);
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
if (!r.ok) return;
|
|
914
|
+
const st = ((await r.json()).status || "").toLowerCase();
|
|
915
|
+
if (TERMINAL.has(st)) {
|
|
916
|
+
pending.delete(id);
|
|
917
|
+
if (st !== "completed") failed++;
|
|
918
|
+
}
|
|
919
|
+
} catch {
|
|
920
|
+
}
|
|
921
|
+
});
|
|
922
|
+
if (pending.size) {
|
|
923
|
+
this.log(` \u2026 ${pending.size}/${ids.length} ${label} ops pending`);
|
|
924
|
+
await sleep(backoffMs);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
this.log(
|
|
928
|
+
`[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
|
|
929
|
+
);
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
|
|
933
|
+
* caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
|
|
934
|
+
* magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
|
|
935
|
+
* tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
|
|
936
|
+
* tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
|
|
937
|
+
*/
|
|
938
|
+
async reflect(query, opts) {
|
|
939
|
+
const ctrl = new AbortController();
|
|
940
|
+
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
|
|
941
|
+
try {
|
|
942
|
+
const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
|
|
943
|
+
method: "POST",
|
|
944
|
+
body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
|
|
945
|
+
signal: ctrl.signal
|
|
946
|
+
});
|
|
947
|
+
if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
|
|
948
|
+
const data = await resp.json();
|
|
949
|
+
return (data.text || "").trim();
|
|
950
|
+
} finally {
|
|
951
|
+
clearTimeout(timer);
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* The bank's knowledge-base tree (folders + pages, nested). The tree carries names, source
|
|
956
|
+
* queries and staleness but NOT synthesized content, so it is cheap enough to poll.
|
|
957
|
+
*/
|
|
958
|
+
async tree() {
|
|
959
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
960
|
+
const r = await this.req("GET", this.bankUrl("/knowledge-base/tree"));
|
|
961
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
962
|
+
this.knowledgePagesSupported = false;
|
|
963
|
+
throw new KnowledgePagesUnavailableError();
|
|
964
|
+
}
|
|
965
|
+
this.knowledgePagesSupported = true;
|
|
966
|
+
try {
|
|
967
|
+
return (await r.json()).roots ?? [];
|
|
968
|
+
} catch {
|
|
969
|
+
return [];
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* List knowledge pages (ids + names only — no synthesized content), flattened out of the tree
|
|
974
|
+
* and shaped as `{items:[…]}` for `parsePageList`. Folders are dropped: they carry no content
|
|
975
|
+
* to read, and a caller enumerating pages wants leaves, not structure.
|
|
976
|
+
*
|
|
977
|
+
* NOTE the ids are knowledge-base node ids (`kp-…`), NOT the backing mental-model ids. Every
|
|
978
|
+
* page read/update in this client goes through the same knowledge-base ids, so a page id from
|
|
979
|
+
* here, from `searchKnowledgePages`, or from a `[[page:<id>]]` link all resolve identically.
|
|
980
|
+
*/
|
|
981
|
+
async listPages() {
|
|
982
|
+
const items = [];
|
|
983
|
+
const walk = (nodes, folder) => {
|
|
984
|
+
for (const n of nodes) {
|
|
985
|
+
if (!n?.id || !n?.name) continue;
|
|
986
|
+
if (n.kind === "page") {
|
|
987
|
+
items.push({
|
|
988
|
+
id: n.id,
|
|
989
|
+
name: n.name,
|
|
990
|
+
...n.description ? { description: n.description } : {},
|
|
991
|
+
...folder ? { folder } : {}
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
if (n.children?.length) walk(n.children, n.kind === "folder" ? n.name : folder);
|
|
995
|
+
}
|
|
996
|
+
};
|
|
997
|
+
walk(await this.tree());
|
|
998
|
+
return { items };
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Read one knowledge page's synthesized content by knowledge-base id, as an OKF document
|
|
1002
|
+
* (YAML frontmatter + markdown body). The endpoint omits the internal reflect trace that built
|
|
1003
|
+
* the page — that is 70-95% of the raw bytes and can blow past an MCP host's per-tool-result
|
|
1004
|
+
* token cap.
|
|
1005
|
+
*/
|
|
1006
|
+
async getPage(pageId) {
|
|
1007
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
1008
|
+
const r = await this.req(
|
|
1009
|
+
"GET",
|
|
1010
|
+
this.bankUrl(`/knowledge-base/pages/${encodeURIComponent(pageId)}`)
|
|
1011
|
+
);
|
|
1012
|
+
if (r.status === 404) throw new Error(`knowledge page not found: ${pageId}`);
|
|
1013
|
+
return await r.json();
|
|
1014
|
+
}
|
|
1015
|
+
/** Hybrid (BM25 + vector, RRF-fused) server-side search over the bank's knowledge pages.
|
|
1016
|
+
* Returns page-level hits with a relevance snippet — the real search behind
|
|
1017
|
+
* hindsight_search_knowledge_pages. */
|
|
1018
|
+
async searchKnowledgePages(query, limit = 3) {
|
|
1019
|
+
if (this.knowledgePagesSupported === false) throw new KnowledgePagesUnavailableError();
|
|
1020
|
+
const q = `?q=${encodeURIComponent(query)}&limit=${limit}`;
|
|
1021
|
+
const r = await this.req("GET", this.bankUrl(`/knowledge-base/search${q}`));
|
|
1022
|
+
const j = await r.json();
|
|
1023
|
+
return (j.results ?? []).map((x) => ({
|
|
1024
|
+
id: x.id,
|
|
1025
|
+
name: x.name,
|
|
1026
|
+
snippet: x.snippet ?? "",
|
|
1027
|
+
score: x.score ?? 0
|
|
1028
|
+
}));
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
|
|
1032
|
+
*
|
|
1033
|
+
* Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
|
|
1034
|
+
* client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
|
|
1035
|
+
* off a slug). Names are unique per folder server-side, which makes them a sound key.
|
|
1036
|
+
*
|
|
1037
|
+
* An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
|
|
1038
|
+
* `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
|
|
1039
|
+
* which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
|
|
1040
|
+
*/
|
|
1041
|
+
async seedPages(pageTrigger = buildPageTrigger()) {
|
|
1042
|
+
const pages = pagesFor(this.project ?? this.bank);
|
|
1043
|
+
const existing = /* @__PURE__ */ new Map();
|
|
1044
|
+
let roots;
|
|
1045
|
+
try {
|
|
1046
|
+
roots = await this.tree();
|
|
1047
|
+
} catch (e) {
|
|
1048
|
+
if (e instanceof KnowledgePagesUnavailableError) {
|
|
1049
|
+
this.log(`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`);
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
throw e;
|
|
1053
|
+
}
|
|
1054
|
+
for (const n of roots) {
|
|
1055
|
+
if (n.kind === "page" && n.name) existing.set(n.name.toLowerCase(), n);
|
|
1056
|
+
}
|
|
1057
|
+
let created = 0;
|
|
1058
|
+
let updated = 0;
|
|
1059
|
+
for (const page of pages) {
|
|
1060
|
+
const hit = existing.get(page.name.toLowerCase());
|
|
1061
|
+
const body = {
|
|
1062
|
+
name: page.name,
|
|
1063
|
+
source_query: page.source_query,
|
|
1064
|
+
tags: page.tags,
|
|
1065
|
+
max_tokens: PAGE_MAX_TOKENS,
|
|
1066
|
+
// Resolved HERE, not in `buildPageTrigger`: a hashed cron (`H`) needs the page's identity,
|
|
1067
|
+
// and one trigger is built per session for all of them.
|
|
1068
|
+
trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
|
|
1069
|
+
};
|
|
1070
|
+
if (!hit) {
|
|
1071
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
|
|
1072
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
1073
|
+
this.knowledgePagesSupported = false;
|
|
1074
|
+
this.log(
|
|
1075
|
+
`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
|
|
1076
|
+
);
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
if (r.status !== 409) created++;
|
|
1080
|
+
} else {
|
|
1081
|
+
const sourceDrift = hit.description !== page.source_query;
|
|
1082
|
+
const triggerDrift = hit.trigger != null && hit.trigger.tags_match !== pageTrigger.tags_match;
|
|
1083
|
+
if (!sourceDrift && !triggerDrift) continue;
|
|
1084
|
+
const patch = {};
|
|
1085
|
+
if (sourceDrift) {
|
|
1086
|
+
patch.source_query = page.source_query;
|
|
1087
|
+
patch.tags = page.tags;
|
|
1088
|
+
}
|
|
1089
|
+
if (triggerDrift) patch.trigger = pageTrigger;
|
|
1090
|
+
const r = await this.req(
|
|
1091
|
+
"PATCH",
|
|
1092
|
+
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
|
|
1093
|
+
patch
|
|
1094
|
+
);
|
|
1095
|
+
if ([404, 405, 501].includes(r.status)) {
|
|
1096
|
+
this.knowledgePagesSupported = false;
|
|
1097
|
+
this.log(
|
|
1098
|
+
`[bank] knowledge pages unavailable on ${this.apiUrl}; continuing without pages`
|
|
1099
|
+
);
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
1102
|
+
updated++;
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
this.log(
|
|
1106
|
+
`[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
|
|
1107
|
+
);
|
|
1108
|
+
}
|
|
1109
|
+
/** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
|
|
1110
|
+
slugify(s) {
|
|
1111
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* Active-path capture: register a major feature as a per-initiative page + a marker memory.
|
|
1115
|
+
* New initiative → creates a page under the Initiatives folder.
|
|
1116
|
+
* Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
|
|
1117
|
+
* enhancement or a mid-work plan change lands on the initiative it belongs to.
|
|
1118
|
+
*
|
|
1119
|
+
* The marker carries its page id in two places, neither of them a tag (#3641):
|
|
1120
|
+
* `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
|
|
1121
|
+
* expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
|
|
1122
|
+
* three channels a page synthesis actually reads — reflect's search results keep `context` and
|
|
1123
|
+
* `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
|
|
1124
|
+
* vocabulary that exists to be matched with exact set-ops.
|
|
1125
|
+
*/
|
|
1126
|
+
async captureInitiative(args) {
|
|
1127
|
+
let pageId = args.relatesToPageId;
|
|
1128
|
+
if (!pageId) {
|
|
1129
|
+
const folderId = await this.ensureFolder("Initiatives");
|
|
1130
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
|
|
1131
|
+
name: args.title,
|
|
1132
|
+
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.`,
|
|
1133
|
+
parent_id: folderId,
|
|
1134
|
+
tags: ["knowledge:feature-work"],
|
|
1135
|
+
trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
|
|
1136
|
+
});
|
|
1137
|
+
try {
|
|
1138
|
+
const j = await r.json();
|
|
1139
|
+
pageId = j.page_id ?? j.id;
|
|
1140
|
+
} catch {
|
|
1141
|
+
}
|
|
1142
|
+
pageId ||= `initiative-${this.slugify(args.title)}`;
|
|
1143
|
+
}
|
|
1144
|
+
const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
|
|
1145
|
+
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
1146
|
+
const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
|
|
1147
|
+
const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
|
|
1148
|
+
const context = `initiative marker for [[page:${pageId}]]`;
|
|
1149
|
+
await this.retain(content, context, markerId, tags, "document", {
|
|
1150
|
+
metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
|
|
1151
|
+
});
|
|
1152
|
+
return { page_id: pageId };
|
|
1153
|
+
}
|
|
1154
|
+
/** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
|
|
1155
|
+
async ensureFolder(name) {
|
|
1156
|
+
try {
|
|
1157
|
+
const tree = await (await this.req("GET", this.bankUrl("/knowledge-base/tree"))).json();
|
|
1158
|
+
const hit = (tree.roots || []).find(
|
|
1159
|
+
(n) => n.kind === "folder" && (n.name || "").toLowerCase() === name.toLowerCase()
|
|
1160
|
+
);
|
|
1161
|
+
if (hit?.id) return hit.id;
|
|
1162
|
+
} catch {
|
|
1163
|
+
}
|
|
1164
|
+
try {
|
|
1165
|
+
const r = await this.req("POST", this.bankUrl("/knowledge-base/folders"), { name });
|
|
1166
|
+
return (await r.json()).id;
|
|
1167
|
+
} catch {
|
|
1168
|
+
return void 0;
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
};
|
|
1172
|
+
|
|
1173
|
+
// src/core/config.ts
|
|
1174
|
+
var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join6(homedir2(), ".hindsight", "coding-agent.json");
|
|
1175
|
+
var DEFAULT_DAEMON_PORT = 9077;
|
|
1176
|
+
var DEFAULT_DAEMON_PROFILE = "coding-agent";
|
|
1177
|
+
function resolvePageTriggerType(raw) {
|
|
1178
|
+
if (raw.pageTriggerType === "manual") return "manual";
|
|
1179
|
+
if (raw.pageTriggerType === "cron") {
|
|
1180
|
+
const cron = raw.pageTriggerCron?.trim();
|
|
1181
|
+
if (cron && (!isHashedCron(cron) || parseHashedCron(cron))) return "cron";
|
|
1182
|
+
log.warn(
|
|
1183
|
+
"config",
|
|
1184
|
+
cron ? `pageTriggerCron ${JSON.stringify(cron)} has a malformed hashed field \u2014 write \`H\` or \`H(<lo>-<hi>)\` within the field's own range, e.g. "H H(0-5) * * *" \u2014 falling back to "auto-refresh"` : 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "H H * * *") \u2014 falling back to "auto-refresh"'
|
|
1185
|
+
);
|
|
1186
|
+
}
|
|
1187
|
+
return "auto-refresh";
|
|
1188
|
+
}
|
|
1189
|
+
var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
|
|
1190
|
+
var REFLECT_BUDGETS = ["low", "mid", "high"];
|
|
1191
|
+
function resolveReflectBudget(raw) {
|
|
1192
|
+
const value = raw.reflectBudget;
|
|
1193
|
+
if (value === void 0) return "high";
|
|
1194
|
+
if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
|
|
1195
|
+
return value;
|
|
1196
|
+
log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
|
|
1197
|
+
return "high";
|
|
1198
|
+
}
|
|
1199
|
+
var OBSERVATION_SCOPE_MODES = [
|
|
1200
|
+
"shared",
|
|
1201
|
+
"combined",
|
|
1202
|
+
"per_tag",
|
|
1203
|
+
"all_combinations",
|
|
1204
|
+
"per_source"
|
|
1205
|
+
];
|
|
1206
|
+
function resolveObservationScopes(raw) {
|
|
1207
|
+
const value = raw;
|
|
1208
|
+
if (typeof value === "string")
|
|
1209
|
+
return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
|
|
1210
|
+
if (Array.isArray(value)) {
|
|
1211
|
+
const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
|
|
1212
|
+
if (scopes.length) return scopes;
|
|
1213
|
+
}
|
|
1214
|
+
return DEFAULT_OBSERVATION_SCOPES;
|
|
1215
|
+
}
|
|
1216
|
+
function resolveConfig(raw = {}) {
|
|
1217
|
+
const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
|
|
1218
|
+
const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
|
|
1219
|
+
return {
|
|
1220
|
+
serverMode,
|
|
1221
|
+
// Daemon mode resolves the URL HERE rather than at each call site: every entry point already
|
|
1222
|
+
// builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
|
|
1223
|
+
// daemon needs no plumbing through eight separate constructors.
|
|
1224
|
+
apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
|
|
1225
|
+
apiToken: raw.apiToken || void 0,
|
|
1226
|
+
apiPort,
|
|
1227
|
+
daemonIdleTimeout: raw.daemonIdleTimeout,
|
|
1228
|
+
daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
|
|
1229
|
+
embedVersion: raw.embedVersion || void 0,
|
|
1230
|
+
embedPackagePath: raw.embedPackagePath || void 0,
|
|
1231
|
+
bankId: raw.bankId,
|
|
1232
|
+
dynamicBankId: raw.dynamicBankId,
|
|
1233
|
+
bankIdTemplate: raw.bankIdTemplate,
|
|
1234
|
+
mapPathToBank: raw.mapPathToBank,
|
|
1235
|
+
resolveWorktrees: raw.resolveWorktrees,
|
|
1236
|
+
optInOnly: raw.optInOnly ?? false,
|
|
1237
|
+
// Same shape as retainTags: a config typo must not become a path that silently approves nothing.
|
|
1238
|
+
optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
|
|
1239
|
+
harness: raw.harness ?? "opencode",
|
|
1240
|
+
disabled: raw.disabled ?? false,
|
|
1241
|
+
retainSessions: raw.retainSessions ?? true,
|
|
1242
|
+
// write sessions back by default, every harness
|
|
1243
|
+
manageBankConfig: raw.manageBankConfig ?? true,
|
|
1244
|
+
maxParallelRetains: raw.maxParallelRetains || 10,
|
|
1245
|
+
reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
|
|
1246
|
+
// Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
|
|
1247
|
+
// reflect already set), but never let it LOWER the tool below the default — a short window is
|
|
1248
|
+
// set to bound the automatic hook, not to cut off a call the agent is waiting on.
|
|
1249
|
+
reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
|
|
1250
|
+
reflectBudget: resolveReflectBudget(raw),
|
|
1251
|
+
autoReflect: raw.autoReflect ?? true,
|
|
1252
|
+
pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
|
|
1253
|
+
pageTriggerType: resolvePageTriggerType(raw),
|
|
1254
|
+
pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
|
|
1255
|
+
autoSeed: raw.autoSeed ?? true,
|
|
1256
|
+
seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
|
|
1257
|
+
codebaseSurvey: raw.codebaseSurvey ?? true,
|
|
1258
|
+
surveyModel: raw.surveyModel || "haiku",
|
|
1259
|
+
surveyBudgetUsd: raw.surveyBudgetUsd || 2,
|
|
1260
|
+
surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
|
|
1261
|
+
gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
|
|
1262
|
+
// Hostile input is a config typo, not an attack: keep only string entries so a stray number or
|
|
1263
|
+
// nested object cannot reach the API as a tag and fail the whole retain.
|
|
1264
|
+
retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
|
|
1265
|
+
retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
|
|
1266
|
+
Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
|
|
1267
|
+
) : {},
|
|
1268
|
+
observationScopes: resolveObservationScopes(raw.observationScopes),
|
|
1269
|
+
banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
|
|
1270
|
+
logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info",
|
|
1271
|
+
autoUpdate: raw.autoUpdate ?? true
|
|
1272
|
+
};
|
|
1273
|
+
}
|
|
1274
|
+
function readRaw(path) {
|
|
1275
|
+
try {
|
|
1276
|
+
return JSON.parse(readFileSync2(path, "utf8"));
|
|
1277
|
+
} catch (e) {
|
|
1278
|
+
if (e?.code !== "ENOENT") {
|
|
1279
|
+
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
1280
|
+
}
|
|
1281
|
+
return {};
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
function mergeRaw(a, b) {
|
|
1285
|
+
const { harnesses: _drop, ...flat } = b;
|
|
1286
|
+
return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
|
|
1287
|
+
}
|
|
1288
|
+
function applyLayer(raw, layer, harness) {
|
|
1289
|
+
let out = mergeRaw(raw, layer);
|
|
1290
|
+
const perHarness = harness ? layer.harnesses?.[harness] : void 0;
|
|
1291
|
+
if (perHarness) out = mergeRaw(out, perHarness);
|
|
1292
|
+
return out;
|
|
1293
|
+
}
|
|
1294
|
+
var ENV_KEYS = {
|
|
1295
|
+
serverMode: "HINDSIGHT_SERVER_MODE",
|
|
1296
|
+
apiUrl: "HINDSIGHT_API_URL",
|
|
1297
|
+
apiToken: "HINDSIGHT_API_TOKEN",
|
|
1298
|
+
// These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
|
|
1299
|
+
// it can carry their existing environment over unchanged.
|
|
1300
|
+
apiPort: "HINDSIGHT_API_PORT",
|
|
1301
|
+
daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
|
|
1302
|
+
embedVersion: "HINDSIGHT_EMBED_VERSION",
|
|
1303
|
+
embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
|
|
1304
|
+
daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
|
|
1305
|
+
bankId: "HINDSIGHT_BANK_ID",
|
|
1306
|
+
dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
|
|
1307
|
+
bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
|
|
1308
|
+
resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
|
|
1309
|
+
optInOnly: "HINDSIGHT_OPT_IN_ONLY",
|
|
1310
|
+
optInPaths: "HINDSIGHT_OPT_IN_PATHS",
|
|
1311
|
+
harness: "HINDSIGHT_HARNESS",
|
|
1312
|
+
disabled: "HINDSIGHT_DISABLED",
|
|
1313
|
+
retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
|
|
1314
|
+
maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
|
|
1315
|
+
reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
|
|
1316
|
+
reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
|
|
1317
|
+
reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
|
|
1318
|
+
autoReflect: "HINDSIGHT_AUTO_REFLECT",
|
|
1319
|
+
pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
|
|
1320
|
+
pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
|
|
1321
|
+
pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
|
|
1322
|
+
autoSeed: "HINDSIGHT_AUTO_SEED",
|
|
1323
|
+
seedLimit: "HINDSIGHT_SEED_LIMIT",
|
|
1324
|
+
codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
|
|
1325
|
+
surveyModel: "HINDSIGHT_SURVEY_MODEL",
|
|
1326
|
+
surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
|
|
1327
|
+
surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
|
|
1328
|
+
logLevel: "HINDSIGHT_LOG_LEVEL",
|
|
1329
|
+
autoUpdate: "HINDSIGHT_AUTO_UPDATE",
|
|
1330
|
+
gitIngest: "HINDSIGHT_GIT_INGEST",
|
|
1331
|
+
// Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
|
|
1332
|
+
// list is a list OF lists, which does not survive flattening into one variable — file-only.
|
|
1333
|
+
observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
|
|
1334
|
+
// Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
|
|
1335
|
+
// a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
|
|
1336
|
+
retainTags: "HINDSIGHT_RETAIN_TAGS",
|
|
1337
|
+
manageBankConfig: "HINDSIGHT_MANAGE_BANK_CONFIG"
|
|
1338
|
+
};
|
|
1339
|
+
var ENV_BOOLEANS = /* @__PURE__ */ new Set([
|
|
1340
|
+
"dynamicBankId",
|
|
1341
|
+
"resolveWorktrees",
|
|
1342
|
+
"optInOnly",
|
|
1343
|
+
"disabled",
|
|
1344
|
+
"retainSessions",
|
|
1345
|
+
"autoReflect",
|
|
1346
|
+
"autoSeed",
|
|
1347
|
+
"codebaseSurvey",
|
|
1348
|
+
"autoUpdate",
|
|
1349
|
+
"manageBankConfig"
|
|
1350
|
+
]);
|
|
1351
|
+
var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
|
|
1352
|
+
var ENV_NUMBERS = /* @__PURE__ */ new Set([
|
|
1353
|
+
"apiPort",
|
|
1354
|
+
"daemonIdleTimeout",
|
|
1355
|
+
"maxParallelRetains",
|
|
1356
|
+
"reflectTimeoutMs",
|
|
1357
|
+
"reflectToolTimeoutMs",
|
|
1358
|
+
"pageRefreshEveryTurns",
|
|
1359
|
+
"seedLimit",
|
|
1360
|
+
"surveyBudgetUsd",
|
|
1361
|
+
"surveyRefreshCommits"
|
|
1362
|
+
]);
|
|
1363
|
+
function readEnvConfig(env = process.env) {
|
|
1364
|
+
const out = {};
|
|
1365
|
+
for (const [key, name] of Object.entries(ENV_KEYS)) {
|
|
1366
|
+
const value = env[name];
|
|
1367
|
+
if (value === void 0 || value.trim() === "") continue;
|
|
1368
|
+
if (ENV_BOOLEANS.has(key)) {
|
|
1369
|
+
out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
|
|
1370
|
+
} else if (ENV_LISTS.has(key)) {
|
|
1371
|
+
const items = value.split(",").map((v) => v.trim()).filter(Boolean);
|
|
1372
|
+
if (items.length) out[key] = items;
|
|
1373
|
+
} else if (ENV_NUMBERS.has(key)) {
|
|
1374
|
+
const n = Number(value);
|
|
1375
|
+
if (Number.isFinite(n)) out[key] = n;
|
|
1376
|
+
else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
|
|
1377
|
+
} else {
|
|
1378
|
+
out[key] = value;
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
return out;
|
|
1382
|
+
}
|
|
1383
|
+
function loadConfig(opts = {}) {
|
|
1384
|
+
const o = typeof opts === "string" ? { path: opts } : opts;
|
|
1385
|
+
const withEnv = applyLayer({}, readEnvConfig(), o.harness);
|
|
1386
|
+
const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
|
|
1387
|
+
if (!raw.harness && o.harness) raw.harness = o.harness;
|
|
1388
|
+
return resolveConfig(raw);
|
|
1389
|
+
}
|
|
1390
|
+
var BANK_OVERRIDE_EXCLUDED = [
|
|
1391
|
+
"bankId",
|
|
1392
|
+
"bankIdTemplate",
|
|
1393
|
+
"mapPathToBank",
|
|
1394
|
+
"dynamicBankId",
|
|
1395
|
+
"resolveWorktrees",
|
|
1396
|
+
// Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
|
|
1397
|
+
// only ever arrive too late to matter — strip them rather than let them read as effective.
|
|
1398
|
+
"optInOnly",
|
|
1399
|
+
"optInPaths",
|
|
1400
|
+
"harness"
|
|
1401
|
+
];
|
|
1402
|
+
function applyBankConfig(cfg, resolvedId, directory) {
|
|
1403
|
+
if (directory !== void 0 && !isOptedIn(cfg, directory))
|
|
1404
|
+
return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
|
|
1405
|
+
const section = cfg.banks[resolvedId];
|
|
1406
|
+
if (!section) return { cfg, bankId: resolvedId };
|
|
1407
|
+
const safe = { ...section };
|
|
1408
|
+
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
1409
|
+
delete safe.banks;
|
|
1410
|
+
const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
|
|
1411
|
+
delete safe.bank;
|
|
1412
|
+
return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
|
|
1413
|
+
}
|
|
1414
|
+
function resolvePartial(cfg, patch) {
|
|
1415
|
+
const full = resolveConfig(patch);
|
|
1416
|
+
const out = {};
|
|
1417
|
+
for (const key of Object.keys(patch)) {
|
|
1418
|
+
if (key in full)
|
|
1419
|
+
out[key] = full[key];
|
|
1420
|
+
}
|
|
1421
|
+
return out;
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
// src/core/brand.ts
|
|
1425
|
+
function brandWord() {
|
|
1426
|
+
const start = [0, 116, 217];
|
|
1427
|
+
const end = [0, 146, 150];
|
|
1428
|
+
const word = "Hindsight";
|
|
1429
|
+
let out = "";
|
|
1430
|
+
for (let i = 0; i < word.length; i++) {
|
|
1431
|
+
const t = i / (word.length - 1);
|
|
1432
|
+
const [r, g, b] = start.map((s, k) => Math.round(s + (end[k] - s) * t));
|
|
1433
|
+
out += `\x1B[38;2;${r};${g};${b}m${word[i]}`;
|
|
1434
|
+
}
|
|
1435
|
+
return `${out}\x1B[0m`;
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
// src/core/knowledge-injection.ts
|
|
1439
|
+
function parsePageList(raw) {
|
|
1440
|
+
const items = raw?.items;
|
|
1441
|
+
if (!Array.isArray(items)) return [];
|
|
1442
|
+
const out = [];
|
|
1443
|
+
for (const it of items) {
|
|
1444
|
+
const id = it?.id;
|
|
1445
|
+
const name = it?.name;
|
|
1446
|
+
if (typeof id === "string" && typeof name === "string") out.push({ id, title: name });
|
|
1447
|
+
}
|
|
1448
|
+
return out;
|
|
1449
|
+
}
|
|
1450
|
+
function roster(pages) {
|
|
1451
|
+
return pages.map((p) => `- ${p.title} (${p.id})`).join("\n");
|
|
1452
|
+
}
|
|
1453
|
+
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>".
|
|
1454
|
+
- 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.
|
|
1455
|
+
- 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>").
|
|
1456
|
+
- 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.
|
|
1457
|
+
- 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).`;
|
|
1458
|
+
var PAGES_FIRST_ON_GOALS = "- The user just set a NEW task or goal \u2192 search the knowledge pages FIRST with hindsight_search_knowledge_pages. No synthesis is injected automatically in this configuration; call hindsight_reflect only when those pages are too shallow and deeper reasoning is needed.\n";
|
|
1459
|
+
function toolGuide(opts) {
|
|
1460
|
+
return (opts?.reflectOnNewGoals ? PAGES_FIRST_ON_GOALS : "") + TOOL_GUIDE;
|
|
1461
|
+
}
|
|
1462
|
+
function buildKnowledgePreamble(pages, opts) {
|
|
1463
|
+
const body = pages.length ? `Knowledge pages currently in this repository:
|
|
1464
|
+
${roster(pages)}` : "No knowledge pages yet \u2014 Hindsight is still learning this repo; they'll appear as it processes.";
|
|
1465
|
+
return `<hindsight_knowledge>
|
|
1466
|
+
This repository has a Hindsight memory + knowledge base (curated, continuously-updated pages plus the raw memory behind them). The tools below are registered, but you must actually CALL them at the right moments:
|
|
1467
|
+
${toolGuide(opts)}
|
|
1468
|
+
ALSO your correction tool: when you verify a Hindsight memory is wrong or stale, ingest a "Correction: <topic>" doc stating what memory claimed, what is true now, and the evidence \u2014 newer facts supersede older ones.
|
|
1469
|
+
${body}
|
|
1470
|
+
This tool guide and the page list are re-injected for you periodically as things change.
|
|
1471
|
+
</hindsight_knowledge>`;
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
// src/core/session-cache.ts
|
|
1475
|
+
import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync } from "fs";
|
|
1476
|
+
import { tmpdir as tmpdir2 } from "os";
|
|
1477
|
+
import { dirname as dirname5, join as join7 } from "path";
|
|
1478
|
+
function sessionCacheFile(harness, sessionId) {
|
|
1479
|
+
return join7(tmpdir2(), `hindsight-${harness}`, `${sessionId}.json`);
|
|
1480
|
+
}
|
|
1481
|
+
function writeFileAtomic(path, body) {
|
|
1482
|
+
mkdirSync2(dirname5(path), { recursive: true });
|
|
1483
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
1484
|
+
try {
|
|
1485
|
+
writeFileSync(tmp, body);
|
|
1486
|
+
renameSync(tmp, path);
|
|
1487
|
+
} catch (e) {
|
|
1488
|
+
try {
|
|
1489
|
+
rmSync(tmp, { force: true });
|
|
1490
|
+
} catch {
|
|
1491
|
+
}
|
|
1492
|
+
throw e;
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
function writeSessionCache(cacheFile, cache) {
|
|
1496
|
+
try {
|
|
1497
|
+
writeFileAtomic(cacheFile, JSON.stringify(cache));
|
|
1498
|
+
} catch {
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
function sessionRootFile(harness, sessionId) {
|
|
1502
|
+
return join7(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
|
|
1503
|
+
}
|
|
1504
|
+
function sessionRootDir(harness, sessionId, cwd) {
|
|
1505
|
+
if (!sessionId || !cwd) return cwd;
|
|
1506
|
+
const file = sessionRootFile(harness, sessionId);
|
|
1507
|
+
try {
|
|
1508
|
+
const recorded = readFileSync3(file, "utf8").trim();
|
|
1509
|
+
if (recorded) return recorded;
|
|
1510
|
+
} catch {
|
|
1511
|
+
}
|
|
1512
|
+
try {
|
|
1513
|
+
writeFileAtomic(file, cwd);
|
|
1514
|
+
} catch {
|
|
1515
|
+
}
|
|
1516
|
+
return cwd;
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
// src/core/retain-hook.ts
|
|
1520
|
+
import { readFileSync as readFileSync5 } from "fs";
|
|
1521
|
+
|
|
1522
|
+
// src/core/retain-cursor.ts
|
|
1523
|
+
import { createHash as createHash2 } from "crypto";
|
|
1524
|
+
var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
|
|
1525
|
+
var PENDING_MAX_BYTES = 256 * 1024;
|
|
1526
|
+
|
|
1527
|
+
// src/core/uuid.ts
|
|
1528
|
+
import { createHash as createHash3 } from "crypto";
|
|
1529
|
+
|
|
1530
|
+
// src/core/daemon.ts
|
|
1531
|
+
import { execFileSync, spawn as realSpawn2 } from "child_process";
|
|
1532
|
+
import { dirname as dirname6, join as join8 } from "path";
|
|
1533
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
1534
|
+
var DAEMON_WAIT_SESSION_START_MS = 12e3;
|
|
1535
|
+
async function isServerHealthy(baseUrl, timeoutMs = 2e3) {
|
|
1536
|
+
try {
|
|
1537
|
+
const res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(timeoutMs) });
|
|
1538
|
+
return res.ok;
|
|
1539
|
+
} catch {
|
|
1540
|
+
return false;
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
function hasRustToolchain() {
|
|
1544
|
+
if (process.platform !== "darwin") return true;
|
|
1545
|
+
try {
|
|
1546
|
+
execFileSync("cargo", ["--version"], {
|
|
1547
|
+
stdio: "pipe",
|
|
1548
|
+
timeout: 1e4,
|
|
1549
|
+
windowsHide: true
|
|
1550
|
+
});
|
|
1551
|
+
return true;
|
|
1552
|
+
} catch {
|
|
1553
|
+
return false;
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
function hasUvx() {
|
|
1557
|
+
try {
|
|
1558
|
+
execFileSync("uvx", ["--version"], {
|
|
1559
|
+
stdio: "pipe",
|
|
1560
|
+
timeout: 1e4,
|
|
1561
|
+
windowsHide: true
|
|
1562
|
+
});
|
|
1563
|
+
return true;
|
|
1564
|
+
} catch {
|
|
1565
|
+
return false;
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
var PROVIDER_PROBES = [
|
|
1569
|
+
{ provider: "openai", keyEnv: "OPENAI_API_KEY" },
|
|
1570
|
+
{ provider: "anthropic", keyEnv: "ANTHROPIC_API_KEY" },
|
|
1571
|
+
{ provider: "gemini", keyEnv: "GEMINI_API_KEY" },
|
|
1572
|
+
{ provider: "groq", keyEnv: "GROQ_API_KEY" }
|
|
1573
|
+
];
|
|
1574
|
+
function detectLlm(env = process.env) {
|
|
1575
|
+
const explicit = env.HINDSIGHT_API_LLM_PROVIDER?.trim();
|
|
1576
|
+
if (explicit) {
|
|
1577
|
+
return {
|
|
1578
|
+
provider: explicit,
|
|
1579
|
+
apiKey: env.HINDSIGHT_API_LLM_API_KEY?.trim() || void 0,
|
|
1580
|
+
source: "HINDSIGHT_API_LLM_PROVIDER"
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
for (const probe of PROVIDER_PROBES) {
|
|
1584
|
+
const key = env[probe.keyEnv]?.trim();
|
|
1585
|
+
if (key) return { provider: probe.provider, apiKey: key, source: probe.keyEnv };
|
|
1586
|
+
}
|
|
1587
|
+
if (onPath("claude")) {
|
|
1588
|
+
return { provider: "claude-code", source: "the Claude Code CLI on PATH (no API key needed)" };
|
|
1589
|
+
}
|
|
1590
|
+
return void 0;
|
|
1591
|
+
}
|
|
1592
|
+
function onPath(bin) {
|
|
1593
|
+
try {
|
|
1594
|
+
execFileSync("which", [bin], {
|
|
1595
|
+
stdio: "pipe",
|
|
1596
|
+
timeout: 5e3,
|
|
1597
|
+
windowsHide: true
|
|
1598
|
+
});
|
|
1599
|
+
return true;
|
|
1600
|
+
} catch {
|
|
1601
|
+
return false;
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
function startDaemonDetached(cfg, harness, spawnFn = realSpawn2) {
|
|
1605
|
+
try {
|
|
1606
|
+
const starter = join8(dirname6(fileURLToPath2(import.meta.url)), "daemon-start.js");
|
|
1607
|
+
const child = spawnFn("node", [starter, "--harness", harness], {
|
|
1608
|
+
detached: true,
|
|
1609
|
+
stdio: "ignore",
|
|
1610
|
+
windowsHide: true
|
|
1611
|
+
});
|
|
1612
|
+
child.on("error", () => {
|
|
1613
|
+
});
|
|
1614
|
+
child.unref();
|
|
1615
|
+
diag(harness, "daemon_start_spawned", { apiUrl: cfg.apiUrl });
|
|
1616
|
+
} catch {
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
async function ensureDaemon(cfg, harness, opts = {}) {
|
|
1620
|
+
if (cfg.serverMode !== "daemon") return;
|
|
1621
|
+
if (await isServerHealthy(cfg.apiUrl)) return;
|
|
1622
|
+
if (!preflightDaemon(cfg, harness)) return;
|
|
1623
|
+
startDaemonDetached(cfg, harness, opts.spawnFn);
|
|
1624
|
+
await waitForHealth(cfg.apiUrl, opts.waitMs ?? 0);
|
|
1625
|
+
}
|
|
1626
|
+
async function waitForHealth(baseUrl, budgetMs, pollMs = 1e3) {
|
|
1627
|
+
const deadline = Date.now() + budgetMs;
|
|
1628
|
+
while (Date.now() < deadline) {
|
|
1629
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
1630
|
+
if (await isServerHealthy(baseUrl)) return true;
|
|
1631
|
+
}
|
|
1632
|
+
return false;
|
|
1633
|
+
}
|
|
1634
|
+
function preflightDaemon(cfg, harness) {
|
|
1635
|
+
if (!hasUvx()) {
|
|
1636
|
+
diag(harness, "daemon_uvx_missing", { apiUrl: cfg.apiUrl });
|
|
1637
|
+
log.warn(harness, "daemon mode needs `uv` on PATH \u2014 see https://docs.astral.sh/uv/");
|
|
1638
|
+
return false;
|
|
1639
|
+
}
|
|
1640
|
+
if (!hasRustToolchain()) {
|
|
1641
|
+
diag(harness, "daemon_rust_missing", { platform: process.platform });
|
|
1642
|
+
log.warn(
|
|
1643
|
+
harness,
|
|
1644
|
+
"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`"
|
|
1645
|
+
);
|
|
1646
|
+
return false;
|
|
1647
|
+
}
|
|
1648
|
+
if (!detectLlm()) {
|
|
1649
|
+
diag(harness, "daemon_no_llm", {});
|
|
1650
|
+
log.warn(
|
|
1651
|
+
harness,
|
|
1652
|
+
"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"
|
|
1653
|
+
);
|
|
1654
|
+
return false;
|
|
1655
|
+
}
|
|
1656
|
+
return true;
|
|
1657
|
+
}
|
|
1658
|
+
|
|
1659
|
+
// src/core/retain-stamp.ts
|
|
1660
|
+
import { basename as basename2 } from "path";
|
|
1661
|
+
var RESERVED_TAG_PREFIX = /^(source|harness):/;
|
|
1662
|
+
function resolversFor(ctx) {
|
|
1663
|
+
return {
|
|
1664
|
+
// Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
|
|
1665
|
+
// otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
|
|
1666
|
+
gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
|
|
1667
|
+
project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
|
|
1668
|
+
harness: () => ctx.harness,
|
|
1669
|
+
bankId: () => ctx.bankId,
|
|
1670
|
+
sessionId: () => ctx.sessionId ?? "unknown",
|
|
1671
|
+
timestamp: () => (/* @__PURE__ */ new Date()).toISOString(),
|
|
1672
|
+
channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
|
|
1673
|
+
user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
function buildRetainStamp(cfg, ctx) {
|
|
1677
|
+
const hasTags = Boolean(cfg.retainTags?.length);
|
|
1678
|
+
const hasMetadata = Boolean(cfg.retainMetadata && Object.keys(cfg.retainMetadata).length);
|
|
1679
|
+
if (!hasTags && !hasMetadata) return { tags: [], metadata: {} };
|
|
1680
|
+
const base = resolversFor(ctx);
|
|
1681
|
+
const cache = /* @__PURE__ */ new Map();
|
|
1682
|
+
const resolvers = Object.fromEntries(
|
|
1683
|
+
Object.entries(base).map(([name, resolve3]) => [
|
|
1684
|
+
name,
|
|
1685
|
+
() => {
|
|
1686
|
+
const hit = cache.get(name);
|
|
1687
|
+
if (hit !== void 0) return hit;
|
|
1688
|
+
const value = resolve3();
|
|
1689
|
+
cache.set(name, value);
|
|
1690
|
+
return value;
|
|
1691
|
+
}
|
|
1692
|
+
])
|
|
1693
|
+
);
|
|
1694
|
+
const tags = (cfg.retainTags ?? []).map((t) => applyTemplate(t, resolvers, "retainTags").trim()).filter(Boolean).filter((t) => {
|
|
1695
|
+
if (!RESERVED_TAG_PREFIX.test(t)) return true;
|
|
1696
|
+
log.warn("retain-stamp", "ignoring reserved retainTags entry", { tag: t });
|
|
1697
|
+
return false;
|
|
1698
|
+
});
|
|
1699
|
+
const metadata = {};
|
|
1700
|
+
for (const [key, value] of Object.entries(cfg.retainMetadata ?? {})) {
|
|
1701
|
+
metadata[key] = applyTemplate(value, resolvers, "retainMetadata");
|
|
1702
|
+
}
|
|
1703
|
+
return { tags, metadata };
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
// src/core/jsonl.ts
|
|
1707
|
+
import { closeSync, openSync, readSync, statSync } from "fs";
|
|
1708
|
+
import { StringDecoder } from "string_decoder";
|
|
1709
|
+
var CHUNK_BYTES = 64 * 1024;
|
|
1710
|
+
var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
|
|
1711
|
+
function readJsonlTail(path, opts) {
|
|
1712
|
+
const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
|
|
1713
|
+
let size;
|
|
1714
|
+
try {
|
|
1715
|
+
size = statSync(path).size;
|
|
1716
|
+
} catch {
|
|
1717
|
+
return { lines: emptyLines(), skippedBytes: 0 };
|
|
1718
|
+
}
|
|
1719
|
+
const skippedBytes = size > maxBytes ? size - maxBytes : 0;
|
|
1720
|
+
if (skippedBytes > 0) {
|
|
1721
|
+
log.warn(opts.scope, "transcript too large \u2014 retaining the most recent portion only", {
|
|
1722
|
+
path,
|
|
1723
|
+
sizeBytes: size,
|
|
1724
|
+
skippedBytes
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
return { lines: streamLines(path, skippedBytes), skippedBytes };
|
|
1728
|
+
}
|
|
1729
|
+
function* emptyLines() {
|
|
1730
|
+
}
|
|
1731
|
+
function* streamLines(path, start) {
|
|
1732
|
+
let fd;
|
|
1733
|
+
try {
|
|
1734
|
+
fd = openSync(path, "r");
|
|
1735
|
+
} catch {
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
try {
|
|
1739
|
+
const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
|
|
1740
|
+
const decoder = new StringDecoder("utf8");
|
|
1741
|
+
let pending = "";
|
|
1742
|
+
let position = start > 0 ? start - 1 : 0;
|
|
1743
|
+
let dropPartial = start > 0;
|
|
1744
|
+
for (; ; ) {
|
|
1745
|
+
const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
|
|
1746
|
+
if (bytesRead <= 0) break;
|
|
1747
|
+
position += bytesRead;
|
|
1748
|
+
pending += decoder.write(buffer.subarray(0, bytesRead));
|
|
1749
|
+
let newline;
|
|
1750
|
+
while ((newline = pending.indexOf("\n")) !== -1) {
|
|
1751
|
+
const line = pending.slice(0, newline);
|
|
1752
|
+
pending = pending.slice(newline + 1);
|
|
1753
|
+
if (dropPartial) {
|
|
1754
|
+
dropPartial = false;
|
|
1755
|
+
continue;
|
|
1756
|
+
}
|
|
1757
|
+
yield line;
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
pending += decoder.end();
|
|
1761
|
+
if (pending && !dropPartial) yield pending;
|
|
1762
|
+
} finally {
|
|
1763
|
+
closeSync(fd);
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
// src/core/transcript-util.ts
|
|
1768
|
+
var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
|
|
1769
|
+
function stripInjectedMemory(s) {
|
|
1770
|
+
return s.replace(MEMORY_TAG_RE, "");
|
|
1771
|
+
}
|
|
1772
|
+
var TARGET_KEYS = [
|
|
1773
|
+
"file_path",
|
|
1774
|
+
"path",
|
|
1775
|
+
"notebook_path",
|
|
1776
|
+
"command",
|
|
1777
|
+
"pattern",
|
|
1778
|
+
"query",
|
|
1779
|
+
"url",
|
|
1780
|
+
"name",
|
|
1781
|
+
"id"
|
|
1782
|
+
];
|
|
1783
|
+
var ACTION_TARGET_CAP = 100;
|
|
1784
|
+
function actionLine(tool, input) {
|
|
1785
|
+
let target = "";
|
|
1786
|
+
if (input && typeof input === "object") {
|
|
1787
|
+
const rec = input;
|
|
1788
|
+
for (const k of TARGET_KEYS) {
|
|
1789
|
+
const v = rec[k];
|
|
1790
|
+
if (typeof v === "string" && v.trim()) {
|
|
1791
|
+
target = v.trim().split("\n")[0];
|
|
1792
|
+
break;
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
} else if (typeof input === "string") {
|
|
1796
|
+
target = input.trim().split("\n")[0];
|
|
1797
|
+
}
|
|
1798
|
+
if (target.length > ACTION_TARGET_CAP) target = `${target.slice(0, ACTION_TARGET_CAP)}\u2026`;
|
|
1799
|
+
return target ? `${tool} ${target}` : tool;
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
// src/core/session-start.ts
|
|
1803
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
1804
|
+
|
|
1805
|
+
// src/core/git.ts
|
|
1806
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
1807
|
+
import { resolve as resolve2 } from "path";
|
|
1808
|
+
function git(repo, ...args) {
|
|
1809
|
+
return execFileSync2("git", ["-C", repo, ...args], {
|
|
1810
|
+
encoding: "utf8",
|
|
1811
|
+
maxBuffer: 1 << 28,
|
|
1812
|
+
windowsHide: true
|
|
1813
|
+
});
|
|
1814
|
+
}
|
|
1815
|
+
function repoNameOf(repo) {
|
|
1816
|
+
return projectNameOf(resolve2(repo));
|
|
1817
|
+
}
|
|
1818
|
+
function gitHeadSha(dir) {
|
|
1819
|
+
try {
|
|
1820
|
+
return git(dir, "rev-parse", "HEAD").trim() || null;
|
|
1821
|
+
} catch {
|
|
1822
|
+
return null;
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
function commitsSince(dir, sinceSha) {
|
|
1826
|
+
try {
|
|
1827
|
+
const n = Number.parseInt(git(dir, "rev-list", "--count", `${sinceSha}..HEAD`).trim(), 10);
|
|
1828
|
+
return Number.isFinite(n) ? n : null;
|
|
1829
|
+
} catch {
|
|
1830
|
+
return null;
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
function hasGitHistory(dir) {
|
|
1834
|
+
try {
|
|
1835
|
+
return git(dir, "rev-list", "--max-count=1", "HEAD").trim().length > 0;
|
|
1836
|
+
} catch {
|
|
1837
|
+
return false;
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
// src/core/status.ts
|
|
1842
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
1843
|
+
|
|
1844
|
+
// src/core/survey.ts
|
|
1845
|
+
import { spawn as realSpawn3 } from "child_process";
|
|
1846
|
+
import { existsSync as existsSync3 } from "fs";
|
|
1847
|
+
import { homedir as homedir3 } from "os";
|
|
1848
|
+
import { dirname as dirname7, join as join9 } from "path";
|
|
1849
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
1850
|
+
var SURVEY_DOC_IDS = [
|
|
1851
|
+
"repository-component-map",
|
|
1852
|
+
"repository-core-concepts",
|
|
1853
|
+
"repository-conventions-and-patterns",
|
|
1854
|
+
"repository-tech-stack-and-features"
|
|
1855
|
+
];
|
|
1856
|
+
function resolveClaudeBin(explicit) {
|
|
1857
|
+
if (explicit) return explicit;
|
|
1858
|
+
if (process.env.HINDSIGHT_CLAUDE_BIN) return process.env.HINDSIGHT_CLAUDE_BIN;
|
|
1859
|
+
const nativeInstallPath = join9(homedir3(), ".claude", "local", "claude");
|
|
1860
|
+
try {
|
|
1861
|
+
if (existsSync3(nativeInstallPath)) return nativeInstallPath;
|
|
1862
|
+
} catch {
|
|
1863
|
+
}
|
|
1864
|
+
return "claude";
|
|
1865
|
+
}
|
|
1866
|
+
var SURVEY_AGENT = "hindsight-survey";
|
|
1867
|
+
function resolveAgentBin(harness, claudeBin) {
|
|
1868
|
+
switch (harness) {
|
|
1869
|
+
case "claude-code":
|
|
1870
|
+
return resolveClaudeBin(claudeBin);
|
|
1871
|
+
case "codex":
|
|
1872
|
+
return process.env.HINDSIGHT_CODEX_BIN || "codex";
|
|
1873
|
+
case "antigravity-cli":
|
|
1874
|
+
return process.env.HINDSIGHT_ANTIGRAVITY_BIN || "agy";
|
|
1875
|
+
case "opencode":
|
|
1876
|
+
return process.env.HINDSIGHT_OPENCODE_BIN || "opencode";
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
var SURVEY_PROMPT = 'You are performing a one-time structural survey of THIS repository to seed its Hindsight memory. Work efficiently \u2014 DO NOT read every file; sample enough to understand the architecture: the directory layout, entry points, package manifests (package.json / pyproject.toml / Cargo.toml / go.mod), the README, and a few representative source files per major area. Use Glob (e.g. `**/*`) to see the directory layout \u2014 Read takes a FILE path only and errors on a directory; never call Read on a bare directory path.\nIMPORTANT \u2014 DO NOT read, quote, summarize, or ingest agent-instruction files: CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*, or .github/copilot-instructions.md. These are live, user-controlled instructions (not repository knowledge); capturing them as memory would let a stale copy override the user\'s current instructions. Exclude them entirely from your survey and from every ingested document.\nThen use the hindsight_ingest_document tool to save what you learned as separate documents (one call each), with these titles and factual, developer-oriented content grounded in what you actually saw:\n- "Repository component map": the top-level modules/directories, each one\'s responsibility, and how they connect (data flow / dependencies).\n- "Repository core concepts": the domain model and key abstractions a new contributor must understand.\n- "Repository conventions and patterns": naming, file/module organization, testing approach, error handling, and other recurring patterns.\n- "Repository tech stack and features": languages, frameworks, build/test tooling, and the notable features the project provides.\nKeep each a few hundred words. When done, stop.';
|
|
1880
|
+
var SURVEY_DISALLOWED_TOOLS = [
|
|
1881
|
+
"Bash",
|
|
1882
|
+
"Write",
|
|
1883
|
+
"Edit",
|
|
1884
|
+
"NotebookEdit",
|
|
1885
|
+
"WebFetch",
|
|
1886
|
+
"WebSearch",
|
|
1887
|
+
"Task"
|
|
1888
|
+
];
|
|
1889
|
+
function buildSurveyPlan(harness, bin, repoDir, opts) {
|
|
1890
|
+
const env = {
|
|
1891
|
+
...process.env,
|
|
1892
|
+
// Anti-recursion: the survey's own agent session must not fire our hooks (session-start,
|
|
1893
|
+
// UserPromptSubmit/BeforeAgent, Stop/SessionEnd) or re-seed — see the HINDSIGHT_DISABLE_HOOKS
|
|
1894
|
+
// guard in hook.ts / retain-hook.ts / session-start.ts / runtime.ts.
|
|
1895
|
+
HINDSIGHT_DISABLE_HOOKS: "1",
|
|
1896
|
+
// Bank scoping for the MCP server the survey agent spawns.
|
|
1897
|
+
HINDSIGHT_MCP_PROJECT_CWD: repoDir
|
|
1898
|
+
};
|
|
1899
|
+
switch (harness) {
|
|
1900
|
+
case "claude-code": {
|
|
1901
|
+
const mcpConfig = JSON.stringify({
|
|
1902
|
+
mcpServers: {
|
|
1903
|
+
hindsight: {
|
|
1904
|
+
command: "node",
|
|
1905
|
+
args: [opts.mcpServerPath],
|
|
1906
|
+
// HINDSIGHT_MCP_HARNESS names the agent whose CLI this recipe drives — the survey's
|
|
1907
|
+
// ingests are its writes. mcp-server.js REQUIRES it (it used to default to
|
|
1908
|
+
// "claude-code", which is how the codex recipe below silently stamped its findings
|
|
1909
|
+
// harness:claude-code and wrote them to Claude Code's bank — #3603).
|
|
1910
|
+
env: { HINDSIGHT_MCP_PROJECT_CWD: repoDir, HINDSIGHT_MCP_HARNESS: "claude-code" }
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
});
|
|
1914
|
+
return {
|
|
1915
|
+
bin,
|
|
1916
|
+
args: [
|
|
1917
|
+
"-p",
|
|
1918
|
+
SURVEY_PROMPT,
|
|
1919
|
+
"--model",
|
|
1920
|
+
opts.model ?? "haiku",
|
|
1921
|
+
"--mcp-config",
|
|
1922
|
+
mcpConfig,
|
|
1923
|
+
"--strict-mcp-config",
|
|
1924
|
+
"--allowedTools",
|
|
1925
|
+
"Read",
|
|
1926
|
+
"Glob",
|
|
1927
|
+
"Grep",
|
|
1928
|
+
"mcp__hindsight__hindsight_ingest_document",
|
|
1929
|
+
"--disallowedTools",
|
|
1930
|
+
...SURVEY_DISALLOWED_TOOLS,
|
|
1931
|
+
"--max-budget-usd",
|
|
1932
|
+
String(opts.budgetUsd ?? 2)
|
|
1933
|
+
],
|
|
1934
|
+
env
|
|
1935
|
+
};
|
|
1936
|
+
}
|
|
1937
|
+
case "codex": {
|
|
1938
|
+
return {
|
|
1939
|
+
bin,
|
|
1940
|
+
args: [
|
|
1941
|
+
"exec",
|
|
1942
|
+
"--sandbox",
|
|
1943
|
+
"read-only",
|
|
1944
|
+
"-c",
|
|
1945
|
+
`mcp_servers.hindsight.command="node"`,
|
|
1946
|
+
"-c",
|
|
1947
|
+
`mcp_servers.hindsight.args=["${opts.mcpServerPath}"]`,
|
|
1948
|
+
"-c",
|
|
1949
|
+
`mcp_servers.hindsight.env.HINDSIGHT_MCP_PROJECT_CWD="${repoDir}"`,
|
|
1950
|
+
"-c",
|
|
1951
|
+
`mcp_servers.hindsight.env.HINDSIGHT_MCP_HARNESS="codex"`,
|
|
1952
|
+
SURVEY_PROMPT
|
|
1953
|
+
],
|
|
1954
|
+
env
|
|
1955
|
+
};
|
|
1956
|
+
}
|
|
1957
|
+
case "antigravity-cli": {
|
|
1958
|
+
return {
|
|
1959
|
+
bin,
|
|
1960
|
+
args: ["-p", SURVEY_PROMPT, "--mode=plan"],
|
|
1961
|
+
env
|
|
1962
|
+
};
|
|
1963
|
+
}
|
|
1964
|
+
case "opencode": {
|
|
1965
|
+
return {
|
|
1966
|
+
bin,
|
|
1967
|
+
args: ["run", "--agent", SURVEY_AGENT, SURVEY_PROMPT],
|
|
1968
|
+
env
|
|
1969
|
+
};
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
function startCodebaseSurvey(repoDir, opts = {}) {
|
|
1974
|
+
try {
|
|
1975
|
+
const spawnFn = opts.spawn ?? realSpawn3;
|
|
1976
|
+
const exists = opts.exists ?? binOnPath;
|
|
1977
|
+
const mcpServerPath = opts.mcpServerPath ?? join9(dirname7(fileURLToPath3(import.meta.url)), "mcp-server.js");
|
|
1978
|
+
const preferred = opts.harness ?? "claude-code";
|
|
1979
|
+
const order = [
|
|
1980
|
+
preferred,
|
|
1981
|
+
"claude-code",
|
|
1982
|
+
"codex",
|
|
1983
|
+
"antigravity-cli",
|
|
1984
|
+
"opencode"
|
|
1985
|
+
];
|
|
1986
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1987
|
+
for (const harness of order) {
|
|
1988
|
+
if (seen.has(harness)) continue;
|
|
1989
|
+
seen.add(harness);
|
|
1990
|
+
const bin = resolveAgentBin(harness, opts.claudeBin);
|
|
1991
|
+
if (!exists(bin)) continue;
|
|
1992
|
+
const plan = buildSurveyPlan(harness, bin, repoDir, {
|
|
1993
|
+
model: opts.model,
|
|
1994
|
+
budgetUsd: opts.budgetUsd,
|
|
1995
|
+
mcpServerPath
|
|
1996
|
+
});
|
|
1997
|
+
const child = spawnFn(plan.bin, plan.args, {
|
|
1998
|
+
cwd: repoDir,
|
|
1999
|
+
detached: true,
|
|
2000
|
+
stdio: "ignore",
|
|
2001
|
+
windowsHide: true,
|
|
2002
|
+
env: plan.env
|
|
2003
|
+
});
|
|
2004
|
+
child.on("error", () => {
|
|
2005
|
+
});
|
|
2006
|
+
child.unref();
|
|
2007
|
+
return;
|
|
2008
|
+
}
|
|
2009
|
+
} catch {
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
// src/core/status.ts
|
|
2014
|
+
var DEEPEN_DIFF_TARGET = 300;
|
|
2015
|
+
|
|
2016
|
+
// src/core/auto-update.ts
|
|
2017
|
+
import { spawn as realSpawn4 } from "child_process";
|
|
2018
|
+
import {
|
|
2019
|
+
existsSync as existsSync4,
|
|
2020
|
+
mkdirSync as mkdirSync3,
|
|
2021
|
+
readFileSync as readFileSync6,
|
|
2022
|
+
realpathSync as realpathSync2,
|
|
2023
|
+
unlinkSync,
|
|
2024
|
+
writeFileSync as writeFileSync2
|
|
2025
|
+
} from "fs";
|
|
2026
|
+
import { homedir as homedir4, tmpdir as tmpdir3 } from "os";
|
|
2027
|
+
import { dirname as dirname8, join as join10 } from "path";
|
|
2028
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
2029
|
+
var PACKAGE_NAME = "@vectorize-io/hindsight-coding-agents";
|
|
2030
|
+
var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
2031
|
+
var FETCH_TIMEOUT_MS = 5e3;
|
|
2032
|
+
function stateFile(runtimeDir) {
|
|
2033
|
+
return join10(runtimeDir, ".update-check.json");
|
|
2034
|
+
}
|
|
2035
|
+
function packageRoot() {
|
|
2036
|
+
return join10(dirname8(fileURLToPath4(import.meta.url)), "..");
|
|
2037
|
+
}
|
|
2038
|
+
function stagedRuntimeDir() {
|
|
2039
|
+
return join10(homedir4(), ".hindsight", "coding-agents");
|
|
2040
|
+
}
|
|
2041
|
+
function sameDir(a, b) {
|
|
2042
|
+
try {
|
|
2043
|
+
return realpathSync2(a) === realpathSync2(b);
|
|
2044
|
+
} catch {
|
|
2045
|
+
return a === b;
|
|
2046
|
+
}
|
|
2047
|
+
}
|
|
2048
|
+
function stagedVersion(pkgRoot) {
|
|
2049
|
+
try {
|
|
2050
|
+
const pkg = JSON.parse(readFileSync6(join10(pkgRoot, "package.json"), "utf8"));
|
|
2051
|
+
return typeof pkg.version === "string" ? pkg.version : "";
|
|
2052
|
+
} catch {
|
|
2053
|
+
return "";
|
|
2054
|
+
}
|
|
2055
|
+
}
|
|
2056
|
+
function isNewer(candidate, current2) {
|
|
2057
|
+
const parse = (v) => {
|
|
2058
|
+
const [core = "", ...rest] = v.trim().split("-");
|
|
2059
|
+
return {
|
|
2060
|
+
nums: core.split(".").map((n) => Number.parseInt(n, 10)),
|
|
2061
|
+
pre: rest.length > 0
|
|
2062
|
+
};
|
|
2063
|
+
};
|
|
2064
|
+
const a = parse(candidate);
|
|
2065
|
+
const b = parse(current2);
|
|
2066
|
+
if (a.nums.length !== 3 || b.nums.length !== 3) return false;
|
|
2067
|
+
if (a.nums.some(Number.isNaN) || b.nums.some(Number.isNaN)) return false;
|
|
2068
|
+
for (let i = 0; i < 3; i++) {
|
|
2069
|
+
if (a.nums[i] !== b.nums[i]) return a.nums[i] > b.nums[i];
|
|
2070
|
+
}
|
|
2071
|
+
return b.pre && !a.pre;
|
|
2072
|
+
}
|
|
2073
|
+
function dueForCheck(file, now) {
|
|
2074
|
+
try {
|
|
2075
|
+
const state = JSON.parse(readFileSync6(file, "utf8"));
|
|
2076
|
+
return typeof state.lastCheck !== "number" || now - state.lastCheck >= CHECK_INTERVAL_MS;
|
|
2077
|
+
} catch {
|
|
2078
|
+
return true;
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
2081
|
+
var ORIGIN_FILE = ".install-origin.json";
|
|
2082
|
+
function selfUpdatable(runtimeDir) {
|
|
2083
|
+
try {
|
|
2084
|
+
const origin = JSON.parse(readFileSync6(join10(runtimeDir, ORIGIN_FILE), "utf8"));
|
|
2085
|
+
if (typeof origin.source !== "string" || !origin.source) return false;
|
|
2086
|
+
return origin.source.split(/[\\/]/).includes("_npx");
|
|
2087
|
+
} catch {
|
|
2088
|
+
return false;
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
var LOCK_STALE_MS = 10 * 60 * 1e3;
|
|
2092
|
+
function lockFile() {
|
|
2093
|
+
return join10(tmpdir3(), "hindsight-coding-agent", "auto-update.lock");
|
|
2094
|
+
}
|
|
2095
|
+
function acquireUpdateLock(file, now) {
|
|
2096
|
+
try {
|
|
2097
|
+
const held = JSON.parse(readFileSync6(file, "utf8"));
|
|
2098
|
+
if (held.ts && now - held.ts < LOCK_STALE_MS) {
|
|
2099
|
+
let holderAlive = false;
|
|
2100
|
+
if (held.pid) {
|
|
2101
|
+
try {
|
|
2102
|
+
process.kill(held.pid, 0);
|
|
2103
|
+
holderAlive = true;
|
|
2104
|
+
} catch {
|
|
2105
|
+
}
|
|
2106
|
+
}
|
|
2107
|
+
if (holderAlive) return false;
|
|
2108
|
+
}
|
|
2109
|
+
} catch {
|
|
2110
|
+
}
|
|
2111
|
+
try {
|
|
2112
|
+
mkdirSync3(dirname8(file), { recursive: true });
|
|
2113
|
+
writeFileSync2(file, JSON.stringify({ pid: process.pid, ts: now }));
|
|
2114
|
+
return true;
|
|
2115
|
+
} catch {
|
|
2116
|
+
return false;
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
function holdLockFor(file, pid, now) {
|
|
2120
|
+
try {
|
|
2121
|
+
if (pid === void 0) return releaseUpdateLock(file);
|
|
2122
|
+
writeFileSync2(file, JSON.stringify({ pid, ts: now }));
|
|
2123
|
+
} catch {
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
function releaseUpdateLock(file) {
|
|
2127
|
+
try {
|
|
2128
|
+
unlinkSync(file);
|
|
2129
|
+
} catch {
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
function stampCheck(file, now, latest) {
|
|
2133
|
+
try {
|
|
2134
|
+
writeFileSync2(file, JSON.stringify({ lastCheck: now, latest }));
|
|
2135
|
+
} catch {
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
async function latestVersion(fetchImpl) {
|
|
2139
|
+
try {
|
|
2140
|
+
const r = await fetchImpl(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, {
|
|
2141
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
|
|
2142
|
+
});
|
|
2143
|
+
if (!r.ok) return "";
|
|
2144
|
+
const body = await r.json();
|
|
2145
|
+
return typeof body.version === "string" ? body.version : "";
|
|
2146
|
+
} catch {
|
|
2147
|
+
return "";
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
async function maybeAutoUpdate(cfg, opts = {}) {
|
|
2151
|
+
try {
|
|
2152
|
+
if (!cfg.autoUpdate) return "";
|
|
2153
|
+
if (process.env.HINDSIGHT_DISABLE_HOOKS) return "";
|
|
2154
|
+
const pkgRoot = opts.pkgRoot ?? packageRoot();
|
|
2155
|
+
const runtime = opts.runtimeDir ?? stagedRuntimeDir();
|
|
2156
|
+
if (!existsSync4(runtime)) return "";
|
|
2157
|
+
if (!sameDir(pkgRoot, runtime)) return "";
|
|
2158
|
+
const now = opts.now ?? Date.now();
|
|
2159
|
+
const file = stateFile(runtime);
|
|
2160
|
+
if (!dueForCheck(file, now)) return "";
|
|
2161
|
+
const current2 = stagedVersion(pkgRoot);
|
|
2162
|
+
if (!current2) return "";
|
|
2163
|
+
if (!(opts.selfUpdatable ?? selfUpdatable)(runtime)) {
|
|
2164
|
+
log.info("auto-update", "runtime is managed outside npx \u2014 leaving its version alone");
|
|
2165
|
+
stampCheck(file, now, "");
|
|
2166
|
+
return "";
|
|
2167
|
+
}
|
|
2168
|
+
if (!(opts.binOnPath ?? binOnPath)("npx")) {
|
|
2169
|
+
log.info("auto-update", "npx is not on PATH \u2014 skipping the update check");
|
|
2170
|
+
stampCheck(file, now, "");
|
|
2171
|
+
return "";
|
|
2172
|
+
}
|
|
2173
|
+
const lock = opts.lockFile ?? lockFile();
|
|
2174
|
+
if (!acquireUpdateLock(lock, now)) return "";
|
|
2175
|
+
try {
|
|
2176
|
+
const latest = await latestVersion(opts.fetch ?? fetch);
|
|
2177
|
+
stampCheck(file, now, latest);
|
|
2178
|
+
if (!latest || !isNewer(latest, current2)) {
|
|
2179
|
+
releaseUpdateLock(lock);
|
|
2180
|
+
return "";
|
|
2181
|
+
}
|
|
2182
|
+
log.info("auto-update", `updating the Hindsight runtime ${current2} -> ${latest}`);
|
|
2183
|
+
const child = (opts.spawn ?? realSpawn4)(
|
|
2184
|
+
"npx",
|
|
2185
|
+
["-y", `${PACKAGE_NAME}@${latest}`, "update"],
|
|
2186
|
+
{
|
|
2187
|
+
detached: true,
|
|
2188
|
+
stdio: "ignore",
|
|
2189
|
+
windowsHide: true
|
|
2190
|
+
}
|
|
2191
|
+
);
|
|
2192
|
+
child.on("error", (e) => {
|
|
2193
|
+
log.warn("auto-update", `update spawn failed: ${e.message}`);
|
|
2194
|
+
releaseUpdateLock(lock);
|
|
2195
|
+
});
|
|
2196
|
+
child.unref();
|
|
2197
|
+
holdLockFor(lock, child.pid, now);
|
|
2198
|
+
return latest;
|
|
2199
|
+
} catch (e) {
|
|
2200
|
+
releaseUpdateLock(lock);
|
|
2201
|
+
throw e;
|
|
2202
|
+
}
|
|
2203
|
+
} catch {
|
|
2204
|
+
return "";
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
|
|
2208
|
+
// src/core/skill-sync.ts
|
|
2209
|
+
import { cpSync, existsSync as existsSync5, readFileSync as readFileSync7 } from "fs";
|
|
2210
|
+
import { homedir as homedir5 } from "os";
|
|
2211
|
+
import { dirname as dirname9, join as join11 } from "path";
|
|
2212
|
+
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
2213
|
+
|
|
2214
|
+
// src/core/skill-dirs.ts
|
|
2215
|
+
var SKILL_DIRS = {
|
|
2216
|
+
"claude-code": [".claude", "skills"],
|
|
2217
|
+
// Codex and dsh share the agentskills-standard root; uninstalling either removes the one copy.
|
|
2218
|
+
codex: [".agents", "skills"],
|
|
2219
|
+
dsh: [".agents", "skills"],
|
|
2220
|
+
"antigravity-cli": [".gemini", "config", "skills"],
|
|
2221
|
+
"cursor-cli": [".cursor", "skills"],
|
|
2222
|
+
"copilot-cli": [".copilot", "skills"],
|
|
2223
|
+
"grok-build": [".grok", "skills"],
|
|
2224
|
+
"cline-cli": [".cline", "data", "settings", "skills"],
|
|
2225
|
+
"qwen-code": [".qwen", "skills"],
|
|
2226
|
+
// Qwen's user-level skills root (Storage.getUserSkillsDirs)
|
|
2227
|
+
"factory-droid": [".factory", "skills"],
|
|
2228
|
+
// Droid's user-level skills root
|
|
2229
|
+
// The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
|
|
2230
|
+
// by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
|
|
2231
|
+
// and dsh's copy with it.
|
|
2232
|
+
pi: [".pi", "agent", "skills"],
|
|
2233
|
+
"prime-agent": [".prime", "agent", "skills"]
|
|
2234
|
+
};
|
|
2235
|
+
|
|
2236
|
+
// src/core/skill-sync.ts
|
|
2237
|
+
function packagedSkillDir() {
|
|
2238
|
+
return join11(dirname9(fileURLToPath5(import.meta.url)), "..", "skill");
|
|
2239
|
+
}
|
|
2240
|
+
function syncCompanionSkill(harness, opts = {}) {
|
|
2241
|
+
try {
|
|
2242
|
+
const parts = SKILL_DIRS[harness];
|
|
2243
|
+
if (!parts) return;
|
|
2244
|
+
const src = opts.srcDir ?? packagedSkillDir();
|
|
2245
|
+
const srcMd = join11(src, "SKILL.md");
|
|
2246
|
+
if (!existsSync5(srcMd)) return;
|
|
2247
|
+
const dst = join11(opts.home ?? homedir5(), ...parts, "hindsight-coding-agent");
|
|
2248
|
+
const dstMd = join11(dst, "SKILL.md");
|
|
2249
|
+
if (!existsSync5(dstMd)) return;
|
|
2250
|
+
if (readFileSync7(srcMd, "utf8") !== readFileSync7(dstMd, "utf8")) {
|
|
2251
|
+
cpSync(src, dst, { recursive: true });
|
|
2252
|
+
}
|
|
2253
|
+
} catch {
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
|
|
2257
|
+
// src/core/session-start.ts
|
|
2258
|
+
function buildSeedBanner(bankId, cold = true, gitNote) {
|
|
2259
|
+
const headline = cold ? `${brandWord()} is learning this repo \u2014 ingesting its decisions, conventions and history` : `${brandWord()} is tracking the decisions, conventions and history of this repo`;
|
|
2260
|
+
const details = ` \u21B3 memory bank \u201C${bankId}\u201D` + (gitNote ? ` \xB7 ${gitNote}` : "");
|
|
2261
|
+
return `${headline}
|
|
2262
|
+
${details}`;
|
|
2263
|
+
}
|
|
2264
|
+
async function gitSyncNote(args) {
|
|
2265
|
+
const { client, cwd, gitIds, mode, cold } = args;
|
|
2266
|
+
if (mode === "none" || cold) return void 0;
|
|
2267
|
+
const head = gitHeadSha(cwd);
|
|
2268
|
+
if (!head) return void 0;
|
|
2269
|
+
const gitlogCurrent = await client.listDocumentIds(`gitlog-head:${head}`, "all_strict").then((s) => s.has(`gitlog:${repoNameOf(cwd)}`)).catch(() => void 0);
|
|
2270
|
+
if (gitlogCurrent === void 0) return void 0;
|
|
2271
|
+
if (mode === "message") return gitlogCurrent ? "git in sync" : "catching up on new commits";
|
|
2272
|
+
const deepened = [...gitIds].filter((id) => id.startsWith("git:")).length;
|
|
2273
|
+
let target = DEEPEN_DIFF_TARGET;
|
|
2274
|
+
try {
|
|
2275
|
+
const { execFileSync: execFileSync4 } = await import("child_process");
|
|
2276
|
+
const n = Number(
|
|
2277
|
+
execFileSync4("git", ["-C", cwd, "rev-list", "--count", "HEAD"], {
|
|
2278
|
+
encoding: "utf8",
|
|
2279
|
+
windowsHide: true
|
|
2280
|
+
}).trim()
|
|
2281
|
+
);
|
|
2282
|
+
if (n > 0) target = Math.min(DEEPEN_DIFF_TARGET, n);
|
|
2283
|
+
} catch {
|
|
2284
|
+
}
|
|
2285
|
+
return gitlogCurrent && deepened >= target ? "git in sync" : `syncing git history (${Math.min(deepened, target)}/${target})`;
|
|
2286
|
+
}
|
|
2287
|
+
async function buildSessionStartContext(args) {
|
|
2288
|
+
const { cwd, bankId, cfg, client, stateDir } = args;
|
|
2289
|
+
const t0 = Date.now();
|
|
2290
|
+
let cold;
|
|
2291
|
+
let gitDocIds;
|
|
2292
|
+
const harness = args.harness ?? "claude-code";
|
|
2293
|
+
const hasGit = args.hasGit ?? hasGitHistory;
|
|
2294
|
+
const startSeed = args.startSeed ?? startBackgroundSeed;
|
|
2295
|
+
const startSurvey = args.startSurvey ?? startCodebaseSurvey;
|
|
2296
|
+
const resolveHeadSha = args.headSha ?? gitHeadSha;
|
|
2297
|
+
const countCommitsSince = args.commitsSince ?? commitsSince;
|
|
2298
|
+
const retainStamp = () => buildRetainStamp(cfg, { directory: cwd, sessionRoot: args.sessionRoot, harness, bankId });
|
|
2299
|
+
const SURVEY_BASELINE_TAG = "source:survey-baseline";
|
|
2300
|
+
const SURVEY_BASELINE_PREFIX = "survey-baseline:";
|
|
2301
|
+
const recordSurveyBaseline = (sha) => {
|
|
2302
|
+
if (!client.retain) return;
|
|
2303
|
+
try {
|
|
2304
|
+
const stamp = retainStamp();
|
|
2305
|
+
const content = `\u{1F6F0}\uFE0F Hindsight is researching this codebase \u2014 survey started at commit ${sha.slice(0, 12)}. (Internal marker: no memories are extracted from this document.)`;
|
|
2306
|
+
const tags = [.../* @__PURE__ */ new Set([...stamp.tags, SURVEY_BASELINE_TAG])];
|
|
2307
|
+
const retained = client.retain(
|
|
2308
|
+
content,
|
|
2309
|
+
"hindsight codebase-survey baseline",
|
|
2310
|
+
`${SURVEY_BASELINE_PREFIX}${sha}`,
|
|
2311
|
+
tags,
|
|
2312
|
+
"survey",
|
|
2313
|
+
// `retain` only sets metadata when it is truthy, so an empty stamp sends none.
|
|
2314
|
+
{ metadata: Object.keys(stamp.metadata).length ? stamp.metadata : void 0 }
|
|
2315
|
+
);
|
|
2316
|
+
void Promise.resolve(retained).catch(() => {
|
|
2317
|
+
});
|
|
2318
|
+
} catch {
|
|
2319
|
+
}
|
|
2320
|
+
};
|
|
2321
|
+
let systemMessage;
|
|
2322
|
+
if (cfg.autoSeed !== false) {
|
|
2323
|
+
if (hasGit(cwd)) {
|
|
2324
|
+
{
|
|
2325
|
+
let docIds;
|
|
2326
|
+
try {
|
|
2327
|
+
docIds = await client.listDocumentIds("source:git", "all_strict");
|
|
2328
|
+
} catch {
|
|
2329
|
+
docIds = void 0;
|
|
2330
|
+
}
|
|
2331
|
+
cold = docIds !== void 0 ? docIds.size === 0 : void 0;
|
|
2332
|
+
gitDocIds = docIds;
|
|
2333
|
+
if (docIds !== void 0) {
|
|
2334
|
+
startSeed(cwd, { limit: cfg.seedLimit, harness });
|
|
2335
|
+
if (docIds.size === 0) {
|
|
2336
|
+
if (cfg.codebaseSurvey !== false) {
|
|
2337
|
+
startSurvey(cwd, {
|
|
2338
|
+
harness,
|
|
2339
|
+
model: cfg.surveyModel,
|
|
2340
|
+
budgetUsd: cfg.surveyBudgetUsd
|
|
2341
|
+
});
|
|
2342
|
+
const sha = resolveHeadSha(cwd);
|
|
2343
|
+
if (sha) recordSurveyBaseline(sha);
|
|
2344
|
+
}
|
|
2345
|
+
diag(harness, "seed_started", { bank: bankId });
|
|
2346
|
+
} else if (cfg.codebaseSurvey !== false && cfg.surveyRefreshCommits > 0) {
|
|
2347
|
+
const sha = resolveHeadSha(cwd);
|
|
2348
|
+
if (sha) {
|
|
2349
|
+
const markers = await client.listDocumentIds(SURVEY_BASELINE_TAG, "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
2350
|
+
const counts = [];
|
|
2351
|
+
for (const id of markers) {
|
|
2352
|
+
if (!id.startsWith(SURVEY_BASELINE_PREFIX)) continue;
|
|
2353
|
+
const n = countCommitsSince(cwd, id.slice(SURVEY_BASELINE_PREFIX.length));
|
|
2354
|
+
if (n !== null) counts.push(n);
|
|
2355
|
+
}
|
|
2356
|
+
const sinceLast = counts.length ? Math.min(...counts) : null;
|
|
2357
|
+
const uploads = await client.listDocumentIds("source:upload", "all_strict").catch(() => /* @__PURE__ */ new Set());
|
|
2358
|
+
const findingsAbsent = counts.length > 0 && !SURVEY_DOC_IDS.some((id) => uploads.has(id));
|
|
2359
|
+
if (sinceLast !== null && sinceLast >= cfg.surveyRefreshCommits || findingsAbsent) {
|
|
2360
|
+
startSurvey(cwd, {
|
|
2361
|
+
harness,
|
|
2362
|
+
model: cfg.surveyModel,
|
|
2363
|
+
budgetUsd: cfg.surveyBudgetUsd
|
|
2364
|
+
});
|
|
2365
|
+
recordSurveyBaseline(sha);
|
|
2366
|
+
diag(harness, "survey_refresh", {
|
|
2367
|
+
bank: bankId,
|
|
2368
|
+
commits: sinceLast,
|
|
2369
|
+
retry: findingsAbsent
|
|
2370
|
+
});
|
|
2371
|
+
} else if (sinceLast === null) {
|
|
2372
|
+
recordSurveyBaseline(sha);
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
let pages = [];
|
|
2381
|
+
let pageListKnown = false;
|
|
2382
|
+
try {
|
|
2383
|
+
pages = parsePageList(await client.listPages());
|
|
2384
|
+
pageListKnown = true;
|
|
2385
|
+
} catch {
|
|
2386
|
+
if (client.knowledgePagesSupported === false) {
|
|
2387
|
+
diag(harness, "knowledge_pages_unavailable", { bank: bankId });
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
const additionalContext = buildKnowledgePreamble(pages, { reflectOnNewGoals: !cfg.autoReflect });
|
|
2391
|
+
const deferInitialReflect = cold === true || pageListKnown && pages.length === 0;
|
|
2392
|
+
let gitNote;
|
|
2393
|
+
if (gitDocIds) {
|
|
2394
|
+
gitNote = await gitSyncNote({
|
|
2395
|
+
client,
|
|
2396
|
+
cwd,
|
|
2397
|
+
gitIds: gitDocIds,
|
|
2398
|
+
mode: cfg.gitIngest,
|
|
2399
|
+
cold: cold === true
|
|
2400
|
+
}).catch(() => void 0);
|
|
2401
|
+
}
|
|
2402
|
+
systemMessage = buildSeedBanner(bankId, cold === true, gitNote);
|
|
2403
|
+
diag(harness, "session_start", { bank: bankId, cold, pages: pages.length, ms: Date.now() - t0 });
|
|
2404
|
+
return { systemMessage, additionalContext, deferInitialReflect };
|
|
2405
|
+
}
|
|
2406
|
+
async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
2407
|
+
if (process.env.HINDSIGHT_DISABLE_HOOKS) return;
|
|
2408
|
+
try {
|
|
2409
|
+
let ev = {};
|
|
2410
|
+
try {
|
|
2411
|
+
ev = JSON.parse(readFileSync8(0, "utf8"));
|
|
2412
|
+
} catch {
|
|
2413
|
+
return;
|
|
2414
|
+
}
|
|
2415
|
+
const { harness } = spec;
|
|
2416
|
+
const { cwd: rawCwd, sessionId } = spec.parse(ev);
|
|
2417
|
+
const cwd = rawCwd || process.cwd();
|
|
2418
|
+
let cfg = loadConfig({ harness });
|
|
2419
|
+
setLogLevel(cfg.logLevel);
|
|
2420
|
+
syncCompanionSkill(harness);
|
|
2421
|
+
if (cfg.disabled) return;
|
|
2422
|
+
void maybeAutoUpdate(cfg);
|
|
2423
|
+
const sessionRoot = sessionRootDir(harness, sessionId, cwd);
|
|
2424
|
+
const derived = deriveBankIdOrSkip(cfg, cwd, harness, sessionRoot);
|
|
2425
|
+
if (derived === null) return;
|
|
2426
|
+
const resolved2 = applyBankConfig(cfg, derived, cwd);
|
|
2427
|
+
cfg = resolved2.cfg;
|
|
2428
|
+
const bankId = resolved2.bankId;
|
|
2429
|
+
if (cfg.disabled) return;
|
|
2430
|
+
await ensureDaemon(cfg, harness, { waitMs: DAEMON_WAIT_SESSION_START_MS });
|
|
2431
|
+
const client = makeClient({
|
|
2432
|
+
apiUrl: cfg.apiUrl,
|
|
2433
|
+
apiToken: cfg.apiToken,
|
|
2434
|
+
bank: bankId,
|
|
2435
|
+
maxParallelRetains: cfg.maxParallelRetains,
|
|
2436
|
+
observationScopes: cfg.observationScopes
|
|
2437
|
+
});
|
|
2438
|
+
const out = await buildSessionStartContext({ cwd, sessionRoot, bankId, cfg, client, harness });
|
|
2439
|
+
if (out.deferInitialReflect && sessionId) {
|
|
2440
|
+
writeSessionCache(sessionCacheFile(harness, sessionId), { deferInitialReflect: true });
|
|
2441
|
+
}
|
|
2442
|
+
const payload = spec.emit(out);
|
|
2443
|
+
if (out.systemMessage || out.additionalContext) {
|
|
2444
|
+
process.stdout.write(JSON.stringify(payload));
|
|
2445
|
+
}
|
|
2446
|
+
} catch {
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
// src/core/transcript-codex.ts
|
|
2451
|
+
function isSyntheticUserText(text) {
|
|
2452
|
+
const s = text.trimStart();
|
|
2453
|
+
return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
|
|
2454
|
+
}
|
|
2455
|
+
function messageText(payload) {
|
|
2456
|
+
return (payload.content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
|
|
2457
|
+
}
|
|
2458
|
+
function readCodexTranscript(path) {
|
|
2459
|
+
const turns = [];
|
|
2460
|
+
for (const rawLine of readJsonlTail(path, { scope: "codex" }).lines) {
|
|
2461
|
+
const trimmed = rawLine.trim();
|
|
2462
|
+
if (!trimmed) continue;
|
|
2463
|
+
let parsed;
|
|
2464
|
+
try {
|
|
2465
|
+
parsed = JSON.parse(trimmed);
|
|
2466
|
+
} catch {
|
|
2467
|
+
continue;
|
|
2468
|
+
}
|
|
2469
|
+
if (typeof parsed !== "object" || parsed === null) continue;
|
|
2470
|
+
const line = parsed;
|
|
2471
|
+
if (line.type !== "response_item") continue;
|
|
2472
|
+
const p = line.payload;
|
|
2473
|
+
if (!p || typeof p !== "object") continue;
|
|
2474
|
+
if (p.type === "message") {
|
|
2475
|
+
if (p.role !== "user" && p.role !== "assistant") continue;
|
|
2476
|
+
const text = stripInjectedMemory(messageText(p)).trim();
|
|
2477
|
+
if (!text) continue;
|
|
2478
|
+
if (p.role === "user" && isSyntheticUserText(text)) continue;
|
|
2479
|
+
turns.push({ role: p.role, content: text });
|
|
2480
|
+
} else if (p.type === "function_call" && typeof p.name === "string") {
|
|
2481
|
+
let input;
|
|
2482
|
+
try {
|
|
2483
|
+
input = JSON.parse(p.arguments || "");
|
|
2484
|
+
} catch {
|
|
2485
|
+
input = void 0;
|
|
2486
|
+
}
|
|
2487
|
+
turns.push({ role: "action", content: actionLine(p.name, input) });
|
|
2488
|
+
}
|
|
2489
|
+
}
|
|
2490
|
+
return turns;
|
|
2491
|
+
}
|
|
2492
|
+
|
|
2493
|
+
// src/core/transcript-cursor.ts
|
|
2494
|
+
function withTimestamp(turn, timestamp) {
|
|
2495
|
+
return timestamp ? { ...turn, timestamp } : turn;
|
|
2496
|
+
}
|
|
2497
|
+
function textFrom(content) {
|
|
2498
|
+
if (typeof content === "string") return content;
|
|
2499
|
+
if (!Array.isArray(content)) return "";
|
|
2500
|
+
return content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
|
|
2501
|
+
}
|
|
2502
|
+
function readCursorTranscript(path) {
|
|
2503
|
+
const turns = [];
|
|
2504
|
+
for (const rawLine of readJsonlTail(path, { scope: "cursor-cli" }).lines) {
|
|
2505
|
+
let parsed;
|
|
2506
|
+
try {
|
|
2507
|
+
parsed = JSON.parse(rawLine);
|
|
2508
|
+
} catch {
|
|
2509
|
+
continue;
|
|
2510
|
+
}
|
|
2511
|
+
if (typeof parsed !== "object" || parsed === null) continue;
|
|
2512
|
+
const line = parsed;
|
|
2513
|
+
const role = line.message?.role ?? line.role ?? (line.type === "user" || line.type === "assistant" ? line.type : void 0);
|
|
2514
|
+
const content = line.message?.content ?? line.content;
|
|
2515
|
+
if (role === "user" || role === "assistant") {
|
|
2516
|
+
const text = stripInjectedMemory(textFrom(content)).trim();
|
|
2517
|
+
if (text) turns.push(withTimestamp({ role, content: text }, line.timestamp));
|
|
2518
|
+
if (role === "assistant" && Array.isArray(content)) {
|
|
2519
|
+
for (const block of content) {
|
|
2520
|
+
if (block?.type === "tool_use" && typeof block.name === "string") {
|
|
2521
|
+
turns.push(
|
|
2522
|
+
withTimestamp(
|
|
2523
|
+
{ role: "action", content: actionLine(block.name, block.input) },
|
|
2524
|
+
line.timestamp
|
|
2525
|
+
)
|
|
2526
|
+
);
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2530
|
+
} else if (line.type === "tool_call" && typeof line.name === "string") {
|
|
2531
|
+
turns.push(
|
|
2532
|
+
withTimestamp({ role: "action", content: actionLine(line.name, line.args) }, line.timestamp)
|
|
2533
|
+
);
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
return turns;
|
|
2537
|
+
}
|
|
2538
|
+
|
|
2539
|
+
// src/core/transcript-antigravity.ts
|
|
2540
|
+
function readAntigravityTranscript(path) {
|
|
2541
|
+
if (!path) return [];
|
|
2542
|
+
const turns = [];
|
|
2543
|
+
for (const line of readJsonlTail(path, { scope: "antigravity-cli" }).lines) {
|
|
2544
|
+
try {
|
|
2545
|
+
const event = JSON.parse(line);
|
|
2546
|
+
const role = event.role ?? event.message?.role ?? event.type;
|
|
2547
|
+
const normalizedRole = role === "user" || role === "USER_INPUT" ? "user" : role === "assistant" || role === "model" || role === "PLANNER_RESPONSE" ? "assistant" : void 0;
|
|
2548
|
+
const content = event.content ?? event.text ?? event.message?.content ?? event.message?.text;
|
|
2549
|
+
const clean = typeof content === "string" ? stripInjectedMemory(content).trim() : "";
|
|
2550
|
+
if (normalizedRole && clean) {
|
|
2551
|
+
turns.push({
|
|
2552
|
+
role: normalizedRole,
|
|
2553
|
+
content: clean,
|
|
2554
|
+
...event.timestamp ? { timestamp: event.timestamp } : {}
|
|
2555
|
+
});
|
|
2556
|
+
}
|
|
2557
|
+
} catch {
|
|
2558
|
+
}
|
|
2559
|
+
}
|
|
2560
|
+
return turns;
|
|
2561
|
+
}
|
|
2562
|
+
|
|
2563
|
+
// src/core/transcript-copilot.ts
|
|
2564
|
+
function readCopilotTranscript(path) {
|
|
2565
|
+
const turns = [];
|
|
2566
|
+
for (const rawLine of readJsonlTail(path, { scope: "copilot-cli" }).lines) {
|
|
2567
|
+
try {
|
|
2568
|
+
const event = JSON.parse(rawLine);
|
|
2569
|
+
const role = event.type === "user.message" ? "user" : event.type === "assistant.message" ? "assistant" : void 0;
|
|
2570
|
+
const content = typeof event.data?.content === "string" ? stripInjectedMemory(event.data.content).trim() : "";
|
|
2571
|
+
if (!role || !content) continue;
|
|
2572
|
+
turns.push({ role, content, ...event.timestamp ? { timestamp: event.timestamp } : {} });
|
|
2573
|
+
} catch {
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
return turns;
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
// src/core/transcript-grok.ts
|
|
2580
|
+
import { existsSync as existsSync6, readFileSync as readFileSync9, readdirSync } from "fs";
|
|
2581
|
+
import { homedir as homedir6 } from "os";
|
|
2582
|
+
import { join as join12 } from "path";
|
|
2583
|
+
var CHAT_HISTORY = "chat_history.jsonl";
|
|
2584
|
+
function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME || join12(homedir6(), ".grok")) {
|
|
2585
|
+
const sessionsDir = join12(grokHome, "sessions");
|
|
2586
|
+
const direct = join12(sessionsDir, encodeURIComponent(cwd), sessionId, CHAT_HISTORY);
|
|
2587
|
+
if (existsSync6(direct)) return direct;
|
|
2588
|
+
try {
|
|
2589
|
+
for (const candidate of readdirSync(sessionsDir)) {
|
|
2590
|
+
const directory = join12(sessionsDir, candidate);
|
|
2591
|
+
if (readFileSync9(join12(directory, ".cwd"), "utf8").trim() === cwd) {
|
|
2592
|
+
return join12(directory, sessionId, CHAT_HISTORY);
|
|
2593
|
+
}
|
|
2594
|
+
}
|
|
2595
|
+
} catch {
|
|
2596
|
+
}
|
|
2597
|
+
return direct;
|
|
2598
|
+
}
|
|
2599
|
+
function readGrokTranscript(path) {
|
|
2600
|
+
const turns = [];
|
|
2601
|
+
for (const rawLine of readJsonlTail(path, { scope: "grok-build" }).lines) {
|
|
2602
|
+
try {
|
|
2603
|
+
const event = JSON.parse(rawLine);
|
|
2604
|
+
if (event.type !== "user" && event.type !== "assistant") continue;
|
|
2605
|
+
if (event.type === "user" && typeof event.prompt_index !== "number") continue;
|
|
2606
|
+
const content = typeof event.content === "string" ? event.content : Array.isArray(event.content) ? event.content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("\n") : "";
|
|
2607
|
+
const clean = stripInjectedMemory(content).trim();
|
|
2608
|
+
if (clean) turns.push({ role: event.type, content: clean });
|
|
2609
|
+
for (const toolCall of event.tool_calls ?? []) {
|
|
2610
|
+
if (!toolCall.name) continue;
|
|
2611
|
+
let input = toolCall.arguments;
|
|
2612
|
+
if (typeof input === "string") {
|
|
2613
|
+
try {
|
|
2614
|
+
input = JSON.parse(input);
|
|
2615
|
+
} catch {
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2618
|
+
turns.push({ role: "action", content: actionLine(toolCall.name, input) });
|
|
2619
|
+
}
|
|
2620
|
+
} catch {
|
|
2621
|
+
}
|
|
2622
|
+
}
|
|
2623
|
+
return turns;
|
|
2624
|
+
}
|
|
2625
|
+
|
|
2626
|
+
// src/core/transcript-devin.ts
|
|
2627
|
+
import { existsSync as existsSync7 } from "fs";
|
|
2628
|
+
import { createRequire } from "module";
|
|
2629
|
+
import { homedir as homedir7 } from "os";
|
|
2630
|
+
import { join as join13 } from "path";
|
|
2631
|
+
function devinSessionDb(home = homedir7()) {
|
|
2632
|
+
return join13(home, ".local", "share", "devin", "cli", "sessions.db");
|
|
2633
|
+
}
|
|
2634
|
+
function parseDevinMessages(nodes) {
|
|
2635
|
+
const messages = /* @__PURE__ */ new Map();
|
|
2636
|
+
for (const node of nodes) {
|
|
2637
|
+
try {
|
|
2638
|
+
const message = JSON.parse(node.chat_message);
|
|
2639
|
+
if (message.role !== "user" && message.role !== "assistant" || !message.content?.trim())
|
|
2640
|
+
continue;
|
|
2641
|
+
const content = stripInjectedMemory(message.content).trim();
|
|
2642
|
+
if (!content) continue;
|
|
2643
|
+
const id = message.message_id || `node:${node.node_id}`;
|
|
2644
|
+
messages.set(id, {
|
|
2645
|
+
index: messages.get(id)?.index ?? node.node_id,
|
|
2646
|
+
role: message.role,
|
|
2647
|
+
content
|
|
2648
|
+
});
|
|
2649
|
+
} catch {
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
return [...messages.values()].sort((a, b) => a.index - b.index).map(({ role, content }) => ({ role, content }));
|
|
2653
|
+
}
|
|
2654
|
+
var requireBuiltin = createRequire(import.meta.url);
|
|
2655
|
+
function loadSqlite() {
|
|
2656
|
+
try {
|
|
2657
|
+
return requireBuiltin("node:sqlite").DatabaseSync;
|
|
2658
|
+
} catch {
|
|
2659
|
+
return void 0;
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
function readDevinTranscript(sessionId, dbPath = devinSessionDb()) {
|
|
2663
|
+
if (!sessionId) return [];
|
|
2664
|
+
const Database = loadSqlite();
|
|
2665
|
+
if (!Database) {
|
|
2666
|
+
diag("devin-cli", "sqlite_unavailable", { node: process.version, dbPath });
|
|
2667
|
+
return [];
|
|
2668
|
+
}
|
|
2669
|
+
if (!existsSync7(dbPath)) {
|
|
2670
|
+
diag("devin-cli", "session_db_missing", { dbPath });
|
|
2671
|
+
return [];
|
|
2672
|
+
}
|
|
2673
|
+
let db;
|
|
2674
|
+
try {
|
|
2675
|
+
db = new Database(dbPath, { readOnly: true });
|
|
2676
|
+
const rows = db.prepare(
|
|
2677
|
+
"SELECT node_id, chat_message FROM message_nodes WHERE session_id = ? ORDER BY node_id"
|
|
2678
|
+
).all(sessionId);
|
|
2679
|
+
return parseDevinMessages(rows);
|
|
2680
|
+
} catch (error) {
|
|
2681
|
+
diag("devin-cli", "session_db_read_failed", { dbPath, error: String(error) });
|
|
2682
|
+
return [];
|
|
2683
|
+
} finally {
|
|
2684
|
+
try {
|
|
2685
|
+
db?.close();
|
|
2686
|
+
} catch {
|
|
2687
|
+
}
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
|
|
2691
|
+
// src/core/transcript-dcode.ts
|
|
2692
|
+
var BLOCK_JOIN = "\n";
|
|
2693
|
+
function contentText(content) {
|
|
2694
|
+
if (typeof content === "string") return content;
|
|
2695
|
+
if (!Array.isArray(content)) return "";
|
|
2696
|
+
return content.flatMap((block) => {
|
|
2697
|
+
if (typeof block === "string") return [block];
|
|
2698
|
+
if (!block || typeof block !== "object") return [];
|
|
2699
|
+
const text = block.text;
|
|
2700
|
+
return typeof text === "string" ? [text] : [];
|
|
2701
|
+
}).join(BLOCK_JOIN);
|
|
2702
|
+
}
|
|
2703
|
+
function readPyValue(s, i) {
|
|
2704
|
+
const skip = (j) => {
|
|
2705
|
+
while (j < s.length && /\s/.test(s[j])) j++;
|
|
2706
|
+
return j;
|
|
2707
|
+
};
|
|
2708
|
+
i = skip(i);
|
|
2709
|
+
if (i >= s.length) return null;
|
|
2710
|
+
const c = s[i];
|
|
2711
|
+
if (c === "'" || c === '"') {
|
|
2712
|
+
let out = "";
|
|
2713
|
+
let j = i + 1;
|
|
2714
|
+
while (j < s.length) {
|
|
2715
|
+
const ch = s[j];
|
|
2716
|
+
if (ch === "\\") {
|
|
2717
|
+
const esc = s[j + 1];
|
|
2718
|
+
if (esc === void 0) return null;
|
|
2719
|
+
if (esc === "n") out += "\n";
|
|
2720
|
+
else if (esc === "t") out += " ";
|
|
2721
|
+
else if (esc === "r") out += "\r";
|
|
2722
|
+
else if (esc === "x") {
|
|
2723
|
+
const hex = s.slice(j + 2, j + 4);
|
|
2724
|
+
if (!/^[0-9a-fA-F]{2}$/.test(hex)) return null;
|
|
2725
|
+
out += String.fromCharCode(parseInt(hex, 16));
|
|
2726
|
+
j += 4;
|
|
2727
|
+
continue;
|
|
2728
|
+
} else if (esc === "u") {
|
|
2729
|
+
const hex = s.slice(j + 2, j + 6);
|
|
2730
|
+
if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null;
|
|
2731
|
+
out += String.fromCharCode(parseInt(hex, 16));
|
|
2732
|
+
j += 6;
|
|
2733
|
+
continue;
|
|
2734
|
+
} else out += esc;
|
|
2735
|
+
j += 2;
|
|
2736
|
+
continue;
|
|
2737
|
+
}
|
|
2738
|
+
if (ch === c) return { value: out, end: j + 1 };
|
|
2739
|
+
out += ch;
|
|
2740
|
+
j++;
|
|
2741
|
+
}
|
|
2742
|
+
return null;
|
|
2743
|
+
}
|
|
2744
|
+
if (s.startsWith("True", i)) return { value: true, end: i + 4 };
|
|
2745
|
+
if (s.startsWith("False", i)) return { value: false, end: i + 5 };
|
|
2746
|
+
if (s.startsWith("None", i)) return { value: null, end: i + 4 };
|
|
2747
|
+
if (c === "[" || c === "{") {
|
|
2748
|
+
const isList = c === "[";
|
|
2749
|
+
const close = isList ? "]" : "}";
|
|
2750
|
+
const list = [];
|
|
2751
|
+
const obj = {};
|
|
2752
|
+
let j = skip(i + 1);
|
|
2753
|
+
if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
|
|
2754
|
+
for (; ; ) {
|
|
2755
|
+
const key = readPyValue(s, j);
|
|
2756
|
+
if (!key) return null;
|
|
2757
|
+
j = skip(key.end);
|
|
2758
|
+
if (isList) {
|
|
2759
|
+
list.push(key.value);
|
|
2760
|
+
} else {
|
|
2761
|
+
if (s[j] !== ":" || typeof key.value !== "string") return null;
|
|
2762
|
+
const val = readPyValue(s, j + 1);
|
|
2763
|
+
if (!val) return null;
|
|
2764
|
+
obj[key.value] = val.value;
|
|
2765
|
+
j = skip(val.end);
|
|
2766
|
+
}
|
|
2767
|
+
if (s[j] === ",") {
|
|
2768
|
+
j = skip(j + 1);
|
|
2769
|
+
if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
|
|
2770
|
+
continue;
|
|
2771
|
+
}
|
|
2772
|
+
if (s[j] === close) return { value: isList ? list : obj, end: j + 1 };
|
|
2773
|
+
return null;
|
|
2774
|
+
}
|
|
2775
|
+
}
|
|
2776
|
+
const num = /^-?\d+(\.\d+)?([eE][-+]?\d+)?/.exec(s.slice(i));
|
|
2777
|
+
if (num) return { value: Number(num[0]), end: i + num[0].length };
|
|
2778
|
+
return null;
|
|
2779
|
+
}
|
|
2780
|
+
function dcodeAssistantText(raw) {
|
|
2781
|
+
const trimmed = raw.trim();
|
|
2782
|
+
if (!trimmed.startsWith("[{") && !trimmed.startsWith("[ {")) return raw;
|
|
2783
|
+
const parsed = readPyValue(trimmed, 0);
|
|
2784
|
+
if (!parsed || readPyValue(trimmed, parsed.end) !== null) return "";
|
|
2785
|
+
if (!Array.isArray(parsed.value)) return "";
|
|
2786
|
+
return contentText(parsed.value);
|
|
2787
|
+
}
|
|
2788
|
+
function readDcodeTranscript(path) {
|
|
2789
|
+
const turns = [];
|
|
2790
|
+
for (const rawLine of readJsonlTail(path, { scope: "dcode" }).lines) {
|
|
2791
|
+
if (!rawLine.trim()) continue;
|
|
2792
|
+
let parsed;
|
|
2793
|
+
try {
|
|
2794
|
+
parsed = JSON.parse(rawLine);
|
|
2795
|
+
} catch {
|
|
2796
|
+
continue;
|
|
2797
|
+
}
|
|
2798
|
+
if (!parsed || typeof parsed !== "object") continue;
|
|
2799
|
+
const record = parsed;
|
|
2800
|
+
if (record.schema_version !== 1) continue;
|
|
2801
|
+
const role = record.role;
|
|
2802
|
+
const stamp = typeof record.timestamp === "string" && record.timestamp ? { timestamp: record.timestamp } : {};
|
|
2803
|
+
if (role === "user" || role === "assistant") {
|
|
2804
|
+
const text = stripInjectedMemory(contentText(record.content)).trim();
|
|
2805
|
+
if (text) turns.push({ role, content: text, ...stamp });
|
|
2806
|
+
} else if (role === "tool" && typeof record.name === "string" && record.name.trim()) {
|
|
2807
|
+
turns.push({ role: "action", content: actionLine(record.name, record.content), ...stamp });
|
|
2808
|
+
}
|
|
2809
|
+
}
|
|
2810
|
+
return turns;
|
|
2811
|
+
}
|
|
2812
|
+
|
|
2813
|
+
// src/core/transcript-qwen.ts
|
|
2814
|
+
var HOOK_CONTEXT_PART_RE = /^\s*<qwen:user-prompt-submit-context>[\s\S]*<\/qwen:user-prompt-submit-context>\s*$/;
|
|
2815
|
+
function isWholeHookContextPart(part) {
|
|
2816
|
+
return typeof part.text === "string" && HOOK_CONTEXT_PART_RE.test(part.text);
|
|
2817
|
+
}
|
|
2818
|
+
function isRealUser(line) {
|
|
2819
|
+
if (typeof line.provenance === "string") return line.provenance === "real_user";
|
|
2820
|
+
if (line.provenance !== void 0) return false;
|
|
2821
|
+
const isSubagentEnvelope = line.agentId !== void 0 || line.isSidechain !== void 0;
|
|
2822
|
+
if (!isSubagentEnvelope) return false;
|
|
2823
|
+
return line.subtype === void 0 || line.subtype === "mid_turn_user_message";
|
|
2824
|
+
}
|
|
2825
|
+
function renderLine(parts, type) {
|
|
2826
|
+
if (!Array.isArray(parts)) return [];
|
|
2827
|
+
const last = parts.length > 1 ? parts[parts.length - 1] : void 0;
|
|
2828
|
+
const dropLast = !!last && typeof last === "object" && isWholeHookContextPart(last) ? parts.length - 1 : -1;
|
|
2829
|
+
const texts = [];
|
|
2830
|
+
const actions = [];
|
|
2831
|
+
for (const [i, part] of parts.entries()) {
|
|
2832
|
+
if (!part || typeof part !== "object") continue;
|
|
2833
|
+
if (i === dropLast) continue;
|
|
2834
|
+
if (part.thought === true) continue;
|
|
2835
|
+
if (typeof part.text === "string") {
|
|
2836
|
+
const text = stripInjectedMemory(part.text).trim();
|
|
2837
|
+
if (text) texts.push(text);
|
|
2838
|
+
} else if (part.functionCall && typeof part.functionCall.name === "string") {
|
|
2839
|
+
actions.push({
|
|
2840
|
+
role: "action",
|
|
2841
|
+
content: actionLine(part.functionCall.name, part.functionCall.args)
|
|
2842
|
+
});
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
const out = [];
|
|
2846
|
+
const joined = texts.join("\n").trim();
|
|
2847
|
+
if (joined) out.push({ role: type, content: joined });
|
|
2848
|
+
out.push(...actions);
|
|
2849
|
+
return out;
|
|
2850
|
+
}
|
|
2851
|
+
function readQwenTranscript(path) {
|
|
2852
|
+
const turns = [];
|
|
2853
|
+
try {
|
|
2854
|
+
collectQwenTurns(path, turns);
|
|
2855
|
+
} catch (err) {
|
|
2856
|
+
log.warn("qwen-code", "transcript read failed \u2014 retaining what was parsed", {
|
|
2857
|
+
path,
|
|
2858
|
+
turns: turns.length,
|
|
2859
|
+
error: err instanceof Error ? err.message : String(err)
|
|
2860
|
+
});
|
|
2861
|
+
}
|
|
2862
|
+
return turns;
|
|
2863
|
+
}
|
|
2864
|
+
function collectQwenTurns(path, turns) {
|
|
2865
|
+
for (const rawLine of readJsonlTail(path, { scope: "qwen-code" }).lines) {
|
|
2866
|
+
const trimmed = rawLine.trim();
|
|
2867
|
+
if (!trimmed) continue;
|
|
2868
|
+
let parsed;
|
|
2869
|
+
try {
|
|
2870
|
+
parsed = JSON.parse(trimmed);
|
|
2871
|
+
} catch {
|
|
2872
|
+
continue;
|
|
2873
|
+
}
|
|
2874
|
+
if (typeof parsed !== "object" || parsed === null) continue;
|
|
2875
|
+
const line = parsed;
|
|
2876
|
+
if (line.type !== "user" && line.type !== "assistant") continue;
|
|
2877
|
+
if (line.type === "user" && !isRealUser(line)) continue;
|
|
2878
|
+
if (typeof line.message !== "object" || line.message === null) continue;
|
|
2879
|
+
const sp = line.systemPayload;
|
|
2880
|
+
if (line.type === "user" && sp && typeof sp === "object" && typeof sp.hookContext === "string" && typeof sp.displayText === "string") {
|
|
2881
|
+
const content = stripInjectedMemory(sp.displayText).trim();
|
|
2882
|
+
if (content) {
|
|
2883
|
+
const turn = { role: "user", content };
|
|
2884
|
+
if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
|
|
2885
|
+
turns.push(turn);
|
|
2886
|
+
}
|
|
2887
|
+
continue;
|
|
2888
|
+
}
|
|
2889
|
+
for (const rendered of renderLine(line.message.parts, line.type)) {
|
|
2890
|
+
const turn = { role: rendered.role, content: rendered.content };
|
|
2891
|
+
if (typeof line.timestamp === "string") turn.timestamp = line.timestamp;
|
|
2892
|
+
turns.push(turn);
|
|
2893
|
+
}
|
|
2894
|
+
}
|
|
2895
|
+
}
|
|
2896
|
+
|
|
2897
|
+
// src/core/transcript-droid.ts
|
|
2898
|
+
function renderContent(content, role) {
|
|
2899
|
+
if (!Array.isArray(content)) return [];
|
|
2900
|
+
const texts = [];
|
|
2901
|
+
const actions = [];
|
|
2902
|
+
for (const block of content) {
|
|
2903
|
+
if (!block || typeof block !== "object") continue;
|
|
2904
|
+
const b = block;
|
|
2905
|
+
if (b.type === "text" && typeof b.text === "string") {
|
|
2906
|
+
const text = stripInjectedMemory(b.text).trim();
|
|
2907
|
+
if (text) texts.push(text);
|
|
2908
|
+
} else if (b.type === "tool_use" && typeof b.name === "string") {
|
|
2909
|
+
actions.push({ role: "action", content: actionLine(b.name, b.input) });
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
const out = [];
|
|
2913
|
+
const joined = texts.join("\n").trim();
|
|
2914
|
+
if (joined) out.push({ role, content: joined });
|
|
2915
|
+
out.push(...actions);
|
|
2916
|
+
return out;
|
|
2917
|
+
}
|
|
2918
|
+
function readDroidTranscript(path) {
|
|
2919
|
+
const turns = [];
|
|
2920
|
+
for (const rawLine of readJsonlTail(path, { scope: "factory-droid" }).lines) {
|
|
2921
|
+
if (!rawLine.trim()) continue;
|
|
2922
|
+
let parsed;
|
|
2923
|
+
try {
|
|
2924
|
+
parsed = JSON.parse(rawLine);
|
|
2925
|
+
} catch {
|
|
2926
|
+
continue;
|
|
2927
|
+
}
|
|
2928
|
+
if (!parsed || typeof parsed !== "object") continue;
|
|
2929
|
+
const line = parsed;
|
|
2930
|
+
if (line.type !== "message" || !line.message || typeof line.message !== "object") continue;
|
|
2931
|
+
const message = line.message;
|
|
2932
|
+
const role = message.role;
|
|
2933
|
+
if (role !== "user" && role !== "assistant") continue;
|
|
2934
|
+
if (message.visibility === "user_only" || message.visibility === "llm_only") continue;
|
|
2935
|
+
const stamp = typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
|
|
2936
|
+
turns.push(...renderContent(message.content, role).map((turn) => ({ ...turn, ...stamp })));
|
|
2937
|
+
}
|
|
2938
|
+
return turns;
|
|
2939
|
+
}
|
|
2940
|
+
|
|
2941
|
+
// src/harness/hook-lifecycle.ts
|
|
2942
|
+
var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
|
|
2943
|
+
var claudePrompt = {
|
|
2944
|
+
harness: "claude-code",
|
|
2945
|
+
parse: (ev) => ({
|
|
2946
|
+
prompt: ev.prompt,
|
|
2947
|
+
cwd: ev.cwd,
|
|
2948
|
+
sessionId: ev.session_id
|
|
2949
|
+
}),
|
|
2950
|
+
emit: (context, notice) => ({
|
|
2951
|
+
...notice ? { systemMessage: notice } : {},
|
|
2952
|
+
hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
|
|
2953
|
+
})
|
|
2954
|
+
};
|
|
2955
|
+
var codexPrompt = {
|
|
2956
|
+
...claudePrompt,
|
|
2957
|
+
harness: "codex",
|
|
2958
|
+
parse: (ev) => ({
|
|
2959
|
+
prompt: ev.prompt ?? ev.user_prompt,
|
|
2960
|
+
cwd: ev.cwd,
|
|
2961
|
+
sessionId: ev.session_id
|
|
2962
|
+
})
|
|
2963
|
+
};
|
|
2964
|
+
var dcodePrompt = {
|
|
2965
|
+
...claudePrompt,
|
|
2966
|
+
harness: "dcode"
|
|
2967
|
+
};
|
|
2968
|
+
var droidPrompt = {
|
|
2969
|
+
...claudePrompt,
|
|
2970
|
+
harness: "factory-droid"
|
|
2971
|
+
};
|
|
2972
|
+
var qwenPrompt = {
|
|
2973
|
+
...claudePrompt,
|
|
2974
|
+
harness: "qwen-code",
|
|
2975
|
+
parse: (ev) => ({
|
|
2976
|
+
prompt: ev.submitted_prompt,
|
|
2977
|
+
cwd: ev.cwd,
|
|
2978
|
+
sessionId: ev.session_id
|
|
2979
|
+
})
|
|
2980
|
+
};
|
|
2981
|
+
var antigravityCwd = (ev) => Array.isArray(ev.workspacePaths) ? ev.workspacePaths[0] : void 0;
|
|
2982
|
+
var antigravityPrompt = {
|
|
2983
|
+
harness: "antigravity-cli",
|
|
2984
|
+
requireCwd: true,
|
|
2985
|
+
parse: (ev) => ({
|
|
2986
|
+
// Antigravity's PreInvocation payload deliberately omits the prompt. Its transcript is already
|
|
2987
|
+
// persisted at that point, so recover the latest real user turn from the supplied JSONL path.
|
|
2988
|
+
prompt: readAntigravityTranscript(ev.transcriptPath).filter((turn) => turn.role === "user").at(-1)?.content,
|
|
2989
|
+
cwd: antigravityCwd(ev),
|
|
2990
|
+
sessionId: ev.conversationId
|
|
2991
|
+
}),
|
|
2992
|
+
emit: (context) => ({ injectSteps: context ? [{ ephemeralMessage: context }] : [] })
|
|
2993
|
+
};
|
|
2994
|
+
var cursorPrompt = {
|
|
2995
|
+
harness: "cursor-cli",
|
|
2996
|
+
parse: (ev) => ({
|
|
2997
|
+
prompt: ev.prompt ?? ev.user_prompt,
|
|
2998
|
+
cwd: cursorCwd(ev),
|
|
2999
|
+
sessionId: ev.conversation_id ?? ev.session_id
|
|
3000
|
+
}),
|
|
3001
|
+
emit: (context) => ({ continue: true, additional_context: context })
|
|
3002
|
+
};
|
|
3003
|
+
var copilotPrompt = {
|
|
3004
|
+
harness: "copilot-cli",
|
|
3005
|
+
parse: (ev) => ({
|
|
3006
|
+
prompt: ev.prompt,
|
|
3007
|
+
cwd: ev.cwd,
|
|
3008
|
+
sessionId: ev.sessionId
|
|
3009
|
+
}),
|
|
3010
|
+
emit: (context, _notice, ev) => ({
|
|
3011
|
+
// Copilot's userPromptTransformed hook replaces model-facing content rather than appending
|
|
3012
|
+
// hook context. Preserve its transformed prompt and add the shared Hindsight injection.
|
|
3013
|
+
modifiedTransformedPrompt: `${ev?.transformedPrompt ?? ""}
|
|
3014
|
+
|
|
3015
|
+
${context}`.trim()
|
|
3016
|
+
})
|
|
3017
|
+
};
|
|
3018
|
+
var devinCwd = () => process.env.DEVIN_PROJECT_DIR;
|
|
3019
|
+
var devinPrompt = {
|
|
3020
|
+
harness: "devin-cli",
|
|
3021
|
+
requireCwd: true,
|
|
3022
|
+
parse: (ev) => ({
|
|
3023
|
+
prompt: ev.prompt,
|
|
3024
|
+
cwd: devinCwd(),
|
|
3025
|
+
sessionId: ev.session_id
|
|
3026
|
+
}),
|
|
3027
|
+
emit: (context) => ({
|
|
3028
|
+
hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context }
|
|
3029
|
+
})
|
|
3030
|
+
};
|
|
3031
|
+
var standardSessionStart = (harness) => ({
|
|
3032
|
+
harness,
|
|
3033
|
+
parse: (ev) => ({
|
|
3034
|
+
cwd: ev.cwd,
|
|
3035
|
+
sessionId: ev.session_id
|
|
3036
|
+
}),
|
|
3037
|
+
emit: (out) => ({
|
|
3038
|
+
...out.systemMessage ? { systemMessage: out.systemMessage } : {},
|
|
3039
|
+
hookSpecificOutput: {
|
|
3040
|
+
hookEventName: "SessionStart",
|
|
3041
|
+
...out.additionalContext ? { additionalContext: out.additionalContext } : {}
|
|
3042
|
+
}
|
|
3043
|
+
})
|
|
3044
|
+
});
|
|
3045
|
+
var HOOK_HARNESSES = {
|
|
3046
|
+
"claude-code": {
|
|
3047
|
+
configStyle: "nested",
|
|
3048
|
+
install: {
|
|
3049
|
+
sessionStart: { event: "SessionStart", entry: "claude-sessionstart-hook.js", timeout: 30 },
|
|
3050
|
+
prompt: { event: "UserPromptSubmit", entry: "claude-hook.js", timeout: 30 },
|
|
3051
|
+
stop: { event: "Stop", entry: "claude-stop-hook.js", timeout: 60 }
|
|
3052
|
+
},
|
|
3053
|
+
sessionStart: standardSessionStart("claude-code"),
|
|
3054
|
+
prompt: claudePrompt,
|
|
3055
|
+
retain: {
|
|
3056
|
+
hostTimeoutSec: 60,
|
|
3057
|
+
harness: "claude-code",
|
|
3058
|
+
parse: (ev) => ({
|
|
3059
|
+
sessionId: ev.session_id,
|
|
3060
|
+
transcriptPath: ev.transcript_path,
|
|
3061
|
+
cwd: ev.cwd
|
|
3062
|
+
})
|
|
3063
|
+
}
|
|
3064
|
+
},
|
|
3065
|
+
codex: {
|
|
3066
|
+
configStyle: "nested",
|
|
3067
|
+
install: {
|
|
3068
|
+
sessionStart: { event: "SessionStart", entry: "codex-sessionstart-hook.js", timeout: 30 },
|
|
3069
|
+
prompt: { event: "UserPromptSubmit", entry: "codex-hook.js", timeout: 30 },
|
|
3070
|
+
stop: { event: "Stop", entry: "codex-stop-hook.js", timeout: 60 }
|
|
3071
|
+
},
|
|
3072
|
+
sessionStart: standardSessionStart("codex"),
|
|
3073
|
+
prompt: codexPrompt,
|
|
3074
|
+
retain: {
|
|
3075
|
+
hostTimeoutSec: 60,
|
|
3076
|
+
harness: "codex",
|
|
3077
|
+
parse: (ev) => ({
|
|
3078
|
+
sessionId: ev.session_id,
|
|
3079
|
+
transcriptPath: ev.transcript_path,
|
|
3080
|
+
cwd: ev.cwd
|
|
3081
|
+
}),
|
|
3082
|
+
readTranscript: readCodexTranscript
|
|
3083
|
+
}
|
|
3084
|
+
},
|
|
3085
|
+
dcode: {
|
|
3086
|
+
configStyle: "nested",
|
|
3087
|
+
install: {
|
|
3088
|
+
sessionStart: { event: "SessionStart", entry: "dcode-sessionstart-hook.js", timeout: 30 },
|
|
3089
|
+
prompt: { event: "UserPromptSubmit", entry: "dcode-hook.js", timeout: 30 },
|
|
3090
|
+
stop: { event: "Stop", entry: "dcode-stop-hook.js", timeout: 60 }
|
|
3091
|
+
},
|
|
3092
|
+
sessionStart: standardSessionStart("dcode"),
|
|
3093
|
+
prompt: dcodePrompt,
|
|
3094
|
+
retain: {
|
|
3095
|
+
hostTimeoutSec: 60,
|
|
3096
|
+
harness: "dcode",
|
|
3097
|
+
parse: (ev) => ({
|
|
3098
|
+
sessionId: ev.session_id,
|
|
3099
|
+
transcriptPath: ev.transcript_path,
|
|
3100
|
+
cwd: ev.cwd,
|
|
3101
|
+
lastAssistantMessage: ev.last_assistant_message
|
|
3102
|
+
}),
|
|
3103
|
+
readTranscript: readDcodeTranscript,
|
|
3104
|
+
readLastMessage: dcodeAssistantText
|
|
3105
|
+
}
|
|
3106
|
+
},
|
|
3107
|
+
"antigravity-cli": {
|
|
3108
|
+
configStyle: "flat",
|
|
3109
|
+
install: {
|
|
3110
|
+
// PreInvocation is Antigravity's only lifecycle point that can inject context. Its first
|
|
3111
|
+
// invocation also performs the SessionStart responsibilities through runHook's seed guard.
|
|
3112
|
+
sessionStart: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
|
|
3113
|
+
prompt: { event: "PreInvocation", entry: "antigravity-hook.js", timeout: 30 },
|
|
3114
|
+
stop: { event: "Stop", entry: "antigravity-stop-hook.js", timeout: 30 }
|
|
3115
|
+
},
|
|
3116
|
+
sessionStart: {
|
|
3117
|
+
harness: "antigravity-cli",
|
|
3118
|
+
parse: (ev) => ({
|
|
3119
|
+
cwd: antigravityCwd(ev),
|
|
3120
|
+
sessionId: ev.conversationId
|
|
3121
|
+
}),
|
|
3122
|
+
emit: () => ({})
|
|
3123
|
+
},
|
|
3124
|
+
prompt: antigravityPrompt,
|
|
3125
|
+
retain: {
|
|
3126
|
+
hostTimeoutSec: 30,
|
|
3127
|
+
harness: "antigravity-cli",
|
|
3128
|
+
parse: (ev) => ({
|
|
3129
|
+
sessionId: ev.conversationId,
|
|
3130
|
+
transcriptPath: ev.transcriptPath,
|
|
3131
|
+
cwd: antigravityCwd(ev)
|
|
3132
|
+
}),
|
|
3133
|
+
readTranscript: readAntigravityTranscript
|
|
3134
|
+
}
|
|
3135
|
+
},
|
|
3136
|
+
"cursor-cli": {
|
|
3137
|
+
configStyle: "flat",
|
|
3138
|
+
install: {
|
|
3139
|
+
sessionStart: { event: "sessionStart", entry: "cursor-sessionstart-hook.js", timeout: 30 },
|
|
3140
|
+
prompt: { event: "beforeSubmitPrompt", entry: "cursor-hook.js" },
|
|
3141
|
+
stop: { event: "stop", entry: "cursor-stop-hook.js", timeout: 30 }
|
|
3142
|
+
},
|
|
3143
|
+
sessionStart: {
|
|
3144
|
+
harness: "cursor-cli",
|
|
3145
|
+
parse: (ev) => ({
|
|
3146
|
+
cwd: cursorCwd(ev),
|
|
3147
|
+
sessionId: ev.conversation_id ?? ev.session_id
|
|
3148
|
+
}),
|
|
3149
|
+
emit: (out) => ({
|
|
3150
|
+
...out.additionalContext ? { additional_context: out.additionalContext } : {}
|
|
3151
|
+
})
|
|
3152
|
+
},
|
|
3153
|
+
prompt: cursorPrompt,
|
|
3154
|
+
retain: {
|
|
3155
|
+
hostTimeoutSec: 30,
|
|
3156
|
+
harness: "cursor-cli",
|
|
3157
|
+
parse: (ev) => ({
|
|
3158
|
+
sessionId: ev.conversation_id ?? ev.session_id,
|
|
3159
|
+
transcriptPath: ev.transcript_path,
|
|
3160
|
+
cwd: cursorCwd(ev)
|
|
3161
|
+
}),
|
|
3162
|
+
readTranscript: readCursorTranscript
|
|
3163
|
+
}
|
|
3164
|
+
},
|
|
3165
|
+
"copilot-cli": {
|
|
3166
|
+
configStyle: "flat",
|
|
3167
|
+
install: {
|
|
3168
|
+
sessionStart: { event: "sessionStart", entry: "copilot-sessionstart-hook.js", timeout: 30 },
|
|
3169
|
+
prompt: { event: "userPromptTransformed", entry: "copilot-hook.js", timeout: 30 },
|
|
3170
|
+
stop: { event: "agentStop", entry: "copilot-stop-hook.js", timeout: 60 }
|
|
3171
|
+
},
|
|
3172
|
+
sessionStart: {
|
|
3173
|
+
harness: "copilot-cli",
|
|
3174
|
+
parse: (ev) => ({
|
|
3175
|
+
cwd: ev.cwd,
|
|
3176
|
+
sessionId: ev.sessionId
|
|
3177
|
+
}),
|
|
3178
|
+
// Copilot CLI's SessionStart response only has model-facing `additionalContext`; unlike
|
|
3179
|
+
// Claude/Cursor it has no supported in-TUI system-message/banner channel. Keep memory
|
|
3180
|
+
// quiet rather than auto-submitting a synthetic prompt or showing an OS notification. When
|
|
3181
|
+
// Copilot exposes a real TUI extension point, add the banner there without changing this
|
|
3182
|
+
// shared lifecycle output.
|
|
3183
|
+
emit: (out) => ({
|
|
3184
|
+
...out.additionalContext ? { additionalContext: out.additionalContext } : {}
|
|
3185
|
+
})
|
|
3186
|
+
},
|
|
3187
|
+
prompt: copilotPrompt,
|
|
3188
|
+
retain: {
|
|
3189
|
+
hostTimeoutSec: 60,
|
|
3190
|
+
harness: "copilot-cli",
|
|
3191
|
+
parse: (ev) => ({
|
|
3192
|
+
sessionId: ev.sessionId,
|
|
3193
|
+
transcriptPath: ev.transcriptPath,
|
|
3194
|
+
cwd: ev.cwd
|
|
3195
|
+
}),
|
|
3196
|
+
readTranscript: readCopilotTranscript
|
|
3197
|
+
}
|
|
3198
|
+
},
|
|
3199
|
+
"devin-cli": {
|
|
3200
|
+
configStyle: "nested",
|
|
3201
|
+
install: {
|
|
3202
|
+
sessionStart: { event: "SessionStart", entry: "devin-sessionstart-hook.js", timeout: 30 },
|
|
3203
|
+
prompt: { event: "UserPromptSubmit", entry: "devin-hook.js", timeout: 30 },
|
|
3204
|
+
stop: { event: "Stop", entry: "devin-stop-hook.js", timeout: 60 }
|
|
3205
|
+
},
|
|
3206
|
+
sessionStart: {
|
|
3207
|
+
harness: "devin-cli",
|
|
3208
|
+
parse: (ev) => ({ cwd: devinCwd(), sessionId: ev.session_id }),
|
|
3209
|
+
emit: (out) => ({
|
|
3210
|
+
hookSpecificOutput: {
|
|
3211
|
+
hookEventName: "SessionStart",
|
|
3212
|
+
...out.additionalContext ? { additionalContext: out.additionalContext } : {}
|
|
3213
|
+
}
|
|
3214
|
+
})
|
|
3215
|
+
},
|
|
3216
|
+
prompt: devinPrompt,
|
|
3217
|
+
retain: {
|
|
3218
|
+
hostTimeoutSec: 60,
|
|
3219
|
+
harness: "devin-cli",
|
|
3220
|
+
parse: (ev) => {
|
|
3221
|
+
const sessionId = ev.session_id;
|
|
3222
|
+
return {
|
|
3223
|
+
sessionId,
|
|
3224
|
+
// RetainHook calls the supplied reader with transcriptPath; Devin's reader uses its
|
|
3225
|
+
// session id because the CLI persists conversations in sessions.db rather than a file.
|
|
3226
|
+
transcriptPath: sessionId,
|
|
3227
|
+
cwd: devinCwd()
|
|
3228
|
+
};
|
|
3229
|
+
},
|
|
3230
|
+
readTranscript: readDevinTranscript
|
|
3231
|
+
}
|
|
3232
|
+
},
|
|
3233
|
+
"grok-build": {
|
|
3234
|
+
configStyle: "nested",
|
|
3235
|
+
install: {
|
|
3236
|
+
sessionStart: { event: "SessionStart", entry: "grok-sessionstart-hook.js", timeout: 30 },
|
|
3237
|
+
prompt: { event: "UserPromptSubmit", entry: "grok-hook.js", timeout: 30 },
|
|
3238
|
+
stop: { event: "Stop", entry: "grok-stop-hook.js", timeout: 60 }
|
|
3239
|
+
},
|
|
3240
|
+
sessionStart: {
|
|
3241
|
+
...standardSessionStart("grok-build"),
|
|
3242
|
+
// Grok's wire envelope is camelCase, unlike Claude's similarly named hook events.
|
|
3243
|
+
parse: (ev) => ({
|
|
3244
|
+
cwd: ev.cwd,
|
|
3245
|
+
sessionId: ev.sessionId
|
|
3246
|
+
})
|
|
3247
|
+
},
|
|
3248
|
+
prompt: {
|
|
3249
|
+
...claudePrompt,
|
|
3250
|
+
harness: "grok-build",
|
|
3251
|
+
parse: (ev) => ({
|
|
3252
|
+
prompt: ev.prompt,
|
|
3253
|
+
cwd: ev.cwd,
|
|
3254
|
+
sessionId: ev.sessionId
|
|
3255
|
+
})
|
|
3256
|
+
},
|
|
3257
|
+
retain: {
|
|
3258
|
+
hostTimeoutSec: 60,
|
|
3259
|
+
harness: "grok-build",
|
|
3260
|
+
parse: (ev) => ({
|
|
3261
|
+
sessionId: ev.sessionId,
|
|
3262
|
+
transcriptPath: typeof ev.cwd === "string" && typeof ev.sessionId === "string" ? grokTranscriptPath(ev.cwd, ev.sessionId) : void 0,
|
|
3263
|
+
cwd: ev.cwd
|
|
3264
|
+
}),
|
|
3265
|
+
readTranscript: readGrokTranscript
|
|
3266
|
+
}
|
|
3267
|
+
},
|
|
3268
|
+
"qwen-code": {
|
|
3269
|
+
configStyle: "nested",
|
|
3270
|
+
timeoutUnit: "milliseconds",
|
|
3271
|
+
// TIMEOUTS ARE MILLISECONDS HERE, not seconds like every other harness in this table: Qwen's
|
|
3272
|
+
// hookRunner does `setTimeout(..., hookConfig.timeout ?? DEFAULT_HOOK_TIMEOUT)` with
|
|
3273
|
+
// DEFAULT_HOOK_TIMEOUT = 60_000 ("Timeout in milliseconds, default 60000"). Writing 30/60
|
|
3274
|
+
// registers 30ms/60ms hooks, which die before a Node process starts — and Qwen spawns hooks
|
|
3275
|
+
// `detached` and terminates the whole process TREE on timeout, so the retain is genuinely lost
|
|
3276
|
+
// rather than merely orphaned. `retain.hostTimeoutSec` below stays SECONDS, as its name says;
|
|
3277
|
+
// these two numbers are the same budget in different units for this harness alone.
|
|
3278
|
+
// The prompt timeout must also stay above core/hook.ts's HOOK_REFLECT_CAP_MS (25_000).
|
|
3279
|
+
install: {
|
|
3280
|
+
sessionStart: { event: "SessionStart", entry: "qwen-sessionstart-hook.js", timeout: 3e4 },
|
|
3281
|
+
prompt: { event: "UserPromptSubmit", entry: "qwen-hook.js", timeout: 3e4 },
|
|
3282
|
+
stop: { event: "Stop", entry: "qwen-stop-hook.js", timeout: 6e4 }
|
|
3283
|
+
},
|
|
3284
|
+
sessionStart: standardSessionStart("qwen-code"),
|
|
3285
|
+
prompt: qwenPrompt,
|
|
3286
|
+
retain: {
|
|
3287
|
+
hostTimeoutSec: 60,
|
|
3288
|
+
harness: "qwen-code",
|
|
3289
|
+
parse: (ev) => ({
|
|
3290
|
+
sessionId: ev.session_id,
|
|
3291
|
+
// Qwen supplies the path, but as the EMPTY STRING (not null, not absent) when chat
|
|
3292
|
+
// recording is off — runRetainHook's `if (!transcriptPath) return` already covers that.
|
|
3293
|
+
transcriptPath: ev.transcript_path,
|
|
3294
|
+
cwd: ev.cwd
|
|
3295
|
+
}),
|
|
3296
|
+
readTranscript: readQwenTranscript
|
|
3297
|
+
}
|
|
3298
|
+
},
|
|
3299
|
+
"factory-droid": {
|
|
3300
|
+
configStyle: "nested",
|
|
3301
|
+
install: {
|
|
3302
|
+
sessionStart: { event: "SessionStart", entry: "droid-sessionstart-hook.js", timeout: 30 },
|
|
3303
|
+
prompt: { event: "UserPromptSubmit", entry: "droid-hook.js", timeout: 30 },
|
|
3304
|
+
stop: { event: "Stop", entry: "droid-stop-hook.js", timeout: 60 }
|
|
3305
|
+
},
|
|
3306
|
+
// Droid emits Notification(idle_prompt), not Stop, after user cancellation. Reusing the
|
|
3307
|
+
// idempotent retain entry point captures that final partial turn; its event gate ignores every
|
|
3308
|
+
// other notification type before config or daemon work begins.
|
|
3309
|
+
additionalHooks: [{ event: "Notification", entry: "droid-stop-hook.js", timeout: 60 }],
|
|
3310
|
+
sessionStart: standardSessionStart("factory-droid"),
|
|
3311
|
+
prompt: droidPrompt,
|
|
3312
|
+
retain: {
|
|
3313
|
+
hostTimeoutSec: 60,
|
|
3314
|
+
harness: "factory-droid",
|
|
3315
|
+
accept: (ev) => ev.hook_event_name === "Stop" || ev.hook_event_name === "Notification" && ev.notification_type === "idle_prompt",
|
|
3316
|
+
parse: (ev) => ({
|
|
3317
|
+
sessionId: ev.session_id,
|
|
3318
|
+
transcriptPath: ev.transcript_path,
|
|
3319
|
+
cwd: ev.cwd
|
|
3320
|
+
}),
|
|
3321
|
+
readTranscript: readDroidTranscript
|
|
3322
|
+
}
|
|
3323
|
+
}
|
|
3324
|
+
};
|
|
3325
|
+
var runHarnessSessionStart = (harness) => runSessionStartHook(HOOK_HARNESSES[harness].sessionStart);
|
|
3326
|
+
|
|
3327
|
+
// src/droid-sessionstart-hook.ts
|
|
3328
|
+
void runHarnessSessionStart("factory-droid");
|