@vectorize-io/hindsight-coding-agents 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +44 -3
  2. package/dist/antigravity-hook.js +142 -9
  3. package/dist/antigravity-statusline.js +42 -4
  4. package/dist/antigravity-stop-hook.js +222 -59
  5. package/dist/claude-hook.js +142 -9
  6. package/dist/claude-sessionstart-hook.js +144 -9
  7. package/dist/claude-stop-hook.js +222 -59
  8. package/dist/cline.js +148 -59
  9. package/dist/codex-hook.js +142 -9
  10. package/dist/codex-sessionstart-hook.js +144 -9
  11. package/dist/codex-stop-hook.js +222 -59
  12. package/dist/copilot-hook.js +142 -9
  13. package/dist/copilot-sessionstart-hook.js +144 -9
  14. package/dist/copilot-stop-hook.js +222 -59
  15. package/dist/cursor-hook.js +142 -9
  16. package/dist/cursor-sessionstart-hook.js +144 -9
  17. package/dist/cursor-stop-hook.js +222 -59
  18. package/dist/daemon-start.js +36 -2
  19. package/dist/dcode-hook.js +142 -9
  20. package/dist/dcode-sessionstart-hook.js +144 -9
  21. package/dist/dcode-stop-hook.js +222 -59
  22. package/dist/deepen.js +97 -14
  23. package/dist/devin-hook.js +142 -9
  24. package/dist/devin-sessionstart-hook.js +144 -9
  25. package/dist/devin-stop-hook.js +222 -59
  26. package/dist/droid-hook.js +2710 -0
  27. package/dist/droid-sessionstart-hook.js +3328 -0
  28. package/dist/droid-stop-hook.js +2970 -0
  29. package/dist/dsh.js +153 -60
  30. package/dist/grok-hook.js +142 -9
  31. package/dist/grok-sessionstart-hook.js +144 -9
  32. package/dist/grok-stop-hook.js +222 -59
  33. package/dist/hindsight-seed.js +42 -4
  34. package/dist/index.js +148 -59
  35. package/dist/installer.js +155 -13
  36. package/dist/kilo.js +148 -59
  37. package/dist/mcp-server.js +474 -133
  38. package/dist/opencode2.js +148 -59
  39. package/dist/pi.js +148 -59
  40. package/dist/prime-agent.js +148 -59
  41. package/dist/qwen-hook.js +142 -9
  42. package/dist/qwen-sessionstart-hook.js +144 -9
  43. package/dist/qwen-stop-hook.js +222 -59
  44. package/dist/status.js +65 -7
  45. package/package.json +6 -3
  46. package/plugin.json +1 -1
  47. package/skill/SKILL.md +26 -2
package/dist/dsh.js CHANGED
@@ -332,9 +332,13 @@ function isOptedIn(config2, directory) {
332
332
  const pathMap = config2.mapPathToBank;
333
333
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
334
334
  }
