litmus-cli 1.5.0-beta.11 → 1.5.0-beta.13

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 (69) hide show
  1. package/README.md +14 -2
  2. package/dist/commands/capture.d.ts +10 -0
  3. package/dist/commands/capture.d.ts.map +1 -0
  4. package/dist/commands/capture.js +83 -0
  5. package/dist/commands/capture.js.map +1 -0
  6. package/dist/commands/connect.d.ts +3 -1
  7. package/dist/commands/connect.d.ts.map +1 -1
  8. package/dist/commands/connect.js +12 -4
  9. package/dist/commands/connect.js.map +1 -1
  10. package/dist/lib/capture-conversation-catalog.d.ts +3 -0
  11. package/dist/lib/capture-conversation-catalog.d.ts.map +1 -0
  12. package/dist/lib/capture-conversation-catalog.js +56 -0
  13. package/dist/lib/capture-conversation-catalog.js.map +1 -0
  14. package/dist/lib/capture-conversations.d.ts +63 -0
  15. package/dist/lib/capture-conversations.d.ts.map +1 -0
  16. package/dist/lib/capture-conversations.js +114 -0
  17. package/dist/lib/capture-conversations.js.map +1 -0
  18. package/dist/lib/capture-network.d.ts +24 -0
  19. package/dist/lib/capture-network.d.ts.map +1 -0
  20. package/dist/lib/capture-network.js +84 -0
  21. package/dist/lib/capture-network.js.map +1 -0
  22. package/dist/lib/capture-selection-server.d.ts +19 -0
  23. package/dist/lib/capture-selection-server.d.ts.map +1 -0
  24. package/dist/lib/capture-selection-server.js +212 -0
  25. package/dist/lib/capture-selection-server.js.map +1 -0
  26. package/dist/lib/capture-startup-diagnostics.d.ts.map +1 -1
  27. package/dist/lib/capture-startup-diagnostics.js +3 -1
  28. package/dist/lib/capture-startup-diagnostics.js.map +1 -1
  29. package/dist/lib/cursor-session.d.ts +2 -0
  30. package/dist/lib/cursor-session.d.ts.map +1 -1
  31. package/dist/lib/cursor-session.js +30 -2
  32. package/dist/lib/cursor-session.js.map +1 -1
  33. package/dist/lib/detection.d.ts +2 -1
  34. package/dist/lib/detection.d.ts.map +1 -1
  35. package/dist/lib/detection.js +2 -1
  36. package/dist/lib/detection.js.map +1 -1
  37. package/dist/lib/hook-logger.cjs +339 -70
  38. package/dist/lib/hosted-capture.d.ts +4 -3
  39. package/dist/lib/hosted-capture.d.ts.map +1 -1
  40. package/dist/lib/hosted-capture.js +52 -25
  41. package/dist/lib/hosted-capture.js.map +1 -1
  42. package/dist/lib/hosted-transcripts.d.ts +8 -1
  43. package/dist/lib/hosted-transcripts.d.ts.map +1 -1
  44. package/dist/lib/hosted-transcripts.js +89 -21
  45. package/dist/lib/hosted-transcripts.js.map +1 -1
  46. package/dist/lib/hosted-watcher.js +28 -4
  47. package/dist/lib/hosted-watcher.js.map +1 -1
  48. package/dist/lib/platform.d.ts +5 -2
  49. package/dist/lib/platform.d.ts.map +1 -1
  50. package/dist/lib/platform.js +16 -8
  51. package/dist/lib/platform.js.map +1 -1
  52. package/dist/lib/practice-handoff.d.ts.map +1 -1
  53. package/dist/lib/practice-handoff.js +4 -3
  54. package/dist/lib/practice-handoff.js.map +1 -1
  55. package/dist/lib/selected-capture-control.d.ts +15 -0
  56. package/dist/lib/selected-capture-control.d.ts.map +1 -0
  57. package/dist/lib/selected-capture-control.js +86 -0
  58. package/dist/lib/selected-capture-control.js.map +1 -0
  59. package/dist/lib/selected-capture-lease.d.ts +13 -0
  60. package/dist/lib/selected-capture-lease.d.ts.map +1 -0
  61. package/dist/lib/selected-capture-lease.js +22 -0
  62. package/dist/lib/selected-capture-lease.js.map +1 -0
  63. package/dist/lib/windows-process-scan.d.ts +11 -0
  64. package/dist/lib/windows-process-scan.d.ts.map +1 -0
  65. package/dist/lib/windows-process-scan.js +96 -0
  66. package/dist/lib/windows-process-scan.js.map +1 -0
  67. package/dist/program.js +14 -0
  68. package/dist/program.js.map +1 -1
  69. package/package.json +1 -1
@@ -576,6 +576,99 @@ function sessionOverMarked(litmusDir) {
576
576
  return !current || current === marked
577
577
  }
578
578
 
