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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +145 -11
  7. package/dist/claude-stop-hook.js +222 -59
  8. package/dist/cline.js +149 -61
  9. package/dist/codex-hook.js +142 -9
  10. package/dist/codex-sessionstart-hook.js +145 -11
  11. package/dist/codex-stop-hook.js +222 -59
  12. package/dist/copilot-hook.js +142 -9
  13. package/dist/copilot-sessionstart-hook.js +145 -11
  14. package/dist/copilot-stop-hook.js +222 -59
  15. package/dist/cursor-hook.js +142 -9
  16. package/dist/cursor-sessionstart-hook.js +145 -11
  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 +145 -11
  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 +145 -11
  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 +154 -62
  30. package/dist/grok-hook.js +142 -9
  31. package/dist/grok-sessionstart-hook.js +145 -11
  32. package/dist/grok-stop-hook.js +222 -59
  33. package/dist/hindsight-seed.js +42 -4
  34. package/dist/index.js +149 -61
  35. package/dist/installer.js +155 -13
  36. package/dist/kilo.js +149 -61
  37. package/dist/mcp-server.js +474 -133
  38. package/dist/opencode2.js +149 -61
  39. package/dist/pi.js +149 -61
  40. package/dist/prime-agent.js +149 -61
  41. package/dist/qwen-hook.js +142 -9
  42. package/dist/qwen-sessionstart-hook.js +145 -11
  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
@@ -302,9 +302,13 @@ function lookupDirectories(config, directory, sessionRoot = "") {
302
302
  }
303
303
  return directories;
304
304
  }
305
- function deriveBankId(config, directory, harness = "coding", sessionRoot) {
305
+ function mappedBank(config, directory, sessionRoot) {
306
306
  const pathMap = config.mapPathToBank;
307
- const mapped = directory && pathMap ? lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
307
+ if (!directory || !pathMap) return void 0;
308
+ return lookupDirectories(config, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0);
309
+ }
310
+ function deriveBankId(config, directory, harness = "coding", sessionRoot) {
311
+ const mapped = mappedBank(config, directory, sessionRoot);
308
312
  if (mapped) return mapped;
309
313
  const dynamic = config.dynamicBankId ?? !config.bankId;
310
314
  if (!dynamic) return config.bankId || DEFAULT_BANK_NAME;
@@ -331,6 +335,39 @@ function deriveBankIdOrSkip(config, directory, harness = "coding", sessionRoot)
331
335
  }
332
336
  }
333
337
 
338
+ // src/core/missions.ts
339
+ import { createHash } from "crypto";
340
+ var CRON_FIELD_RANGES = [
341
+ [0, 59],
342
+ // minute
343
+ [0, 23],
344
+ // hour
345
+ [1, 31],
346
+ // day of month
347
+ [1, 12],
348
+ // month
349
+ [0, 6]
350
+ // day of week
351
+ ];
352
+ var HASHED_FIELD = /^H(?:\((\d+)-(\d+)\))?$/;
353
+ function isHashedCron(cron) {
354
+ return /(^|\s)H/.test(cron);
355
+ }
356
+ function parseHashedCron(cron) {
357
+ const fields = cron.trim().split(/\s+/);
358
+ if (fields.length !== CRON_FIELD_RANGES.length) return void 0;
359
+ for (const [i, field] of fields.entries()) {
360
+ if (!field.startsWith("H")) continue;
361
+ const m = HASHED_FIELD.exec(field);
362
+ if (!m) return void 0;
363
+ if (m[1] === void 0) continue;
364
+ const [lo, hi] = [Number(m[1]), Number(m[2])];
365
+ const [min, max] = CRON_FIELD_RANGES[i];
366
+ if (lo > hi || lo < min || hi > max) return void 0;
367
+ }
368
+ return fields;
369
+ }
370
+
334
371
  // src/core/util.ts
335
372
  import { accessSync, constants } from "fs";
336
373
  import { delimiter, join as join5 } from "path";