335
- function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
335
+ function mappedBank(config2, directory, sessionRoot) {
336
336
  const pathMap = config2.mapPathToBank;
337
- const mapped = directory && pathMap ? lookupDirectories(config2, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
337
+ if (!directory || !pathMap) return void 0;
338
+ return lookupDirectories(config2, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0);
339
+ }
340
+ function deriveBankId(config2, directory, harness = "coding", sessionRoot) {
341
+ const mapped = mappedBank(config2, directory, sessionRoot);
338
342
  if (mapped) return mapped;
339
343
  const dynamic = config2.dynamicBankId ?? !config2.bankId;
340
344
  if (!dynamic) return config2.bankId || DEFAULT_BANK_NAME;
@@ -362,6 +366,7 @@ function deriveBankIdOrSkip(config2, directory, harness = "coding", sessionRoot)
362
366
  }
363
367
 
364
368
  // src/core/missions.ts
369
+ import { createHash } from "crypto";
365
370
  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.";
366
371
  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.";
367
372
  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.`;
@@ -473,6 +478,56 @@ function pagesFor(project) {
473
478
  var PAGE_MAX_TOKENS = 4096;
474
479
  var PAGE_TAGS_MATCH = "all";
475
480
  var PAGE_FACT_TYPES = ["world", "experience", "observation"];
481
+ var CRON_FIELD_RANGES = [
482
+ [0, 59],
483
+ // minute
484
+ [0, 23],
485
+ // hour
486
+ [1, 31],
487
+ // day of month
488
+ [1, 12],
489
+ // month
490
+ [0, 6]
491
+ // day of week
492
+ ];
493
+ var HASHED_FIELD = /^H(?:\((\d+)-(\d+)\))?$/;
494
+ function isHashedCron(cron) {
495
+ return /(^|\s)H/.test(cron);
496
+ }
497
+ function parseHashedCron(cron) {
498
+ const fields = cron.trim().split(/\s+/);
499
+ if (fields.length !== CRON_FIELD_RANGES.length) return void 0;
500
+ for (const [i, field] of fields.entries()) {
501
+ if (!field.startsWith("H")) continue;
502
+ const m = HASHED_FIELD.exec(field);
503
+ if (!m) return void 0;
504
+ if (m[1] === void 0) continue;
505
+ const [lo, hi] = [Number(m[1]), Number(m[2])];
506
+ const [min, max] = CRON_FIELD_RANGES[i];
507
+ if (lo > hi || lo < min || hi > max) return void 0;
508
+ }
509
+ return fields;
510
+ }
511
+ function hashedValue(seed, field, lo, hi) {
512
+ const digest = createHash("sha256").update(`${seed}\0${field}`).digest();
513
+ return lo + digest.readUInt32BE(0) % (hi - lo + 1);
514
+ }
515
+ function expandCronHash(cron, seed) {
516
+ if (!isHashedCron(cron)) return cron;
517
+ const fields = parseHashedCron(cron);
518
+ if (!fields) return cron;
519
+ return fields.map((field, i) => {
520
+ const m = HASHED_FIELD.exec(field);
521
+ if (!m) return field;
522
+ const [lo, hi] = m[1] === void 0 ? CRON_FIELD_RANGES[i] : [Number(m[1]), Number(m[2])];
523
+ return String(hashedValue(seed, i, lo, hi));
524
+ }).join(" ");
525
+ }
526
+ function pageTriggerFor(trigger, bank, page) {
527
+ const cron = trigger.refresh_cron;
528
+ if (!cron || !isHashedCron(cron)) return trigger;
529
+ return { ...trigger, refresh_cron: expandCronHash(cron, `${bank}\0${page}`) };
530
+ }
476
531
  function buildPageTrigger(cfg = {}) {
477
532
  const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
478
533
  switch (cfg.pageTriggerType) {
@@ -1026,7 +1081,9 @@ var HindsightClient = class {
1026
1081
  source_query: page.source_query,
1027
1082
  tags: page.tags,
1028
1083
  max_tokens: PAGE_MAX_TOKENS,
1029
- trigger: pageTrigger
1084
+ // Resolved HERE, not in `buildPageTrigger`: a hashed cron (`H`) needs the page's identity,
1085
+ // and one trigger is built per session for all of them.
1086
+ trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
1030
1087
  };
1031
1088
  if (!hit) {
1032
1089
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -1064,7 +1121,7 @@ var HindsightClient = class {
1064
1121
  }
1065
1122
  }
1066
1123
  this.log(
1067
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
1124
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
1068
1125
  );
1069
1126
  }
1070
1127
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -1093,7 +1150,7 @@ var HindsightClient = class {
1093
1150
  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.`,
1094
1151
  parent_id: folderId,
1095
1152
  tags: ["knowledge:feature-work"],
1096
- trigger: args.pageTrigger ?? buildPageTrigger()
1153
+ trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1097
1154
  });
1098
1155
  try {
1099
1156
  const j = await r.json();
@@ -1138,10 +1195,11 @@ var DEFAULT_DAEMON_PROFILE = "coding-agent";
1138
1195
  function resolvePageTriggerType(raw) {
1139
1196
  if (raw.pageTriggerType === "manual") return "manual";
1140
1197
  if (raw.pageTriggerType === "cron") {
1141
- if (raw.pageTriggerCron?.trim()) return "cron";
1198
+ const cron = raw.pageTriggerCron?.trim();
1199
+ if (cron && (!isHashedCron(cron) || parseHashedCron(cron))) return "cron";
1142
1200
  log.warn(
1143
1201
  "config",
1144
- 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
1202
+ cron ? `pageTriggerCron ${JSON.stringify(cron)} has a malformed hashed field \u2014 write \`H\` or \`H(<lo>-<hi>)\` within the field's own range, e.g. "H H(0-5) * * *" \u2014 falling back to "auto-refresh"` : 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "H H * * *") \u2014 falling back to "auto-refresh"'
1145
1203
  );
1146
1204
  }
1147
1205
  return "auto-refresh";
@@ -16748,15 +16806,24 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16748
16806
  }
