litmus-cli 1.5.0-beta.10 → 1.5.0-beta.12

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 (56) hide show
  1. package/README.md +14 -2
  2. package/dist/commands/connect.d.ts +8 -1
  3. package/dist/commands/connect.d.ts.map +1 -1
  4. package/dist/commands/connect.js +39 -10
  5. package/dist/commands/connect.js.map +1 -1
  6. package/dist/lib/capture-conversation-catalog.d.ts +3 -0
  7. package/dist/lib/capture-conversation-catalog.d.ts.map +1 -0
  8. package/dist/lib/capture-conversation-catalog.js +56 -0
  9. package/dist/lib/capture-conversation-catalog.js.map +1 -0
  10. package/dist/lib/capture-conversations.d.ts +58 -0
  11. package/dist/lib/capture-conversations.d.ts.map +1 -0
  12. package/dist/lib/capture-conversations.js +94 -0
  13. package/dist/lib/capture-conversations.js.map +1 -0
  14. package/dist/lib/capture-network.d.ts +24 -0
  15. package/dist/lib/capture-network.d.ts.map +1 -0
  16. package/dist/lib/capture-network.js +84 -0
  17. package/dist/lib/capture-network.js.map +1 -0
  18. package/dist/lib/capture-selection-server.d.ts +19 -0
  19. package/dist/lib/capture-selection-server.d.ts.map +1 -0
  20. package/dist/lib/capture-selection-server.js +211 -0
  21. package/dist/lib/capture-selection-server.js.map +1 -0
  22. package/dist/lib/capture-startup-diagnostics.d.ts.map +1 -1
  23. package/dist/lib/capture-startup-diagnostics.js +3 -1
  24. package/dist/lib/capture-startup-diagnostics.js.map +1 -1
  25. package/dist/lib/cursor-session.d.ts +6 -0
  26. package/dist/lib/cursor-session.d.ts.map +1 -1
  27. package/dist/lib/cursor-session.js +51 -8
  28. package/dist/lib/cursor-session.js.map +1 -1
  29. package/dist/lib/detection.d.ts +2 -1
  30. package/dist/lib/detection.d.ts.map +1 -1
  31. package/dist/lib/detection.js +2 -1
  32. package/dist/lib/detection.js.map +1 -1
  33. package/dist/lib/hook-logger.cjs +315 -70
  34. package/dist/lib/hosted-capture.d.ts +2 -1
  35. package/dist/lib/hosted-capture.d.ts.map +1 -1
  36. package/dist/lib/hosted-capture.js +17 -13
  37. package/dist/lib/hosted-capture.js.map +1 -1
  38. package/dist/lib/hosted-transcripts.d.ts +8 -1
  39. package/dist/lib/hosted-transcripts.d.ts.map +1 -1
  40. package/dist/lib/hosted-transcripts.js +89 -21
  41. package/dist/lib/hosted-transcripts.js.map +1 -1
  42. package/dist/lib/platform.d.ts +5 -2
  43. package/dist/lib/platform.d.ts.map +1 -1
  44. package/dist/lib/platform.js +16 -8
  45. package/dist/lib/platform.js.map +1 -1
  46. package/dist/lib/portal-launcher.d.ts.map +1 -1
  47. package/dist/lib/portal-launcher.js +8 -0
  48. package/dist/lib/portal-launcher.js.map +1 -1
  49. package/dist/lib/practice-handoff.d.ts.map +1 -1
  50. package/dist/lib/practice-handoff.js +4 -3
  51. package/dist/lib/practice-handoff.js.map +1 -1
  52. package/dist/lib/windows-process-scan.d.ts +11 -0
  53. package/dist/lib/windows-process-scan.d.ts.map +1 -0
  54. package/dist/lib/windows-process-scan.js +96 -0
  55. package/dist/lib/windows-process-scan.js.map +1 -0
  56. 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,85 @@ 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 readCaptureConversationSelection(projectDir, captureSetupId) {
2028
+ const empty = { version: 1, captureSetupId, selected: [] }
2029
+ if (typeof captureSetupId !== "string" || !captureSetupId) return empty
2030
+ let fd
2031
+ try {
2032
+ const file = path.join(projectDir, ".litmus", "capture-selections.json")
2033
+ if (fs.lstatSync(file).isSymbolicLink()) return empty
2034
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0))
2035
+ const stat = fs.fstatSync(fd)
2036
+ if (!stat.isFile() || stat.size > 32768) return empty
2037
+ const buffer = Buffer.alloc(32769), count = fs.readSync(fd, buffer, 0, buffer.length, 0)
2038
+ if (count > 32768) return empty
2039
+ const data = JSON.parse(buffer.subarray(0, count).toString("utf8"))
2040
+ const valid = row => row && validCaptureConversationIdentity(row.tool, row.sessionId)
2041
+ && row.key === captureConversationKey(row.tool, row.sessionId)
2042
+ && 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)
2043
+ && Number.isFinite(row.selectedAt) && row.selectedAt >= 0
2044
+ && (row.transcript === undefined || (row.transcript && typeof row.transcript.file === "string"
2045
+ && path.isAbsolute(row.transcript.file) && Number.isSafeInteger(row.transcript.offset)
2046
+ && row.transcript.offset >= 0 && typeof row.transcript.identity === "string"))
2047
+ if (data?.version !== 1 || data.captureSetupId !== captureSetupId || !Array.isArray(data.selected)
2048
+ || data.selected.length > 8 || !data.selected.every(valid)
2049
+ || new Set(data.selected.map(row => row.key)).size !== data.selected.length) return empty
2050
+ return data
2051
+ } catch { return empty }
2052
+ finally { if (fd !== undefined) fs.closeSync(fd) }
2053
+ }
2054
+ function captureSelectionDigest(selection) {
2055
+ const scopes = selection.selected.map(row => ({ tool: row.tool, sessionId: row.sessionId, selectionId: row.selectionId }))
2056
+ .sort((a, b) => a.tool < b.tool ? -1 : a.tool > b.tool ? 1 : a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0)
2057
+ return crypto.createHash("sha256").update(JSON.stringify(scopes)).digest("hex")
2058
+ }
2059
+ function selectedHostedConversation(window, tool, sessionId, now = Date.now()) {
2060
+ if (window?.disclosureVersion !== SELECTED_CAPTURE_DISCLOSURE || !validCaptureConversationIdentity(tool, sessionId)) return null
2061
+ const state = readCaptureConversationSelection(path.dirname(window.litmusDir), window.captureSetupId)
2062
+ return state.selected.find(row => row.tool === tool && row.sessionId === sessionId
2063
+ && row.selectedAt >= window.startedAt && row.selectedAt <= now) || null
2064
+ }
2065
+ function hostedTurnStorageKey(window, tool, sessionId) {
2066
+ return window?.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
2067
+ ? selectedHostedConversation(window, tool, sessionId)?.selectionId || null : sessionId
2068
+ }
2069
+ function recordHostedConversationCandidate(window, tool, sessionId, payload) {
2070
+ if (window?.disclosureVersion !== SELECTED_CAPTURE_DISCLOSURE || !validCaptureConversationIdentity(tool, sessionId)) return
2071
+ const dir = path.join(window.litmusDir, "conversation-candidates")
2072
+ const key = captureConversationKey(tool, sessionId)
2073
+ const location = typeof payload?.cwd === "string" ? payload.cwd
2074
+ : Array.isArray(payload?.workspace_roots) ? payload.workspace_roots.find(value => typeof value === "string") : ""
2075
+ const project = typeof location === "string" ? path.basename(location.replace(/\\/g, "/")).replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 120) : ""
2076
+ const record = { captureSetupId: window.captureSetupId, tool, sessionId, label: project ? `${tool} · ${project}` : `${tool} conversation`, lastActiveAt: Date.now() }
2077
+ let temporary
2078
+ try {
2079
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
2080
+ temporary = path.join(dir, `${key}.${crypto.randomUUID()}.tmp`)
2081
+ fs.writeFileSync(temporary, JSON.stringify(record), { mode: 0o600, flag: "wx" })
2082
+ fs.renameSync(temporary, path.join(dir, `${key}.json`))
2083
+ // Metadata only; never persist prompt/response/transcript_path from payload.
2084
+ const entries = fs.readdirSync(dir).filter(name => /^[a-f0-9]{64}\.json$/.test(name))
2085
+ if (entries.length > 128) {
2086
+ const selected = new Set(readCaptureConversationSelection(path.dirname(window.litmusDir), window.captureSetupId).selected.map(row => `${row.key}.json`))
2087
+ const removable = entries.filter(name => !selected.has(name))
2088
+ .map(name => ({ name, time: fs.lstatSync(path.join(dir, name)).mtimeMs })).sort((a, b) => a.time - b.time)
2089
+ for (const entry of removable.slice(0, entries.length - 128)) fs.unlinkSync(path.join(dir, entry.name))
2090
+ }
2091
+ } catch { /* A metadata failure must neither record a body nor break the AI tool. */ }
2092
+ finally { if (temporary) try { fs.unlinkSync(temporary) } catch {} }
2093
+ }
2094
+
2095
+ // Legacy windows were computer-wide; v3 additionally requires an explicit
2096
+ // conversation selection. Expired authorization never falls back to credentials.
1918
2097
  function hostedCaptureWindow(now = Date.now()) {
1919
2098
  try {
1920
2099
  const window = JSON.parse(fs.readFileSync(path.join(os.homedir(), ".litmus", "hosted-capture.json"), "utf8"))
@@ -1926,12 +2105,22 @@ function hostedCaptureWindow(now = Date.now()) {
1926
2105
  const config = readConfig(dir)
1927
2106
  if (!config || config.captureMode !== "hosted-local") return null
1928
2107
  if (tokenDigest(config.token) !== window.tokenKey) return null
2108
+ if (window.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
2109
+ && (!window.captureSetupId || window.captureSetupId !== config.captureSetupId
2110
+ || window.selectionDigest !== captureSelectionDigest(readCaptureConversationSelection(window.projectDir, window.captureSetupId)))) return null
1929
2111
  return { ...window, litmusDir: dir }
1930
2112
  } catch { return null }
1931
2113
  }
1932
2114
 
1933
2115
  function ownedHostedTranscript(window, effectiveTool, id) {
1934
2116
  if (!window || !id || !["claude", "codex"].includes(effectiveTool)) return null
2117
+ if (window.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE) {
2118
+ const selected = selectedHostedConversation(window, effectiveTool, id)
2119
+ // The chosen EOF boundary owns this transcript even before the observer's
2120
+ // next poll, so a hook cannot race it into writing a duplicate first turn.
2121
+ return selected?.transcript ? { ...selected.transcript, tool: effectiveTool, sessionId: id,
2122
+ selectionId: selected.selectionId } : null
2123
+ }
1935
2124
  try {
1936
2125
  const state = JSON.parse(fs.readFileSync(path.join(window.litmusDir, "transcript-observer.json"), "utf8"))
1937
2126
  if (state.version !== 1 || state.startedAt !== window.startedAt) return null
@@ -1951,14 +2140,14 @@ function markHostedClaudeCompletion(window, cursor, parsed) {
1951
2140
  const finalText = reply.blocks.filter(block => block.id === final?.id).map(block => block.text).join("\n")
1952
2141
  if (typeof parsed.last_assistant_message === "string" && finalText !== parsed.last_assistant_message) return null
1953
2142
  return final?.id || null
1954
- })
2143
+ }, window.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE ? cursor : undefined)
1955
2144
  if (!entryId || hostedCaptureWindow()?.litmusDir !== window.litmusDir) return