579
+ // ENG-4121: apply the existing ENG-2108/3038 credential contract BEFORE the
580
+ // local capture outbox, drain and HTTP copies. This standalone file is copied
581
+ // into user hook directories, so it cannot import the frontend's TS module.
582
+ // The shared corpus and a direct pattern/key parity test pin this fourth copy.
583
+ // No anchors: prefixing a credential must not hide it. These patterns are
584
+ // defence in depth, not a guarantee of detecting every secret or arbitrary PII.
585
+ const CAPTURE_REDACTION = "[REDACTED]"
586
+ const CAPTURE_CREDENTIAL_PATTERNS = [
587
+ // Ours, and the most likely to appear: the workspace AI token, the grade and
588
+ // review session tokens, and the broker grant. Not covered before ENG-2108 —
589
+ // the old set caught `lwt_` only when it followed the word "Bearer", so
590
+ // `export OPENAI_API_KEY=lwt_...` at a shell reached the database intact.
591
+ // ENG-3038: `lrt_wt.` is the walkthrough terminal's token; the `.` used to stop the body.
592
+ ["litmus_session", String.raw`l(?:wt|gt|rt|sg)_(?:wt\.)?[A-Za-z0-9_-]{16,}`],
593
+ ["anthropic", String.raw`sk-ant-[A-Za-z0-9_-]{16,}`],
594
+ // ENG-2837: a segmented key's body carries `-` and `_`. Only the segmented form
595
+ // allows them; an unprefixed body that did would redact kebab-case after "task".
596
+ ["openai_segmented", String.raw`sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{24,}`],
597
+ ["openai", String.raw`sk-[A-Za-z0-9]{24,}`],
598
+ ["vendor_live_key", String.raw`(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{24,}`],
599
+ ["bearer", String.raw`Bearer\s+[A-Za-z0-9._~+/-]{16,}=*`],
600
+ ["jwt", String.raw`ey[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{6,}`],
601
+ ["github", String.raw`gh[pousr]_[A-Za-z0-9]{20,}`],
602
+ ["slack", String.raw`xox[baprs]-[A-Za-z0-9-]{10,}`],
603
+ ["aws_access_key_id", String.raw`(?:AKIA|ASIA)[0-9A-Z]{16}`],
604
+ ["google_api_key", String.raw`AIza[0-9A-Za-z_-]{35}`],
605
+ // URL userinfo. Only the PASSWORD goes: the scheme, user and host are what let
606
+ // a reviewer see which database was reached, and the Phase-3 fallback delivers
607
+ // DATABASE_URL candidate-visible by design.
608
+ ["url_userinfo", String.raw`(?<=:\/\/)(?<uu_user>[^\s:/@]+):(?<uu_pass>[^\s:/@]{3,})(?=@)`],
609
+ ]
610
+ const CAPTURE_CREDENTIAL_KEYS = new Set([
611
+ "authorization", "auth", "cookie", "cookies", "set-cookie",
612
+ "api_key", "apikey", "api-key", "x-api-key", "x-goog-api-key",
613
+ "access_token", "accesstoken", "refresh_token", "id_token",
614
+ "client_secret", "clientsecret", "private_key", "privatekey",
615
+ "password", "passwd", "secret", "token", "bearer",
616
+ "credential", "credentials",
617
+ "openai_api_key", "anthropic_api_key",
618
+ "aws_secret_access_key", "aws_access_key_id",
619
+ ])
620
+ const CAPTURE_SECRET_RE = new RegExp(CAPTURE_CREDENTIAL_PATTERNS.map(([, p]) => `(?:${p})`).join("|"), "gi")
621
+
622
+ function redactCaptureText(value, known = []) {
623
+ for (const secret of known) value = value.split(secret).join(CAPTURE_REDACTION)
624
+ CAPTURE_SECRET_RE.lastIndex = 0
625
+ return value.replace(CAPTURE_SECRET_RE, (match, ...args) => {
626
+ const groups = args[args.length - 1]
627
+ return groups?.uu_user !== undefined ? `${groups.uu_user}:${CAPTURE_REDACTION}` : CAPTURE_REDACTION
628
+ })
629
+ }
630
+
631
+ function scrubCaptureContent(value, known = []) {
632
+ if (typeof value === "string") return redactCaptureText(value, known)
633
+ if (!value || typeof value !== "object") return value
634
+ const out = Array.isArray(value) ? [] : {}
635
+ const seen = new Map([[value, out]]), pending = [[value, out]]
636
+ while (pending.length) {
637
+ const [source, target] = pending.pop()
638
+ for (const [key, child] of Object.entries(source)) {
639
+ let scrubbed = child
640
+ if (CAPTURE_CREDENTIAL_KEYS.has(key.trim().toLowerCase())) scrubbed = child === null ? null : CAPTURE_REDACTION
641
+ else if (typeof child === "string") scrubbed = redactCaptureText(child, known)
642
+ else if (child && typeof child === "object") {
643
+ scrubbed = seen.get(child)
644
+ if (!scrubbed) {
645
+ scrubbed = Array.isArray(child) ? [] : {}
646
+ seen.set(child, scrubbed); pending.push([child, scrubbed])
647
+ }
648
+ }
649
+ // Preserve even JSON keys such as __proto__ as data, never setters.
650
+ Object.defineProperty(target, key, { value: scrubbed, enumerable: true, writable: true, configurable: true })
651
+ }
652
+ }
653
+ return out
654
+ }
655
+
656
+ function captureKnownTokens(token) {
657
+ // Same minimum as knownValues: short configuration/test strings are not
658
+ // usable credentials and must not erase ordinary words in activity evidence.
659
+ return typeof token === "string" && token.trim().length >= 16 ? [token.trim()] : []
660
+ }
661
+
662
+ function sanitizeCaptureEvent(event, token) {
663
+ const known = captureKnownTokens(token)
664
+ // Event identity and the capture receipt authorize/group uploads. Only
665
+ // content is scrubbed here; never rewrite those protocol fields locally.
666
+ for (const key of ["prompt", "text", "tool_calls", "file_writes"]) {
667
+ if (key in event) event[key] = scrubCaptureContent(event[key], known)
668
+ }
669
+ return event
670
+ }
671
+
579
672
  /**
580
673
  * POST the event to /cli/activity and WAIT for it to complete, bounded.
581
674
  *
@@ -1003,31 +1096,24 @@ function isResponseEvent(data) {
1003
1096
  return RESPONSE_HOOK_EVENTS.has(data.hook_event_name)
1004
1097
  }
1005
1098
 
1006
- function readTranscriptRaw(transcriptPath, endOffset) {
1007
- const fileSize = fs.statSync(transcriptPath).size
1008
- const size = Number.isSafeInteger(endOffset) ? Math.min(fileSize, Math.max(0, endOffset)) : fileSize
1009
- if (size > MAX_TRANSCRIPT_BYTES) {
1010
- const fd = fs.openSync(transcriptPath, "r")
1011
- try {
1012
- const buf = Buffer.alloc(TRANSCRIPT_TAIL_BYTES)
1013
- const read = fs.readSync(fd, buf, 0, TRANSCRIPT_TAIL_BYTES, size - TRANSCRIPT_TAIL_BYTES)
1014
- const raw = buf.slice(0, read).toString("utf8")
1015
- // Drop the (likely partial) first line of the tail.
1016
- const firstNewline = raw.indexOf("\n")
1017
- return firstNewline === -1 ? "" : raw.slice(firstNewline + 1)
1018
- } finally {
1019
- fs.closeSync(fd)
1020
- }
1021
- }
1022
- if (Number.isSafeInteger(endOffset)) {
1023
- const fd = fs.openSync(transcriptPath, "r")
1024
- try {
1025
- const buf = Buffer.alloc(size)
1026
- const count = fs.readSync(fd, buf, 0, size, 0)
1027
- return buf.subarray(0, count).toString("utf8")
1028
- } finally { fs.closeSync(fd) }
1029
- }
1030
- return fs.readFileSync(transcriptPath, "utf8")
1099
+ function readTranscriptRaw(transcriptPath, endOffset, startOffset = 0, expectedIdentity) {
1100
+ if (!Number.isSafeInteger(startOffset) || startOffset < 0) throw new Error("Invalid transcript boundary")
1101
+ if (fs.lstatSync(transcriptPath).isSymbolicLink()) throw new Error("Transcript symlink refused")
1102
+ const fd = fs.openSync(transcriptPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0))
1103
+ try {
1104
+ const stat = fs.fstatSync(fd)
1105
+ if (!stat.isFile() || (expectedIdentity && `${stat.dev}:${stat.ino}` !== expectedIdentity)) throw new Error("Transcript changed")
1106
+ const end = Number.isSafeInteger(endOffset) ? Math.min(stat.size, Math.max(0, endOffset)) : stat.size
1107
+ if (end < startOffset) throw new Error("Transcript truncated")
1108
+ const tail = end - startOffset > MAX_TRANSCRIPT_BYTES
1109
+ const start = tail ? Math.max(startOffset, end - TRANSCRIPT_TAIL_BYTES) : startOffset
1110
+ const buffer = Buffer.alloc(end - start)
1111
+ const count = fs.readSync(fd, buffer, 0, buffer.length, start)
1112
+ let raw = buffer.subarray(0, count).toString("utf8")
1113
+ // A bounded tail can start in the middle of a record. Never parse it.
1114
+ if (tail) { const newline = raw.indexOf("\n"); raw = newline < 0 ? "" : raw.slice(newline + 1) }
1115
+ return raw
1116
+ } finally { fs.closeSync(fd) }
1031
1117
  }
1032
1118
 
1033
1119
  /**
@@ -1119,7 +1205,7 @@ function parseClaudeTranscript(raw) {
1119
1205
  */