16749
16807
 
16750
16808
  // src/core/retain-cursor.ts
16751
- import { createHash } from "crypto";
16809
+ import { createHash as createHash2 } from "crypto";
16810
+ var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
16811
+ var PENDING_MAX_BYTES = 256 * 1024;
16812
+ function pendingReplayable(cursor, now) {
16813
+ const pending = cursor.pending ?? [];
16814
+ if (!pending.length) return true;
16815
+ if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
16816
+ return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
16817
+ }
16752
16818
  function fingerprintTurns(turns, count) {
16753
- const h = createHash("sha1").update(String(count));
16819
+ const h = createHash2("sha1").update(String(count));
16754
16820
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
16755
16821
  return h.digest("hex");
16756
16822
  }
16757
16823
  function planRetain(turns, cursor, opts) {
16758
16824
  if (!turns.length) return { mode: "skip" };
16759
16825
  if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
16826
+ if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
16760
16827
  if (cursor.bank !== opts.bank) return { mode: "replace" };
16761
16828
  if (cursor.turns > turns.length) return { mode: "replace" };
16762
16829
  if (fingerprintTurns(turns, cursor.turns) !== cursor.fingerprint) return { mode: "replace" };
@@ -16772,13 +16839,13 @@ function memoryCursorStore() {
16772
16839
  }
16773
16840
 
16774
16841
  // src/core/uuid.ts
16775
- import { createHash as createHash2 } from "crypto";
16842
+ import { createHash as createHash3 } from "crypto";
16776
16843
  var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
16777
16844
  function uuidV5(name2, namespace = HINDSIGHT_NAMESPACE) {
16778
16845
  const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
16779
16846
  if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
16780
16847
  const bytes = Buffer.from(
16781
- createHash2("sha1").update(ns).update(Buffer.from(name2, "utf8")).digest().subarray(0, 16)
16848
+ createHash3("sha1").update(ns).update(Buffer.from(name2, "utf8")).digest().subarray(0, 16)
16782
16849
  );
16783
16850
  bytes[6] = bytes[6] & 15 | 80;
16784
16851
  bytes[8] = bytes[8] & 63 | 128;
@@ -16855,61 +16922,83 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
16855
16922
  );
16856
16923
  }
16857
16924
  async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
16925
+ if (!turns.length) return;
16858
16926
  const refId = `conversation:${sessionId}`;
16859
16927
  const appendSupported = Boolean(cursors) && await supportsAppend(client);
16860
- const plan = planRetain(turns, cursors?.read(sessionId), { appendSupported, bank: client.bank });
16861
- if (plan.mode === "skip") return;
16862
- const content = plan.mode === "append" ? turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n") : renderSessionJsonl(refId, turns, startTs);
16928
+ const cursor = cursors?.read(sessionId);
16929
+ const plan = planRetain(turns, cursor, { appendSupported, bank: client.bank });
16930
+ const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
16931
+ if (plan.mode === "skip" && !outbox.length) return;
16932
+ const opId = (mode, content) => uuidV5(`${client.bank}
16933
+ ${refId}
16934
+ ${mode}
16935
+ ${content}`);
16936
+ const submit = (content, operationId, append) => client.retain(
16937
+ content,
16938
+ "coding agent session",
16939
+ refId,
16940
+ // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
16941
+ // the documents list filters and draws its agent logo from, so a template cannot displace them.
16942
+ [
16943
+ .../* @__PURE__ */ new Set([
16944
+ ...stamp?.tags ?? [],
16945
+ "source:chat",
16946
+ ...harness ? [`harness:${harness}`] : []
16947
+ ])
16948
+ ],
16949
+ "conversation",
16950
+ {
16951
+ timestamp: startTs,
16952
+ updateMode: append ? "append" : void 0,
16953
+ operationId,
16954
+ metadata: {
16955
+ ...stamp?.metadata,
16956
+ // configured first: the built-ins below win on any key collision
16957
+ source: "chat",
16958
+ session_id: sessionId,
16959
+ ref_id: refId,
16960
+ ...harness ? { harness } : {}
16961
+ }
16962
+ }
16963
+ );
16863
16964
  const next = {
16864
16965
  turns: turns.length,
16865
16966
  fingerprint: fingerprintTurns(turns, turns.length),
16866
16967
  bank: client.bank
16867
16968
  };