1956
2145
  const dir = path.join(window.litmusDir, "transcript-completions")
1957
2146
  if (fs.existsSync(dir + ".done")) return false
1958
2147
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
1959
2148
  const key = crypto.createHash("sha256").update(JSON.stringify([cursor.sessionId])).digest("hex")
1960
2149
  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 })
2150
+ fs.writeFileSync(temp, JSON.stringify({ startedAt: window.startedAt, completedAt: Date.now(), entryId, ...(cursor.selectionId ? { selectionId: cursor.selectionId } : {}) }), { mode: 0o600 })
1962
2151
  fs.renameSync(temp, file)
1963
2152
  } catch { /* completion metadata is best-effort; terminal transcript rows still work */ }
1964
2153
  }
@@ -1967,7 +2156,11 @@ function resolveAssessmentDir(parsed, workspaceRoots, effectiveTool = tool, self
1967
2156
  // Copilot retains its assessment-folder hook; it is outside the
1968
2157
  // machine-wide disclosure and must never use that routing window.
1969
2158
  const hosted = effectiveTool === "copilot" ? null : hostedCaptureWindow()
1970
- if (hosted && !selftest) return hosted.litmusDir
2159
+ if (hosted && !selftest) {
2160
+ if (hosted.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
2161
+ && !selectedHostedConversation(hosted, effectiveTool, parsed?.session_id || parsed?.sessionId || parsed?.conversation_id)) return null
2162
+ return hosted.litmusDir
2163
+ }
1971
2164
  const sessionDirs = [
1972
2165
  ...(workspaceRoots || []),
1973
2166
  ...(parsed && typeof parsed.cwd === "string" && parsed.cwd ? [parsed.cwd] : []),
@@ -2037,6 +2230,13 @@ async function main() {
2037
2230
  if (earlyLitmusDir && sessionOverMarked(earlyLitmusDir)) return
2038
2231
  const hostedWindow = effectiveTool === "copilot" ? null : hostedCaptureWindow()
2039
2232
  const hostedAtStart = selftestNonce && hostedWindow?.litmusDir !== earlyLitmusDir ? null : hostedWindow
2233
+ const nativeSessionId = parsed && (parsed.session_id || parsed.sessionId || parsed.conversation_id)
2234
+ const selectionAtStart = selectedHostedConversation(hostedAtStart, effectiveTool, nativeSessionId)
2235
+ if (hostedAtStart?.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE && !selftestNonce) {
2236
+ recordHostedConversationCandidate(hostedAtStart, effectiveTool, nativeSessionId, parsed)
2237
+ // Do not open transcripts, result caches, or edit ledgers for unselected chats.
2238
+ if (!selectionAtStart) return
2239
+ }
2040
2240
  const owned = ownedHostedTranscript(hostedAtStart, effectiveTool, parsed && (parsed.session_id || parsed.sessionId))
2041
2241
  if (owned && effectiveTool === "claude" && parsed?.hook_event_name === "Stop") {
2042
2242
  markHostedClaudeCompletion(hostedAtStart, owned, parsed)
@@ -2051,8 +2251,9 @@ async function main() {
2051
2251
  // read/import a transcript for a conversation that predates setup.
2052
2252
  if (hostedAtStart && isResponseEvent(parsed)) {
2053
2253
  const id = parsed && (parsed.session_id || parsed.sessionId || parsed.conversation_id)
2054
- const turn = currentTurnRecord(id)
2254
+ const turn = currentTurnRecord(hostedTurnStorageKey(hostedAtStart, effectiveTool, id))
2055
2255
  if (!turn || !turn.turnId || turn.ts < hostedAtStart.startedAt) return
2256
+ if (selectionAtStart && (turn.selectionId !== selectionAtStart.selectionId || turn.ts < selectionAtStart.selectedAt)) return
2056
2257
  }
2057
2258
 
2058
2259
  // ENG-2477: a capture SELF-TEST probe. `litmus init` (and `litmus doctor`)
@@ -2093,7 +2294,7 @@ async function main() {
2093
2294
  if (
2094
2295
  effectiveTool === "cursor"
2095
2296
  && parsed && parsed.hook_event_name === "stop"
2096
- && cursorResponseAlreadyCaptured(cursorConversation)
2297
+ && cursorResponseAlreadyCaptured(selectionAtStart?.selectionId || cursorConversation)
2097
2298
  ) {
2098
2299
  return
2099
2300
  }
@@ -2110,10 +2311,11 @@ async function main() {
2110
2311
  // Gated on the same assessment resolution a prompt gets, so an edit in a
2111
2312
  // project that is not the assessment is not written anywhere.
2112
2313
  if (effectiveTool === "cursor" && parsed && parsed.hook_event_name === CURSOR_EDIT_EVENT) {
2314
+ if (selectionAtStart && currentTurnRecord(selectionAtStart.selectionId).selectionId !== selectionAtStart.selectionId) return
2113
2315
  const roots = Array.isArray(parsed.workspace_roots) ? parsed.workspace_roots : []
2114
2316
  const editLitmusDir = resolveAssessmentDir(parsed, roots, effectiveTool)
2115
2317
  if (!editLitmusDir || sessionOverMarked(editLitmusDir)) return
2116
- recordCursorFileEdit(parsed, parsed.session_id || parsed.conversation_id || null,
2318
+ recordCursorFileEdit(parsed, selectionAtStart?.selectionId || parsed.session_id || parsed.conversation_id || null,
2117
2319
  path.dirname(editLitmusDir))
2118
2320
  return
2119
2321
  }
@@ -2124,15 +2326,17 @@ async function main() {
2124
2326
  let responseMeta = null
2125
2327
  // ENG-2793: the entry this reply ends on, recorded once the reply is written.
2126
2328
  let repliedEntry = null
2329
+ const responseBoundary = selectionAtStart && responseEvent ? currentTurnRecord(selectionAtStart.selectionId).transcriptBoundary : null
2330
+ const matchingBoundary = responseBoundary?.file === parsed?.transcript_path ? responseBoundary : null
2127
2331
  if (responseEvent) {
2128
- const extracted = extractResponse(parsed, effectiveTool)
2332
+ const extracted = extractResponse(parsed, effectiveTool, selectionAtStart ? { boundary: matchingBoundary, inlineOnly: !matchingBoundary } : {})
2129
2333
  content = extracted.text
2130
2334
  sessionId = extracted.sessionId
2131
2335
  workspaceRoots = extracted.workspaceRoots || []
2132
2336
  responseMeta = extracted.meta || null
2133
2337
  const blocks = extracted.blocks
2134
2338
  if (blocks && blocks.length && sessionId && !selftestNonce) {
2135
- const unsent = unsentBlocks(blocks, lastRepliedEntry(sessionId))
2339
+ const unsent = unsentBlocks(blocks, lastRepliedEntry(selectionAtStart?.selectionId || sessionId))
2136
2340
  content = unsent.length ? unsent.map((b) => b.text).join("\n\n") : null
2137
2341
  repliedEntry = blocks[blocks.length - 1].id
2138
2342
  }
@@ -2146,25 +2350,26 @@ async function main() {
2146
2350
  // isSystemInjectedPrompt.
2147
2351
  if (isSystemInjectedPrompt(content)) return
2148
2352
  }
2353
+ const litmusDir = resolveAssessmentDir(parsed, workspaceRoots, effectiveTool, !!selftestNonce)
2354
+ if (!litmusDir) return
2355
+ if (hostedAtStart && hostedCaptureWindow()?.litmusDir !== hostedAtStart.litmusDir) return
2356
+ if (litmusDir !== earlyLitmusDir && sessionOverMarked(litmusDir)) return
2357
+ const captureToken = readConfig(litmusDir)?.token
2358
+ const knownCaptureTokens = captureKnownTokens(captureToken)
2149
2359
  let toolTrace = null
2150
2360
  const cursorResultsDir = responseEvent && effectiveTool === "cursor" && !selftestNonce
2151
2361
  ? cursorResultScope({ session_id: sessionId }, hostedAtStart) : null
2152
2362
  if (responseEvent && !selftestNonce && typeof parsed?.transcript_path === "string"
2153
- && (hostedWorkspaceHome || hostedAtStart?.disclosureVersion === "hosted_local_v2")) {
2154
- try { toolTrace = parseToolEvidence(readTranscriptRaw(parsed.transcript_path), effectiveTool) }
2363
+ && (hostedWorkspaceHome || hostedAtStart?.disclosureVersion === "hosted_local_v2" || (selectionAtStart && matchingBoundary))) {
2364
+ try { toolTrace = parseToolEvidence(readTranscriptRaw(parsed.transcript_path, undefined, matchingBoundary?.offset ?? 0, matchingBoundary?.identity), effectiveTool, knownCaptureTokens) }
2155
2365
  catch { toolTrace = { version: 1, records: [], complete: false, reason: "transcript_unavailable", dropped: 0 } }
2156
2366
  }
2157
- if (responseEvent && effectiveTool === "cursor" && !selftestNonce && hostedAtStart?.disclosureVersion === "hosted_local_v2") {
2367
+ if (responseEvent && effectiveTool === "cursor" && !selftestNonce && ["hosted_local_v2", SELECTED_CAPTURE_DISCLOSURE].includes(hostedAtStart?.disclosureVersion)) {
2158
2368
  toolTrace = cursorHookToolTrace(toolTrace, readCursorToolResults(sessionId, hostedAtStart, cursorResultsDir))
2159
2369
  }
2160
2370
  if (!content && !toolTrace?.records?.length) return
2161
2371
  content = content || ""
2162
2372
 
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
2373
  // Claim as LATE as possible — only once we know we have content and somewhere
2169
2374
  // to put it. Claiming earlier would let an invocation that then bails (no
2170
2375
  // content, no assessment in scope) consume the claim and silence the sibling
@@ -2172,13 +2377,17 @@ async function main() {
2172
2377
  // (generation_id is per assistant message, but a prompt and its response
2173
2378
  // could conceivably share one) so the two kinds never contend.
2174
2379
  if (cursorShaped && parsed && parsed.generation_id) {
2175
- const claimKey = responseEvent ? `${parsed.generation_id}.resp` : parsed.generation_id
2380
+ const generationKey = selectionAtStart ? `${selectionAtStart.selectionId}:${parsed.generation_id}` : parsed.generation_id
2381
+ const claimKey = responseEvent ? `${generationKey}.resp` : generationKey
2176
2382
  if (!claimPrompt(claimKey)) {
2177
2383
  return // the sibling hook is writing this same event
2178
2384
  }
2179
2385
  }
2180
2386
 
2181
2387
  const fullCursorPrompt = !responseEvent && effectiveTool === "cursor"
2388
+ // Redact the full body first: clipping a credential at a character limit
2389
+ // would otherwise prevent exact-value recognition in the final event pass.
2390
+ content = redactCaptureText(content, knownCaptureTokens)
2182
2391
  const maxLength = fullCursorPrompt ? Infinity : responseEvent ? MAX_RESPONSE_LENGTH : MAX_PROMPT_LENGTH
2183
2392
  const truncated = content.length > maxLength
2184
2393
  ? content.slice(0, maxLength) + "...[truncated]"
@@ -2186,8 +2395,9 @@ async function main() {
2186
2395
 
2187
2396
  // Pair the two invocations: a prompt opens a turn, its response inherits the
2188
2397
  // 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)
2398
+ const storageKey = selectionAtStart?.selectionId || sessionId
2399
+ const turnRecord = responseEvent && !selftestNonce ? currentTurnRecord(storageKey) : null
2400
+ const turnId = selftestNonce ? null : responseEvent ? turnRecord.turnId : startTurn(storageKey, parsed?.generation_id, selectionAtStart?.selectionId, selectionAtStart ? captureTranscriptBoundary(parsed?.transcript_path) : null)
2191
2401
 
2192
2402
  const event = selftestNonce
2193
2403
  ? {
@@ -2230,6 +2440,7 @@ async function main() {
2230
2440
  if (hostedAtStart) {
2231
2441
  event.capture_location = "local"
2232
2442
  event.capture_receipt = hostedAtStart.receipt
2443
+ if (selectionAtStart && !selftestNonce) event.capture_selection_id = selectionAtStart.selectionId
2233
2444
  event.ts = new Date(hostedCapturedAt).toISOString()
2234
2445
  }
2235
2446
  if (sessionId) event.sessionId = sessionId
@@ -2239,7 +2450,7 @@ async function main() {
2239
2450
  // the byte-cap loop, like the metering, so the body is trimmed around it.
2240
2451
  let editLedger = null
2241
2452
  if (responseEvent && effectiveTool === "cursor" && !selftestNonce) {
2242
- editLedger = takeCursorFileEdits(sessionId, turnRecord ? turnRecord.ts : null)
2453
+ editLedger = takeCursorFileEdits(storageKey, turnRecord ? turnRecord.ts : null)
2243
2454
  if (editLedger) event.file_writes = editLedger.writes
2244
2455
  }
2245
2456
  if (toolTrace) event.tool_calls = { trace: toolTrace }
@@ -2262,6 +2473,7 @@ async function main() {
2262
2473
  // Preserve complete Cursor prompts in both the file and upload lanes. Other
2263
2474
  // bodies keep their existing serialized budget; the server's size filter is
2264
2475
  // still the final storage bound.
2476
+ sanitizeCaptureEvent(event, captureToken)
2265
2477
  const MAX_SERIALIZED_BYTES = 60000
2266
2478
  const bodyField = responseEvent ? "text" : "prompt"
2267
2479
  if (!fullCursorPrompt) trimEventToBytes(event, bodyField, MAX_SERIALIZED_BYTES, toolTrace ? storageBytes : undefined)
@@ -2270,11 +2482,12 @@ async function main() {
2270
2482
  // Record that this turn's reply is captured, so the sibling `stop` hook
2271
2483
  // doesn't record it a second time (IDE only — see the claim helpers).
2272
2484
  if (responseEvent && effectiveTool === "cursor" && parsed.hook_event_name === "afterAgentResponse") {
2273
- markCursorResponseCaptured(cursorConversation)
2485
+ markCursorResponseCaptured(selectionAtStart?.selectionId || cursorConversation)
2274
2486
  }
2275
2487
 
2276
2488
  // Recheck after transcript reads/settling: teardown may have happened meanwhile.
2277
2489
  if (hostedAtStart && hostedCaptureWindow()?.litmusDir !== litmusDir) return
2490
+ if (selectionAtStart && selectedHostedConversation(hostedCaptureWindow(), effectiveTool, sessionId)?.selectionId !== selectionAtStart.selectionId) return
2278
2491
 
2279
2492
  // 1. Append to activity.jsonl (for submission ZIP)
2280
2493
  const logPath = path.join(litmusDir, "activity.jsonl")
@@ -2289,7 +2502,7 @@ async function main() {
2289
2502
  // ENG-2793: the next Stop starts after this reply only once a copy of it is
2290
2503
  // on disk. The drain and the upload report no outcome, so a reply whose append
2291
2504
  // failed is sent again by the next Stop, and the report folds the repeat.
2292
- if (repliedEntry && logged) recordRepliedEntry(sessionId, repliedEntry)
2505
+ if (repliedEntry && logged) recordRepliedEntry(storageKey, repliedEntry)
2293
2506
  // ENG-2344: the edits this reply carries leave the ledger only now that the
2294
2507
  // reply is on disk. An append that failed hands them back for the next reply.
2295
2508
  if (editLedger) {
@@ -2426,8 +2639,23 @@ function storageBytes(value) {
2426
2639
 
2427
2640
  const MAX_RECORDS = 128
2428
2641
  const MAX_BYTES = 48000
2429
- function boundedText(value, cap) {
2430
- const full = typeof value === 'string' ? value : JSON.stringify(value ?? null)
2642
+ function boundedText(value, cap, known = []) {
2643
+ // Codex supplies JSON arguments as a STRING, while Claude supplies an object.
2644
+ // Scrub credential keys in either form before stringification or clipping.
2645
+ // Preserve a harmless JSON string's formatting when it needs no redaction.
2646
+ let scrubbed = value
2647
+ if (typeof value === "string") {
2648
+ let parsed
2649
+ try { parsed = JSON.parse(value) } catch { /* ordinary tool output is not necessarily JSON */ }
2650
+ if (parsed && typeof parsed === "object") {
2651
+ const safe = scrubCaptureContent(parsed, known)
2652
+ if (JSON.stringify(safe) !== JSON.stringify(parsed)) scrubbed = JSON.stringify(safe)
2653
+ }
2654
+ }
2655
+ scrubbed = scrubCaptureContent(scrubbed, known)
2656
+ // Hashes/byte counts describe the sanitized evidence, never a retained raw
2657
+ // secret. Both transcript and post-tool-hook writers use this same order.
2658
+ const full = typeof scrubbed === 'string' ? scrubbed : JSON.stringify(scrubbed ?? null)
2431
2659
  let text = full
2432
2660
  while (storageBytes(text) > cap) text = text.slice(0, Math.floor(text.length * 0.9))
2433
2661
  if (text && /[\uD800-\uDBFF]$/.test(text)) text = text.slice(0, -1)
@@ -2436,7 +2664,7 @@ function boundedText(value, cap) {
2436
2664
 
2437
2665
  /** Only the final genuine user turn is in scope. A bounded tail without its
2438
2666
  * boundary is unavailable, never a license to import historical tool output. */
2439
- function parseToolEvidence(raw, tool) {
2667
+ function parseToolEvidence(raw, tool, known = []) {
2440
2668
  let records = [], boundary = false, seen = new Set(), dropped = 0
2441
2669
  for (const [lineIndex, line] of raw.split('\n').entries()) {
2442
2670
  let row
@@ -2475,7 +2703,7 @@ function parseToolEvidence(raw, tool) {
2475
2703
  seen.add(key)
2476
2704
  if (records.length >= MAX_RECORDS) { dropped++; continue }
2477
2705
  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) })
2706
+ 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
2707
  }
2480
2708
  }
2481
2709
  while (storageBytes(records) > MAX_BYTES) { records.pop(); dropped++ }
@@ -2514,30 +2742,36 @@ function finishCursorToolResults(dir) {
2514
2742
  pruneCursorToolResults()
2515
2743
  }
2516
2744
  function cursorResultScope(data, window) {
2517
- if (!window || window.disclosureVersion !== "hosted_local_v2") return null
2745
+ if (!window || !["hosted_local_v2", SELECTED_CAPTURE_DISCLOSURE].includes(window.disclosureVersion)) return null
2518
2746
  const session = data?.session_id || data?.conversation_id
2519
- const turn = currentTurnRecord(session)
2747
+ const turn = currentTurnRecord(hostedTurnStorageKey(window, "cursor", session))
2520
2748
  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")
2749
+ const key = crypto.createHash("sha256").update(JSON.stringify([session, turn.turnId, window.startedAt, window.litmusDir, ...(turn.selectionId ? [turn.selectionId] : [])])).digest("hex")
2522
2750
  return path.join(cursorResultsRoot(), key)
2523
2751
  }
2524
2752
  function recordCursorToolResult(data, window) {
2525
2753
  pruneCursorToolResults()
2526
2754
  const dir = cursorResultScope(data, window)
2527
2755
  const failed = data?.hook_event_name === "postToolUseFailure"
2528
- const observed = currentTurnRecord(data?.session_id || data?.conversation_id)
2756
+ const session = data?.session_id || data?.conversation_id
2757
+ const selected = selectedHostedConversation(window, "cursor", session)
2758
+ const observed = currentTurnRecord(hostedTurnStorageKey(window, "cursor", session))
2759
+ if (window?.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
2760
+ && (!selected || observed.selectionId !== selected.selectionId || observed.ts < selected.selectedAt)) return false
2529
2761
  if (!observed.generationId || data?.generation_id !== observed.generationId) return false
2530
2762
  if (!dir || typeof data.tool_use_id !== "string" || !data.tool_use_id || data.tool_use_id.length > 128
2531
2763
  || typeof data.tool_name !== "string" || !data.tool_name || data.tool_name.length > 128
2532
2764
  || data.tool_input === undefined
2533
2765
  || (failed ? typeof data.error_message !== "string" : data.tool_output === undefined)) return false
2534
2766
  const id = data.tool_use_id
2767
+ const known = captureKnownTokens(window.litmusDir ? readConfig(window.litmusDir)?.token : undefined)
2535
2768
  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) },
2769
+ { kind: "call", id, name: data.tool_name, input: boundedText(data.tool_input, 40000, known) },
2770
+ { kind: "result", id, ...(failed ? { ok: false } : {}), output: boundedText(failed ? data.error_message : data.tool_output, 40000, known) },
2538
2771
  ]
2539
2772
  let tmp
2540
2773
  try {
2774
+ if (selected && selectedHostedConversation(hostedCaptureWindow(), "cursor", session)?.selectionId !== selected.selectionId) return false
2541
2775
  if (fs.existsSync(dir + ".done")) return false
2542
2776
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
2543
2777
  if (fs.readdirSync(dir).filter(n => n.endsWith(".json")).length >= MAX_RECORDS / 2) return false
@@ -2613,6 +2847,17 @@ function cursorHookToolTrace(transcript, hookRecords) {
2613
2847
 
2614
2848
  // Exported for unit tests only; every hook invocation runs this file directly.
2615
2849
  module.exports = {
2850
+ sanitizeCaptureEvent,
2851
+ captureConversationKey,
2852
+ validCaptureConversationIdentity,
2853
+ readCaptureConversationSelection,
2854
+ selectedHostedConversation,
2855
+ captureSelectionDigest,
2856
+ captureKnownTokens,
2857
+ redactCaptureText,
2858
+ scrubCaptureContent,
2859
+ CAPTURE_CREDENTIAL_PATTERNS,
2860
+ CAPTURE_CREDENTIAL_KEYS,
2616
2861
  recordCursorToolResult,
2617
2862
  readCursorToolResults,
2618
2863
  cursorHookToolTrace,