@@ -347,10 +384,11 @@ var DEFAULT_DAEMON_PROFILE = "coding-agent";
347
384
  function resolvePageTriggerType(raw) {
348
385
  if (raw.pageTriggerType === "manual") return "manual";
349
386
  if (raw.pageTriggerType === "cron") {
350
- if (raw.pageTriggerCron?.trim()) return "cron";
387
+ const cron = raw.pageTriggerCron?.trim();
388
+ if (cron && (!isHashedCron(cron) || parseHashedCron(cron))) return "cron";
351
389
  log.warn(
352
390
  "config",
353
- 'pageTriggerType "cron" needs pageTriggerCron (UTC 5-field, e.g. "0 3 * * *") \u2014 falling back to "auto-refresh"'
391
+ 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"'
354
392
  );
355
393
  }
356
394
  return "auto-refresh";
package/dist/index.js CHANGED
@@ -332,9 +332,13 @@ function isOptedIn(config3, directory) {
332
332
  const pathMap = config3.mapPathToBank;
333
333
  return Boolean(pathMap && directories.some((candidate) => mapLookup(pathMap, candidate)));
334
334
  }
335
- function deriveBankId(config3, directory, harness = "coding", sessionRoot) {
335
+ function mappedBank(config3, directory, sessionRoot) {
336
336
  const pathMap = config3.mapPathToBank;
337
- const mapped = directory && pathMap ? lookupDirectories(config3, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0) : void 0;
337
+ if (!directory || !pathMap) return void 0;
338
+ return lookupDirectories(config3, directory, sessionRoot).map((candidate) => mapLookup(pathMap, candidate)).find((bank) => bank !== void 0);
339
+ }
340
+ function deriveBankId(config3, directory, harness = "coding", sessionRoot) {
341
+ const mapped = mappedBank(config3, directory, sessionRoot);
338
342
  if (mapped) return mapped;
339
343
  const dynamic = config3.dynamicBankId ?? !config3.bankId;
340
344
  if (!dynamic) return config3.bankId || DEFAULT_BANK_NAME;
@@ -362,6 +366,7 @@ function deriveBankIdOrSkip(config3, 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";
@@ -1534,8 +1592,7 @@ function stampCheck(file3, now, latest) {
1534
1592
  async function latestVersion(fetchImpl) {
1535
1593
  try {
1536
1594
  const r = await fetchImpl(`https://registry.npmjs.org/${PACKAGE_NAME}/latest`, {
1537
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
1538
- headers: { accept: "application/vnd.npm.install-v1+json" }
1595
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
1539
1596
  });
1540
1597
  if (!r.ok) return "";
1541
1598
  const body = await r.json();
@@ -16760,15 +16817,24 @@ function buildKnowledgeTools(client, bankId, opts = {}) {
16760
16817
  }
16761
16818
 
16762
16819
  // src/core/retain-cursor.ts
16763
- import { createHash } from "crypto";
16820
+ import { createHash as createHash2 } from "crypto";
16821
+ var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
16822
+ var PENDING_MAX_BYTES = 256 * 1024;
16823
+ function pendingReplayable(cursor, now) {
16824
+ const pending = cursor.pending ?? [];
16825
+ if (!pending.length) return true;
16826
+ if (pending.some((p) => now - p.at > PENDING_MAX_AGE_MS)) return false;
16827
+ return pending.reduce((n, p) => n + p.content.length, 0) <= PENDING_MAX_BYTES;
16828
+ }
16764
16829
  function fingerprintTurns(turns, count) {
16765
- const h = createHash("sha1").update(String(count));
16830
+ const h = createHash2("sha1").update(String(count));
16766
16831
  for (let i = 0; i < count; i++) h.update("\n" + JSON.stringify(turns[i]));
16767
16832
  return h.digest("hex");
16768
16833
  }
16769
16834
  function planRetain(turns, cursor, opts) {
16770
16835
  if (!turns.length) return { mode: "skip" };
16771
16836
  if (!opts.appendSupported || !cursor || cursor.dirty) return { mode: "replace" };
16837
+ if (!pendingReplayable(cursor, opts.now ?? Date.now())) return { mode: "replace" };
16772
16838
  if (cursor.bank !== opts.bank) return { mode: "replace" };
16773
16839
  if (cursor.turns > turns.length) return { mode: "replace" };
16774
16840
  if (fingerprintTurns(turns, cursor.turns) !== cursor.fingerprint) return { mode: "replace" };
@@ -16784,13 +16850,13 @@ function memoryCursorStore() {
16784
16850
  }
16785
16851
 
16786
16852
  // src/core/uuid.ts
16787
- import { createHash as createHash2 } from "crypto";
16853
+ import { createHash as createHash3 } from "crypto";
16788
16854
  var HINDSIGHT_NAMESPACE = "e75686a4-e923-4326-a0d1-358f1c6c3eb4";
16789
16855
  function uuidV5(name, namespace = HINDSIGHT_NAMESPACE) {
16790
16856
  const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
16791
16857
  if (ns.length !== 16) throw new Error(`invalid UUID namespace: ${namespace}`);
16792
16858
  const bytes = Buffer.from(
16793
- createHash2("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
16859
+ createHash3("sha1").update(ns).update(Buffer.from(name, "utf8")).digest().subarray(0, 16)
16794
16860
  );
16795
16861
  bytes[6] = bytes[6] & 15 | 80;
16796
16862
  bytes[8] = bytes[8] & 63 | 128;
@@ -16867,61 +16933,83 @@ async function retainLiveSession(client, sessionId, turns, startTs, harness, opt
16867
16933
  );
16868
16934
  }
16869
16935
  async function writeSession(client, sessionId, turns, startTs, harness, stamp, cursors, retryUntil = Date.now() + DEFAULT_RETRY_WINDOW_MS) {
16936
+ if (!turns.length) return;
16870
16937
  const refId = `conversation:${sessionId}`;
16871
16938
  const appendSupported = Boolean(cursors) && await supportsAppend(client);
16872
- const plan = planRetain(turns, cursors?.read(sessionId), { appendSupported, bank: client.bank });
16873
- if (plan.mode === "skip") return;
16874
- const content = plan.mode === "append" ? turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n") : renderSessionJsonl(refId, turns, startTs);
16939
+ const cursor = cursors?.read(sessionId);
16940
+ const plan = planRetain(turns, cursor, { appendSupported, bank: client.bank });
16941
+ const outbox = plan.mode === "replace" ? [] : cursor?.pending ?? [];
16942
+ if (plan.mode === "skip" && !outbox.length) return;
16943
+ const opId = (mode, content) => uuidV5(`${client.bank}
16944
+ ${refId}
16945
+ ${mode}
16946
+ ${content}`);
16947
+ const submit = (content, operationId, append) => client.retain(
16948
+ content,
16949
+ "coding agent session",
16950
+ refId,
16951
+ // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
16952
+ // the documents list filters and draws its agent logo from, so a template cannot displace them.
16953
+ [
16954
+ .../* @__PURE__ */ new Set([
16955
+ ...stamp?.tags ?? [],
16956
+ "source:chat",
16957
+ ...harness ? [`harness:${harness}`] : []
16958
+ ])
16959
+ ],
16960
+ "conversation",
16961
+ {
16962
+ timestamp: startTs,
16963
+ updateMode: append ? "append" : void 0,
16964
+ operationId,
16965
+ metadata: {
16966
+ ...stamp?.metadata,
16967
+ // configured first: the built-ins below win on any key collision
16968
+ source: "chat",
16969
+ session_id: sessionId,
16970
+ ref_id: refId,
16971
+ ...harness ? { harness } : {}
16972
+ }
16973
+ }
16974
+ );
16875
16975
  const next = {
16876
16976
  turns: turns.length,
16877
16977
  fingerprint: fingerprintTurns(turns, turns.length),
16878
16978
  bank: client.bank
16879
16979
  };
16880
- cursors?.write(sessionId, { ...next, dirty: true });
16881
- const claimed = { ...next, dirty: true };
16882
- await submitWithRetry(
16883
- () => client.retain(
16884
- content,
16885
- "coding agent session",
16886
- refId,
16887
- // Configured tags first, built-ins last and deduped: `source:chat` and `harness:<id>` are what
16888
- // the documents list filters and draws its agent logo from, so a template cannot displace them.
16889
- [
16890
- .../* @__PURE__ */ new Set([
16891
- ...stamp?.tags ?? [],
16892
- "source:chat",
16893
- ...harness ? [`harness:${harness}`] : []
16894
- ])
16895
- ],
16896
- "conversation",
16897
- {
16898
- timestamp: startTs,
16899
- updateMode: plan.mode === "append" ? "append" : void 0,
16900
- // Identity of THIS payload: a resubmission of the same bytes is collapsed server-side into
16901
- // the original operation instead of extracting (or appending) twice.
16902
- operationId: uuidV5(`${client.bank}
16903
- ${refId}
16904
- ${plan.mode}
16905
- ${content}`),
16906
- metadata: {
16907
- ...stamp?.metadata,
16908
- // configured first: the built-ins below win on any key collision
16909
- source: "chat",
16910
- session_id: sessionId,
16911
- ref_id: refId,
16912
- ...harness ? { harness } : {}
16913
- }
16914
- }
16915
- ),
16916
- // Still ours to retry only while the cursor holds the claim we wrote above.
16917
- () => {
16918
- if (!cursors) return true;
16919
- const now = cursors.read(sessionId);
16920
- return now?.turns === claimed.turns && now?.fingerprint === claimed.fingerprint;
16921
- },
16922
- retryUntil
16923
- );
16924
- cursors?.write(sessionId, next);
16980
+ const stillOurs = () => {
16981
+ if (!cursors) return true;
16982
+ const now = cursors.read(sessionId);
16983
+ return now?.turns === next.turns && now?.fingerprint === next.fingerprint;
16984
+ };
16985
+ if (plan.mode === "replace") {
16986
+ const content = renderSessionJsonl(refId, turns, startTs);
16987
+ cursors?.write(sessionId, { ...next, dirty: true });
16988
+ await submitWithRetry(
16989
+ () => submit(content, opId("replace", content), false),
16990
+ stillOurs,
16991
+ retryUntil
16992
+ );
16993
+ cursors?.write(sessionId, next);
16994
+ return;
16995
+ }
16996
+ const queue = [...outbox];
16997
+ if (plan.mode === "append") {
16998
+ const content = turns.slice(plan.fromTurn).map((t) => JSON.stringify(t)).join("\n");
16999
+ queue.push({ content, operationId: opId("append", content), at: Date.now() });
17000
+ }
17001
+ cursors?.write(sessionId, { ...next, pending: queue });
17002
+ for (let i = 0; i < queue.length; i++) {
17003
+ if (i > 0 && Date.now() + REQUEST_BUDGET_MS > retryUntil) return;
17004
+ const entry = queue[i];
17005
+ await submitWithRetry(
17006
+ () => submit(entry.content, entry.operationId, true),
17007
+ stillOurs,
17008
+ retryUntil
17009
+ );
17010
+ const remaining = queue.slice(i + 1);
17011
+ cursors?.write(sessionId, remaining.length ? { ...next, pending: remaining } : next);
17012
+ }
16925
17013
  }
16926
17014
 
16927
17015
  // src/core/retain-stamp.ts
package/dist/installer.js CHANGED
@@ -1417,6 +1417,9 @@ import { spawn as realSpawn } from "child_process";
1417
1417
  import { dirname as dirname4, join as join4 } from "path";
1418
1418
  import { fileURLToPath } from "url";
1419
1419
 
1420
+ // src/core/missions.ts
1421
+ import { createHash } from "crypto";
1422
+
1420
1423
  // src/core/util.ts
1421
1424
  import { accessSync, constants } from "fs";
1422
1425
  import { delimiter, join as join5 } from "path";
@@ -1452,10 +1455,12 @@ import { dirname as dirname5, join as join7 } from "path";
1452
1455
  import { readFileSync as readFileSync5 } from "fs";
1453
1456
 
1454
1457
  // src/core/retain-cursor.ts
1455
- import { createHash } from "crypto";
1458
+ import { createHash as createHash2 } from "crypto";
1459
+ var PENDING_MAX_AGE_MS = 12 * 60 * 60 * 1e3;
1460
+ var PENDING_MAX_BYTES = 256 * 1024;
1456
1461
 
1457
1462
  // src/core/uuid.ts
1458
- import { createHash as createHash2 } from "crypto";
1463
+ import { createHash as createHash3 } from "crypto";
1459
1464
 
1460
1465
  // src/core/daemon.ts
1461
1466
  import { execFileSync, spawn as realSpawn2 } from "child_process";
@@ -1725,6 +1730,8 @@ var SKILL_DIRS = {
1725
1730
  "cline-cli": [".cline", "data", "settings", "skills"],
1726
1731
  "qwen-code": [".qwen", "skills"],
1727
1732
  // Qwen's user-level skills root (Storage.getUserSkillsDirs)
1733
+ "factory-droid": [".factory", "skills"],
1734
+ // Droid's user-level skills root
1728
1735
  // The pi family reads the shared ~/.agents/skills too, but writes its OWN root: skill removal is
1729
1736
  // by fixed directory name, so installing to the shared one would make `uninstall pi` take Codex's
1730
1737
  // and dsh's copy with it.
@@ -2179,6 +2186,50 @@ function collectQwenTurns(path, turns) {
2179
2186
  }
2180
2187
  }
2181
2188
 
2189
+ // src/core/transcript-droid.ts
2190
+ function renderContent(content, role) {
2191
+ if (!Array.isArray(content)) return [];
2192
+ const texts = [];
2193
+ const actions = [];
2194
+ for (const block of content) {
2195
+ if (!block || typeof block !== "object") continue;
2196
+ const b = block;
2197
+ if (b.type === "text" && typeof b.text === "string") {
2198
+ const text = stripInjectedMemory(b.text).trim();
2199
+ if (text) texts.push(text);
2200
+ } else if (b.type === "tool_use" && typeof b.name === "string") {
2201
+ actions.push({ role: "action", content: actionLine(b.name, b.input) });
2202
+ }
2203
+ }
2204
+ const out = [];
2205
+ const joined = texts.join("\n").trim();
2206
+ if (joined) out.push({ role, content: joined });
2207
+ out.push(...actions);
2208
+ return out;
2209
+ }
2210
+ function readDroidTranscript(path) {
2211
+ const turns = [];
2212
+ for (const rawLine of readJsonlTail(path, { scope: "factory-droid" }).lines) {
2213
+ if (!rawLine.trim()) continue;
2214
+ let parsed;
2215
+ try {
2216
+ parsed = JSON.parse(rawLine);
2217
+ } catch {
2218
+ continue;
2219
+ }
2220
+ if (!parsed || typeof parsed !== "object") continue;
2221
+ const line = parsed;
2222
+ if (line.type !== "message" || !line.message || typeof line.message !== "object") continue;
2223
+ const message = line.message;
2224
+ const role = message.role;
2225
+ if (role !== "user" && role !== "assistant") continue;
2226
+ if (message.visibility === "user_only" || message.visibility === "llm_only") continue;
2227
+ const stamp = typeof line.timestamp === "string" && line.timestamp ? { timestamp: line.timestamp } : {};
2228
+ turns.push(...renderContent(message.content, role).map((turn) => ({ ...turn, ...stamp })));
2229
+ }
2230
+ return turns;
2231
+ }
2232
+
2182
2233
  // src/harness/hook-lifecycle.ts
2183
2234
  var cursorCwd = (ev) => ev.cwd ?? ev.workspace_root ?? (Array.isArray(ev.workspace_roots) ? ev.workspace_roots[0] : void 0);
2184
2235
  var claudePrompt = {
@@ -2206,6 +2257,10 @@ var dcodePrompt = {
2206
2257
  ...claudePrompt,
2207
2258
  harness: "dcode"
2208
2259
  };
2260
+ var droidPrompt = {
2261
+ ...claudePrompt,
2262
+ harness: "factory-droid"
2263
+ };
2209
2264
  var qwenPrompt = {
2210
2265
  ...claudePrompt,
2211
2266
  harness: "qwen-code",
@@ -2532,6 +2587,31 @@ var HOOK_HARNESSES = {
2532
2587
  }),
2533
2588
  readTranscript: readQwenTranscript
2534
2589
  }
2590
+ },
2591
+ "factory-droid": {
2592
+ configStyle: "nested",
2593
+ install: {
2594
+ sessionStart: { event: "SessionStart", entry: "droid-sessionstart-hook.js", timeout: 30 },
2595
+ prompt: { event: "UserPromptSubmit", entry: "droid-hook.js", timeout: 30 },
2596
+ stop: { event: "Stop", entry: "droid-stop-hook.js", timeout: 60 }
2597
+ },
2598
+ // Droid emits Notification(idle_prompt), not Stop, after user cancellation. Reusing the
2599
+ // idempotent retain entry point captures that final partial turn; its event gate ignores every
2600
+ // other notification type before config or daemon work begins.
2601
+ additionalHooks: [{ event: "Notification", entry: "droid-stop-hook.js", timeout: 60 }],
2602
+ sessionStart: standardSessionStart("factory-droid"),
2603
+ prompt: droidPrompt,
2604
+ retain: {
2605
+ hostTimeoutSec: 60,
2606
+ harness: "factory-droid",
2607
+ accept: (ev) => ev.hook_event_name === "Stop" || ev.hook_event_name === "Notification" && ev.notification_type === "idle_prompt",
2608
+ parse: (ev) => ({
2609
+ sessionId: ev.session_id,
2610
+ transcriptPath: ev.transcript_path,
2611
+ cwd: ev.cwd
2612
+ }),
2613
+ readTranscript: readDroidTranscript
2614
+ }
2535
2615
  }
2536
2616
  };
2537
2617
 
@@ -2546,7 +2626,7 @@ import {
2546
2626
  readSync as readSync2,
2547
2627
  statSync as statSync2
2548
2628
  } from "fs";
2549
- import { createHash as createHash3 } from "crypto";
2629
+ import { createHash as createHash4 } from "crypto";
2550
2630
  import { homedir as homedir8 } from "os";
2551
2631
  import { join as join14 } from "path";
2552
2632
  import * as zlib2 from "zlib";
@@ -2802,7 +2882,7 @@ function codexHistory(repoDir, home) {
2802
2882
  }
2803
2883
  var DCODE_THREADS_SCHEMA_VERSION = 1;
2804
2884
  function dcodeTranscriptPath(root, threadId) {
2805
- const digest = createHash3("sha256").update(threadId, "utf8").digest("hex");
2885
+ const digest = createHash4("sha256").update(threadId, "utf8").digest("hex");
2806
2886
  const suffix = `--${digest}.jsonl`;
2807
2887
  try {
2808
2888
  const match = readdirSync2(root).find((entry) => entry.endsWith(suffix));
@@ -3291,10 +3371,19 @@ var mcpServerEntry = (dist, harness) => ({
3291
3371
  args: [join16(dist, "mcp-server.js")],
3292
3372
  env: { HINDSIGHT_MCP_HARNESS: harness }
3293
3373
  });
3374
+ function isOurMcpEntry(entry) {
3375
+ if (!entry || typeof entry !== "object") return false;
3376
+ const candidate = entry;
3377
+ if (candidate.command !== "node" || !Array.isArray(candidate.args)) return false;
3378
+ const script = candidate.args[0];
3379
+ if (typeof script !== "string") return false;
3380
+ const parts = script.replaceAll("\\", "/").split("/").filter(Boolean);
3381
+ return parts.at(-1) === "mcp-server.js" && parts.at(-2) === "dist" && (parts.at(-3) === "coding-agents" || parts.at(-3) === "hindsight-coding-agents");
3382
+ }
3294
3383
  function mergeHarnessHooks(hooks, harness, dist) {
3295
3384
  const spec = HOOK_HARNESSES[harness];
3296
3385
  const installedEvents = /* @__PURE__ */ new Set();
3297
- for (const hook of Object.values(spec.install)) {
3386
+ for (const hook of [...Object.values(spec.install), ...spec.additionalHooks ?? []]) {
3298
3387
  if (installedEvents.has(hook.event)) continue;
3299
3388
  installedEvents.add(hook.event);
3300
3389
  const entry = spec.configStyle === "nested" ? cmdHook(dist, hook.entry, hook.timeout) : {
@@ -3306,7 +3395,8 @@ function mergeHarnessHooks(hooks, harness, dist) {
3306
3395
  }
3307
3396
  function stripHarnessHooks(hooks, harness) {
3308
3397
  const strippedEvents = /* @__PURE__ */ new Set();
3309
- for (const hook of Object.values(HOOK_HARNESSES[harness].install)) {
3398
+ const spec = HOOK_HARNESSES[harness];
3399
+ for (const hook of [...Object.values(spec.install), ...spec.additionalHooks ?? []]) {
3310
3400
  if (strippedEvents.has(hook.event)) continue;
3311
3401
  strippedEvents.add(hook.event);
3312
3402
  setOrDelete(hooks, hook.event, stripOurs(hooks[hook.event]));
@@ -4300,6 +4390,57 @@ function defaultQwenMcp(args) {
4300
4390
  return false;
4301
4391
  }
4302
4392
  }
4393
+ var factoryDroid = {
4394
+ name: "factory-droid",
4395
+ detect: (c) => onPath2("droid") || existsSync10(join16(c.home, ".factory")),
4396
+ preflight(c) {
4397
+ const mcpPath = join16(c.home, ".factory", "mcp.json");
4398
+ const existing = readJson(mcpPath).mcpServers?.hindsight;
4399
+ if (existing && !isOurMcpEntry(existing)) {
4400
+ return `${mcpPath} already contains a user-managed MCP server named "hindsight". Rename or remove that entry, then re-run install.`;
4401
+ }
4402
+ },
4403
+ install(c) {
4404
+ const hooksPath = join16(c.home, ".factory", "hooks.json");
4405
+ const hooks = readJson(hooksPath);
4406
+ if (!existsSync10(hooksPath)) {
4407
+ const fallback = readJson(join16(c.home, ".factory", "settings.json")).hooks;
4408
+ if (fallback && typeof fallback === "object" && !Array.isArray(fallback)) {
4409
+ Object.assign(hooks, fallback);
4410
+ }
4411
+ }
4412
+ mergeHarnessHooks(hooks, "factory-droid", c.dist);
4413
+ writeJson(hooksPath, hooks);
4414
+ c.log?.(`factory-droid: hooks merged into ${hooksPath}`);
4415
+ installSkill(c, "factory-droid");
4416
+ const mcpPath = join16(c.home, ".factory", "mcp.json");
4417
+ const mcp = readJson(mcpPath);
4418
+ mcp.mcpServers = mcp.mcpServers ?? {};
4419
+ mcp.mcpServers.hindsight = mcpServerEntry(c.dist, "factory-droid");
4420
+ writeJson(mcpPath, mcp);
4421
+ c.log?.(`factory-droid: MCP server registered in ${mcpPath}`);
4422
+ },
4423
+ uninstall(c) {
4424
+ const hooksPath = join16(c.home, ".factory", "hooks.json");
4425
+ if (existsSync10(hooksPath)) {
4426
+ const hooks = readJson(hooksPath);
4427
+ stripHarnessHooks(hooks, "factory-droid");
4428
+ if (Object.keys(hooks).length) writeJson(hooksPath, hooks);
4429
+ else rmSync2(hooksPath);
4430
+ }
4431
+ const mcpPath = join16(c.home, ".factory", "mcp.json");
4432
+ if (existsSync10(mcpPath)) {
4433
+ const mcp = readJson(mcpPath);
4434
+ if (isOurMcpEntry(mcp.mcpServers?.hindsight)) {
4435
+ delete mcp.mcpServers.hindsight;
4436
+ if (Object.keys(mcp.mcpServers).length) writeJson(mcpPath, mcp);
4437
+ else rmSync2(mcpPath);
4438
+ }
4439
+ }
4440
+ uninstallSkill(c, "factory-droid");
4441
+ c.log?.("factory-droid: hooks + MCP registration + skill removed");
4442
+ }
4443
+ };
4303
4444
  var INSTALLERS = [
4304
4445
  opencode,
4305
4446
  opencode2,
@@ -4316,7 +4457,8 @@ var INSTALLERS = [
4316
4457
  qwen,
4317
4458
  cline,
4318
4459
  dcode,
4319
- dsh
4460
+ dsh,
4461
+ factoryDroid
4320
4462
  ];
4321
4463
  var HARNESS_ALIASES = { agy: "antigravity-cli" };
4322
4464
  function importConversations(harness, ctx) {
@@ -4405,12 +4547,6 @@ harnesses: ${INSTALLERS.map((i) => i.name).join(", ")} (agy aliases antigravity-
4405
4547
  );
4406
4548
  return 1;
4407
4549
  }
4408
- if (command === "install" && !configureServer(
4409
- ctx,
4410
- rawArgs,
4411
- targets.map((t) => t.name)
4412
- ))
4413
- return 1;
4414
4550
  const blocked = /* @__PURE__ */ new Set();
4415
4551
  if (command === "install") {
4416
4552
  for (const t of targets) {
@@ -4422,6 +4558,12 @@ harnesses: ${INSTALLERS.map((i) => i.name).join(", ")} (agy aliases antigravity-
4422
4558
  }
4423
4559
  }
4424
4560
  const runnable = targets.filter((t) => !blocked.has(t.name));
4561
+ if (command === "install" && runnable.length > 0 && !configureServer(
4562
+ ctx,
4563
+ rawArgs,
4564
+ runnable.map((t) => t.name)
4565
+ ))
4566
+ return 1;
4425
4567
  const failed = [];
4426
4568
  for (const t of runnable) {
4427
4569
  if (t[command](ctx) === false) failed.push(t.name);