16868
- cursors?.write(sessionId, { ...next, dirty: true });
16869
- const claimed = { ...next, dirty: true };
16870
- await submitWithRetry(
16871
- () => client.retain(
16872
- content,
16873
- "coding agent session",
16874
- refId,
16875
- // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
16876
- // the documents list filters and draws its agent logo from, so a template cannot displace them.
16877
- [
16878
- .../* @__PURE__ */ new Set([
16879
- ...stamp?.tags ?? [],
16880
- "source:chat",
16881
- ...harness ? [`harness:${harness}`] : []
16882
- ])
16883
- ],
16884
- "conversation",
16885
- {
16886
- timestamp: startTs,
16887
- updateMode: plan.mode === "append" ? "append" : void 0,
16888
- // Identity of THIS payload: a resubmission of the same bytes is collapsed server-side into
16889
- // the original operation instead of extracting (or appending) twice.
16890
- operationId: uuidV5(`${client.bank}
16891
- ${refId}
16892
- ${plan.mode}
16893
- ${content}`),
16894
- metadata: {
16895
- ...stamp?.metadata,
16896
- // configured first: the built-ins below win on any key collision
16897
- source: "chat",
16898
- session_id: sessionId,
16899
- ref_id: refId,
16900
- ...harness ? { harness } : {}
16901
- }
16902
- }
16903
- ),
16904
- // Still ours to retry only while the cursor holds the claim we wrote above.
16905
- () => {
16906
- if (!cursors) return true;
16907
- const now = cursors.read(sessionId);
16908
- return now?.turns === claimed.turns && now?.fingerprint === claimed.fingerprint;
16909
- },
16910
- retryUntil
16911
- );
16912
- cursors?.write(sessionId, next);
16969
+ const stillOurs = () => {
16970
+ if (!cursors) return true;
16971
+ const now = cursors.read(sessionId);
16972
+ return now?.turns === next.turns && now?.fingerprint === next.fingerprint;
16973
+ };
16974
+ if (plan.mode === "replace") {
16975
+ const content = renderSessionJsonl(refId, turns, startTs);
16976
+ cursors?.write(sessionId, { ...next, dirty: true });
16977
+ await submitWithRetry(
16978
+ () => submit(content, opId("replace", content), false),
16979
+ stillOurs,
16980
+ retryUntil
16981
+ );
16982
+ cursors?.write(sessionId, next);
16983
+ return;
16984
+ }
16985
+ const queue = [...outbox];
16986
+ if (plan.mode === "append") {
16987
+ const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
16988
+ queue.push({ content, operationId: opId("append", content), at: Date.now() });
16989
+ }
16990
+ cursors?.write(sessionId, { ...next, pending: queue });
16991
+ for (let i = 0; i < queue.length; i++) {
16992
+ if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
16993
+ const entry = queue[i];
16994
+ await submitWithRetry(
16995
+ () => submit(entry.content, entry.operationId, true),
16996
+ stillOurs,
16997
+ retryUntil
16998
+ );
16999
+ const remaining = queue.slice(i + 1);
17000
+ cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
17001
+ }
16913
17002
  }
16914
17003
 
16915
17004
  // src/core/retain-stamp.ts
@@ -17593,6 +17682,9 @@ var name = HINDSIGHT_PLUGIN;
17593
17682
  var inject = ["agents"];
17594
17683
  var workspaces = /* @__PURE__ */ new Map();
17595
17684
  var liveAgents = /* @__PURE__ */ new Map();
17685
+ function dshSessionEvents(session) {
17686
+ return session.snapshotEvents?.() ?? session.events ?? [];
17687
+ }
17596
17688
  function workspaceRoot(agent) {
17597
17689
  return agent.session.header.cwd || process.cwd();
17598
17690
  }
