@vectorize-io/hindsight-coding-agents 0.8.0 → 0.8.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.
Files changed (62) hide show
  1. package/README.md +73 -8
  2. package/dist/antigravity-hook.js +444 -80
  3. package/dist/antigravity-statusline.js +9 -4
  4. package/dist/antigravity-stop-hook.js +444 -95
  5. package/dist/claude-hook.js +444 -80
  6. package/dist/claude-sessionstart-hook.js +476 -93
  7. package/dist/claude-stop-hook.js +444 -95
  8. package/dist/cline.js +322 -122
  9. package/dist/codebuddy-hook.js +4273 -0
  10. package/dist/codebuddy-sessionstart-hook.js +5033 -0
  11. package/dist/codebuddy-stop-hook.js +4567 -0
  12. package/dist/codex-hook.js +444 -80
  13. package/dist/codex-sessionstart-hook.js +476 -93
  14. package/dist/codex-stop-hook.js +444 -95
  15. package/dist/copilot-hook.js +444 -80
  16. package/dist/copilot-sessionstart-hook.js +476 -93
  17. package/dist/copilot-stop-hook.js +444 -95
  18. package/dist/cursor-hook.js +444 -80
  19. package/dist/cursor-sessionstart-hook.js +476 -93
  20. package/dist/cursor-stop-hook.js +444 -95
  21. package/dist/daemon-start.js +16 -8
  22. package/dist/dcode-hook.js +444 -80
  23. package/dist/dcode-sessionstart-hook.js +476 -93
  24. package/dist/dcode-stop-hook.js +444 -95
  25. package/dist/deepen.js +252 -79
  26. package/dist/devin-hook.js +444 -80
  27. package/dist/devin-sessionstart-hook.js +476 -93
  28. package/dist/devin-stop-hook.js +444 -95
  29. package/dist/droid-hook.js +444 -80
  30. package/dist/droid-sessionstart-hook.js +476 -93
  31. package/dist/droid-stop-hook.js +444 -95
  32. package/dist/dsh.js +329 -122
  33. package/dist/grok-hook.js +444 -80
  34. package/dist/grok-sessionstart-hook.js +476 -93
  35. package/dist/grok-stop-hook.js +444 -95
  36. package/dist/hindsight-seed.js +9 -4
  37. package/dist/index.js +331 -131
  38. package/dist/installer.js +1046 -647
  39. package/dist/kilo.js +331 -131
  40. package/dist/kimi-hook.js +444 -80
  41. package/dist/kimi-sessionstart-hook.js +476 -93
  42. package/dist/kimi-stop-hook.js +444 -95
  43. package/dist/mcp-server.js +272 -89
  44. package/dist/opencode2.js +328 -128
  45. package/dist/pi.js +384 -134
  46. package/dist/prime-agent.js +384 -134
  47. package/dist/qwen-hook.js +444 -80
  48. package/dist/qwen-sessionstart-hook.js +476 -93
  49. package/dist/qwen-stop-hook.js +444 -95
  50. package/dist/status.js +124 -43
  51. package/dist/traecode-hook.js +444 -80
  52. package/dist/traecode-sessionstart-hook.js +476 -93
  53. package/dist/traecode-stop-hook.js +444 -95
  54. package/dist/workbuddy-hook.js +4273 -0
  55. package/dist/workbuddy-sessionstart-hook.js +5033 -0
  56. package/dist/workbuddy-stop-hook.js +4567 -0
  57. package/dist/zcode-hook.js +444 -80
  58. package/dist/zcode-sessionstart-hook.js +476 -93
  59. package/dist/zcode-stop-hook.js +444 -95
  60. package/package.json +9 -3
  61. package/plugin.json +1 -1
  62. package/skill/SKILL.md +10 -6
@@ -8059,11 +8059,11 @@ function datetimeRegex(args) {
8059
8059
  regex = `${regex}(${opts.join("|")})`;
8060
8060
  return new RegExp(`^${regex}$`);
8061
8061
  }
8062
- function isValidIP(ip, version2) {
8063
- if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
8062
+ function isValidIP(ip, version3) {
8063
+ if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) {
8064
8064
  return true;
8065
8065
  }
8066
- if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
8066
+ if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) {
8067
8067
  return true;
8068
8068
  }
8069
8069
  return false;
@@ -8090,11 +8090,11 @@ function isValidJWT(jwt2, alg) {
8090
8090
  return false;
8091
8091
  }
8092
8092
  }
8093
- function isValidCidr(ip, version2) {
8094
- if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
8093
+ function isValidCidr(ip, version3) {
8094
+ if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) {
8095
8095
  return true;
8096
8096
  }
8097
- if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
8097
+ if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) {
8098
8098
  return true;
8099
8099
  }
8100
8100
  return false;
@@ -12428,10 +12428,10 @@ var nanoid = /^[a-zA-Z0-9_-]{21}$/;
12428
12428
  var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
12429
12429
  var extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
12430
12430
  var guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
12431
- var uuid = (version2) => {
12432
- if (!version2)
12431
+ var uuid = (version3) => {
12432
+ if (!version3)
12433
12433
  return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
12434
- return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
12434
+ return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version3}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
12435
12435
  };
12436
12436
  var uuid4 = /* @__PURE__ */ uuid(4);
12437
12437
  var uuid6 = /* @__PURE__ */ uuid(6);
@@ -23354,17 +23354,33 @@ function normalizeObjectSchema(schema) {
23354
23354
  }
23355
23355
  return void 0;
23356
23356
  }
