@vectorize-io/hindsight-coding-agents 0.3.4 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +101 -32
- package/dist/antigravity-hook.js +449 -282
- package/dist/antigravity-statusline.js +130 -27
- package/dist/antigravity-stop-hook.js +456 -284
- package/dist/claude-hook.js +449 -282
- package/dist/claude-sessionstart-hook.js +461 -288
- package/dist/claude-stop-hook.js +456 -284
- package/dist/cline.js +652 -348
- package/dist/codex-hook.js +449 -282
- package/dist/codex-sessionstart-hook.js +461 -288
- package/dist/codex-stop-hook.js +456 -284
- package/dist/copilot-hook.js +449 -282
- package/dist/copilot-sessionstart-hook.js +461 -288
- package/dist/copilot-stop-hook.js +456 -284
- package/dist/cursor-hook.js +449 -282
- package/dist/cursor-sessionstart-hook.js +461 -288
- package/dist/cursor-stop-hook.js +456 -284
- package/dist/daemon-start.js +101 -45
- package/dist/deepen.js +314 -149
- package/dist/devin-hook.js +449 -282
- package/dist/devin-sessionstart-hook.js +461 -288
- package/dist/devin-stop-hook.js +456 -284
- package/dist/dsh.js +888 -585
- package/dist/grok-hook.js +449 -282
- package/dist/grok-sessionstart-hook.js +461 -288
- package/dist/grok-stop-hook.js +456 -284
- package/dist/hindsight-seed.js +122 -24
- package/dist/index.js +676 -371
- package/dist/installer.js +40 -48
- package/dist/kilo.js +676 -371
- package/dist/mcp-server.js +550 -318
- package/dist/prime-agent.js +888 -582
- package/dist/status.js +444 -263
- package/package.json +10 -2
- package/skill/SKILL.md +20 -4
package/dist/claude-stop-hook.js
CHANGED
|
@@ -41,8 +41,8 @@ function getProjectRootFromGit(directory) {
|
|
|
41
41
|
return null;
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
-
function projectNameOf(directory) {
|
|
45
|
-
return gitProjectName(directory, true);
|
|
44
|
+
function projectNameOf(directory, sessionRoot) {
|
|
45
|
+
return gitProjectName(directory, true, sessionRoot);
|
|
46
46
|
}
|
|
47
47
|
var PROJECT_ROOT_ENV = ["CLAUDE_PROJECT_DIR"];
|
|
48
48
|
function nearestExistingDir(directory) {
|
|
@@ -58,18 +58,24 @@ function nearestExistingDir(directory) {
|
|
|
58
58
|
function dirName(directory) {
|
|
59
59
|
return directory && basename(directory) || "unknown";
|
|
60
60
|
}
|
|
61
|
-
function
|
|
61
|
+
function mainWorktreeRoot(directory, sessionRoot = "") {
|
|
62
|
+
const candidates = [
|
|
63
|
+
nearestExistingDir(directory),
|
|
64
|
+
sessionRoot,
|
|
65
|
+
...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
|
|
66
|
+
];
|
|
67
|
+
for (const candidate of candidates) {
|
|
68
|
+
const root = candidate ? getProjectRootFromGit(candidate) : null;
|
|
69
|
+
if (root) return root;
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
function gitProjectName(directory, resolveWorktrees, sessionRoot = "") {
|
|
62
74
|
if (resolveWorktrees) {
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
...PROJECT_ROOT_ENV.map((v) => process.env[v] || "")
|
|
66
|
-
];
|
|
67
|
-
for (const candidate of candidates) {
|
|
68
|
-
const root = candidate ? getProjectRootFromGit(candidate) : null;
|
|
69
|
-
if (root) return basename(root);
|
|
70
|
-
}
|
|
75
|
+
const root = mainWorktreeRoot(directory, sessionRoot);
|
|
76
|
+
if (root) return basename(root);
|
|
71
77
|
}
|
|
72
|
-
return dirName(directory);
|
|
78
|
+
return dirName(sessionRoot || directory);
|
|
73
79
|
}
|
|
74
80
|
function configuredDir(dir) {
|
|
75
81
|
const expanded = dir === "~" || dir.startsWith("~/") ? join(homedir(), dir.slice(1)) : dir;
|
|
@@ -89,23 +95,38 @@ function mapLookup(map, directory) {
|
|
|
89
95
|
}
|
|
90
96
|
return best?.bank;
|
|
91
97
|
}
|
|
98
|
+
function lookupDirectories(config, directory, sessionRoot = "") {
|
|
99
|
+
const directories = [normalize(directory)];
|
|
100
|
+
if (config.resolveWorktrees ?? true) {
|
|
101
|
+
const root = mainWorktreeRoot(directory, sessionRoot);
|
|
102
|
+
const normalizedRoot = root ? normalize(root) : "";
|
|
103
|
+
if (normalizedRoot && normalizedRoot !== directories[0]) directories.push(normalizedRoot);
|
|
104
|
+
}
|
|
105
|
+
return directories;
|
|
106
|
+
}
|
|
92
107
|
function isOptedIn(config, directory) {
|
|
93
108
|
if (!config.optInOnly) return true;
|
|
94
109
|
if (!directory) return false;
|
|
95
|
-
const
|
|
96
|
-
if (
|
|
110
|
+
const directories = lookupDirectories(config, directory);
|
|
111
|
+
if (directories.some(
|
|
112
|
+
(candidate) => (config.optInPaths ?? []).some(
|
|
113
|
+
(configured) => configured && isWithin(candidate, configuredDir(configured))
|
|
114
|
+
)
|
|
115
|
+
))
|
|
97
116
|
return true;
|
|
98
|
-
|
|
117
|
+
const pathMap = config.mapPathToBank;
|
|
118
|
+
return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
|
|
99
119
|
}
|
|
100
|
-
function deriveBankId(config, directory, harness = "coding") {
|
|
101
|
-
const
|
|
120
|
+
function deriveBankId(config, directory, harness = "coding", sessionRoot) {
|
|
121
|
+
const pathMap = config.mapPathToBank;
|
|
122
|
+
const mapped = directory && pathMap ? lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
|
|
102
123
|
if (mapped) return mapped;
|
|
103
124
|
const dynamic = config.dynamicBankId ?? !config.bankId;
|
|
104
125
|
if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
|
|
105
126
|
const resolvers = {
|
|
106
127
|
harness: () => harness,
|
|
107
128
|
project: () => dirName(directory),
|
|
108
|
-
gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true),
|
|
129
|
+
gitProject: () => gitProjectName(directory, config.resolveWorktrees ?? true, sessionRoot),
|
|
109
130
|
channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
|
|
110
131
|
user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
|
|
111
132
|
};
|
|
@@ -115,7 +136,7 @@ function deriveBankId(config, directory, harness = "coding") {
|
|
|
115
136
|
// src/core/config.ts
|
|
116
137
|
import { readFileSync } from "fs";
|
|
117
138
|
import { homedir as homedir2 } from "os";
|
|
118
|
-
import { join as
|
|
139
|
+
import { join as join4 } from "path";
|
|
119
140
|
|
|
120
141
|
// src/core/seed.ts
|
|
121
142
|
import { spawn as realSpawn } from "child_process";
|
|
@@ -123,204 +144,10 @@ import { dirname as dirname2, join as join2 } from "path";
|
|
|
123
144
|
import { fileURLToPath } from "url";
|
|
124
145
|
var DEFAULT_SEED_LIMIT = 300;
|
|
125
146
|
|
|
126
|
-
// src/core/config.ts
|
|
127
|
-
var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join3(homedir2(), ".hindsight", "coding-agent.json");
|
|
128
|
-
var DEFAULT_DAEMON_PORT = 9077;
|
|
129
|
-
var DEFAULT_DAEMON_IDLE_TIMEOUT = 300;
|
|
130
|
-
var DEFAULT_DAEMON_PROFILE = "coding-agent";
|
|
131
|
-
function resolveConfig(raw = {}) {
|
|
132
|
-
const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
|
|
133
|
-
const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
|
|
134
|
-
return {
|
|
135
|
-
serverMode,
|
|
136
|
-
// Daemon mode resolves the URL HERE rather than at each call site: every entry point already
|
|
137
|
-
// builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
|
|
138
|
-
// daemon needs no plumbing through eight separate constructors.
|
|
139
|
-
apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
|
|
140
|
-
apiToken: raw.apiToken || void 0,
|
|
141
|
-
apiPort,
|
|
142
|
-
daemonIdleTimeout: raw.daemonIdleTimeout ?? DEFAULT_DAEMON_IDLE_TIMEOUT,
|
|
143
|
-
daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
|
|
144
|
-
embedVersion: raw.embedVersion || void 0,
|
|
145
|
-
embedPackagePath: raw.embedPackagePath || void 0,
|
|
146
|
-
bankId: raw.bankId,
|
|
147
|
-
dynamicBankId: raw.dynamicBankId,
|
|
148
|
-
bankIdTemplate: raw.bankIdTemplate,
|
|
149
|
-
mapPathToBank: raw.mapPathToBank,
|
|
150
|
-
resolveWorktrees: raw.resolveWorktrees,
|
|
151
|
-
optInOnly: raw.optInOnly ?? false,
|
|
152
|
-
// Same shape as retainTags: a config typo must not become a path that silently approves nothing.
|
|
153
|
-
optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
|
|
154
|
-
harness: raw.harness ?? "opencode",
|
|
155
|
-
disabled: raw.disabled ?? false,
|
|
156
|
-
retainSessions: raw.retainSessions ?? true,
|
|
157
|
-
// opencode: write back by default (parity with hook-harness Stop)
|
|
158
|
-
maxParallelRetains: raw.maxParallelRetains || 10,
|
|
159
|
-
reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
|
|
160
|
-
autoReflect: raw.autoReflect ?? true,
|
|
161
|
-
pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
|
|
162
|
-
autoSeed: raw.autoSeed ?? true,
|
|
163
|
-
seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
|
|
164
|
-
codebaseSurvey: raw.codebaseSurvey ?? true,
|
|
165
|
-
surveyModel: raw.surveyModel || "haiku",
|
|
166
|
-
surveyBudgetUsd: raw.surveyBudgetUsd || 2,
|
|
167
|
-
surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
|
|
168
|
-
gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
|
|
169
|
-
// Hostile input is a config typo, not an attack: keep only string entries so a stray number or
|
|
170
|
-
// nested object cannot reach the API as a tag and fail the whole retain.
|
|
171
|
-
retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
|
|
172
|
-
retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
|
|
173
|
-
Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
|
|
174
|
-
) : {},
|
|
175
|
-
banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
|
|
176
|
-
logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
function readRaw(path) {
|
|
180
|
-
try {
|
|
181
|
-
return JSON.parse(readFileSync(path, "utf8"));
|
|
182
|
-
} catch (e) {
|
|
183
|
-
if (e?.code !== "ENOENT") {
|
|
184
|
-
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
185
|
-
}
|
|
186
|
-
return {};
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
function mergeRaw(a, b) {
|
|
190
|
-
const { harnesses: _drop, ...flat } = b;
|
|
191
|
-
return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
|
|
192
|
-
}
|
|
193
|
-
function applyLayer(raw, layer, harness) {
|
|
194
|
-
let out = mergeRaw(raw, layer);
|
|
195
|
-
const perHarness = harness ? layer.harnesses?.[harness] : void 0;
|
|
196
|
-
if (perHarness) out = mergeRaw(out, perHarness);
|
|
197
|
-
return out;
|
|
198
|
-
}
|
|
199
|
-
var ENV_KEYS = {
|
|
200
|
-
serverMode: "HINDSIGHT_SERVER_MODE",
|
|
201
|
-
apiUrl: "HINDSIGHT_API_URL",
|
|
202
|
-
apiToken: "HINDSIGHT_API_TOKEN",
|
|
203
|
-
// These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
|
|
204
|
-
// it can carry their existing environment over unchanged.
|
|
205
|
-
apiPort: "HINDSIGHT_API_PORT",
|
|
206
|
-
daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
|
|
207
|
-
embedVersion: "HINDSIGHT_EMBED_VERSION",
|
|
208
|
-
embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
|
|
209
|
-
daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
|
|
210
|
-
bankId: "HINDSIGHT_BANK_ID",
|
|
211
|
-
dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
|
|
212
|
-
bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
|
|
213
|
-
resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
|
|
214
|
-
optInOnly: "HINDSIGHT_OPT_IN_ONLY",
|
|
215
|
-
optInPaths: "HINDSIGHT_OPT_IN_PATHS",
|
|
216
|
-
harness: "HINDSIGHT_HARNESS",
|
|
217
|
-
disabled: "HINDSIGHT_DISABLED",
|
|
218
|
-
retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
|
|
219
|
-
maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
|
|
220
|
-
reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
|
|
221
|
-
autoReflect: "HINDSIGHT_AUTO_REFLECT",
|
|
222
|
-
pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
|
|
223
|
-
autoSeed: "HINDSIGHT_AUTO_SEED",
|
|
224
|
-
seedLimit: "HINDSIGHT_SEED_LIMIT",
|
|
225
|
-
codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
|
|
226
|
-
surveyModel: "HINDSIGHT_SURVEY_MODEL",
|
|
227
|
-
surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
|
|
228
|
-
surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
|
|
229
|
-
logLevel: "HINDSIGHT_LOG_LEVEL",
|
|
230
|
-
gitIngest: "HINDSIGHT_GIT_INGEST",
|
|
231
|
-
// Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
|
|
232
|
-
// a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
|
|
233
|
-
retainTags: "HINDSIGHT_RETAIN_TAGS"
|
|
234
|
-
};
|
|
235
|
-
var ENV_BOOLEANS = /* @__PURE__ */ new Set([
|
|
236
|
-
"dynamicBankId",
|
|
237
|
-
"resolveWorktrees",
|
|
238
|
-
"optInOnly",
|
|
239
|
-
"disabled",
|
|
240
|
-
"retainSessions",
|
|
241
|
-
"autoReflect",
|
|
242
|
-
"autoSeed",
|
|
243
|
-
"codebaseSurvey"
|
|
244
|
-
]);
|
|
245
|
-
var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
|
|
246
|
-
var ENV_NUMBERS = /* @__PURE__ */ new Set([
|
|
247
|
-
"apiPort",
|
|
248
|
-
"daemonIdleTimeout",
|
|
249
|
-
"maxParallelRetains",
|
|
250
|
-
"reflectTimeoutMs",
|
|
251
|
-
"pageRefreshEveryTurns",
|
|
252
|
-
"seedLimit",
|
|
253
|
-
"surveyBudgetUsd",
|
|
254
|
-
"surveyRefreshCommits"
|
|
255
|
-
]);
|
|
256
|
-
function readEnvConfig(env = process.env) {
|
|
257
|
-
const out = {};
|
|
258
|
-
for (const [key, name] of Object.entries(ENV_KEYS)) {
|
|
259
|
-
const value = env[name];
|
|
260
|
-
if (value === void 0 || value.trim() === "") continue;
|
|
261
|
-
if (ENV_BOOLEANS.has(key)) {
|
|
262
|
-
out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
|
|
263
|
-
} else if (ENV_LISTS.has(key)) {
|
|
264
|
-
const items = value.split(",").map((v) => v.trim()).filter(Boolean);
|
|
265
|
-
if (items.length) out[key] = items;
|
|
266
|
-
} else if (ENV_NUMBERS.has(key)) {
|
|
267
|
-
const n = Number(value);
|
|
268
|
-
if (Number.isFinite(n)) out[key] = n;
|
|
269
|
-
else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
|
|
270
|
-
} else {
|
|
271
|
-
out[key] = value;
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
return out;
|
|
275
|
-
}
|
|
276
|
-
function loadConfig(opts = {}) {
|
|
277
|
-
const o = typeof opts === "string" ? { path: opts } : opts;
|
|
278
|
-
const withEnv = applyLayer({}, readEnvConfig(), o.harness);
|
|
279
|
-
const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
|
|
280
|
-
if (!raw.harness && o.harness) raw.harness = o.harness;
|
|
281
|
-
return resolveConfig(raw);
|
|
282
|
-
}
|
|
283
|
-
var BANK_OVERRIDE_EXCLUDED = [
|
|
284
|
-
"bankId",
|
|
285
|
-
"bankIdTemplate",
|
|
286
|
-
"mapPathToBank",
|
|
287
|
-
"dynamicBankId",
|
|
288
|
-
"resolveWorktrees",
|
|
289
|
-
// Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
|
|
290
|
-
// only ever arrive too late to matter — strip them rather than let them read as effective.
|
|
291
|
-
"optInOnly",
|
|
292
|
-
"optInPaths",
|
|
293
|
-
"harness"
|
|
294
|
-
];
|
|
295
|
-
function applyBankConfig(cfg, resolvedId, directory) {
|
|
296
|
-
if (directory !== void 0 && !isOptedIn(cfg, directory))
|
|
297
|
-
return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
|
|
298
|
-
const section = cfg.banks[resolvedId];
|
|
299
|
-
if (!section) return { cfg, bankId: resolvedId };
|
|
300
|
-
const safe = { ...section };
|
|
301
|
-
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
302
|
-
delete safe.banks;
|
|
303
|
-
const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
|
|
304
|
-
delete safe.bank;
|
|
305
|
-
return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
|
|
306
|
-
}
|
|
307
|
-
function resolvePartial(cfg, patch) {
|
|
308
|
-
const full = resolveConfig(patch);
|
|
309
|
-
const out = {};
|
|
310
|
-
for (const key of Object.keys(patch)) {
|
|
311
|
-
if (key in full)
|
|
312
|
-
out[key] = full[key];
|
|
313
|
-
}
|
|
314
|
-
return out;
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
// src/core/diag.ts
|
|
318
|
-
import { appendFileSync as appendFileSync2 } from "fs";
|
|
319
|
-
|
|
320
147
|
// src/core/log.ts
|
|
321
148
|
import { appendFileSync, mkdirSync } from "fs";
|
|
322
149
|
import { tmpdir } from "os";
|
|
323
|
-
import { dirname as dirname3, join as
|
|
150
|
+
import { dirname as dirname3, join as join3 } from "path";
|
|
324
151
|
var WEIGHT = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
325
152
|
var current = ["debug", "info", "warn", "error"].find(
|
|
326
153
|
(l) => l === process.env.HINDSIGHT_LOG_LEVEL
|
|
@@ -329,7 +156,7 @@ function setLogLevel(level) {
|
|
|
329
156
|
if (!process.env.HINDSIGHT_LOG_LEVEL) current = level;
|
|
330
157
|
}
|
|
331
158
|
function logFilePath() {
|
|
332
|
-
return process.env.HINDSIGHT_LOG_FILE ||
|
|
159
|
+
return process.env.HINDSIGHT_LOG_FILE || join3(tmpdir(), "hindsight-coding-agent", "plugin.log");
|
|
333
160
|
}
|
|
334
161
|
function write(level, scope, msg, extra) {
|
|
335
162
|
if (WEIGHT[level] < WEIGHT[current]) return;
|
|
@@ -364,21 +191,6 @@ function describeError(value, maxChars = 200) {
|
|
|
364
191
|
return (parts.join(": ") || String(value)).slice(0, maxChars);
|
|
365
192
|
}
|
|
366
193
|
|
|
367
|
-
// src/core/diag.ts
|
|
368
|
-
function diagFilePath() {
|
|
369
|
-
return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
|
|
370
|
-
}
|
|
371
|
-
function diag(harness, event, extra = {}) {
|
|
372
|
-
log.debug(harness, `diag:${event}`, extra);
|
|
373
|
-
try {
|
|
374
|
-
appendFileSync2(
|
|
375
|
-
diagFilePath(),
|
|
376
|
-
JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
|
|
377
|
-
);
|
|
378
|
-
} catch {
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
|
|
382
194
|
// src/core/missions.ts
|
|
383
195
|
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.";
|
|
384
196
|
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.";
|
|
@@ -454,7 +266,10 @@ var KNOWLEDGE_LABELS = {
|
|
|
454
266
|
}
|
|
455
267
|
]
|
|
456
268
|
};
|
|
457
|
-
|
|
269
|
+
function pageScopeRule(project) {
|
|
270
|
+
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.`;
|
|
271
|
+
}
|
|
272
|
+
var PAGE_TAXONOMY = [
|
|
458
273
|
{
|
|
459
274
|
name: "Component map",
|
|
460
275
|
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.",
|
|
@@ -477,15 +292,28 @@ var PAGES = [
|
|
|
477
292
|
},
|
|
478
293
|
{
|
|
479
294
|
name: "Initiatives and enhancements",
|
|
480
|
-
source_query: "Based on this repository's commit history, what are the major initiatives, features, and enhancements the project has worked on? Summarize the themes and notable changes over time. When a source memory carries a
|
|
295
|
+
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.",
|
|
481
296
|
tags: ["knowledge:feature-work"]
|
|
482
297
|
}
|
|
483
298
|
];
|
|
299
|
+
function pagesFor(project) {
|
|
300
|
+
const scope = pageScopeRule(project);
|
|
301
|
+
return PAGE_TAXONOMY.map((page) => ({ ...page, source_query: page.source_query + scope }));
|
|
302
|
+
}
|
|
484
303
|
var PAGE_MAX_TOKENS = 4096;
|
|
485
|
-
var
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
};
|
|
304
|
+
var PAGE_TAGS_MATCH = "all";
|
|
305
|
+
var PAGE_FACT_TYPES = ["world", "experience", "observation"];
|
|
306
|
+
function buildPageTrigger(cfg = {}) {
|
|
307
|
+
const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
|
|
308
|
+
switch (cfg.pageTriggerType) {
|
|
309
|
+
case "cron":
|
|
310
|
+
return { ...base, refresh_cron: cfg.pageTriggerCron };
|
|
311
|
+
case "manual":
|
|
312
|
+
return { ...base, refresh_after_consolidation: false };
|
|
313
|
+
default:
|
|
314
|
+
return { ...base, refresh_after_consolidation: true };
|
|
315
|
+
}
|
|
316
|
+
}
|
|
489
317
|
var CODING_BANK_TEMPLATE = {
|
|
490
318
|
version: "1",
|
|
491
319
|
bank: {
|
|
@@ -540,6 +368,7 @@ async function pool(items, n, fn, onError, onProgress) {
|
|
|
540
368
|
}
|
|
541
369
|
|
|
542
370
|
// src/core/hindsight.ts
|
|
371
|
+
var DEFAULT_OBSERVATION_SCOPES = "shared";
|
|
543
372
|
var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
|
|
544
373
|
var RateLimitedError = class extends Error {
|
|
545
374
|
constructor(retryAfterMs2) {
|
|
@@ -572,8 +401,12 @@ var RETRY_AFTER_CEILING_MS = 60 * 1e3;
|
|
|
572
401
|
var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
|
|
573
402
|
var HindsightClient = class {
|
|
574
403
|
apiUrl;
|
|
575
|
-
|
|
404
|
+
/** The credential the NEXT request will sign with — NOT the one the config file holds. The two
|
|
405
|
+
* diverge exactly when #3600 bites, which is why `hindsight_diagnose` reports both. */
|
|
406
|
+
token;
|
|
407
|
+
tokenProvider;
|
|
576
408
|
bank;
|
|
409
|
+
project;
|
|
577
410
|
opIds = [];
|
|
578
411
|
// async operation ids collected by retain(), for drain()
|
|
579
412
|
/** Tri-state capability probe: unknown until the first page request, then cached. */
|
|
@@ -582,34 +415,81 @@ var HindsightClient = class {
|
|
|
582
415
|
idempotentRetain;
|
|
583
416
|
log;
|
|
584
417
|
maxParallelRetains;
|
|
418
|
+
observationScopes;
|
|
585
419
|
constructor(o) {
|
|
586
420
|
this.apiUrl = o.apiUrl.replace(/\/$/, "");
|
|
587
|
-
this.
|
|
421
|
+
this.token = o.apiToken;
|
|
422
|
+
this.tokenProvider = o.tokenProvider;
|
|
588
423
|
this.bank = o.bank;
|
|
424
|
+
this.project = o.project;
|
|
589
425
|
this.log = o.log ?? (() => {
|
|
590
426
|
});
|
|
591
427
|
this.maxParallelRetains = o.maxParallelRetains || DEFAULT_MAX_PARALLEL_RETAINS;
|
|
428
|
+
this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
|
|
429
|
+
}
|
|
430
|
+
/** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
|
|
431
|
+
get apiToken() {
|
|
432
|
+
return this.token;
|
|
592
433
|
}
|
|
593
434
|
headers() {
|
|
594
435
|
const h = { "Content-Type": "application/json" };
|
|
595
|
-
if (this.
|
|
436
|
+
if (this.token) h["Authorization"] = `Bearer ${this.token}`;
|
|
596
437
|
return h;
|
|
597
438
|
}
|
|
439
|
+
/** Re-read the credential from the live config. Returns whether it actually CHANGED — a retry is
|
|
440
|
+
* only worth sending if it did, so a genuinely wrong key still surfaces as one 401 rather than
|
|
441
|
+
* doubling every failing request. */
|
|
442
|
+
refreshToken() {
|
|
443
|
+
if (!this.tokenProvider) return false;
|
|
444
|
+
let next;
|
|
445
|
+
try {
|
|
446
|
+
next = this.tokenProvider();
|
|
447
|
+
} catch {
|
|
448
|
+
return false;
|
|
449
|
+
}
|
|
450
|
+
if (next === this.token) return false;
|
|
451
|
+
this.token = next;
|
|
452
|
+
return true;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* The ONE place a request is signed. Every fetch goes through it — the generic `req`, the drain
|
|
456
|
+
* poll and `reflect` — because a 401 recovery wired into only one of them leaves the others
|
|
457
|
+
* failing forever, which is how #3600 read from the outside: hooks worked, in-session tools did
|
|
458
|
+
* not.
|
|
459
|
+
*
|
|
460
|
+
* On a 401 the credential is re-resolved and the request replayed ONCE (its body is already a
|
|
461
|
+
* string, so replay is exact). A 401 means the server did nothing, so replaying is side-effect
|
|
462
|
+
* free even for retain. The retry shares the caller's `signal`, deliberately: one deadline still
|
|
463
|
+
* bounds the whole call.
|
|
464
|
+
*/
|
|
465
|
+
async fetchWithAuth(url, init) {
|
|
466
|
+
const send = () => fetch(url, { ...init, headers: this.headers() });
|
|
467
|
+
const r = await send();
|
|
468
|
+
if (r.status !== 401 || !this.refreshToken()) return r;
|
|
469
|
+
return send();
|
|
470
|
+
}
|
|
471
|
+
/** A 401 with no `Authorization` header is a different failure from a rejected key, and the
|
|
472
|
+
* server answers identically for both — only the client knows which it sent. */
|
|
473
|
+
authHint(status) {
|
|
474
|
+
if (status !== 401) return "";
|
|
475
|
+
return this.token ? " (the configured apiToken was rejected \u2014 check ~/.hindsight/coding-agent.json)" : " (no apiToken is configured, so no Authorization header was sent)";
|
|
476
|
+
}
|
|
598
477
|
bankUrl(suffix = "") {
|
|
599
478
|
return `${this.apiUrl}/v1/default/banks/${encodeURIComponent(this.bank)}${suffix}`;
|
|
600
479
|
}
|
|
601
480
|
/** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
|
|
602
481
|
async req(method, url, body, tolerate = []) {
|
|
603
|
-
const r = await
|
|
482
|
+
const r = await this.fetchWithAuth(url, {
|
|
604
483
|
method,
|
|
605
|
-
headers: this.headers(),
|
|
606
484
|
body: body ? JSON.stringify(body) : void 0,
|
|
607
485
|
signal: AbortSignal.timeout(15e3)
|
|
608
486
|
});
|
|
609
487
|
if (r.status === 429 && !tolerate.includes(429))
|
|
610
488
|
throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
|
|
611
489
|
if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
|
|
612
|
-
throw new Error(
|
|
490
|
+
throw new Error(
|
|
491
|
+
`${method} ${url} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
|
|
492
|
+
);
|
|
613
493
|
return r;
|
|
614
494
|
}
|
|
615
495
|
/** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
|
|
@@ -620,7 +500,11 @@ var HindsightClient = class {
|
|
|
620
500
|
context,
|
|
621
501
|
document_id: documentId,
|
|
622
502
|
tags,
|
|
623
|
-
strategy
|
|
503
|
+
strategy,
|
|
504
|
+
// Sent on EVERY retain, including the server default `combined`, so the scoping a bank's
|
|
505
|
+
// observations were built under is a property of the write rather than of whichever server
|
|
506
|
+
// version happened to process it. Servers older than 0.4.15 ignore the field.
|
|
507
|
+
observation_scopes: this.observationScopes
|
|
624
508
|
};
|
|
625
509
|
if (opts.timestamp) item.timestamp = opts.timestamp;
|
|
626
510
|
if (opts.metadata) item.metadata = opts.metadata;
|
|
@@ -699,7 +583,7 @@ var HindsightClient = class {
|
|
|
699
583
|
this.log(
|
|
700
584
|
seeded ? `[bank] structure applied to ${this.bank}: entity_labels {knowledge}, strategies {git, gitlog, conversation, document} \u2014 missions left as configured` : `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
|
|
701
585
|
);
|
|
702
|
-
await this.seedPages();
|
|
586
|
+
await this.seedPages(opts.pageTrigger);
|
|
703
587
|
}
|
|
704
588
|
/**
|
|
705
589
|
* Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
|
|
@@ -757,7 +641,7 @@ var HindsightClient = class {
|
|
|
757
641
|
let backoffMs = POLL_CYCLE_MS;
|
|
758
642
|
await pool([...pending], this.maxParallelRetains, async (id) => {
|
|
759
643
|
try {
|
|
760
|
-
const r = await
|
|
644
|
+
const r = await this.fetchWithAuth(this.bankUrl(`/operations/${id}`), { method: "GET" });
|
|
761
645
|
if (r.status === 429) {
|
|
762
646
|
backoffMs = Math.min(
|
|
763
647
|
RETRY_AFTER_CEILING_MS,
|
|
@@ -783,18 +667,23 @@ var HindsightClient = class {
|
|
|
783
667
|
`[wait] ${label} drained \u2014 ${ids.length - pending.size} done, ${failed} failed` + (pending.size ? `, ${pending.size} still pending at timeout` : "")
|
|
784
668
|
);
|
|
785
669
|
}
|
|
786
|
-
/**
|
|
787
|
-
|
|
670
|
+
/**
|
|
671
|
+
* Reflect: synthesized, root-cause answer over the bank. Bounded so a slow server never hangs a
|
|
672
|
+
* caller — but `timeoutMs` is REQUIRED, deliberately: the right deadline differs by an order of
|
|
673
|
+
* magnitude between the automatic hook (25s, to fit the host's window) and the agent-invoked
|
|
674
|
+
* tool (minutes, on a populated bank). This used to default to 120s, which silently overrode the
|
|
675
|
+
* tool's configured window and aborted every high-budget synthesis mid-flight (#3590).
|
|
676
|
+
*/
|
|
677
|
+
async reflect(query, opts) {
|
|
788
678
|
const ctrl = new AbortController();
|
|
789
|
-
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs
|
|
679
|
+
const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs);
|
|
790
680
|
try {
|
|
791
|
-
const resp = await
|
|
681
|
+
const resp = await this.fetchWithAuth(this.bankUrl("/reflect"), {
|
|
792
682
|
method: "POST",
|
|
793
|
-
headers: this.headers(),
|
|
794
683
|
body: JSON.stringify({ query, budget: opts.budget ?? "high" }),
|
|
795
684
|
signal: ctrl.signal
|
|
796
685
|
});
|
|
797
|
-
if (!resp.ok) throw new Error(`reflect ${resp.status}`);
|
|
686
|
+
if (!resp.ok) throw new Error(`reflect ${resp.status}${this.authHint(resp.status)}`);
|
|
798
687
|
const data = await resp.json();
|
|
799
688
|
return (data.text || "").trim();
|
|
800
689
|
} finally {
|
|
@@ -878,16 +767,18 @@ var HindsightClient = class {
|
|
|
878
767
|
}));
|
|
879
768
|
}
|
|
880
769
|
/**
|
|
881
|
-
* Seed the fixed
|
|
770
|
+
* Seed the fixed page taxonomy as knowledge-base pages at the tree root, idempotently.
|
|
882
771
|
*
|
|
883
772
|
* Matched by NAME, not id: `/knowledge-base/pages` mints its own `kp-…` id, so a stable
|
|
884
773
|
* client-chosen id isn't available to match on (unlike the old mental-model path, which keyed
|
|
885
774
|
* off a slug). Names are unique per folder server-side, which makes them a sound key.
|
|
886
775
|
*
|
|
887
776
|
* An existing page is PATCHed rather than recreated so a plugin upgrade that rewords a
|
|
888
|
-
* `source_query` re-syncs onto the live page instead of orphaning its synthesized content
|
|
777
|
+
* `source_query` re-syncs onto the live page instead of orphaning its synthesized content —
|
|
778
|
+
* which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
|
|
889
779
|
*/
|
|
890
|
-
async seedPages() {
|
|
780
|
+
async seedPages(pageTrigger = buildPageTrigger()) {
|
|
781
|
+
const pages = pagesFor(this.project ?? this.bank);
|
|
891
782
|
const existing = /* @__PURE__ */ new Map();
|
|
892
783
|
let roots;
|
|
893
784
|
try {
|
|
@@ -904,14 +795,14 @@ var HindsightClient = class {
|
|
|
904
795
|
}
|
|
905
796
|
let created = 0;
|
|
906
797
|
let updated = 0;
|
|
907
|
-
for (const page of
|
|
798
|
+
for (const page of pages) {
|
|
908
799
|
const hit = existing.get(page.name.toLowerCase());
|
|
909
800
|
const body = {
|
|
910
801
|
name: page.name,
|
|
911
802
|
source_query: page.source_query,
|
|
912
803
|
tags: page.tags,
|
|
913
804
|
max_tokens: PAGE_MAX_TOKENS,
|
|
914
|
-
trigger:
|
|
805
|
+
trigger: pageTrigger
|
|
915
806
|
};
|
|
916
807
|
if (!hit) {
|
|
917
808
|
const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
|
|
@@ -923,11 +814,18 @@ var HindsightClient = class {
|
|
|
923
814
|
return;
|
|
924
815
|
}
|
|
925
816
|
if (r.status !== 409) created++;
|
|
926
|
-
} else if (hit.description !== page.source_query) {
|
|
817
|
+
} else if (hit.description !== page.source_query || hit.trigger?.tags_match !== pageTrigger.tags_match) {
|
|
818
|
+
const patch = {
|
|
819
|
+
trigger: pageTrigger
|
|
820
|
+
};
|
|
821
|
+
if (hit.description !== page.source_query) {
|
|
822
|
+
patch.source_query = page.source_query;
|
|
823
|
+
patch.tags = page.tags;
|
|
824
|
+
}
|
|
927
825
|
const r = await this.req(
|
|
928
826
|
"PATCH",
|
|
929
827
|
this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(hit.id)}`),
|
|
930
|
-
|
|
828
|
+
patch
|
|
931
829
|
);
|
|
932
830
|
if ([404, 405, 501].includes(r.status)) {
|
|
933
831
|
this.knowledgePagesSupported = false;
|
|
@@ -940,7 +838,7 @@ var HindsightClient = class {
|
|
|
940
838
|
}
|
|
941
839
|
}
|
|
942
840
|
this.log(
|
|
943
|
-
`[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${
|
|
841
|
+
`[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
|
|
944
842
|
);
|
|
945
843
|
}
|
|
946
844
|
/** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
|
|
@@ -948,9 +846,17 @@ var HindsightClient = class {
|
|
|
948
846
|
return s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "initiative";
|
|
949
847
|
}
|
|
950
848
|
/**
|
|
951
|
-
* Active-path capture: register a major feature as a per-initiative page + a
|
|
952
|
-
* New initiative → creates a page under the Initiatives folder
|
|
953
|
-
*
|
|
849
|
+
* Active-path capture: register a major feature as a per-initiative page + a marker memory.
|
|
850
|
+
* New initiative → creates a page under the Initiatives folder.
|
|
851
|
+
* Update (relatesToPageId) → no new page; only a marker accruing to the existing page, so an
|
|
852
|
+
* enhancement or a mid-work plan change lands on the initiative it belongs to.
|
|
853
|
+
*
|
|
854
|
+
* The marker carries its page id in two places, neither of them a tag (#3641):
|
|
855
|
+
* `metadata.relatedPageId` for provenance (visible on the document, and to a reflect loop that
|
|
856
|
+
* expands one), and a `[[page:<id>]]` link in the retain CONTEXT, which is the only one of the
|
|
857
|
+
* three channels a page synthesis actually reads — reflect's search results keep `context` and
|
|
858
|
+
* `tags` but strip `metadata` (`_UNREAD_RESULT_FIELDS`), and the id has no business in a tag
|
|
859
|
+
* vocabulary that exists to be matched with exact set-ops.
|
|
954
860
|
*/
|
|
955
861
|
async captureInitiative(args) {
|
|
956
862
|
let pageId = args.relatesToPageId;
|
|
@@ -961,10 +867,7 @@ var HindsightClient = class {
|
|
|
961
867
|
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.`,
|
|
962
868
|
parent_id: folderId,
|
|
963
869
|
tags: ["knowledge:feature-work"],
|
|
964
|
-
trigger:
|
|
965
|
-
fact_types: ["world", "experience", "observation"],
|
|
966
|
-
refresh_after_consolidation: true
|
|
967
|
-
}
|
|
870
|
+
trigger: args.pageTrigger ?? buildPageTrigger()
|
|
968
871
|
});
|
|
969
872
|
try {
|
|
970
873
|
const j = await r.json();
|
|
@@ -973,23 +876,14 @@ var HindsightClient = class {
|
|
|
973
876
|
}
|
|
974
877
|
pageId ||= `initiative-${this.slugify(args.title)}`;
|
|
975
878
|
}
|
|
976
|
-
const verb = args.relatesToPageId ? "
|
|
879
|
+
const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
|
|
977
880
|
const content = `${verb}: ${args.title}. ${args.summary}`;
|
|
978
881
|
const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
|
|
979
|
-
const tags = [
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
])
|
|
985
|
-
];
|
|
986
|
-
if (Object.keys(args.stamp?.metadata ?? {}).length) {
|
|
987
|
-
await this.retain(content, "initiative marker", markerId, tags, "document", {
|
|
988
|
-
metadata: args.stamp?.metadata
|
|
989
|
-
});
|
|
990
|
-
} else {
|
|
991
|
-
await this.retain(content, "initiative marker", markerId, tags, "document");
|
|
992
|
-
}
|
|
882
|
+
const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
|
|
883
|
+
const context = `initiative marker for [[page:${pageId}]]`;
|
|
884
|
+
await this.retain(content, context, markerId, tags, "document", {
|
|
885
|
+
metadata: { ...args.stamp?.metadata ?? {}, relatedPageId: pageId }
|
|
886
|
+
});
|
|
993
887
|
return { page_id: pageId };
|
|
994
888
|
}
|
|
995
889
|
/** Find a root folder by name (case-insensitive) or create it; returns its id. Fail-open to undefined. */
|
|
@@ -1011,6 +905,260 @@ var HindsightClient = class {
|
|
|
1011
905
|
}
|
|
1012
906
|
};
|
|
1013
907
|
|
|
908
|
+
// src/core/config.ts
|
|
909
|
+
var CONFIG_PATH = process.env.HINDSIGHT_CONFIG || join4(homedir2(), ".hindsight", "coding-agent.json");
|
|
910
|
+
var DEFAULT_DAEMON_PORT = 9077;
|
|
911
|
+
var DEFAULT_DAEMON_PROFILE = "coding-agent";
|
|
912
|
+
function resolvePageTriggerType(raw) {
|
|
913
|
+
if (raw.pageTriggerType === "manual") return "manual";
|
|
914
|
+
if (raw.pageTriggerType === "cron") {
|
|
915
|
+
if (raw.pageTriggerCron?.trim()) return "cron";
|
|
916
|
+
log.warn(
|
|
917
|
+
"config",
|
|
918
|
+
'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
|
|
919
|
+
);
|
|
920
|
+
}
|
|
921
|
+
return "auto-refresh";
|
|
922
|
+
}
|
|
923
|
+
var DEFAULT_REFLECT_TOOL_TIMEOUT_MS = 33e4;
|
|
924
|
+
var REFLECT_BUDGETS = ["low", "mid", "high"];
|
|
925
|
+
function resolveReflectBudget(raw) {
|
|
926
|
+
const value = raw.reflectBudget;
|
|
927
|
+
if (value === void 0) return "high";
|
|
928
|
+
if (typeof value === "string" && REFLECT_BUDGETS.includes(value))
|
|
929
|
+
return value;
|
|
930
|
+
log.warn("config", `ignoring reflectBudget=${JSON.stringify(value)} \u2014 expected low|mid|high`);
|
|
931
|
+
return "high";
|
|
932
|
+
}
|
|
933
|
+
var OBSERVATION_SCOPE_MODES = ["shared", "combined", "per_tag", "all_combinations"];
|
|
934
|
+
function resolveObservationScopes(raw) {
|
|
935
|
+
const value = raw;
|
|
936
|
+
if (typeof value === "string")
|
|
937
|
+
return OBSERVATION_SCOPE_MODES.includes(value) ? value : DEFAULT_OBSERVATION_SCOPES;
|
|
938
|
+
if (Array.isArray(value)) {
|
|
939
|
+
const scopes = value.filter((scope) => Array.isArray(scope)).map((scope) => scope.filter((t) => typeof t === "string" && t.trim() !== ""));
|
|
940
|
+
if (scopes.length) return scopes;
|
|
941
|
+
}
|
|
942
|
+
return DEFAULT_OBSERVATION_SCOPES;
|
|
943
|
+
}
|
|
944
|
+
function resolveConfig(raw = {}) {
|
|
945
|
+
const serverMode = ["cloud", "self-hosted", "daemon"].includes(raw.serverMode) ? raw.serverMode : "cloud";
|
|
946
|
+
const apiPort = raw.apiPort || DEFAULT_DAEMON_PORT;
|
|
947
|
+
return {
|
|
948
|
+
serverMode,
|
|
949
|
+
// Daemon mode resolves the URL HERE rather than at each call site: every entry point already
|
|
950
|
+
// builds its client from cfg.apiUrl, so collapsing the mode into that one field means the
|
|
951
|
+
// daemon needs no plumbing through eight separate constructors.
|
|
952
|
+
apiUrl: serverMode === "daemon" ? `http://127.0.0.1:${apiPort}` : raw.apiUrl ?? "https://api.hindsight.vectorize.io",
|
|
953
|
+
apiToken: raw.apiToken || void 0,
|
|
954
|
+
apiPort,
|
|
955
|
+
daemonIdleTimeout: raw.daemonIdleTimeout,
|
|
956
|
+
daemonProfile: raw.daemonProfile || DEFAULT_DAEMON_PROFILE,
|
|
957
|
+
embedVersion: raw.embedVersion || void 0,
|
|
958
|
+
embedPackagePath: raw.embedPackagePath || void 0,
|
|
959
|
+
bankId: raw.bankId,
|
|
960
|
+
dynamicBankId: raw.dynamicBankId,
|
|
961
|
+
bankIdTemplate: raw.bankIdTemplate,
|
|
962
|
+
mapPathToBank: raw.mapPathToBank,
|
|
963
|
+
resolveWorktrees: raw.resolveWorktrees,
|
|
964
|
+
optInOnly: raw.optInOnly ?? false,
|
|
965
|
+
// Same shape as retainTags: a config typo must not become a path that silently approves nothing.
|
|
966
|
+
optInPaths: Array.isArray(raw.optInPaths) ? raw.optInPaths.filter((p) => typeof p === "string" && p.trim() !== "") : [],
|
|
967
|
+
harness: raw.harness ?? "opencode",
|
|
968
|
+
disabled: raw.disabled ?? false,
|
|
969
|
+
retainSessions: raw.retainSessions ?? true,
|
|
970
|
+
// write sessions back by default, every harness
|
|
971
|
+
maxParallelRetains: raw.maxParallelRetains || 10,
|
|
972
|
+
reflectTimeoutMs: raw.reflectTimeoutMs || 12e4,
|
|
973
|
+
// Inherit an explicitly-raised reflectTimeoutMs (that is what users reaching for a longer
|
|
974
|
+
// reflect already set), but never let it LOWER the tool below the default — a short window is
|
|
975
|
+
// set to bound the automatic hook, not to cut off a call the agent is waiting on.
|
|
976
|
+
reflectToolTimeoutMs: raw.reflectToolTimeoutMs || Math.max(raw.reflectTimeoutMs || 0, DEFAULT_REFLECT_TOOL_TIMEOUT_MS),
|
|
977
|
+
reflectBudget: resolveReflectBudget(raw),
|
|
978
|
+
autoReflect: raw.autoReflect ?? true,
|
|
979
|
+
pageRefreshEveryTurns: raw.pageRefreshEveryTurns || 10,
|
|
980
|
+
pageTriggerType: resolvePageTriggerType(raw),
|
|
981
|
+
pageTriggerCron: raw.pageTriggerCron?.trim() || void 0,
|
|
982
|
+
autoSeed: raw.autoSeed ?? true,
|
|
983
|
+
seedLimit: raw.seedLimit || DEFAULT_SEED_LIMIT,
|
|
984
|
+
codebaseSurvey: raw.codebaseSurvey ?? true,
|
|
985
|
+
surveyModel: raw.surveyModel || "haiku",
|
|
986
|
+
surveyBudgetUsd: raw.surveyBudgetUsd || 2,
|
|
987
|
+
surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
|
|
988
|
+
gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
|
|
989
|
+
// Hostile input is a config typo, not an attack: keep only string entries so a stray number or
|
|
990
|
+
// nested object cannot reach the API as a tag and fail the whole retain.
|
|
991
|
+
retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
|
|
992
|
+
retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
|
|
993
|
+
Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
|
|
994
|
+
) : {},
|
|
995
|
+
observationScopes: resolveObservationScopes(raw.observationScopes),
|
|
996
|
+
banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
|
|
997
|
+
logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
function readRaw(path) {
|
|
1001
|
+
try {
|
|
1002
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
1003
|
+
} catch (e) {
|
|
1004
|
+
if (e?.code !== "ENOENT") {
|
|
1005
|
+
console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
|
|
1006
|
+
}
|
|
1007
|
+
return {};
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
function mergeRaw(a, b) {
|
|
1011
|
+
const { harnesses: _drop, ...flat } = b;
|
|
1012
|
+
return { ...a, ...flat, banks: { ...a.banks ?? {}, ...b.banks ?? {} } };
|
|
1013
|
+
}
|
|
1014
|
+
function applyLayer(raw, layer, harness) {
|
|
1015
|
+
let out = mergeRaw(raw, layer);
|
|
1016
|
+
const perHarness = harness ? layer.harnesses?.[harness] : void 0;
|
|
1017
|
+
if (perHarness) out = mergeRaw(out, perHarness);
|
|
1018
|
+
return out;
|
|
1019
|
+
}
|
|
1020
|
+
var ENV_KEYS = {
|
|
1021
|
+
serverMode: "HINDSIGHT_SERVER_MODE",
|
|
1022
|
+
apiUrl: "HINDSIGHT_API_URL",
|
|
1023
|
+
apiToken: "HINDSIGHT_API_TOKEN",
|
|
1024
|
+
// These four keep the names the old per-agent Claude Code plugin used, so a user migrating from
|
|
1025
|
+
// it can carry their existing environment over unchanged.
|
|
1026
|
+
apiPort: "HINDSIGHT_API_PORT",
|
|
1027
|
+
daemonIdleTimeout: "HINDSIGHT_DAEMON_IDLE_TIMEOUT",
|
|
1028
|
+
embedVersion: "HINDSIGHT_EMBED_VERSION",
|
|
1029
|
+
embedPackagePath: "HINDSIGHT_EMBED_PACKAGE_PATH",
|
|
1030
|
+
daemonProfile: "HINDSIGHT_DAEMON_PROFILE",
|
|
1031
|
+
bankId: "HINDSIGHT_BANK_ID",
|
|
1032
|
+
dynamicBankId: "HINDSIGHT_DYNAMIC_BANK_ID",
|
|
1033
|
+
bankIdTemplate: "HINDSIGHT_BANK_ID_TEMPLATE",
|
|
1034
|
+
resolveWorktrees: "HINDSIGHT_RESOLVE_WORKTREES",
|
|
1035
|
+
optInOnly: "HINDSIGHT_OPT_IN_ONLY",
|
|
1036
|
+
optInPaths: "HINDSIGHT_OPT_IN_PATHS",
|
|
1037
|
+
harness: "HINDSIGHT_HARNESS",
|
|
1038
|
+
disabled: "HINDSIGHT_DISABLED",
|
|
1039
|
+
retainSessions: "HINDSIGHT_RETAIN_SESSIONS",
|
|
1040
|
+
maxParallelRetains: "HINDSIGHT_MAX_PARALLEL_RETAINS",
|
|
1041
|
+
reflectTimeoutMs: "HINDSIGHT_REFLECT_TIMEOUT_MS",
|
|
1042
|
+
reflectToolTimeoutMs: "HINDSIGHT_REFLECT_TOOL_TIMEOUT_MS",
|
|
1043
|
+
reflectBudget: "HINDSIGHT_REFLECT_BUDGET",
|
|
1044
|
+
autoReflect: "HINDSIGHT_AUTO_REFLECT",
|
|
1045
|
+
pageRefreshEveryTurns: "HINDSIGHT_PAGE_REFRESH_EVERY_TURNS",
|
|
1046
|
+
pageTriggerType: "HINDSIGHT_PAGE_TRIGGER_TYPE",
|
|
1047
|
+
pageTriggerCron: "HINDSIGHT_PAGE_TRIGGER_CRON",
|
|
1048
|
+
autoSeed: "HINDSIGHT_AUTO_SEED",
|
|
1049
|
+
seedLimit: "HINDSIGHT_SEED_LIMIT",
|
|
1050
|
+
codebaseSurvey: "HINDSIGHT_CODEBASE_SURVEY",
|
|
1051
|
+
surveyModel: "HINDSIGHT_SURVEY_MODEL",
|
|
1052
|
+
surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
|
|
1053
|
+
surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
|
|
1054
|
+
logLevel: "HINDSIGHT_LOG_LEVEL",
|
|
1055
|
+
gitIngest: "HINDSIGHT_GIT_INGEST",
|
|
1056
|
+
// Scalar modes only ("shared", "combined", "per_tag", "all_combinations"). An explicit scope
|
|
1057
|
+
// list is a list OF lists, which does not survive flattening into one variable — file-only.
|
|
1058
|
+
observationScopes: "HINDSIGHT_OBSERVATION_SCOPES",
|
|
1059
|
+
// Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
|
|
1060
|
+
// a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
|
|
1061
|
+
retainTags: "HINDSIGHT_RETAIN_TAGS"
|
|
1062
|
+
};
|
|
1063
|
+
var ENV_BOOLEANS = /* @__PURE__ */ new Set([
|
|
1064
|
+
"dynamicBankId",
|
|
1065
|
+
"resolveWorktrees",
|
|
1066
|
+
"optInOnly",
|
|
1067
|
+
"disabled",
|
|
1068
|
+
"retainSessions",
|
|
1069
|
+
"autoReflect",
|
|
1070
|
+
"autoSeed",
|
|
1071
|
+
"codebaseSurvey"
|
|
1072
|
+
]);
|
|
1073
|
+
var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags", "optInPaths"]);
|
|
1074
|
+
var ENV_NUMBERS = /* @__PURE__ */ new Set([
|
|
1075
|
+
"apiPort",
|
|
1076
|
+
"daemonIdleTimeout",
|
|
1077
|
+
"maxParallelRetains",
|
|
1078
|
+
"reflectTimeoutMs",
|
|
1079
|
+
"reflectToolTimeoutMs",
|
|
1080
|
+
"pageRefreshEveryTurns",
|
|
1081
|
+
"seedLimit",
|
|
1082
|
+
"surveyBudgetUsd",
|
|
1083
|
+
"surveyRefreshCommits"
|
|
1084
|
+
]);
|
|
1085
|
+
function readEnvConfig(env = process.env) {
|
|
1086
|
+
const out = {};
|
|
1087
|
+
for (const [key, name] of Object.entries(ENV_KEYS)) {
|
|
1088
|
+
const value = env[name];
|
|
1089
|
+
if (value === void 0 || value.trim() === "") continue;
|
|
1090
|
+
if (ENV_BOOLEANS.has(key)) {
|
|
1091
|
+
out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
|
|
1092
|
+
} else if (ENV_LISTS.has(key)) {
|
|
1093
|
+
const items = value.split(",").map((v) => v.trim()).filter(Boolean);
|
|
1094
|
+
if (items.length) out[key] = items;
|
|
1095
|
+
} else if (ENV_NUMBERS.has(key)) {
|
|
1096
|
+
const n = Number(value);
|
|
1097
|
+
if (Number.isFinite(n)) out[key] = n;
|
|
1098
|
+
else console.error(`hindsight: ignoring ${name}=${value} \u2014 not a number`);
|
|
1099
|
+
} else {
|
|
1100
|
+
out[key] = value;
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
return out;
|
|
1104
|
+
}
|
|
1105
|
+
function loadConfig(opts = {}) {
|
|
1106
|
+
const o = typeof opts === "string" ? { path: opts } : opts;
|
|
1107
|
+
const withEnv = applyLayer({}, readEnvConfig(), o.harness);
|
|
1108
|
+
const raw = applyLayer(withEnv, readRaw(o.path ?? CONFIG_PATH), o.harness);
|
|
1109
|
+
if (!raw.harness && o.harness) raw.harness = o.harness;
|
|
1110
|
+
return resolveConfig(raw);
|
|
1111
|
+
}
|
|
1112
|
+
var BANK_OVERRIDE_EXCLUDED = [
|
|
1113
|
+
"bankId",
|
|
1114
|
+
"bankIdTemplate",
|
|
1115
|
+
"mapPathToBank",
|
|
1116
|
+
"dynamicBankId",
|
|
1117
|
+
"resolveWorktrees",
|
|
1118
|
+
// Approval is decided BEFORE the bank is resolved, so a `banks.<id>` section naming these could
|
|
1119
|
+
// only ever arrive too late to matter — strip them rather than let them read as effective.
|
|
1120
|
+
"optInOnly",
|
|
1121
|
+
"optInPaths",
|
|
1122
|
+
"harness"
|
|
1123
|
+
];
|
|
1124
|
+
function applyBankConfig(cfg, resolvedId, directory) {
|
|
1125
|
+
if (directory !== void 0 && !isOptedIn(cfg, directory))
|
|
1126
|
+
return { cfg: { ...cfg, disabled: true }, bankId: resolvedId };
|
|
1127
|
+
const section = cfg.banks[resolvedId];
|
|
1128
|
+
if (!section) return { cfg, bankId: resolvedId };
|
|
1129
|
+
const safe = { ...section };
|
|
1130
|
+
for (const k of BANK_OVERRIDE_EXCLUDED) delete safe[k];
|
|
1131
|
+
delete safe.banks;
|
|
1132
|
+
const bankId = typeof safe.bank === "string" && safe.bank ? safe.bank : resolvedId;
|
|
1133
|
+
delete safe.bank;
|
|
1134
|
+
return { cfg: { ...cfg, ...resolvePartial(cfg, safe) }, bankId };
|
|
1135
|
+
}
|
|
1136
|
+
function resolvePartial(cfg, patch) {
|
|
1137
|
+
const full = resolveConfig(patch);
|
|
1138
|
+
const out = {};
|
|
1139
|
+
for (const key of Object.keys(patch)) {
|
|
1140
|
+
if (key in full)
|
|
1141
|
+
out[key] = full[key];
|
|
1142
|
+
}
|
|
1143
|
+
return out;
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
// src/core/diag.ts
|
|
1147
|
+
import { appendFileSync as appendFileSync2 } from "fs";
|
|
1148
|
+
function diagFilePath() {
|
|
1149
|
+
return process.env.HINDSIGHT_DIAG_FILE || "/tmp/hindsight-plugin.log";
|
|
1150
|
+
}
|
|
1151
|
+
function diag(harness, event, extra = {}) {
|
|
1152
|
+
log.debug(harness, `diag:${event}`, extra);
|
|
1153
|
+
try {
|
|
1154
|
+
appendFileSync2(
|
|
1155
|
+
diagFilePath(),
|
|
1156
|
+
JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), harness, event, ...extra }) + "\n"
|
|
1157
|
+
);
|
|
1158
|
+
} catch {
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1014
1162
|
// src/core/session-cache.ts
|
|
1015
1163
|
import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "fs";
|
|
1016
1164
|
import { tmpdir as tmpdir2 } from "os";
|
|
@@ -1029,6 +1177,23 @@ function writeFileAtomic(path, body) {
|
|
|
1029
1177
|
throw e;
|
|
1030
1178
|
}
|
|
1031
1179
|
}
|
|
1180
|
+
function sessionRootFile(harness, sessionId) {
|
|
1181
|
+
return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.root`);
|
|
1182
|
+
}
|
|
1183
|
+
function sessionRootDir(harness, sessionId, cwd) {
|
|
1184
|
+
if (!sessionId || !cwd) return cwd;
|
|
1185
|
+
const file = sessionRootFile(harness, sessionId);
|
|
1186
|
+
try {
|
|
1187
|
+
const recorded = readFileSync2(file, "utf8").trim();
|
|
1188
|
+
if (recorded) return recorded;
|
|
1189
|
+
} catch {
|
|
1190
|
+
}
|
|
1191
|
+
try {
|
|
1192
|
+
writeFileAtomic(file, cwd);
|
|
1193
|
+
} catch {
|
|
1194
|
+
}
|
|
1195
|
+
return cwd;
|
|
1196
|
+
}
|
|
1032
1197
|
function cursorFile(harness, sessionId) {
|
|
1033
1198
|
return join5(tmpdir2(), `hindsight-${harness}`, `${sessionId}.retain.json`);
|
|
1034
1199
|
}
|
|
@@ -1334,7 +1499,7 @@ function resolversFor(ctx) {
|
|
|
1334
1499
|
return {
|
|
1335
1500
|
// Worktree-aware like the bank id, so every linked worktree of a repo stamps the SAME name —
|
|
1336
1501
|
// otherwise a shared bank ends up with `project:app` and `project:app-wt2` for one repository.
|
|
1337
|
-
gitProject: () => projectNameOf(ctx.directory),
|
|
1502
|
+
gitProject: () => projectNameOf(ctx.directory, ctx.sessionRoot),
|
|
1338
1503
|
project: () => ctx.directory ? basename2(ctx.directory) : "unknown",
|
|
1339
1504
|
harness: () => ctx.harness,
|
|
1340
1505
|
bankId: () => ctx.bankId,
|
|
@@ -1563,16 +1728,22 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
|
1563
1728
|
setLogLevel(cfg.logLevel);
|
|
1564
1729
|
if (cfg.disabled) return;
|
|
1565
1730
|
if (!transcriptPath) return;
|
|
1566
|
-
const
|
|
1731
|
+
const sessionRoot = sessionRootDir(spec.harness, sessionId, cwd);
|
|
1732
|
+
const resolved = applyBankConfig(cfg, deriveBankId(cfg, cwd, spec.harness, sessionRoot), cwd);
|
|
1567
1733
|
cfg = resolved.cfg;
|
|
1568
1734
|
const bankId = resolved.bankId;
|
|
1569
1735
|
if (cfg.disabled) return;
|
|
1736
|
+
if (!cfg.retainSessions) {
|
|
1737
|
+
diag(spec.harness, "retain_disabled", { bank: bankId, session: sessionId });
|
|
1738
|
+
return;
|
|
1739
|
+
}
|
|
1570
1740
|
await ensureDaemon(cfg, spec.harness, { waitMs: DAEMON_WAIT_RETAIN_MS });
|
|
1571
1741
|
const client = makeClient({
|
|
1572
1742
|
apiUrl: cfg.apiUrl,
|
|
1573
1743
|
apiToken: cfg.apiToken,
|
|
1574
1744
|
bank: bankId,
|
|
1575
|
-
maxParallelRetains: cfg.maxParallelRetains
|
|
1745
|
+
maxParallelRetains: cfg.maxParallelRetains,
|
|
1746
|
+
observationScopes: cfg.observationScopes
|
|
1576
1747
|
});
|
|
1577
1748
|
await buildRetain({
|
|
1578
1749
|
harness: spec.harness,
|
|
@@ -1583,6 +1754,7 @@ async function runRetainHook(spec, makeClient = (o) => new HindsightClient(o)) {
|
|
|
1583
1754
|
retryUntil: hostDeadline,
|
|
1584
1755
|
stamp: buildRetainStamp(cfg, {
|
|
1585
1756
|
directory: cwd,
|
|
1757
|
+
sessionRoot,
|
|
1586
1758
|
harness: spec.harness,
|
|
1587
1759
|
bankId,
|
|
1588
1760
|
sessionId: sessionId || "no-session"
|