1120
1206
  const TRANSCRIPT_STABLE_READS = 2
1121
1207
 
1122
- function readSettledTranscript(transcriptPath, parse) {
1208
+ function readSettledTranscript(transcriptPath, parse, boundary) {
1123
1209
  if (typeof transcriptPath !== "string" || !transcriptPath) return null
1124
1210
  const deadline = Date.now() + TRANSCRIPT_SETTLE_MS
1125
1211
  let lastSize = -1
@@ -1129,7 +1215,7 @@ function readSettledTranscript(transcriptPath, parse) {
1129
1215
  for (;;) {
1130
1216
  let raw
1131
1217
  try {
1132
- raw = readTranscriptRaw(transcriptPath)
1218
+ raw = readTranscriptRaw(transcriptPath, undefined, boundary?.offset ?? 0, boundary?.identity)
1133
1219
  } catch {
1134
1220
  return best // vanished or unreadable — keep whatever we already had
1135
1221
  }
@@ -1153,11 +1239,11 @@ function readSettledTranscript(transcriptPath, parse) {
1153
1239
 
1154
1240
  // The whole parse, not just its text: `blocks` carries each block's entry id,
1155
1241
  // which is what lets a later Stop send only what this one did not (ENG-2793).
1156
- function readClaudeTranscriptResponse(transcriptPath) {
1242
+ function readClaudeTranscriptResponse(transcriptPath, boundary) {
1157
1243
  return readSettledTranscript(transcriptPath, (raw) => {
1158
1244
  const parsed = parseClaudeTranscript(raw)
1159
1245
  return parsed.text ? parsed : null
1160
- })
1246
+ }, boundary)
1161
1247
  }
1162
1248
 
1163
1249
  /**
@@ -1277,10 +1363,10 @@ function parseCursorTranscript(raw) {
1277
1363
  return { text: lastAnswer, tailComplete: tail === "text" }
1278
1364
  }
1279
1365
 
1280
- function readCursorTranscriptResponse(transcriptPath) {
1366
+ function readCursorTranscriptResponse(transcriptPath, boundary) {
1281
1367
  // Cursor acknowledges `stop` can fire before the turn's last lines are
1282
1368
  // flushed, so wait for quiescence exactly like the Claude reader.
1283
- return readSettledTranscript(transcriptPath, raw => parseCursorTranscript(raw).text)
1369
+ return readSettledTranscript(transcriptPath, raw => parseCursorTranscript(raw).text, boundary)
1284
1370
  }
1285
1371
 
1286
1372
  /**
@@ -1326,7 +1412,7 @@ function cursorTurnMeta(data) {
1326
1412
  * response (e.g. a Cursor-translated Stop with no transcript, or a turn that
1327
1413
  * produced no assistant text).
1328
1414
  */
1329
- function extractResponse(data, toolName) {
1415
+ function extractResponse(data, toolName, options = {}) {
1330
1416
  // Pick the reader from the payload's OWN event name before trusting
1331
1417
  // `toolName`, because `toolName` is the relabeled tool (see effectiveTool in
1332
1418
  // main) and the relabel can be wrong for a response.
@@ -1349,7 +1435,8 @@ function extractResponse(data, toolName) {
1349
1435
  // Claude Code Stop payload: { session_id, transcript_path, cwd,
1350
1436
  // hook_event_name, stop_hook_active }. The response text is not in the
1351
1437
  // payload — read it from the transcript.
1352
- const parsed = readClaudeTranscriptResponse(data.transcript_path)
1438
+ if (options.inlineOnly) return { text: typeof data.last_assistant_message === "string" ? data.last_assistant_message : null, sessionId: data.session_id || null }
1439
+ const parsed = readClaudeTranscriptResponse(data.transcript_path, options.boundary)
1353
1440
  return {
1354
1441
  text: parsed ? parsed.text : null,
1355
1442
  blocks: parsed ? parsed.blocks : null,
@@ -1391,7 +1478,7 @@ function extractResponse(data, toolName) {
1391
1478
  // `stop` is the CLI's only route: read the transcript it points at.
1392
1479
  // Returns null when transcripts are disabled (privacy mode sends
1393
1480
  // transcript_path: null), which is a capture gap, not an error.
1394
- return { ...common, text: readCursorTranscriptResponse(data.transcript_path) }
1481
+ return { ...common, text: options.inlineOnly ? null : readCursorTranscriptResponse(data.transcript_path, options.boundary) }
1395
1482
  }
1396
1483
  case "copilot": {
1397
1484
  // Copilot Stop (both surfaces, via the PascalCase config spelling):
@@ -1522,13 +1609,24 @@ function pruneTurns() {
1522
1609
  }
1523
1610
 
1524
1611
  /** Mint + persist a turn id for this session's new prompt. */
1525
- function startTurn(sessionId, generationId) {
1612
+ function captureTranscriptBoundary(file) {
1613
+ if (typeof file !== "string" || !path.isAbsolute(file)) return null
1614
+ let fd
1615
+ try {
1616
+ if (fs.lstatSync(file).isSymbolicLink()) return null
1617
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0))
1618
+ const stat = fs.fstatSync(fd)
1619
+ return stat.isFile() ? { file, offset: stat.size, identity: `${stat.dev}:${stat.ino}` } : null
1620
+ } catch { return null }
1621
+ finally { if (fd !== undefined) fs.closeSync(fd) }
1622
+ }
1623
+ function startTurn(sessionId, generationId, selectionId, transcriptBoundary) {
1526
1624
  if (!sessionId) return null
1527
1625
  const turnId = crypto.randomUUID()
1528
1626
  try {
1529
1627
  fs.mkdirSync(TURNS_DIR, { recursive: true })
1530
1628
  pruneTurns()
1531
- fs.writeFileSync(turnFile(sessionId), JSON.stringify({ turnId, ts: Date.now(), ...(typeof generationId === "string" ? { generationId } : {}) }))
1629
+ fs.writeFileSync(turnFile(sessionId), JSON.stringify({ turnId, ts: Date.now(), ...(typeof generationId === "string" ? { generationId } : {}), ...(typeof selectionId === "string" ? { selectionId } : {}), ...(transcriptBoundary ? { transcriptBoundary } : {}) }))
1532
1630
  } catch {
1533
1631
  // Unwritable — the event still gets its id, it just can't be paired with
1534
1632
  // the response. Better an unpaired pair than a dropped prompt.
@@ -1549,6 +1647,10 @@ function currentTurnRecord(sessionId) {
1549
1647
  const data = JSON.parse(fs.readFileSync(turnFile(sessionId), "utf8"))
1550
1648
  return {
1551
1649
  generationId: typeof data.generationId === "string" ? data.generationId : null,
1650
+ transcriptBoundary: data.transcriptBoundary && typeof data.transcriptBoundary.file === "string"
1651
+ && path.isAbsolute(data.transcriptBoundary.file) && Number.isSafeInteger(data.transcriptBoundary.offset)
1652
+ && data.transcriptBoundary.offset >= 0 && typeof data.transcriptBoundary.identity === "string" ? data.transcriptBoundary : null,
1653
+ selectionId: typeof data.selectionId === "string" ? data.selectionId : null,
1552
1654
  turnId: typeof data.turnId === "string" ? data.turnId : null,
1553
1655
  ts: typeof data.ts === "number" && Number.isFinite(data.ts) ? data.ts : null,
1554
1656
  }
@@ -1913,8 +2015,107 @@ function claimPrompt(generationId) {
1913
2015
  * session's) and is the only pointer left once a copied explicit path has
1914
2016
  * been rejected.
1915
2017
  */
1916
- // Hosted capture is explicitly machine-wide for the disclosed assessment
1917
- // window. An expired lease never falls back to this registration's credentials.
2018
+ const SELECTED_CAPTURE_DISCLOSURE = "hosted_local_v3"
2019
+ function captureConversationKey(tool, sessionId) {
2020
+ return crypto.createHash("sha256").update(JSON.stringify([tool, sessionId])).digest("hex")
2021
+ }
2022
+ function validCaptureConversationIdentity(tool, sessionId) {
2023
+ return ["claude", "codex", "cursor", "gemini"].includes(tool) && typeof sessionId === "string"
2024
+ && sessionId.length > 0 && Buffer.byteLength(sessionId) <= 128
2025
+ && !/[\u0000-\u001f\u007f\uD800-\uDFFF]/u.test(sessionId)
2026
+ }
2027
+ function captureStopFile(projectDir, captureSetupId) {
2028
+ const key = crypto.createHash("sha256").update(captureSetupId).digest("hex")
2029
+ return path.join(projectDir, ".litmus", "capture-stops", `${key}.json`)
2030
+ }
2031
+ function readCaptureStopId(projectDir, captureSetupId) {
2032
+ let fd
2033
+ try {
2034
+ const file = captureStopFile(projectDir, captureSetupId)
2035
+ if (fs.lstatSync(file).isSymbolicLink()) return null
2036
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0))
2037
+ const stat = fs.fstatSync(fd)
2038
+ if (!stat.isFile() || stat.size > 1024) return null
2039
+ const buffer = Buffer.alloc(1025), count = fs.readSync(fd, buffer, 0, buffer.length, 0)
2040
+ if (count > 1024) return null
2041
+ const value = JSON.parse(buffer.subarray(0, count).toString("utf8"))
2042
+ return value?.captureSetupId === captureSetupId && typeof value.stopId === "string"
2043
+ && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value.stopId) ? value.stopId : null
2044
+ } catch (error) { return error?.code === "ENOENT" ? "" : null }
2045
+ finally { if (fd !== undefined) fs.closeSync(fd) }
2046
+ }
2047
+ function readCaptureConversationSelection(projectDir, captureSetupId) {
2048
+ const empty = { version: 1, captureSetupId, selected: [] }
2049
+ if (typeof captureSetupId !== "string" || !captureSetupId) return empty
2050
+ let fd
2051
+ try {
2052
+ const file = path.join(projectDir, ".litmus", "capture-selections.json")
2053
+ if (fs.lstatSync(file).isSymbolicLink()) return empty
2054
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0))
2055
+ const stat = fs.fstatSync(fd)
2056
+ if (!stat.isFile() || stat.size > 32768) return empty
2057
+ const buffer = Buffer.alloc(32769), count = fs.readSync(fd, buffer, 0, buffer.length, 0)
2058
+ if (count > 32768) return empty
2059
+ const data = JSON.parse(buffer.subarray(0, count).toString("utf8"))
2060
+ const valid = row => row && validCaptureConversationIdentity(row.tool, row.sessionId)
2061
+ && row.key === captureConversationKey(row.tool, row.sessionId)
2062
+ && typeof row.selectionId === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(row.selectionId)
2063
+ && Number.isFinite(row.selectedAt) && row.selectedAt >= 0
2064
+ && (row.transcript === undefined || (row.transcript && typeof row.transcript.file === "string"
2065
+ && path.isAbsolute(row.transcript.file) && Number.isSafeInteger(row.transcript.offset)
2066
+ && row.transcript.offset >= 0 && typeof row.transcript.identity === "string"))
2067
+ if (data?.version !== 1 || data.captureSetupId !== captureSetupId || !Array.isArray(data.selected)
2068
+ || data.selected.length > 8 || !data.selected.every(valid)
2069
+ || new Set(data.selected.map(row => row.key)).size !== data.selected.length) return empty
2070
+ const stopId = readCaptureStopId(projectDir, captureSetupId)
2071
+ if (stopId === null || (data.stopId ?? "") !== stopId) return empty
2072
+ return data
2073
+ } catch { return empty }
2074
+ finally { if (fd !== undefined) fs.closeSync(fd) }
2075
+ }
2076
+ function captureSelectionDigest(selection) {
2077
+ const scopes = selection.selected.map(row => ({ tool: row.tool, sessionId: row.sessionId, selectionId: row.selectionId }))
2078
+ .sort((a, b) => a.tool < b.tool ? -1 : a.tool > b.tool ? 1 : a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0)
2079
+ return crypto.createHash("sha256").update(JSON.stringify(scopes)).digest("hex")
2080
+ }
2081
+ function selectedHostedConversation(window, tool, sessionId, now = Date.now()) {
2082
+ if (window?.disclosureVersion !== SELECTED_CAPTURE_DISCLOSURE || !validCaptureConversationIdentity(tool, sessionId)) return null
2083
+ const state = readCaptureConversationSelection(path.dirname(window.litmusDir), window.captureSetupId)
2084
+ return state.selected.find(row => row.tool === tool && row.sessionId === sessionId
2085
+ && row.selectedAt >= window.startedAt && row.selectedAt <= now) || null
2086
+ }
2087
+ function hostedTurnStorageKey(window, tool, sessionId) {
2088
+ return window?.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
2089
+ ? selectedHostedConversation(window, tool, sessionId)?.selectionId || null : sessionId
2090
+ }
2091
+ function recordHostedConversationCandidate(window, tool, sessionId, payload) {
2092
+ if (window?.disclosureVersion !== SELECTED_CAPTURE_DISCLOSURE || !validCaptureConversationIdentity(tool, sessionId)) return
2093
+ const dir = path.join(window.litmusDir, "conversation-candidates")
2094
+ const key = captureConversationKey(tool, sessionId)
2095
+ const location = typeof payload?.cwd === "string" ? payload.cwd
2096
+ : Array.isArray(payload?.workspace_roots) ? payload.workspace_roots.find(value => typeof value === "string") : ""
2097
+ const project = typeof location === "string" ? path.basename(location.replace(/\\/g, "/")).replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 120) : ""
2098
+ const record = { captureSetupId: window.captureSetupId, tool, sessionId, label: project ? `${tool} · ${project}` : `${tool} conversation`, lastActiveAt: Date.now() }
2099
+ let temporary
2100
+ try {
2101
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
2102
+ temporary = path.join(dir, `${key}.${crypto.randomUUID()}.tmp`)
2103
+ fs.writeFileSync(temporary, JSON.stringify(record), { mode: 0o600, flag: "wx" })
2104
+ fs.renameSync(temporary, path.join(dir, `${key}.json`))
2105
+ // Metadata only; never persist prompt/response/transcript_path from payload.
2106
+ const entries = fs.readdirSync(dir).filter(name => /^[a-f0-9]{64}\.json$/.test(name))
2107
+ if (entries.length > 128) {
2108
+ const selected = new Set(readCaptureConversationSelection(path.dirname(window.litmusDir), window.captureSetupId).selected.map(row => `${row.key}.json`))
2109
+ const removable = entries.filter(name => !selected.has(name))
2110
+ .map(name => ({ name, time: fs.lstatSync(path.join(dir, name)).mtimeMs })).sort((a, b) => a.time - b.time)
2111
+ for (const entry of removable.slice(0, entries.length - 128)) fs.unlinkSync(path.join(dir, entry.name))
2112
+ }
2113
+ } catch { /* A metadata failure must neither record a body nor break the AI tool. */ }
2114
+ finally { if (temporary) try { fs.unlinkSync(temporary) } catch {} }
2115
+ }
2116
+
2117
+ // Legacy windows were computer-wide; v3 additionally requires an explicit
2118
+ // conversation selection. Expired authorization never falls back to credentials.
1918
2119
  function hostedCaptureWindow(now = Date.now()) {
1919
2120
  try {
1920
2121
  const window = JSON.parse(fs.readFileSync(path.join(os.homedir(), ".litmus", "hosted-capture.json"), "utf8"))
@@ -1926,12 +2127,22 @@ function hostedCaptureWindow(now = Date.now()) {
1926
2127
  const config = readConfig(dir)
1927
2128
  if (!config || config.captureMode !== "hosted-local") return null
1928
2129
  if (tokenDigest(config.token) !== window.tokenKey) return null
2130
+ if (window.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
2131
+ && (!window.captureSetupId || window.captureSetupId !== config.captureSetupId
2132
+ || window.selectionDigest !== captureSelectionDigest(readCaptureConversationSelection(window.projectDir, window.captureSetupId)))) return null
1929
2133
  return { ...window, litmusDir: dir }
1930
2134
  } catch { return null }
1931
2135
  }
1932
2136
 
1933
2137
  function ownedHostedTranscript(window, effectiveTool, id) {
1934
2138
  if (!window || !id || !["claude", "codex"].includes(effectiveTool)) return null
2139
+ if (window.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE) {
2140
+ const selected = selectedHostedConversation(window, effectiveTool, id)
2141
+ // The chosen EOF boundary owns this transcript even before the observer's
2142
+ // next poll, so a hook cannot race it into writing a duplicate first turn.
2143
+ return selected?.transcript ? { ...selected.transcript, tool: effectiveTool, sessionId: id,
2144
+ selectionId: selected.selectionId } : null
2145
+ }
1935
2146
  try {
1936
2147
  const state = JSON.parse(fs.readFileSync(path.join(window.litmusDir, "transcript-observer.json"), "utf8"))
1937
2148
  if (state.version !== 1 || state.startedAt !== window.startedAt) return null
@@ -1951,14 +2162,14 @@ function markHostedClaudeCompletion(window, cursor, parsed) {
1951
2162
  const finalText = reply.blocks.filter(block => block.id === final?.id).map(block => block.text).join("\n")
1952
2163
  if (typeof parsed.last_assistant_message === "string" && finalText !== parsed.last_assistant_message) return null
1953
2164
  return final?.id || null
1954
- })
2165
+ }, window.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE ? cursor : undefined)
1955
2166
  if (!entryId || hostedCaptureWindow()?.litmusDir !== window.litmusDir) return
1956
2167
  const dir = path.join(window.litmusDir, "transcript-completions")
1957
2168
  if (fs.existsSync(dir + ".done")) return false
1958
2169
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
1959
2170
  const key = crypto.createHash("sha256").update(JSON.stringify([cursor.sessionId])).digest("hex")
1960
2171
  const file = path.join(dir, `${key}.json`), temp = `${file}.${crypto.randomUUID()}.tmp`
1961
- fs.writeFileSync(temp, JSON.stringify({ startedAt: window.startedAt, completedAt: Date.now(), entryId }), { mode: 0o600 })
2172
+ fs.writeFileSync(temp, JSON.stringify({ startedAt: window.startedAt, completedAt: Date.now(), entryId, ...(cursor.selectionId ? { selectionId: cursor.selectionId } : {}) }), { mode: 0o600 })
1962
2173
  fs.renameSync(temp, file)
1963
2174
  } catch { /* completion metadata is best-effort; terminal transcript rows still work */ }
1964
2175
  }
@@ -1967,7 +2178,11 @@ function resolveAssessmentDir(parsed, workspaceRoots, effectiveTool = tool, self
1967
2178
  // Copilot retains its assessment-folder hook; it is outside the
1968
2179
  // machine-wide disclosure and must never use that routing window.
1969
2180
  const hosted = effectiveTool === "copilot" ? null : hostedCaptureWindow()
1970
- if (hosted && !selftest) return hosted.litmusDir
2181
+ if (hosted && !selftest) {
2182
+ if (hosted.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
2183
+ && !selectedHostedConversation(hosted, effectiveTool, parsed?.session_id || parsed?.sessionId || parsed?.conversation_id)) return null
2184
+ return hosted.litmusDir
2185
+ }
1971
2186
  const sessionDirs = [
1972
2187
  ...(workspaceRoots || []),
1973
2188
  ...(parsed && typeof parsed.cwd === "string" && parsed.cwd ? [parsed.cwd] : []),
@@ -2037,6 +2252,13 @@ async function main() {
2037
2252
  if (earlyLitmusDir && sessionOverMarked(earlyLitmusDir)) return
2038
2253
  const hostedWindow = effectiveTool === "copilot" ? null : hostedCaptureWindow()
2039
2254
  const hostedAtStart = selftestNonce && hostedWindow?.litmusDir !== earlyLitmusDir ? null : hostedWindow
2255
+ const nativeSessionId = parsed && (parsed.session_id || parsed.sessionId || parsed.conversation_id)
2256
+ const selectionAtStart = selectedHostedConversation(hostedAtStart, effectiveTool, nativeSessionId)
2257
+ if (hostedAtStart?.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE && !selftestNonce) {
2258
+ recordHostedConversationCandidate(hostedAtStart, effectiveTool, nativeSessionId, parsed)
2259
+ // Do not open transcripts, result caches, or edit ledgers for unselected chats.
2260
+ if (!selectionAtStart) return
2261
+ }
2040
2262
  const owned = ownedHostedTranscript(hostedAtStart, effectiveTool, parsed && (parsed.session_id || parsed.sessionId))
2041
2263
  if (owned && effectiveTool === "claude" && parsed?.hook_event_name === "Stop") {
2042
2264
  markHostedClaudeCompletion(hostedAtStart, owned, parsed)
@@ -2051,8 +2273,9 @@ async function main() {
2051
2273
  // read/import a transcript for a conversation that predates setup.
2052
2274
  if (hostedAtStart && isResponseEvent(parsed)) {
2053
2275
  const id = parsed && (parsed.session_id || parsed.sessionId || parsed.conversation_id)
2054
- const turn = currentTurnRecord(id)
2276
+ const turn = currentTurnRecord(hostedTurnStorageKey(hostedAtStart, effectiveTool, id))
2055
2277
  if (!turn || !turn.turnId || turn.ts < hostedAtStart.startedAt) return
2278
+ if (selectionAtStart && (turn.selectionId !== selectionAtStart.selectionId || turn.ts < selectionAtStart.selectedAt)) return
2056
2279
  }
2057
2280
 
2058
2281
  // ENG-2477: a capture SELF-TEST probe. `litmus init` (and `litmus doctor`)
@@ -2093,7 +2316,7 @@ async function main() {
2093
2316
  if (
2094
2317
  effectiveTool === "cursor"
2095
2318
  && parsed && parsed.hook_event_name === "stop"
2096
- && cursorResponseAlreadyCaptured(cursorConversation)
2319
+ && cursorResponseAlreadyCaptured(selectionAtStart?.selectionId || cursorConversation)
2097
2320
  ) {
2098
2321
  return
2099
2322
  }
@@ -2110,10 +2333,11 @@ async function main() {
2110
2333
  // Gated on the same assessment resolution a prompt gets, so an edit in a
2111
2334
  // project that is not the assessment is not written anywhere.
2112
2335
  if (effectiveTool === "cursor" && parsed && parsed.hook_event_name === CURSOR_EDIT_EVENT) {
2336
+ if (selectionAtStart && currentTurnRecord(selectionAtStart.selectionId).selectionId !== selectionAtStart.selectionId) return
2113
2337
  const roots = Array.isArray(parsed.workspace_roots) ? parsed.workspace_roots : []
2114
2338
  const editLitmusDir = resolveAssessmentDir(parsed, roots, effectiveTool)
2115
2339
  if (!editLitmusDir || sessionOverMarked(editLitmusDir)) return
2116
- recordCursorFileEdit(parsed, parsed.session_id || parsed.conversation_id || null,
2340
+ recordCursorFileEdit(parsed, selectionAtStart?.selectionId || parsed.session_id || parsed.conversation_id || null,
2117
2341
  path.dirname(editLitmusDir))
2118
2342
  return
2119
2343
  }
@@ -2124,15 +2348,17 @@ async function main() {
2124
2348
  let responseMeta = null
2125
2349
  // ENG-2793: the entry this reply ends on, recorded once the reply is written.
2126
2350
  let repliedEntry = null
2351
+ const responseBoundary = selectionAtStart && responseEvent ? currentTurnRecord(selectionAtStart.selectionId).transcriptBoundary : null
2352
+ const matchingBoundary = responseBoundary?.file === parsed?.transcript_path ? responseBoundary : null
2127
2353
  if (responseEvent) {
2128
- const extracted = extractResponse(parsed, effectiveTool)
2354
+ const extracted = extractResponse(parsed, effectiveTool, selectionAtStart ? { boundary: matchingBoundary, inlineOnly: !matchingBoundary } : {})
2129
2355
  content = extracted.text
2130
2356
  sessionId = extracted.sessionId
2131
2357
  workspaceRoots = extracted.workspaceRoots || []
2132
2358
  responseMeta = extracted.meta || null
2133
2359
  const blocks = extracted.blocks
2134
2360
  if (blocks && blocks.length && sessionId && !selftestNonce) {
2135
- const unsent = unsentBlocks(blocks, lastRepliedEntry(sessionId))
2361
+ const unsent = unsentBlocks(blocks, lastRepliedEntry(selectionAtStart?.selectionId || sessionId))
2136
2362
  content = unsent.length ? unsent.map((b) => b.text).join("\n\n") : null
2137
2363
  repliedEntry = blocks[blocks.length - 1].id
2138
2364
  }
@@ -2146,25 +2372,26 @@ async function main() {
2146
2372
  // isSystemInjectedPrompt.
2147
2373
  if (isSystemInjectedPrompt(content)) return
2148
2374
  }
2375
+ const litmusDir = resolveAssessmentDir(parsed, workspaceRoots, effectiveTool, !!selftestNonce)
2376
+ if (!litmusDir) return
2377
+ if (hostedAtStart && hostedCaptureWindow()?.litmusDir !== hostedAtStart.litmusDir) return
2378
+ if (litmusDir !== earlyLitmusDir && sessionOverMarked(litmusDir)) return
2379
+ const captureToken = readConfig(litmusDir)?.token
2380
+ const knownCaptureTokens = captureKnownTokens(captureToken)
2149
2381
  let toolTrace = null
2150
2382
  const cursorResultsDir = responseEvent && effectiveTool === "cursor" && !selftestNonce
2151
2383
  ? cursorResultScope({ session_id: sessionId }, hostedAtStart) : null
2152
2384
  if (responseEvent && !selftestNonce && typeof parsed?.transcript_path === "string"
2153
- && (hostedWorkspaceHome || hostedAtStart?.disclosureVersion === "hosted_local_v2")) {
2154
- try { toolTrace = parseToolEvidence(readTranscriptRaw(parsed.transcript_path), effectiveTool) }
2385
+ && (hostedWorkspaceHome || hostedAtStart?.disclosureVersion === "hosted_local_v2" || (selectionAtStart && matchingBoundary))) {
2386
+ try { toolTrace = parseToolEvidence(readTranscriptRaw(parsed.transcript_path, undefined, matchingBoundary?.offset ?? 0, matchingBoundary?.identity), effectiveTool, knownCaptureTokens) }
2155
2387
  catch { toolTrace = { version: 1, records: [], complete: false, reason: "transcript_unavailable", dropped: 0 } }
2156
2388
  }
2157
- if (responseEvent && effectiveTool === "cursor" && !selftestNonce && hostedAtStart?.disclosureVersion === "hosted_local_v2") {
2389
+ if (responseEvent && effectiveTool === "cursor" && !selftestNonce && ["hosted_local_v2", SELECTED_CAPTURE_DISCLOSURE].includes(hostedAtStart?.disclosureVersion)) {
2158
2390
  toolTrace = cursorHookToolTrace(toolTrace, readCursorToolResults(sessionId, hostedAtStart, cursorResultsDir))
2159
2391
  }
2160
2392
  if (!content && !toolTrace?.records?.length) return
2161
2393
  content = content || ""
2162
2394
 
2163
- const litmusDir = resolveAssessmentDir(parsed, workspaceRoots, effectiveTool, !!selftestNonce)
2164
- if (!litmusDir) return
2165
- if (hostedAtStart && hostedCaptureWindow()?.litmusDir !== hostedAtStart.litmusDir) return
2166
- if (litmusDir !== earlyLitmusDir && sessionOverMarked(litmusDir)) return
2167
-
2168
2395
  // Claim as LATE as possible — only once we know we have content and somewhere
2169
2396
  // to put it. Claiming earlier would let an invocation that then bails (no
2170
2397
  // content, no assessment in scope) consume the claim and silence the sibling
@@ -2172,13 +2399,17 @@ async function main() {
2172
2399
  // (generation_id is per assistant message, but a prompt and its response
2173
2400
  // could conceivably share one) so the two kinds never contend.
2174
2401
  if (cursorShaped && parsed && parsed.generation_id) {
2175
- const claimKey = responseEvent ? `${parsed.generation_id}.resp` : parsed.generation_id
2402
+ const generationKey = selectionAtStart ? `${selectionAtStart.selectionId}:${parsed.generation_id}` : parsed.generation_id
2403
+ const claimKey = responseEvent ? `${generationKey}.resp` : generationKey
2176
2404
  if (!claimPrompt(claimKey)) {
2177
2405
  return // the sibling hook is writing this same event
2178
2406
  }
2179
2407
  }
2180
2408
 
2181
2409
  const fullCursorPrompt = !responseEvent && effectiveTool === "cursor"
2410
+ // Redact the full body first: clipping a credential at a character limit
2411
+ // would otherwise prevent exact-value recognition in the final event pass.
2412
+ content = redactCaptureText(content, knownCaptureTokens)
2182
2413
  const maxLength = fullCursorPrompt ? Infinity : responseEvent ? MAX_RESPONSE_LENGTH : MAX_PROMPT_LENGTH
2183
2414
  const truncated = content.length > maxLength
2184
2415
  ? content.slice(0, maxLength) + "...[truncated]"
@@ -2186,8 +2417,9 @@ async function main() {
2186
2417
 
2187
2418
  // Pair the two invocations: a prompt opens a turn, its response inherits the
2188
2419
  // same id. See the turn-pairing block above.
2189
- const turnRecord = responseEvent && !selftestNonce ? currentTurnRecord(sessionId) : null
2190
- const turnId = selftestNonce ? null : responseEvent ? turnRecord.turnId : startTurn(sessionId, parsed?.generation_id)
2420
+ const storageKey = selectionAtStart?.selectionId || sessionId
2421
+ const turnRecord = responseEvent && !selftestNonce ? currentTurnRecord(storageKey) : null
2422
+ const turnId = selftestNonce ? null : responseEvent ? turnRecord.turnId : startTurn(storageKey, parsed?.generation_id, selectionAtStart?.selectionId, selectionAtStart ? captureTranscriptBoundary(parsed?.transcript_path) : null)
2191
2423
 
2192
2424
  const event = selftestNonce
2193
2425
  ? {
@@ -2230,6 +2462,7 @@ async function main() {
2230
2462
  if (hostedAtStart) {
2231
2463
  event.capture_location = "local"
2232
2464
  event.capture_receipt = hostedAtStart.receipt
2465
+ if (selectionAtStart && !selftestNonce) event.capture_selection_id = selectionAtStart.selectionId
2233
2466
  event.ts = new Date(hostedCapturedAt).toISOString()
2234
2467
  }
2235
2468
  if (sessionId) event.sessionId = sessionId
@@ -2239,7 +2472,7 @@ async function main() {
2239
2472
  // the byte-cap loop, like the metering, so the body is trimmed around it.
2240
2473
  let editLedger = null
2241
2474
  if (responseEvent && effectiveTool === "cursor" && !selftestNonce) {
2242
- editLedger = takeCursorFileEdits(sessionId, turnRecord ? turnRecord.ts : null)
2475
+ editLedger = takeCursorFileEdits(storageKey, turnRecord ? turnRecord.ts : null)
2243
2476
  if (editLedger) event.file_writes = editLedger.writes
2244
2477
  }
2245
2478
  if (toolTrace) event.tool_calls = { trace: toolTrace }
@@ -2262,6 +2495,7 @@ async function main() {
2262
2495
  // Preserve complete Cursor prompts in both the file and upload lanes. Other
2263
2496
  // bodies keep their existing serialized budget; the server's size filter is
2264
2497
  // still the final storage bound.
2498
+ sanitizeCaptureEvent(event, captureToken)
2265
2499
  const MAX_SERIALIZED_BYTES = 60000
2266
2500
  const bodyField = responseEvent ? "text" : "prompt"
2267
2501
  if (!fullCursorPrompt) trimEventToBytes(event, bodyField, MAX_SERIALIZED_BYTES, toolTrace ? storageBytes : undefined)
@@ -2270,11 +2504,12 @@ async function main() {
2270
2504
  // Record that this turn's reply is captured, so the sibling `stop` hook
2271
2505
  // doesn't record it a second time (IDE only — see the claim helpers).
2272
2506
  if (responseEvent && effectiveTool === "cursor" && parsed.hook_event_name === "afterAgentResponse") {
2273
- markCursorResponseCaptured(cursorConversation)
2507
+ markCursorResponseCaptured(selectionAtStart?.selectionId || cursorConversation)
2274
2508
  }
2275
2509
 
2276
2510
  // Recheck after transcript reads/settling: teardown may have happened meanwhile.
2277
2511
  if (hostedAtStart && hostedCaptureWindow()?.litmusDir !== litmusDir) return
2512
+ if (selectionAtStart && selectedHostedConversation(hostedCaptureWindow(), effectiveTool, sessionId)?.selectionId !== selectionAtStart.selectionId) return
2278
2513
 
2279
2514
  // 1. Append to activity.jsonl (for submission ZIP)
2280
2515
  const logPath = path.join(litmusDir, "activity.jsonl")
@@ -2289,7 +2524,7 @@ async function main() {
2289
2524
  // ENG-2793: the next Stop starts after this reply only once a copy of it is
2290
2525
  // on disk. The drain and the upload report no outcome, so a reply whose append
2291
2526
  // failed is sent again by the next Stop, and the report folds the repeat.
2292
- if (repliedEntry && logged) recordRepliedEntry(sessionId, repliedEntry)
2527
+ if (repliedEntry && logged) recordRepliedEntry(storageKey, repliedEntry)
2293
2528
  // ENG-2344: the edits this reply carries leave the ledger only now that the
2294
2529
  // reply is on disk. An append that failed hands them back for the next reply.
2295
2530
  if (editLedger) {
@@ -2426,8 +2661,23 @@ function storageBytes(value) {
2426
2661
 
2427
2662
  const MAX_RECORDS = 128
2428
2663
  const MAX_BYTES = 48000
2429
- function boundedText(value, cap) {
2430
- const full = typeof value === 'string' ? value : JSON.stringify(value ?? null)
2664
+ function boundedText(value, cap, known = []) {
2665
+ // Codex supplies JSON arguments as a STRING, while Claude supplies an object.
2666
+ // Scrub credential keys in either form before stringification or clipping.
2667
+ // Preserve a harmless JSON string's formatting when it needs no redaction.
2668
+ let scrubbed = value
2669
+ if (typeof value === "string") {
2670
+ let parsed
2671
+ try { parsed = JSON.parse(value) } catch { /* ordinary tool output is not necessarily JSON */ }
2672
+ if (parsed && typeof parsed === "object") {
2673
+ const safe = scrubCaptureContent(parsed, known)
2674
+ if (JSON.stringify(safe) !== JSON.stringify(parsed)) scrubbed = JSON.stringify(safe)
2675
+ }
2676
+ }
2677
+ scrubbed = scrubCaptureContent(scrubbed, known)
2678
+ // Hashes/byte counts describe the sanitized evidence, never a retained raw
2679
+ // secret. Both transcript and post-tool-hook writers use this same order.
2680
+ const full = typeof scrubbed === 'string' ? scrubbed : JSON.stringify(scrubbed ?? null)
2431
2681
  let text = full
2432
2682
  while (storageBytes(text) > cap) text = text.slice(0, Math.floor(text.length * 0.9))
2433
2683
  if (text && /[\uD800-\uDBFF]$/.test(text)) text = text.slice(0, -1)
@@ -2436,7 +2686,7 @@ function boundedText(value, cap) {
2436
2686
 
2437
2687
  /** Only the final genuine user turn is in scope. A bounded tail without its
2438
2688
  * boundary is unavailable, never a license to import historical tool output. */
2439
- function parseToolEvidence(raw, tool) {
2689
+ function parseToolEvidence(raw, tool, known = []) {
2440
2690
  let records = [], boundary = false, seen = new Set(), dropped = 0
2441
2691
  for (const [lineIndex, line] of raw.split('\n').entries()) {
2442
2692
  let row
@@ -2475,7 +2725,7 @@ function parseToolEvidence(raw, tool) {
2475
2725
  seen.add(key)
2476
2726
  if (records.length >= MAX_RECORDS) { dropped++; continue }
2477
2727
  const field = record.kind === 'call' ? 'input' : 'output'
2478
- records.push({ kind: record.kind, id: record.id, ...(record.name ? { name: record.name } : {}), ...(typeof record.ok === 'boolean' ? { ok: record.ok } : {}), [field]: boundedText(record[field], 40000) })
2728
+ records.push({ kind: record.kind, id: record.id, ...(record.name ? { name: record.name } : {}), ...(typeof record.ok === 'boolean' ? { ok: record.ok } : {}), [field]: boundedText(record[field], 40000, known) })
2479
2729
  }
2480
2730
  }
2481
2731
  while (storageBytes(records) > MAX_BYTES) { records.pop(); dropped++ }
@@ -2514,30 +2764,36 @@ function finishCursorToolResults(dir) {
2514
2764
  pruneCursorToolResults()
2515
2765
  }
2516
2766
  function cursorResultScope(data, window) {
2517
- if (!window || window.disclosureVersion !== "hosted_local_v2") return null
2767
+ if (!window || !["hosted_local_v2", SELECTED_CAPTURE_DISCLOSURE].includes(window.disclosureVersion)) return null
2518
2768
  const session = data?.session_id || data?.conversation_id
2519
- const turn = currentTurnRecord(session)
2769
+ const turn = currentTurnRecord(hostedTurnStorageKey(window, "cursor", session))
2520
2770
  if (!turn.turnId || !Number.isFinite(turn.ts) || turn.ts < window.startedAt) return null
2521
- const key = crypto.createHash("sha256").update(JSON.stringify([session, turn.turnId, window.startedAt, window.litmusDir])).digest("hex")
2771
+ const key = crypto.createHash("sha256").update(JSON.stringify([session, turn.turnId, window.startedAt, window.litmusDir, ...(turn.selectionId ? [turn.selectionId] : [])])).digest("hex")
2522
2772
  return path.join(cursorResultsRoot(), key)
2523
2773
  }
2524
2774
  function recordCursorToolResult(data, window) {
2525
2775
  pruneCursorToolResults()
2526
2776
  const dir = cursorResultScope(data, window)
2527
2777
  const failed = data?.hook_event_name === "postToolUseFailure"
2528
- const observed = currentTurnRecord(data?.session_id || data?.conversation_id)
2778
+ const session = data?.session_id || data?.conversation_id
2779
+ const selected = selectedHostedConversation(window, "cursor", session)
2780
+ const observed = currentTurnRecord(hostedTurnStorageKey(window, "cursor", session))
2781
+ if (window?.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
2782
+ && (!selected || observed.selectionId !== selected.selectionId || observed.ts < selected.selectedAt)) return false
2529
2783
  if (!observed.generationId || data?.generation_id !== observed.generationId) return false
2530
2784
  if (!dir || typeof data.tool_use_id !== "string" || !data.tool_use_id || data.tool_use_id.length > 128
2531
2785
  || typeof data.tool_name !== "string" || !data.tool_name || data.tool_name.length > 128
2532
2786
  || data.tool_input === undefined
2533
2787
  || (failed ? typeof data.error_message !== "string" : data.tool_output === undefined)) return false
2534
2788
  const id = data.tool_use_id
2789
+ const known = captureKnownTokens(window.litmusDir ? readConfig(window.litmusDir)?.token : undefined)
2535
2790
  const pair = [
2536
- { kind: "call", id, name: data.tool_name, input: boundedText(data.tool_input, 40000) },
2537
- { kind: "result", id, ...(failed ? { ok: false } : {}), output: boundedText(failed ? data.error_message : data.tool_output, 40000) },
2791
+ { kind: "call", id, name: data.tool_name, input: boundedText(data.tool_input, 40000, known) },
2792
+ { kind: "result", id, ...(failed ? { ok: false } : {}), output: boundedText(failed ? data.error_message : data.tool_output, 40000, known) },
2538
2793
  ]
2539
2794
  let tmp
2540
2795
  try {
2796
+ if (selected && selectedHostedConversation(hostedCaptureWindow(), "cursor", session)?.selectionId !== selected.selectionId) return false
2541
2797
  if (fs.existsSync(dir + ".done")) return false
2542
2798
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
2543
2799
  if (fs.readdirSync(dir).filter(n => n.endsWith(".json")).length >= MAX_RECORDS / 2) return false
@@ -2613,6 +2869,19 @@ function cursorHookToolTrace(transcript, hookRecords) {
2613
2869
 
2614
2870
  // Exported for unit tests only; every hook invocation runs this file directly.
2615
2871
  module.exports = {
2872
+ sanitizeCaptureEvent,
2873
+ captureConversationKey,
2874
+ validCaptureConversationIdentity,
2875
+ readCaptureConversationSelection,
2876
+ selectedHostedConversation,
2877
+ captureSelectionDigest,
2878
+ captureStopFile,
2879
+ readCaptureStopId,
2880
+ captureKnownTokens,
2881
+ redactCaptureText,
2882
+ scrubCaptureContent,
2883
+ CAPTURE_CREDENTIAL_PATTERNS,
2884
+ CAPTURE_CREDENTIAL_KEYS,
2616
2885
  recordCursorToolResult,
2617
2886
  readCursorToolResults,
2618
2887
  cursorHookToolTrace,