23357
+ function getDotPath(path) {
23358
+ if (path.length === 0) {
23359
+ return "object root";
23360
+ }
23361
+ return path.reduce((acc, seg, index) => {
23362
+ if (index === 0) {
23363
+ return String(seg);
23364
+ }
23365
+ if (typeof seg === "number") {
23366
+ return `${acc}[${seg}]`;
23367
+ }
23368
+ return `${acc}.${seg}`;
23369
+ }, "");
23370
+ }
23357
23371
  function getParseErrorMessage(error51) {
23358
23372
  if (error51 && typeof error51 === "object") {
23373
+ if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
23374
+ return error51.issues.map((i) => {
23375
+ if (!i.path?.length) {
23376
+ return i.message;
23377
+ }
23378
+ return `${i.message} at ${getDotPath(i.path)}`;
23379
+ }).join("\n");
23380
+ }
23359
23381
  if ("message" in error51 && typeof error51.message === "string") {
23360
23382
  return error51.message;
23361
23383
  }
23362
- if ("issues" in error51 && Array.isArray(error51.issues) && error51.issues.length > 0) {
23363
- const firstIssue = error51.issues[0];
23364
- if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) {
23365
- return String(firstIssue.message);
23366
- }
23367
- }
23368
23384
  try {
23369
23385
  return JSON.stringify(error51);
23370
23386
  } catch {
@@ -25740,10 +25756,10 @@ function fromJSONSchema(schema, params) {
25740
25756
  } catch {
25741
25757
  throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas");
25742
25758
  }
25743
- const version2 = detectVersion(normalized, params?.defaultTarget);
25759
+ const version3 = detectVersion(normalized, params?.defaultTarget);
25744
25760
  const defs = normalized.$defs || normalized.definitions || {};
25745
25761
  const ctx = {
25746
- version: version2,
25762
+ version: version3,
25747
25763
  defs,
25748
25764
  refs: /* @__PURE__ */ new Map(),
25749
25765
  processing: /* @__PURE__ */ new Set(),
@@ -28684,6 +28700,9 @@ var Protocol = class {
28684
28700
  this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
28685
28701
  const handleTaskResult = async () => {
28686
28702
  const taskId = request.params.taskId;
28703
+ if (!await this._taskStore.getTask(taskId, extra.sessionId)) {
28704
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
28705
+ }
28687
28706
  if (this._taskMessageQueue) {
28688
28707
  let queuedMessage;
28689
28708
  while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
@@ -28714,12 +28733,12 @@ var Protocol = class {
28714
28733
  throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
28715
28734
  }
28716
28735
  if (!isTerminal(task.status)) {
28717
- await this._waitForTaskUpdate(taskId, extra.signal);
28736
+ await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId);
28718
28737
  return await handleTaskResult();
28719
28738
  }
28720
28739
  if (isTerminal(task.status)) {
28721
28740
  const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
28722
- this._clearTaskQueue(taskId);
28741
+ this._clearTaskQueue(taskId, extra.sessionId);
28723
28742
  return {
28724
28743
  ...result,
28725
28744
  _meta: {
@@ -28756,7 +28775,7 @@ var Protocol = class {
28756
28775
  throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
28757
28776
  }
28758
28777
  await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
28759
- this._clearTaskQueue(request.params.taskId);
28778
+ this._clearTaskQueue(request.params.taskId, extra.sessionId);
28760
28779
  const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
28761
28780
  if (!cancelledTask) {
28762
28781
  throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
@@ -28884,6 +28903,19 @@ var Protocol = class {
28884
28903
  const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;
28885
28904
  const capturedTransport = this._transport;
28886
28905
  const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;
28906
+ const sessionId = capturedTransport?.sessionId;
28907
+ const store = this._taskStore;
28908
+ let relatedTaskFound = true;
28909
+ let relatedTaskLookup;
28910
+ if (relatedTaskId && store && this._taskMessageQueue && sessionId !== void 0) {
28911
+ relatedTaskFound = false;
28912
+ relatedTaskLookup = (async () => {
28913
+ if (!await store.getTask(relatedTaskId, sessionId)) {
28914
+ throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`);
28915
+ }
28916
+ relatedTaskFound = true;
28917
+ })();
28918
+ }
28887
28919
  if (handler === void 0) {
28888
28920
  const errorResponse = {
28889
28921
  jsonrpc: "2.0",
@@ -28893,7 +28925,10 @@ var Protocol = class {
28893
28925
  message: "Method not found"
28894
28926
  }
28895
28927
  };
28896
- if (relatedTaskId && this._taskMessageQueue) {
28928
+ if (relatedTaskId && relatedTaskLookup) {
28929
+ const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() };
28930
+ relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error51) => this._onerror(new Error(`Failed to send an error response: ${error51}`)));
28931
+ } else if (relatedTaskId && this._taskMessageQueue) {
28897
28932
  this._enqueueTaskMessage(relatedTaskId, {
28898
28933
  type: "error",
28899
28934
  message: errorResponse,
@@ -28944,7 +28979,10 @@ var Protocol = class {
28944
28979
  closeSSEStream: extra?.closeSSEStream,
28945
28980
  closeStandaloneSSEStream: extra?.closeStandaloneSSEStream
28946
28981
  };
28947
- Promise.resolve().then(() => {
28982
+ (relatedTaskLookup ?? Promise.resolve()).then(() => {
28983
+ if (relatedTaskLookup && abortController.signal.aborted) {
28984
+ throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
28985
+ }
28948
28986
  if (taskCreationParams) {
28949
28987
  this.assertTaskHandlerCapability(request.method);
28950
28988
  }
@@ -28979,7 +29017,7 @@ var Protocol = class {
28979
29017
  ...error51["data"] !== void 0 && { data: error51["data"] }
28980
29018
  }
28981
29019
  };
28982
- if (relatedTaskId && this._taskMessageQueue) {
29020
+ if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) {
28983
29021
  await this._enqueueTaskMessage(relatedTaskId, {
28984
29022
  type: "error",
28985
29023
  message: errorResponse,
@@ -29459,7 +29497,7 @@ var Protocol = class {
29459
29497
  throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
29460
29498
  }
29461
29499
  const maxQueueSize = this._options?.maxTaskQueueSize;
29462
- await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
29500
+ await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize);
29463
29501
  }
29464
29502
  /**
29465
29503
  * Clears the message queue for a task and rejects any pending request resolvers.
@@ -29488,12 +29526,13 @@ var Protocol = class {
29488
29526
  * Uses polling to check for updates at the task's configured poll interval.
29489
29527
  * @param taskId The task ID to wait for
29490
29528
  * @param signal Abort signal to cancel the wait
29529
+ * @param sessionId Session of the request that waits, passed to the task store
29491
29530
  * @returns Promise that resolves when an update occurs or rejects if aborted
29492
29531
  */
29493
- async _waitForTaskUpdate(taskId, signal) {
29532
+ async _waitForTaskUpdate(taskId, signal, sessionId) {
29494
29533
  let interval = this._options?.defaultTaskPollInterval ?? 1e3;
29495
29534
  try {
29496
- const task = await this._taskStore?.getTask(taskId);
29535
+ const task = await this._taskStore?.getTask(taskId, sessionId);
29497
29536
  if (task?.pollInterval) {
29498
29537
  interval = task.pollInterval;
29499
29538
  }
@@ -29979,16 +30018,7 @@ var Server = class extends Protocol {
29979
30018
  if (!methodSchema) {
29980
30019
  throw new Error("Schema is missing a method literal");
29981
30020
  }
29982
- let methodValue;
29983
- if (isZ4Schema(methodSchema)) {
29984
- const v4Schema = methodSchema;
29985
- const v4Def = v4Schema._zod?.def;
29986
- methodValue = v4Def?.value ?? v4Schema.value;
29987
- } else {
29988
- const v3Schema = methodSchema;
29989
- const legacyDef = v3Schema._def;
29990
- methodValue = legacyDef?.value ?? v3Schema.value;
29991
- }
30021
+ const methodValue = getLiteralValue(methodSchema);
29992
30022
  if (typeof methodValue !== "string") {
29993
30023
  throw new Error("Schema method literal must be a string");
29994
30024
  }
@@ -30381,6 +30411,42 @@ var ExperimentalMcpServerTasks = class {
30381
30411
  };
30382
30412
 
30383
30413
  // node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
30414
+ function toolInputElementCount(value, max) {
30415
+ let count = 0;
30416
+ const stack = [value];
30417
+ while (stack.length > 0) {
30418
+ const node = stack.pop();
30419
+ if (node === null || typeof node !== "object")
30420
+ continue;
30421
+ if (Array.isArray(node)) {
30422
+ for (const child of node) {
30423
+ if (++count > max)
30424
+ return count;
30425
+ if (child !== null && typeof child === "object")
30426
+ stack.push(child);
30427
+ }
30428
+ } else {
30429
+ for (const key in node) {
30430
+ if (!Object.prototype.hasOwnProperty.call(node, key))
30431
+ continue;
30432
+ if (++count > max)
30433
+ return count;
30434
+ const child = node[key];
30435
+ if (child !== null && typeof child === "object")
30436
+ stack.push(child);
30437
+ }
30438
+ }
30439
+ }
30440
+ return count;
30441
+ }
30442
+ function resolveMaxToolInputElements(value) {
30443
+ if (value === void 0 || value === Infinity)
30444
+ return void 0;
30445
+ if (typeof value !== "number" || Number.isNaN(value) || value < 1) {
30446
+ throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(value)}`);
30447
+ }
30448
+ return value;
30449
+ }
30384
30450
  var McpServer = class {
30385
30451
  constructor(serverInfo, options) {
30386
30452
  this._registeredResources = {};
@@ -30392,6 +30458,7 @@ var McpServer = class {
30392
30458
  this._resourceHandlersInitialized = false;
30393
30459
  this._promptHandlersInitialized = false;
30394
30460
  this.server = new Server(serverInfo, options);
30461
+ this._maxToolInputElements = resolveMaxToolInputElements(options?.maxToolInputElements);
30395
30462
  }
30396
30463
  /**
30397
30464
  * Access experimental features.
@@ -30522,12 +30589,15 @@ var McpServer = class {
30522
30589
  * Validates tool input arguments against the tool's input schema.
30523
30590
  */
30524
30591
  async validateToolInput(tool, args, toolName) {
30592
+ if (this._maxToolInputElements !== void 0 && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) {
30593
+ throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for tool ${toolName}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);
30594
+ }
30525
30595
  if (!tool.inputSchema) {
30526
30596
  return void 0;
30527
30597
  }
30528
30598
  const inputObj = normalizeObjectSchema(tool.inputSchema);
30529
30599
  const schemaToParse = inputObj ?? tool.inputSchema;
30530
- const parseResult = await safeParseAsync2(schemaToParse, args);
30600
+ const parseResult = await safeParseAsync2(schemaToParse, args ?? {});
30531
30601
  if (!parseResult.success) {
30532
30602
  const error51 = "error" in parseResult ? parseResult.error : "Unknown error";
30533
30603
  const errorMessage = getParseErrorMessage(error51);
@@ -30765,7 +30835,7 @@ var McpServer = class {
30765
30835
  }
30766
30836
  if (prompt.argsSchema) {
30767
30837
  const argsObj = normalizeObjectSchema(prompt.argsSchema);
30768
- const parseResult = await safeParseAsync2(argsObj, request.params.arguments);
30838
+ const parseResult = await safeParseAsync2(argsObj, request.params.arguments ?? {});
30769
30839
  if (!parseResult.success) {
30770
30840
  const error51 = "error" in parseResult ? parseResult.error : "Unknown error";
30771
30841
  const errorMessage = getParseErrorMessage(error51);
@@ -31176,8 +31246,17 @@ var EMPTY_COMPLETION_RESULT = {
31176
31246
  import process3 from "process";
31177
31247
 
31178
31248
  // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
31249
+ var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
31179
31250
  var ReadBuffer = class {
31251
+ constructor(options) {
31252
+ this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;
31253
+ }
31180
31254
  append(chunk) {
31255
+ const newSize = (this._buffer?.length ?? 0) + chunk.length;
31256
+ if (newSize > this._maxBufferSize) {
31257
+ this.clear();
31258
+ throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);
31259
+ }
31181
31260
  this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
31182
31261
  }
31183
31262
  readMessage() {
@@ -31205,18 +31284,24 @@ function serializeMessage(message) {
31205
31284
 
31206
31285
  // node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
31207
31286
  var StdioServerTransport = class {
31208
- constructor(_stdin = process3.stdin, _stdout = process3.stdout) {
31287
+ constructor(_stdin = process3.stdin, _stdout = process3.stdout, options) {
31209
31288
  this._stdin = _stdin;
31210
31289
  this._stdout = _stdout;
31211
- this._readBuffer = new ReadBuffer();
31212
31290
  this._started = false;
31213
31291
  this._ondata = (chunk) => {
31214
- this._readBuffer.append(chunk);
31215
- this.processReadBuffer();
31292
+ try {
31293
+ this._readBuffer.append(chunk);
31294
+ this.processReadBuffer();
31295
+ } catch (error51) {
31296
+ this.onerror?.(error51);
31297
+ this.close().catch(() => {
31298
+ });
31299
+ }
31216
31300
  };
31217
31301
  this._onerror = (error51) => {
31218
31302
  this.onerror?.(error51);
31219
31303
  };
31304
+ this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });
31220
31305
  }
31221
31306
  /**
31222
31307
  * Starts listening for messages on stdin.
@@ -31265,7 +31350,7 @@ var StdioServerTransport = class {
31265
31350
  };
31266
31351
 
31267
31352
  // src/core/config.ts
31268
- import { readFileSync as readFileSync2 } from "fs";
31353
+ import { readFileSync as readFileSync3 } from "fs";
31269
31354
  import { homedir as homedir3 } from "os";
31270
31355
  import { join as join7 } from "path";
31271
31356
 
@@ -31281,6 +31366,7 @@ import { homedir as homedir2 } from "os";
31281
31366
  import { basename, dirname as dirname4, join as join5, normalize, sep } from "path";
31282
31367
 
31283
31368
  // src/core/diag.ts
31369
+ import { readFileSync } from "fs";
31284
31370
  import { join as join3 } from "path";
31285
31371
 
31286
31372
  // src/core/log.ts
@@ -31353,7 +31439,7 @@ function diag(harness, event, extra = {}) {
31353
31439
  }
31354
31440
 
31355
31441
  // src/core/git-layout.ts
31356
- import { lstatSync, readFileSync, realpathSync } from "fs";
31442
+ import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
31357
31443
  import { dirname as dirname3, isAbsolute, join as join4, resolve } from "path";
31358
31444
  var TRANSIENT = /* @__PURE__ */ new Set(["EAGAIN", "EMFILE", "ENFILE", "EBUSY", "EINTR", "EIO", "ETIMEDOUT"]);
31359
31445
  var ATTEMPTS = 3;
@@ -31377,7 +31463,7 @@ function entryKind(path) {
31377
31463
  }
31378
31464
  function readTextOrNull(path) {
31379
31465
  try {
31380
- return readFileSync(path, "utf8");
31466
+ return readFileSync2(path, "utf8");
31381
31467
  } catch (error51) {
31382
31468
  if (TRANSIENT.has(errorCode(error51))) throw new TransientProbeError(errorCode(error51));
31383
31469
  return null;
@@ -31592,6 +31678,19 @@ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
31592
31678
  };
31593
31679
  return applyTemplate(config2.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
31594
31680
  }
31681
+ function bankProjectName(config2, directory, sessionRoot) {
31682
+ if (mappedBank(config2, directory, sessionRoot)) return void 0;
31683
+ const dynamic = config2.dynamicBankId ?? !config2.bankId;
31684
+ if (!dynamic) return void 0;
31685
+ const template = config2.bankIdTemplate || DEFAULT_TEMPLATE;
31686
+ if (!template.includes("{gitProject}")) return void 0;
31687
+ try {
31688
+ return gitProjectName(directory, config2.resolveWorktrees ?? true, sessionRoot);
31689
+ } catch (error51) {
31690
+ if (error51 instanceof BankResolutionError) return void 0;
31691
+ throw error51;
31692
+ }
31693
+ }
31595
31694
  function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot) {
31596
31695
  try {
31597
31696
  return deriveBankId(config2, directory, harness, sessionRoot);
@@ -31609,7 +31708,7 @@ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot)
31609
31708
  // src/core/missions.ts
31610
31709
  import { createHash } from "crypto";
31611
31710
  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.";
31612
- 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.";
31711
+ var GITLOG_MISSION = "You are ingesting an aggregated block of git commit MESSAGES ONLY (no diffs) \u2014 the project's recent commit-message history, oldest 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.";
31613
31712
  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.`;
31614
31713
  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.";
31615
31714
  var DOCUMENT_MISSION = "You are ingesting a standalone document (notes, docs, or structural findings). Extract the concrete facts, concepts, and structure it describes.";
@@ -31685,6 +31784,8 @@ var KNOWLEDGE_LABELS = {
31685
31784
  ]
31686
31785
  };
31687
31786
  function pageScopeRule(project) {
31787
+ if (project === void 0)
31788
+ return ` This bank is shared by several projects: attribute each thing you include to the repository or project its sources name, and group by project where that helps. Leave out facts about external tools, libraries and services those projects merely use, configure, deploy or discuss \u2014 they belong to somebody else's codebase \u2014 including any commit SHA or identifier from such a dependency's repository.`;
31688
31789
  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.`;
31689
31790
  }
31690
31791
  var PAGE_TAXONOMY = [
@@ -31866,16 +31967,19 @@ function codingBankManifest(overrides, mode = DEFAULT_RETAIN_EXTRACTION_MODE, de
31866
31967
  return Object.keys(bank).length > 0 ? { version: "1", bank } : void 0;
31867
31968
  }
31868
31969
 
31970
+ // package.json
31971
+ var version2 = "0.8.2";
31972
+
31869
31973
  // src/core/util.ts
31870
31974
  import { accessSync, constants } from "fs";
31871
31975
  import { delimiter, join as join6 } from "path";
31872
31976
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
31873
- function semverGte(version2, min) {
31977
+ function semverGte(version3, min) {
31874
31978
  const parts = (v) => {
31875
31979
  const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
31876
31980
  return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
31877
31981
  };
31878
- const a = version2 ? parts(version2) : void 0;
31982
+ const a = version3 ? parts(version3) : void 0;
31879
31983
  const b = parts(min);
31880
31984
  if (!a || !b) return false;
31881
31985
  for (let i = 0; i < 3; i++) {
@@ -31900,6 +32004,7 @@ async function pool(items, n, fn, onError, onProgress) {
31900
32004
  }
31901
32005
 
31902
32006
  // src/core/hindsight.ts
32007
+ var USER_AGENT = `hindsight-coding-agents/${version2}`;
31903
32008
  function resolveRetainScopes(tags, configured) {
31904
32009
  if (configured !== "per_source") return configured;
31905
32010
  const sources = [...new Set((tags ?? []).filter((t) => t.startsWith("source:")))].sort();
@@ -31935,7 +32040,7 @@ async function isEndpointMissing(r) {
31935
32040
  const j = await r.json();
31936
32041
  return String(j?.detail ?? "").trim().toLowerCase() === "not found";
31937
32042
  } catch {
31938
- return true;
32043
+ return false;
31939
32044
  }
31940
32045
  }
31941
32046
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
@@ -31954,6 +32059,12 @@ var ReflectError = class extends Error {
31954
32059
  get fallbackEligible() {
31955
32060
  return this.timedOut || this.status !== void 0 && this.status >= 500;
31956
32061
  }
32062
+ /** A 4xx the next attempt would get again (bad key, missing bank, rejected body) — retrying it
32063
+ * only spends another doomed call (#5207). 408/429 are "not now", so they stay retryable. */
32064
+ get permanent() {
32065
+ const s = this.status;
32066
+ return s !== void 0 && s >= 400 && s < 500 && s !== 408 && s !== 429;
32067
+ }
31957
32068
  };
31958
32069
  var DEFAULT_MAX_PARALLEL_RETAINS = 10;
31959
32070
  var DEFAULT_PAGE_SEARCH_LIMIT = 10;
@@ -31964,8 +32075,10 @@ var DEFAULT_RECALL_OPTIONS = {
31964
32075
  include: { entities: null }
31965
32076
  };
31966
32077
  var POLL_CYCLE_MS = 5e3;
32078
+ var POLL_MAX_SERVER_ERRORS = 12;
31967
32079
  var RETRY_AFTER_FLOOR_MS = 10 * 1e3;
31968
32080
  var RETRY_AFTER_CEILING_MS = 60 * 1e3;
32081
+ var RATE_LIMIT_BACKOFF_MS = 1e3;
31969
32082
  function shapePage(page) {
31970
32083
  const p = page ?? {};
31971
32084
  const body = typeof p.body === "string" && p.body.trim() ? p.body : p.markdown;
@@ -31978,6 +32091,15 @@ function shapePage(page) {
31978
32091
  body
31979
32092
  };
31980
32093
  }
32094
+ var GLOBAL_DISPATCHER = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
32095
+ function signalOnlyDispatcher() {
32096
+ void globalThis.Headers;
32097
+ const d = globalThis[GLOBAL_DISPATCHER];
32098
+ if (typeof d?.compose !== "function") return void 0;
32099
+ return d.compose(
32100
+ (dispatch) => (opts, handler) => dispatch({ ...opts, headersTimeout: 0, bodyTimeout: 0 }, handler)
32101
+ );
32102
+ }
31981
32103
  var HindsightClient = class {
31982
32104
  apiUrl;
31983
32105
  /** The credential the NEXT request will sign with — NOT the one the config file holds. The two
@@ -31997,6 +32119,7 @@ var HindsightClient = class {
31997
32119
  observationScopes;
31998
32120
  pageSearchLimit;
31999
32121
  recallOptions;
32122
+ rateLimitPatienceMs;
32000
32123
  constructor(o) {
32001
32124
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
32002
32125
  this.token = o.apiToken;
@@ -32009,6 +32132,7 @@ var HindsightClient = class {
32009
32132
  this.observationScopes = o.observationScopes ?? DEFAULT_OBSERVATION_SCOPES;
32010
32133
  this.pageSearchLimit = o.pageSearchLimit || DEFAULT_PAGE_SEARCH_LIMIT;
32011
32134
  this.recallOptions = { ...DEFAULT_RECALL_OPTIONS, ...o.recallOptions };
32135
+ this.rateLimitPatienceMs = o.rateLimitPatienceMs ?? 0;
32012
32136
  }
32013
32137
  /** The credential in use, for diagnostics. Never log or report the VALUE — booleans only. */
32014
32138
  get apiToken() {
@@ -32017,7 +32141,8 @@ var HindsightClient = class {
32017
32141
  headers() {
32018
32142
  const h = {
32019
32143
  "Content-Type": "application/json",
32020
- "Accept-Encoding": "identity"
32144
+ "Accept-Encoding": "identity",
32145
+ "User-Agent": USER_AGENT
32021
32146
  };
32022
32147
  if (this.token) h["Authorization"] = `Bearer ${this.token}`;
32023
32148
  return h;
@@ -32049,7 +32174,8 @@ var HindsightClient = class {
32049
32174
  * bounds the whole call.
32050
32175
  */
32051
32176
  async fetchWithAuth(url2, init) {
32052
- const send = () => fetch(url2, { ...init, headers: this.headers() });
32177
+ const dispatcher = init.signal ? signalOnlyDispatcher() : void 0;
32178
+ const send = () => fetch(url2, { ...init, headers: this.headers(), ...dispatcher ? { dispatcher } : {} });
32053
32179
  const r = await send();
32054
32180
  if (r.status !== 401 || !this.refreshToken()) return r;
32055
32181
  return send();
@@ -32065,13 +32191,22 @@ var HindsightClient = class {
32065
32191
  }
32066
32192
  /** `tolerate` adds statuses that are returned to the caller instead of thrown (404 always is). */
32067
32193
  async req(method, url2, body, tolerate = [], timeoutMs = 15e3) {
32068
- const r = await this.fetchWithAuth(url2, {
32069
- method,
32070
- body: body ? JSON.stringify(body) : void 0,
32071
- signal: AbortSignal.timeout(timeoutMs)
32072
- });
32073
- if (r.status === 429 && !tolerate.includes(429))
32074
- throw new RateLimitedError(retryAfterMs(r.headers.get("retry-after")));
32194
+ const payload = body ? JSON.stringify(body) : void 0;
32195
+ let r;
32196
+ for (let attempt = 0, waited = 0; ; attempt++) {
32197
+ r = await this.fetchWithAuth(url2, {
32198
+ method,
32199
+ body: payload,
32200
+ signal: AbortSignal.timeout(timeoutMs)
32201
+ });
32202
+ if (r.status !== 429 || tolerate.includes(429)) break;
32203
+ const asked = retryAfterMs(r.headers.get("retry-after"));
32204
+ const backoff = Math.min(RETRY_AFTER_CEILING_MS, RATE_LIMIT_BACKOFF_MS * 2 ** attempt);
32205
+ const wait = Math.min(RETRY_AFTER_CEILING_MS, Math.max(asked, backoff)) * (1 + Math.random() / 2);
32206
+ if (waited + wait > this.rateLimitPatienceMs) throw new RateLimitedError(asked);
32207
+ await sleep(wait);
32208
+ waited += wait;
32209
+ }
32075
32210
  if (!r.ok && r.status !== 404 && !tolerate.includes(r.status))
32076
32211
  throw new Error(
32077
32212
  `${method} ${url2} -> ${r.status} ${await r.text()}${this.authHint(r.status)}`
@@ -32106,7 +32241,7 @@ var HindsightClient = class {
32106
32241
  }
32107
32242
  /**
32108
32243
  * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
32109
- * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
32244
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via the version endpoint; anything
32110
32245
  * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
32111
32246
  */
32112
32247
  async supportsIdempotentRetain() {
@@ -32116,15 +32251,21 @@ var HindsightClient = class {
32116
32251
  }
32117
32252
  return this.idempotentRetain;
32118
32253
  }
32254
+ /** `/v1/version` first: an ingress that routes only `/v1` to the API (the Helm chart's default)
32255
+ * hands a bare `/version` to the control plane, whose HTML 404 or login redirect read as "no",
32256
+ * so append silently never turned on (#5286). Servers that predate the alias still answer
32257
+ * `/version`, so that stays as the fallback. */
32119
32258
  async probeIdempotentRetain() {
32120
- try {
32121
- const r = await this.req("GET", `${this.apiUrl}/version`);
32122
- if (!r.ok) return false;
32123
- const j = await r.json();
32124
- return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
32125
- } catch {
32126
- return false;
32259
+ for (const path of ["/v1/version", "/version"]) {
32260
+ try {
32261
+ const r = await this.req("GET", `${this.apiUrl}${path}`);
32262
+ if (!r.ok) continue;
32263
+ const j = await r.json();
32264
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
32265
+ } catch {
32266
+ }
32127
32267
  }
32268
+ return false;
32128
32269
  }
32129
32270
  /**
32130
32271
  * Whether a session write-back may use `update_mode="append"`: the server must dedupe by
@@ -32186,6 +32327,14 @@ var HindsightClient = class {
32186
32327
  if (items.length < limit || offset + limit >= (j.total ?? 0)) return void 0;
32187
32328
  }
32188
32329
  }
32330
+ /** Whether the bank holds any document at all — a one-row listing. A bank that does not exist
32331
+ * yet (404) holds none; any other failure throws, so a caller can tell "empty" from "unknown". */
32332
+ async hasDocuments() {
32333
+ const r = await this.req("GET", this.bankUrl("/documents?limit=1"));
32334
+ if (r.status === 404) return false;
32335
+ const j = await r.json();
32336
+ return (j.total ?? j.items?.length ?? 0) > 0;
32337
+ }
32189
32338
  /** Configure the bank: POST the coding bank manifest to /import (missions, retain strategies,
32190
32339
  * entity labels), then seed knowledge pages when the server supports them. Both halves are
32191
32340
  * idempotent and ADDITIVE — nothing the bank already says is overwritten (#3927), bar the
@@ -32267,7 +32416,13 @@ var HindsightClient = class {
32267
32416
  this.log(`[wait] draining ${ids.length} ${label} operations \u2026`);
32268
32417
  const start = Date.now();
32269
32418
  const pending = new Set(ids);
32419
+ const serverErrors = /* @__PURE__ */ new Map();
32270
32420
  let failed = 0;
32421
+ const giveUp = (id, status) => {
32422
+ pending.delete(id);
32423
+ failed++;
32424
+ this.log(` \u2026 ${label} op ${id} -> HTTP ${status}, counted as failed`);
32425
+ };
32271
32426
  while (pending.size && Date.now() - start < maxMs) {
32272
32427
  let backoffMs = POLL_CYCLE_MS;
32273
32428
  await pool([...pending], this.maxParallelRetains, async (id) => {
@@ -32280,7 +32435,14 @@ var HindsightClient = class {
32280
32435
  );
32281
32436
  return;
32282
32437
  }
32283
- if (!r.ok) return;
32438
+ if (r.status >= 500) {
32439
+ const n = (serverErrors.get(id) ?? 0) + 1;
32440
+ serverErrors.set(id, n);
32441
+ if (n >= POLL_MAX_SERVER_ERRORS) giveUp(id, r.status);
32442
+ return;
32443
+ }
32444
+ if (!r.ok) return giveUp(id, r.status);
32445
+ serverErrors.delete(id);
32284
32446
  const st = ((await r.json()).status || "").toLowerCase();
32285
32447
  if (TERMINAL.has(st)) {
32286
32448
  pending.delete(id);
@@ -32464,7 +32626,7 @@ var HindsightClient = class {
32464
32626
  * which is how `pageScopeRule`'s repo name reaches banks seeded by an earlier version.
32465
32627
  */
32466
32628
  async seedPages(pageTrigger = buildPageTrigger(), pagesConfig = {}, customPages = {}) {
32467
- const pages = pagesFor(this.project ?? this.bank, pagesConfig, customPages);
32629
+ const pages = pagesFor(this.project, pagesConfig, customPages);
32468
32630
  const existing = /* @__PURE__ */ new Map();
32469
32631
  let roots;
32470
32632
  try {
@@ -32539,7 +32701,7 @@ var HindsightClient = class {
32539
32701
  }
32540
32702
  const initiatives = await this.resyncInitiativeTriggers(roots, pageTrigger);
32541
32703
  this.log(
32542
- `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
32704
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? "the shared bank"}): ${created} created, ${updated} re-synced, ${pages.length - created - updated - vanished} unchanged` + (vanished ? `, ${vanished} deleted under us` : "") + (initiatives ? `, ${initiatives} initiative pages re-synced` : "")
32543
32705
  );
32544
32706
  }
32545
32707
  /**
@@ -32550,23 +32712,33 @@ var HindsightClient = class {
32550
32712
  * it: five taxonomy pages against one page per initiative, each an LLM synthesis per
32551
32713
  * consolidation under the auto-refresh that used to be the default (#3506).
32552
32714
  *
32553
- * Only the trigger is touched. Their `name` and `source_query` are written once, from the
32554
- * initiative's own title, and re-stating either would rebuild a page whose question never
32555
- * changed. The tree read above is reused rather than re-fetched.
32715
+ * Their `name` and `source_query` are written once, from the initiative's own title, and
32716
+ * re-stating either would rebuild a page whose question never changed. The one exception is
32717
+ * the scope clause: a page captured while the clause named the BANK is scoped to a project no
32718
+ * memory is about and comes out empty (#4490), so exactly that clause is swapped for the current
32719
+ * one — the rest of the query, the user's wording included, is kept. The tree read above is
32720
+ * reused rather than re-fetched.
32556
32721
  */
32557
32722
  async resyncInitiativeTriggers(roots, pageTrigger) {
32558
32723
  const folder = roots.find(
32559
32724
  (n) => n.kind === "folder" && (n.name || "").toLowerCase() === "initiatives"
32560
32725
  );
32726
+ const bankScope = pageScopeRule(this.bank);
32561
32727
  let updated = 0;
32562
32728
  for (const page of folder?.children ?? []) {
32563
- if (page.kind !== "page" || page.trigger == null) continue;
32564
- const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
32565
- if (!pageTriggerDrifted(page.trigger, desired)) continue;
32729
+ if (page.kind !== "page") continue;
32730
+ const patch = {};
32731
+ const query = page.description?.replace(bankScope, pageScopeRule(this.project));
32732
+ if (query !== page.description) patch.source_query = query;
32733
+ if (page.trigger != null) {
32734
+ const desired = pageTriggerFor(pageTrigger, this.bank, page.name);
32735
+ if (pageTriggerDrifted(page.trigger, desired)) patch.trigger = pageTriggerPatch(desired);
32736
+ }
32737
+ if (!patch.trigger && !patch.source_query) continue;
32566
32738
  const r = await this.req(
32567
32739
  "PATCH",
32568
32740
  this.bankUrl(`/knowledge-base/nodes/${encodeURIComponent(page.id)}`),
32569
- { trigger: pageTriggerPatch(desired) }
32741
+ patch
32570
32742
  );
32571
32743
  if (r.status === 404) continue;
32572
32744
  updated++;
@@ -32594,10 +32766,9 @@ var HindsightClient = class {
32594
32766
  let pageId = args.relatesToPageId;
32595
32767
  if (!pageId) {
32596
32768
  const folderId = await this.ensureFolder("Initiatives");
32597
- const subject = this.project ?? this.bank;
32598
32769
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), {
32599
32770
  name: args.title,
32600
- 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.` + pageScopeRule(subject),
32771
+ 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.` + pageScopeRule(this.project),
32601
32772
  parent_id: folderId,
32602
32773
  tags: ["knowledge:feature-work"],
32603
32774
  max_tokens: PAGE_MAX_TOKENS,
@@ -32612,7 +32783,7 @@ var HindsightClient = class {
32612
32783
  }
32613
32784
  const verb = args.relatesToPageId ? "Update to an existing initiative" : "New initiative";
32614
32785
  const content = `${verb}: ${args.title}. ${args.summary}`;
32615
- const markerId = `initiative-marker-${this.slugify(args.title)}-${Date.now()}`;
32786
+ const markerId = `initiative-marker-${this.slugify(pageId)}${args.relatesToPageId ? "-update" : ""}`;
32616
32787
  const tags = [.../* @__PURE__ */ new Set([...args.stamp?.tags ?? [], "knowledge:feature-work"])];
32617
32788
  const context = `initiative marker for [[page:${pageId}]]`;
32618
32789
  await this.retain(content, context, markerId, tags, "document", {
@@ -32849,7 +33020,7 @@ function resolveConfig(raw = {}) {
32849
33020
  }
32850
33021
  function readRaw(path) {
32851
33022
  try {
32852
- return JSON.parse(readFileSync2(path, "utf8"));
33023
+ return JSON.parse(readFileSync3(path, "utf8"));
32853
33024
  } catch (e) {
32854
33025
  if (e?.code !== "ENOENT") {
32855
33026
  console.error(`hindsight: ignoring invalid config at ${path}: ${e?.message || e}`);
@@ -33036,10 +33207,12 @@ function resolveHostConfig(harness, directory) {
33036
33207
  if (cfg0.disabled) return { cfg: cfg0, bankId: "" };
33037
33208
  const bankId = deriveBankIdOrSkip(cfg0, directory, harness);
33038
33209
  if (bankId === null) return { cfg: { ...cfg0, disabled: true }, bankId: "" };
33039
- return applyBankConfig(cfg0, bankId, directory);
33210
+ const resolved2 = applyBankConfig(cfg0, bankId, directory);
33211
+ const project = resolved2.bankId === bankId ? bankProjectName(resolved2.cfg, directory) : void 0;
33212
+ return { ...resolved2, project };
33040
33213
  }
33041
33214
  function resolveHostMemory(harness, directory) {
33042
- const { cfg, bankId } = resolveHostConfig(harness, directory);
33215
+ const { cfg, bankId, project } = resolveHostConfig(harness, directory);
33043
33216
  return {
33044
33217
  cfg,
33045
33218
  bankId,
@@ -33047,6 +33220,8 @@ function resolveHostMemory(harness, directory) {
33047
33220
  apiUrl: cfg.apiUrl,
33048
33221
  apiToken: cfg.apiToken,
33049
33222
  bank: bankId,
33223
+ // Names the repo in the initiative pages this host captures, as the seeded pages do.
33224
+ project,
33050
33225
  maxParallelRetains: cfg.maxParallelRetains,
33051
33226
  observationScopes: cfg.observationScopes,
33052
33227
  pageSearchLimit: cfg.pageSearchLimit,
@@ -33066,19 +33241,27 @@ function resolveHostMemory(harness, directory) {
33066
33241
  }
33067
33242
 
33068
33243
  // src/core/knowledge-tools.ts
33069
- import { createHash as createHash3 } from "crypto";
33244
+ import { createHash as createHash4 } from "crypto";
33070
33245
  import { existsSync as existsSync3 } from "fs";
33071
33246
  import { homedir as homedir5 } from "os";
33072
33247
  import { join as join10 } from "path";
33073
33248
 
33074
33249
  // src/core/status.ts
33075
- import { execFileSync as execFileSync2 } from "child_process";
33250
+ import { execFileSync as execFileSync3 } from "child_process";
33076
33251
 
33077
33252
  // src/core/git.ts
33078
33253
  import { execFileSync } from "child_process";
33079
33254
  import { resolve as resolve2 } from "path";
33255
+
33256
+ // src/core/uuid.ts
33257
+ import { createHash as createHash2 } from "crypto";
33258
+
33259
+ // src/core/git.ts
33260
+ var US = "";
33261
+ var RS = "";
33262
+ var GITLOG_FORMAT = `--format=%h${US}%ad${US}%an${US}%s${US}%b${RS}`;
33080
33263
  function git(repo, ...args) {
33081
- return execFileSync("git", ["-C", repo, ...args], {
33264
+ return execFileSync("git", ["-C", repo, "-c", "log.showSignature=false", ...args], {
33082
33265
  encoding: "utf8",
33083
33266
  maxBuffer: 1 << 28,
33084
33267
  windowsHide: true,
@@ -33114,8 +33297,8 @@ function parsePageList(raw) {
33114
33297
  }
33115
33298
 
33116
33299
  // src/core/survey.ts
33117
- import { spawn as realSpawn3 } from "child_process";
33118
- import { createHash as createHash2 } from "crypto";
33300
+ import { execFileSync as execFileSync2, spawn as realSpawn3 } from "child_process";
33301
+ import { createHash as createHash3 } from "crypto";
33119
33302
  import { existsSync as existsSync2 } from "fs";
33120
33303
  import { homedir as homedir4, tmpdir } from "os";
33121
33304
  import { dirname as dirname5, join as join9 } from "path";
@@ -33150,7 +33333,7 @@ var SURVEY_DOC_IDS = [
33150
33333
  var DEEPEN_DIFF_TARGET = 300;
33151
33334
  function commitCount(repoDir) {
33152
33335
  try {
33153
- const out = execFileSync2("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
33336
+ const out = execFileSync3("git", ["-C", repoDir, "rev-list", "--count", "HEAD"], {
33154
33337
  encoding: "utf8",
33155
33338
  windowsHide: true,
33156
33339
  stdio: ["ignore", "pipe", "pipe"]
@@ -33374,7 +33557,7 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
33374
33557
  annotations: NON_DESTRUCTIVE_WRITE_ANNOTATIONS,
33375
33558
  handler: guarded(async ({ title, content }) => {
33376
33559
  const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
33377
- const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash3("sha256").update(title).digest("hex")}` : slug;
33560
+ const docId = /[^\x00-\x7f]/.test(title) || !slug ? `${slug || "doc"}--${createHash4("sha256").update(title).digest("hex")}` : slug;
33378
33561
  const stamp = opts.stampFor?.();
33379
33562
  const metadata = {
33380
33563
  ...stamp?.metadata,