@vectorize-io/hindsight-coding-agents 0.1.1 → 0.2.0

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.
@@ -7,9 +7,25 @@ import { existsSync, readFileSync as readFileSync3 } from "fs";
7
7
  import { execFileSync } from "child_process";
8
8
  import { homedir } from "os";
9
9
  import { basename, dirname, join, normalize, sep } from "path";
10
+
11
+ // src/core/template.ts
12
+ var PLACEHOLDER = /\{([a-zA-Z_]+)\}/g;
13
+ function applyTemplate(template, resolvers, what) {
14
+ return template.replace(PLACEHOLDER, (_, name) => {
15
+ const resolve2 = resolvers[name];
16
+ if (!resolve2) {
17
+ console.error(
18
+ `hindsight: unknown ${what} placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
19
+ );
20
+ return "unknown";
21
+ }
22
+ return resolve2();
23
+ });
24
+ }
25
+
26
+ // src/core/bank.ts
10
27
  var DEFAULT_BANK_NAME = "coding";
11
28
  var DEFAULT_TEMPLATE = "coding-agent::{gitProject}";
12
- var PLACEHOLDER = /\{([a-zA-Z]+)\}/g;
13
29
  function getProjectRootFromGit(directory) {
14
30
  if (!directory) return null;
15
31
  try {
@@ -55,16 +71,7 @@ function deriveBankId(config, directory, harness = "coding") {
55
71
  channel: () => process.env.HINDSIGHT_CHANNEL_ID || "default",
56
72
  user: () => process.env.HINDSIGHT_USER_ID || "anonymous"
57
73
  };
58
- return (config.bankIdTemplate || DEFAULT_TEMPLATE).replace(PLACEHOLDER, (_, name) => {
59
- const r = resolvers[name];
60
- if (!r) {
61
- console.error(
62
- `hindsight: unknown bankIdTemplate placeholder "{${name}}" \u2014 valid: ` + Object.keys(resolvers).sort().map((k) => `{${k}}`).join(", ")
63
- );
64
- return "unknown";
65
- }
66
- return r();
67
- });
74
+ return applyTemplate(config.bankIdTemplate || DEFAULT_TEMPLATE, resolvers, "bankIdTemplate");
68
75
  }
69
76
 
70
77
  // src/core/config.ts
@@ -144,6 +151,12 @@ function resolveConfig(raw = {}) {
144
151
  surveyBudgetUsd: raw.surveyBudgetUsd || 2,
145
152
  surveyRefreshCommits: raw.surveyRefreshCommits ?? 20,
146
153
  gitIngest: ["message", "full", "none"].includes(raw.gitIngest) ? raw.gitIngest : "message",
154
+ // Hostile input is a config typo, not an attack: keep only string entries so a stray number or
155
+ // nested object cannot reach the API as a tag and fail the whole retain.
156
+ retainTags: Array.isArray(raw.retainTags) ? raw.retainTags.filter((t) => typeof t === "string" && t.trim() !== "") : [],
157
+ retainMetadata: raw.retainMetadata && typeof raw.retainMetadata === "object" ? Object.fromEntries(
158
+ Object.entries(raw.retainMetadata).filter(([, v]) => typeof v === "string")
159
+ ) : {},
147
160
  banks: raw.banks && typeof raw.banks === "object" ? raw.banks : {},
148
161
  logLevel: ["debug", "info", "warn", "error"].includes(raw.logLevel) ? raw.logLevel : "info"
149
162
  };
@@ -197,7 +210,10 @@ var ENV_KEYS = {
197
210
  surveyBudgetUsd: "HINDSIGHT_SURVEY_BUDGET_USD",
198
211
  surveyRefreshCommits: "HINDSIGHT_SURVEY_REFRESH_COMMITS",
199
212
  logLevel: "HINDSIGHT_LOG_LEVEL",
200
- gitIngest: "HINDSIGHT_GIT_INGEST"
213
+ gitIngest: "HINDSIGHT_GIT_INGEST",
214
+ // Comma-separated, e.g. HINDSIGHT_RETAIN_TAGS="project:{gitProject},env:work". A LIST rather than
215
+ // a map, so it flattens cleanly; its sibling retainMetadata stays file-only for the reason above.
216
+ retainTags: "HINDSIGHT_RETAIN_TAGS"
201
217
  };
202
218
  var ENV_BOOLEANS = /* @__PURE__ */ new Set([
203
219
  "dynamicBankId",
@@ -208,6 +224,7 @@ var ENV_BOOLEANS = /* @__PURE__ */ new Set([
208
224
  "autoSeed",
209
225
  "codebaseSurvey"
210
226
  ]);
227
+ var ENV_LISTS = /* @__PURE__ */ new Set(["retainTags"]);
211
228
  var ENV_NUMBERS = /* @__PURE__ */ new Set([
212
229
  "apiPort",
213
230
  "daemonIdleTimeout",
@@ -225,6 +242,9 @@ function readEnvConfig(env = process.env) {
225
242
  if (value === void 0 || value.trim() === "") continue;
226
243
  if (ENV_BOOLEANS.has(key)) {
227
244
  out[key] = ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
245
+ } else if (ENV_LISTS.has(key)) {
246
+ const items = value.split(",").map((v) => v.trim()).filter(Boolean);
247
+ if (items.length) out[key] = items;
228
248
  } else if (ENV_NUMBERS.has(key)) {
229
249
  const n = Number(value);
230
250
  if (Number.isFinite(n)) out[key] = n;
@@ -439,11 +459,32 @@ var CODING_BANK_TEMPLATE = {
439
459
  entities_allow_free_form: true
440
460
  }
441
461
  };
462
+ var CODING_BANK_STRUCTURE = {
463
+ version: "1",
464
+ bank: {
465
+ retain_strategies: RETAIN_STRATEGIES,
466
+ entity_labels: [KNOWLEDGE_LABELS]
467
+ }
468
+ };
442
469
 
443
470
  // src/core/util.ts
444
471
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
472
+ function semverGte(version, min) {
473
+ const parts = (v) => {
474
+ const m = v.trim().match(/^(\d+)\.(\d+)(?:\.(\d+))?/);
475
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3] ?? 0)] : void 0;
476
+ };
477
+ const a = version ? parts(version) : void 0;
478
+ const b = parts(min);
479
+ if (!a || !b) return false;
480
+ for (let i = 0; i < 3; i++) {
481
+ if (a[i] !== b[i]) return a[i] > b[i];
482
+ }
483
+ return true;
484
+ }
445
485
 
446
486
  // src/core/hindsight.ts
487
+ var MIN_IDEMPOTENT_RETAIN_VERSION = "0.8.6";
447
488
  var KnowledgePagesUnavailableError = class extends Error {
448
489
  code = "knowledge_pages_unavailable";
449
490
  constructor() {
@@ -452,6 +493,7 @@ var KnowledgePagesUnavailableError = class extends Error {
452
493
  }
453
494
  };
454
495
  var TERMINAL = /* @__PURE__ */ new Set(["completed", "failed", "cancelled", "error"]);
496
+ var MISSION_FIELDS = ["reflect_mission", "retain_mission", "observations_mission"];
455
497
  var HindsightClient = class {
456
498
  apiUrl;
457
499
  apiToken;
@@ -460,6 +502,8 @@ var HindsightClient = class {
460
502
  // async operation ids collected by retain(), for drain()
461
503
  /** Tri-state capability probe: unknown until the first page request, then cached. */
462
504
  knowledgePagesSupported;
505
+ /** Tri-state capability probe: unknown until the first append-mode retain, then cached. */
506
+ idempotentRetain;
463
507
  log;
464
508
  constructor(o) {
465
509
  this.apiUrl = o.apiUrl.replace(/\/$/, "");
@@ -488,7 +532,8 @@ var HindsightClient = class {
488
532
  throw new Error(`${method} ${url} -> ${r.status} ${await r.text()}`);
489
533
  return r;
490
534
  }
491
- /** Retain one memory. Async by default: enqueue extraction server-side and collect its op-id for drain(). */
535
+ /** Retain one memory. ALWAYS async: enqueue extraction server-side and collect its op-id for
536
+ * drain(). Nothing in this plugin can afford to block a coding agent's hook on extraction. */
492
537
  async retain(content, context, documentId, tags, strategy, opts = {}) {
493
538
  const item = {
494
539
  content,
@@ -499,14 +544,36 @@ var HindsightClient = class {
499
544
  };
500
545
  if (opts.timestamp) item.timestamp = opts.timestamp;
501
546
  if (opts.metadata) item.metadata = opts.metadata;
502
- const isAsync = opts.async !== false;
503
- const r = await this.req("POST", this.bankUrl("/memories"), { items: [item], async: isAsync });
504
- if (isAsync) {
505
- try {
506
- const j = await r.json();
507
- if (j.operation_id) this.opIds.push(j.operation_id);
508
- } catch {
509
- }
547
+ if (opts.updateMode) item.update_mode = opts.updateMode;
548
+ const body = { items: [item], async: true };
549
+ if (opts.operationId) body.operation_id = opts.operationId;
550
+ const r = await this.req("POST", this.bankUrl("/memories"), body);
551
+ try {
552
+ const j = await r.json();
553
+ if (j.operation_id) this.opIds.push(j.operation_id);
554
+ } catch {
555
+ }
556
+ }
557
+ /**
558
+ * Whether this server honours `operation_id` on an async retain, and can therefore be appended to
559
+ * safely (see MIN_IDEMPOTENT_RETAIN_VERSION). Probed once per client via GET /version; anything
560
+ * unreachable, unparseable or older answers "no", which costs efficiency, never correctness.
561
+ */
562
+ async supportsIdempotentRetain() {
563
+ if (this.idempotentRetain === void 0) {
564
+ this.idempotentRetain = await this.probeIdempotentRetain();
565
+ this.log(`server retain idempotency: ${this.idempotentRetain ? "supported" : "unavailable"}`);
566
+ }
567
+ return this.idempotentRetain;
568
+ }
569
+ async probeIdempotentRetain() {
570
+ try {
571
+ const r = await this.req("GET", `${this.apiUrl}/version`);
572
+ if (!r.ok) return false;
573
+ const j = await r.json();
574
+ return semverGte(j.api_version, MIN_IDEMPOTENT_RETAIN_VERSION);
575
+ } catch {
576
+ return false;
510
577
  }
511
578
  }
512
579
  /**
@@ -543,12 +610,39 @@ var HindsightClient = class {
543
610
  await this.req("DELETE", this.bankUrl());
544
611
  this.log(`[bank] reset ${this.bank}`);
545
612
  }
546
- await this.req("POST", this.bankUrl("/import"), CODING_BANK_TEMPLATE);
613
+ const seeded = opts.reset ? false : await this.hasBankMissions();
614
+ await this.req(
615
+ "POST",
616
+ this.bankUrl("/import"),
617
+ seeded ? CODING_BANK_STRUCTURE : CODING_BANK_TEMPLATE
618
+ );
547
619
  this.log(
548
- `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
620
+ seeded ? `[bank] structure applied to ${this.bank}: entity_labels {knowledge}, strategies {git, gitlog, conversation, document} \u2014 missions left as configured` : `[bank] template applied to ${this.bank}: missions, entity_labels {knowledge}, strategies {git, gitlog, conversation, document}`
549
621
  );
550
622
  await this.seedPages();
551
623
  }
624
+ /**
625
+ * Whether this bank already carries bank-level mission overrides — ours from an earlier seed, or
626
+ * the user's own edit. Either way they are not ours to overwrite.
627
+ *
628
+ * Reads the bank-scoped OVERRIDES, not the resolved config, so inherited global defaults don't
629
+ * read as "already set". A missing bank, or a deployment with the bank-config API switched off,
630
+ * answers false: there is nothing to preserve, and without that API a user cannot set per-bank
631
+ * missions in the first place.
632
+ */
633
+ async hasBankMissions() {
634
+ try {
635
+ const r = await this.req("GET", this.bankUrl("/config"));
636
+ if (!r.ok) return false;
637
+ const j = await r.json();
638
+ return MISSION_FIELDS.some((f) => {
639
+ const v = j.overrides?.[f];
640
+ return typeof v === "string" && v.trim() !== "";
641
+ });
642
+ } catch {
643
+ return false;
644
+ }
645
+ }
552
646
  /** Delete one document (cascades its memory units/links). Used by deepen's self-cleanup. */
553
647
  async deleteDocument(documentId) {
554
648
  await this.req("DELETE", this.bankUrl(`/documents/${encodeURIComponent(documentId)}`));
@@ -794,8 +888,7 @@ var HindsightClient = class {
794
888
  "initiative marker",
795
889
  markerId,
796
890
  ["knowledge:feature-work", `relatedPageId:${pageId}`],
797
- "document",
798
- { async: true }
891
+ "document"
799
892
  );
800
893
  return { page_id: pageId };
801
894
  }
@@ -884,7 +977,13 @@ function writeSessionCache(cacheFile, cache) {
884
977
  }
885
978
 
886
979
  // src/core/retain-hook.ts
887
- import { readFileSync as readFileSync5 } from "fs";
980
+ import { readFileSync as readFileSync4 } from "fs";
981
+
982
+ // src/core/retain-cursor.ts
983
+ import { createHash } from "crypto";
984
+
985
+ // src/core/uuid.ts
986
+ import { createHash as createHash2 } from "crypto";
888
987
 
889
988
  // src/core/daemon.ts
890
989
  import { execFileSync as execFileSync2, spawn as realSpawn2 } from "child_process";
@@ -1002,11 +1101,72 @@ function preflightDaemon(cfg, harness) {
1002
1101
  return true;
1003
1102
  }
1004
1103
 
1005
- // src/core/transcript.ts
1006
- import { readFileSync as readFileSync4 } from "fs";
1104
+ // src/core/retain-stamp.ts
1105
+ import { basename as basename2 } from "path";
1106
+
1107
+ // src/core/jsonl.ts
1108
+ import { closeSync, openSync, readSync, statSync } from "fs";
1109
+ import { StringDecoder } from "string_decoder";
1110
+ var CHUNK_BYTES = 64 * 1024;
1111
+ var MAX_TRANSCRIPT_BYTES = 32 * 1024 * 1024;
1112
+ function readJsonlTail(path, opts) {
1113
+ const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
1114
+ let size;
1115
+ try {
1116
+ size = statSync(path).size;
1117
+ } catch {
1118
+ return { lines: emptyLines(), skippedBytes: 0 };
1119
+ }
1120
+ const skippedBytes = size > maxBytes ? size - maxBytes : 0;
1121
+ if (skippedBytes > 0) {
1122
+ log.warn(opts.scope, "transcript too large \u2014 retaining the most recent portion only", {
1123
+ path,
1124
+ sizeBytes: size,
1125
+ skippedBytes
1126
+ });
1127
+ }
1128
+ return { lines: streamLines(path, skippedBytes), skippedBytes };
1129
+ }
1130
+ function* emptyLines() {
1131
+ }
1132
+ function* streamLines(path, start) {
1133
+ let fd;
1134
+ try {
1135
+ fd = openSync(path, "r");
1136
+ } catch {
1137
+ return;
1138
+ }
1139
+ try {
1140
+ const buffer = Buffer.allocUnsafe(CHUNK_BYTES);
1141
+ const decoder = new StringDecoder("utf8");
1142
+ let pending = "";
1143
+ let position = start > 0 ? start - 1 : 0;
1144
+ let dropPartial = start > 0;
1145
+ for (; ; ) {
1146
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, position);
1147
+ if (bytesRead <= 0) break;
1148
+ position += bytesRead;
1149
+ pending += decoder.write(buffer.subarray(0, bytesRead));
1150
+ let newline;
1151
+ while ((newline = pending.indexOf("\n")) !== -1) {
1152
+ const line = pending.slice(0, newline);
1153
+ pending = pending.slice(newline + 1);
1154
+ if (dropPartial) {
1155
+ dropPartial = false;
1156
+ continue;
1157
+ }
1158
+ yield line;
1159
+ }
1160
+ }
1161
+ pending += decoder.end();
1162
+ if (pending && !dropPartial) yield pending;
1163
+ } finally {
1164
+ closeSync(fd);
1165
+ }
1166
+ }
1007
1167
 
1008
1168
  // src/core/transcript-util.ts
1009
- var MEMORY_TAG_RE = /<(hook_prompt|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
1169
+ var MEMORY_TAG_RE = /<(hook_prompt|task-notification|system-reminder|hindsight_memory|hindsight_memories|hindsight_bank|relevant_memories|user_feedback|hindsight_knowledge|hindsight_knowledge_refresh)\b[\s\S]*?<\/\1>/g;
1010
1170
  function stripInjectedMemory(s) {
1011
1171
  return s.replace(MEMORY_TAG_RE, "");
1012
1172
  }
@@ -1041,7 +1201,7 @@ function actionLine(tool, input) {
1041
1201
  }
1042
1202
 
1043
1203
  // src/core/session-start.ts
1044
- import { readFileSync as readFileSync7 } from "fs";
1204
+ import { readFileSync as readFileSync6 } from "fs";
1045
1205
 
1046
1206
  // src/core/git.ts
1047
1207
  import { execFileSync as execFileSync3 } from "child_process";
@@ -1266,7 +1426,7 @@ function startCodebaseSurvey(repoDir, opts = {}) {
1266
1426
  var DEEPEN_DIFF_TARGET = 300;
1267
1427
 
1268
1428
  // src/core/skill-sync.ts
1269
- import { cpSync, existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
1429
+ import { cpSync, existsSync as existsSync3, readFileSync as readFileSync5 } from "fs";
1270
1430
  import { homedir as homedir4 } from "os";
1271
1431
  import { dirname as dirname7, join as join8 } from "path";
1272
1432
  import { fileURLToPath as fileURLToPath4 } from "url";
@@ -1290,7 +1450,7 @@ function syncCompanionSkill(harness, opts = {}) {
1290
1450
  const dst = join8(opts.home ?? homedir4(), ...parts, "hindsight-coding-agent");
1291
1451
  const dstMd = join8(dst, "SKILL.md");
1292
1452
  if (!existsSync3(dstMd)) return;
1293
- if (readFileSync6(srcMd, "utf8") !== readFileSync6(dstMd, "utf8")) {
1453
+ if (readFileSync5(srcMd, "utf8") !== readFileSync5(dstMd, "utf8")) {
1294
1454
  cpSync(src, dst, { recursive: true });
1295
1455
  }
1296
1456
  } catch {
@@ -1346,8 +1506,7 @@ async function buildSessionStartContext(args) {
1346
1506
  "hindsight codebase-survey baseline",
1347
1507
  `${SURVEY_BASELINE_PREFIX}${sha}`,
1348
1508
  [SURVEY_BASELINE_TAG],
1349
- "survey",
1350
- { async: true }
1509
+ "survey"
1351
1510
  )
1352
1511
  ).catch(() => {
1353
1512
  });
@@ -1444,7 +1603,7 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
1444
1603
  try {
1445
1604
  let ev = {};
1446
1605
  try {
1447
- ev = JSON.parse(readFileSync7(0, "utf8"));
1606
+ ev = JSON.parse(readFileSync6(0, "utf8"));
1448
1607
  } catch {
1449
1608
  return;
1450
1609
  }
@@ -1474,7 +1633,6 @@ async function runSessionStartHook(spec, makeClient = (o) => new HindsightClient
1474
1633
  }
1475
1634
 
1476
1635
  // src/core/transcript-codex.ts
1477
- import { readFileSync as readFileSync8 } from "fs";
1478
1636
  function isSyntheticUserText(text) {
1479
1637
  const s = text.trimStart();
1480
1638
  return s.startsWith("# AGENTS.md instructions for ") || s.startsWith("<environment_context>");
@@ -1483,14 +1641,8 @@ function messageText(payload) {
1483
1641
  return (payload.content || []).filter((c) => c && typeof c.text === "string").map((c) => c.text).join("\n");
1484
1642
  }
1485
1643
  function readCodexTranscript(path) {
1486
- let raw;
1487
- try {
1488
- raw = readFileSync8(path, "utf8");
1489
- } catch {
1490
- return [];
1491
- }
1492
1644
  const turns = [];
1493
- for (const rawLine of raw.split("\n")) {
1645
+ for (const rawLine of readJsonlTail(path, { scope: "codex" }).lines) {
1494
1646
  const trimmed = rawLine.trim();
1495
1647
  if (!trimmed) continue;
1496
1648
  let parsed;
@@ -1524,7 +1676,6 @@ function readCodexTranscript(path) {
1524
1676
  }
1525
1677
 
1526
1678
  // src/core/transcript-cursor.ts
1527
- import { readFileSync as readFileSync9 } from "fs";
1528
1679
  function withTimestamp(turn, timestamp) {
1529
1680
  return timestamp ? { ...turn, timestamp } : turn;
1530
1681
  }
@@ -1534,14 +1685,8 @@ function textFrom(content) {
1534
1685
  return content.filter((block) => block?.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n");
1535
1686
  }
1536
1687
  function readCursorTranscript(path) {
1537
- let raw;
1538
- try {
1539
- raw = readFileSync9(path, "utf8");
1540
- } catch {
1541
- return [];
1542
- }
1543
1688
  const turns = [];
1544
- for (const rawLine of raw.split("\n")) {
1689
+ for (const rawLine of readJsonlTail(path, { scope: "cursor-cli" }).lines) {
1545
1690
  let parsed;
1546
1691
  try {
1547
1692
  parsed = JSON.parse(rawLine);
@@ -1577,17 +1722,10 @@ function readCursorTranscript(path) {
1577
1722
  }
1578
1723
 
1579
1724
  // src/core/transcript-antigravity.ts
1580
- import { readFileSync as readFileSync10 } from "fs";
1581
1725
  function readAntigravityTranscript(path) {
1582
1726
  if (!path) return [];
1583
- let raw;
1584
- try {
1585
- raw = readFileSync10(path, "utf8");
1586
- } catch {
1587
- return [];
1588
- }
1589
1727
  const turns = [];
1590
- for (const line of raw.split("\n")) {
1728
+ for (const line of readJsonlTail(path, { scope: "antigravity-cli" }).lines) {
1591
1729
  try {
1592
1730
  const event = JSON.parse(line);
1593
1731
  const role = event.role ?? event.message?.role ?? event.type;
@@ -1608,16 +1746,9 @@ function readAntigravityTranscript(path) {
1608
1746
  }
1609
1747
 
1610
1748
  // src/core/transcript-copilot.ts
1611
- import { readFileSync as readFileSync11 } from "fs";
1612
1749
  function readCopilotTranscript(path) {
1613
- let raw;
1614
- try {
1615
- raw = readFileSync11(path, "utf8");
1616
- } catch {
1617
- return [];
1618
- }
1619
1750
  const turns = [];
1620
- for (const rawLine of raw.split("\n")) {
1751
+ for (const rawLine of readJsonlTail(path, { scope: "copilot-cli" }).lines) {
1621
1752
  try {
1622
1753
  const event = JSON.parse(rawLine);
1623
1754
  const role = event.type === "user.message" ? "user" : event.type === "assistant.message" ? "assistant" : void 0;
@@ -1631,7 +1762,7 @@ function readCopilotTranscript(path) {
1631
1762
  }
1632
1763
 
1633
1764
  // src/core/transcript-grok.ts
1634
- import { existsSync as existsSync4, readFileSync as readFileSync12, readdirSync } from "fs";
1765
+ import { existsSync as existsSync4, readFileSync as readFileSync7, readdirSync } from "fs";
1635
1766
  import { homedir as homedir5 } from "os";
1636
1767
  import { join as join9 } from "path";
1637
1768
  var CHAT_HISTORY = "chat_history.jsonl";
@@ -1642,7 +1773,7 @@ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME ||
1642
1773
  try {
1643
1774
  for (const candidate of readdirSync(sessionsDir)) {
1644
1775
  const directory = join9(sessionsDir, candidate);
1645
- if (readFileSync12(join9(directory, ".cwd"), "utf8").trim() === cwd) {
1776
+ if (readFileSync7(join9(directory, ".cwd"), "utf8").trim() === cwd) {
1646
1777
  return join9(directory, sessionId, CHAT_HISTORY);
1647
1778
  }
1648
1779
  }
@@ -1651,14 +1782,8 @@ function grokTranscriptPath(cwd, sessionId, grokHome = process.env.GROK_HOME ||
1651
1782
  return direct;
1652
1783
  }
1653
1784
  function readGrokTranscript(path) {
1654
- let raw;
1655
- try {
1656
- raw = readFileSync12(path, "utf8");
1657
- } catch {
1658
- return [];
1659
- }
1660
1785
  const turns = [];
1661
- for (const rawLine of raw.split("\n")) {
1786
+ for (const rawLine of readJsonlTail(path, { scope: "grok-build" }).lines) {
1662
1787
  try {
1663
1788
  const event = JSON.parse(rawLine);
1664
1789
  if (event.type !== "user" && event.type !== "assistant") continue;