@@ -17607,7 +17699,7 @@ function workspaceFor(root) {
17607
17699
  const core = new RuntimeCore(client, bankId, cfg, HARNESS2, root);
17608
17700
  core.setTranscriptSource(async (sessionId) => {
17609
17701
  const agent = liveAgents.get(sessionId);
17610
- return agent ? readDshEvents(agent.session.events) : [];
17702
+ return agent ? readDshEvents(dshSessionEvents(agent.session)) : [];
17611
17703
  });
17612
17704
  const workspace = { core, root };
17613
17705
  workspaces.set(root, workspace);
@@ -17742,6 +17834,7 @@ export {
17742
17834
  apply,
17743
17835
  createDshHooks,
17744
17836
  dsh_default as default,
17837
+ dshSessionEvents,
17745
17838
  inject,
17746
17839
  name,
17747
17840
  toDshParameters
package/dist/grok-hook.js CHANGED
@@ -287,9 +287,13 @@ function isOptedIn(config, directory) {
287
287
  const pathMap = config.mapPathToBank;
288
288
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
289
289
  }
290
- function deriveBankId(config, directory, harness = "coding", sessionRoot) {
290
+ function mappedBank(config, directory, sessionRoot) {
291
291
  const pathMap = config.mapPathToBank;
292
- const mapped = directory && pathMap ? lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
292
+ if (!directory || !pathMap) return void 0;
293
+ return lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0);
294
+ }
295
+ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
296
+ const mapped = mappedBank(config, directory, sessionRoot);
293
297
  if (mapped) return mapped;
294
298
  const dynamic = config.dynamicBankId ?? !config.bankId;
295
299
  if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
@@ -355,6 +359,7 @@ function startBackgroundSeed(repoDir, opts = {}) {
355
359
  }
356
360
 
357
361
  // src/core/missions.ts
362
+ import { createHash } from "crypto";
358
363
  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.";
359
364
  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.";
360
365
  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.`;
@@ -466,6 +471,56 @@ function pagesFor(project) {
466
471
  var PAGE_MAX_TOKENS = 4096;
467
472
  var PAGE_TAGS_MATCH = "all";
468
473
  var PAGE_FACT_TYPES = ["world", "experience", "observation"];
474
+ var CRON_FIELD_RANGES = [
475
+ [0, 59],
476
+ // minute
477
+ [0, 23],
478
+ // hour
479
+ [1, 31],
480
+ // day of month
481
+ [1, 12],
482
+ // month
483
+ [0, 6]
484
+ // day of week
485
+ ];
486
+ var HASHED_FIELD = /^H(?:\((\d+)-(\d+)\))?$/;
487
+ function isHashedCron(cron) {
488
+ return /(^|\s)H/.test(cron);
489
+ }
490
+ function parseHashedCron(cron) {
491
+ const fields = cron.trim().split(/\s+/);
492
+ if (fields.length !== CRON_FIELD_RANGES.length) return void 0;
493
+ for (const [i, field] of fields.entries()) {
494
+ if (!field.startsWith("H")) continue;
495
+ const m = HASHED_FIELD.exec(field);
496
+ if (!m) return void 0;
497
+ if (m[1] === void 0) continue;
498
+ const [lo, hi] = [Number(m[1]), Number(m[2])];
499
+ const [min, max] = CRON_FIELD_RANGES[i];
500
+ if (lo > hi || lo < min || hi > max) return void 0;
501
+ }
502
+ return fields;
503
+ }
504
+ function hashedValue(seed, field, lo, hi) {
505
+ const digest = createHash("sha256").update(`${seed}\0${field}`).digest();
506
+ return lo + digest.readUInt32BE(0) % (hi - lo + 1);
507
+ }
508
+ function expandCronHash(cron, seed) {
509
+ if (!isHashedCron(cron)) return cron;
510
+ const fields = parseHashedCron(cron);
511
+ if (!fields) return cron;
512
+ return fields.map((field, i) => {
513
+ const m = HASHED_FIELD.exec(field);
514
+ if (!m) return field;
515
+ const [lo, hi] = m[1] === void 0 ? CRON_FIELD_RANGES[i] : [Number(m[1]), Number(m[2])];
516
+ return String(hashedValue(seed, i, lo, hi));
517
+ }).join(" ");
518
+ }
519
+ function pageTriggerFor(trigger, bank, page) {
520
+ const cron = trigger.refresh_cron;
521
+ if (!cron || !isHashedCron(cron)) return trigger;
522
+ return { ...trigger, refresh_cron: expandCronHash(cron, `${bank}\0${page}`) };
523
+ }
469
524
  function buildPageTrigger(cfg = {}) {
470
525
  const base = { fact_types: PAGE_FACT_TYPES, tags_match: PAGE_TAGS_MATCH };
471
526
  switch (cfg.pageTriggerType) {
@@ -1000,7 +1055,9 @@ var HindsightClient = class {
1000
1055
  source_query: page.source_query,
1001
1056
  tags: page.tags,
1002
1057
  max_tokens: PAGE_MAX_TOKENS,
1003
- trigger: pageTrigger
1058
+ // Resolved HERE, not in `buildPageTrigger`: a hashed cron (`H`) needs the page's identity,
1059
+ // and one trigger is built per session for all of them.
1060
+ trigger: pageTriggerFor(pageTrigger, this.bank, page.name)
1004
1061
  };
1005
1062
  if (!hit) {
1006
1063
  const r = await this.req("POST", this.bankUrl("/knowledge-base/pages"), body, [409]);
@@ -1038,7 +1095,7 @@ var HindsightClient = class {
1038
1095
  }
1039
1096
  }
1040
1097
  this.log(
1041
- `[bank] knowledge pages seeded on ${this.bank}: ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
1098
+ `[bank] knowledge pages seeded on ${this.bank} (scoped to ${this.project ?? this.bank}): ${created} created, ${updated} re-synced, ${pages.length - created - updated} unchanged`
1042
1099
  );
1043
1100
  }
1044
1101
  /** URL/id-safe slug: lowercase, non-alphanumerics → "-", trim dashes, cap length; fallback "initiative". */
@@ -1067,7 +1124,7 @@ var HindsightClient = class {
1067
1124
  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.`,
1068
1125
  parent_id: folderId,
1069
1126
  tags: ["knowledge:feature-work"],
1070
- trigger: args.pageTrigger ?? buildPageTrigger()
1127
+ trigger: pageTriggerFor(args.pageTrigger ?? buildPageTrigger(), this.bank, args.title)
1071
1128
  });
1072
1129
  try {
1073
1130
  const j = await r.json();
@@ -1112,10 +1169,11 @@ var DEFAULT_DAEMON_PROFILE = "coding-agent";
1112
1169
  function resolvePageTriggerType(raw) {
1113
1170
  if (raw.pageTriggerType === "manual") return "manual";
1114
1171
  if (raw.pageTriggerType === "cron") {
1115
- if (raw.pageTriggerCron?.trim()) return "cron";
1172
+ const cron = raw.pageTriggerCron?.trim();
1173
+ if (cron && (!isHashedCron(cron) || parseHashedCron(cron))) return "cron";
1116
1174
  log.warn(
1117
1175
  "config",
1118
- 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
1176
+ cron ? `pageTriggerCron ${JSON.stringify(cron)} has a malformed hashed field \u2014 write \`H\` or \`H(<lo>-<hi>)\` within the field's own range, e.g. "H H(0-5) * * *" \u2014 falling back to "auto-refresh"` : 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "H H * * *") \u2014 falling back to "auto-refresh"'
1119
1177
  );
1120
1178
  }
1121
1179
  return "auto-refresh";
@@ -1621,10 +1679,12 @@ async function runHook(spec, makeClient = (o) => new HindsightClient(o)) {
1621
1679
  import { readFileSync as readFileSync5 } from "fs";
1622
1680
 
1623
1681
  // src/core/retain-cursor.ts
1624
- import { createHash } from "crypto";
1682
+ import { createHash as createHash2 } from "crypto";
1683
+ var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
1684
+ var PENDING_MAX_BYTES = 256 * 1024;
1625
1685
 
1626
1686
  // src/core/uuid.ts
1627
- import { createHash as createHash2 } from "crypto";
1687
+ import { createHash as createHash3 } from "crypto";
1628
1688
 
1629
1689
  // src/core/daemon.ts
1630
1690
  import { execFileSync, spawn as realSpawn2 } from "child_process";
@@ -2216,6 +2276,50 @@ function collectQwenTurns(path, turns) {
2216
2276
  }
2217
2277
  }
2218
2278
 
2279
+ // src/core/transcript-droid.ts
2280
+ function renderContent(content, role) {
2281
+ if (!Array.isArray(content)) return [];
2282
+ const texts = [];
2283
+ const actions = [];
2284
+ for (const block of content) {
2285
+ if (!block || typeof block !== "object") continue;
2286
+ const b = block;
2287
+ if (b.type === "text" && typeof b.text === "string") {
2288
+ const text = stripInjectedMemory(b.text).trim();
2289
+ if (text) texts.push(text);
2290
+ } else if (b.type === "tool_use" && typeof b.name === "string") {
2291
+ actions.push({ role: "action", content: actionLine(b.name, b.input) });
2292
+ }
2293
+ }
2294
+ const out = [];
2295
+ const joined = texts.join("\n").trim();
2296
+ if (joined) out.push({ role, content: joined });
2297
+ out.push(...actions);
2298
+ return out;
2299
+ }
2300
+ function readDroidTranscript(path) {
2301
+ const turns = [];
2302
+ for (const rawLine of readJsonlTail(path, { scope: "factory-droid" }).lines) {
2303
+ if (!rawLine.trim()) continue;
2304
+ let parsed;
2305
+ try {
2306
+ parsed = JSON.parse(rawLine);
2307
+ } catch {
2308
+ continue;
2309
+ }
2310
+ if (!parsed || typeof parsed !== "object") continue;
2311
+ const line = parsed;
2312
+ if (line.type !== "message" || !line.message || typeof line.message !== "object") continue;
2313
+ const message = line.message;
2314
+ const role = message.role;
2315
+ if (role !== "user" && role !== "assistant") continue;
2316
+ if (message.visibility === "user_only" || message.visibility === "llm_only") continue;
2317
+ const stamp = typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
2318
+ turns.push(...renderContent(message.content, role).map((turn) => ({ ...turn, ...stamp })));
2319
+ }
2320
+ return turns;
2321
+ }
2322
+
2219
2323
  // src/harness/hook-lifecycle.ts
2220
2324
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
2221
2325
  var claudePrompt = {
@@ -2243,6 +2347,10 @@ var dcodePrompt = {
2243
2347
  ...claudePrompt,
2244
2348
  harness: "dcode"
2245
2349
  };
2350
+ var droidPrompt = {
2351
+ ...claudePrompt,
2352
+ harness: "factory-droid"
2353
+ };
2246
2354
  var qwenPrompt = {
2247
2355
  ...claudePrompt,
2248
2356
  harness: "qwen-code",
@@ -2569,6 +2677,31 @@ var HOOK_HARNESSES = {
2569
2677
  }),
2570
2678
  readTranscript: readQwenTranscript
2571
2679
  }
2680
+ },
2681
+ "factory-droid": {
2682
+ configStyle: "nested",
2683
+ install: {
2684
+ sessionStart: { event: "SessionStart", entry: "droid-sessionstart-hook.js", timeout: 30 },
2685
+ prompt: { event: "UserPromptSubmit", entry: "droid-hook.js", timeout: 30 },
2686
+ stop: { event: "Stop", entry: "droid-stop-hook.js", timeout: 60 }
2687
+ },
2688
+ // Droid emits Notification(idle_prompt), not Stop, after user cancellation. Reusing the
2689
+ // idempotent retain entry point captures that final partial turn; its event gate ignores every
2690
+ // other notification type before config or daemon work begins.
2691
+ additionalHooks: [{ event: "Notification", entry: "droid-stop-hook.js", timeout: 60 }],
2692
+ sessionStart: standardSessionStart("factory-droid"),
2693
+ prompt: droidPrompt,
2694
+ retain: {
2695
+ hostTimeoutSec: 60,
2696
+ harness: "factory-droid",
2697
+ accept: (ev) => ev.hook_event_name === "Stop" || ev.hook_event_name === "Notification" && ev.notification_type === "idle_prompt",
2698
+ parse: (ev) => ({
2699
+ sessionId: ev.session_id,
2700
+ transcriptPath: ev.transcript_path,
2701
+ cwd: ev.cwd
2702
+ }),
2703
+ readTranscript: readDroidTranscript
2704
+ }
2572
2705
  }
2573
2706
  };
2574
2707
  var runHarnessPrompt = (harness) => runHook(HOOK_HARNESSES[harness].prompt);