litmus-cli 1.5.0-beta.9 → 1.5.1
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.
- package/README.md +14 -2
- package/dist/commands/capture.d.ts +10 -0
- package/dist/commands/capture.d.ts.map +1 -0
- package/dist/commands/capture.js +83 -0
- package/dist/commands/capture.js.map +1 -0
- package/dist/commands/connect.d.ts +8 -1
- package/dist/commands/connect.d.ts.map +1 -1
- package/dist/commands/connect.js +44 -10
- package/dist/commands/connect.js.map +1 -1
- package/dist/cursor-session/package.json +1 -1
- package/dist/cursor-session/session.cjs +12 -2
- package/dist/lib/capture-conversation-catalog.d.ts +3 -0
- package/dist/lib/capture-conversation-catalog.d.ts.map +1 -0
- package/dist/lib/capture-conversation-catalog.js +56 -0
- package/dist/lib/capture-conversation-catalog.js.map +1 -0
- package/dist/lib/capture-conversations.d.ts +63 -0
- package/dist/lib/capture-conversations.d.ts.map +1 -0
- package/dist/lib/capture-conversations.js +114 -0
- package/dist/lib/capture-conversations.js.map +1 -0
- package/dist/lib/capture-network.d.ts +24 -0
- package/dist/lib/capture-network.d.ts.map +1 -0
- package/dist/lib/capture-network.js +84 -0
- package/dist/lib/capture-network.js.map +1 -0
- package/dist/lib/capture-selection-server.d.ts +19 -0
- package/dist/lib/capture-selection-server.d.ts.map +1 -0
- package/dist/lib/capture-selection-server.js +212 -0
- package/dist/lib/capture-selection-server.js.map +1 -0
- package/dist/lib/capture-startup-diagnostics.d.ts.map +1 -1
- package/dist/lib/capture-startup-diagnostics.js +3 -1
- package/dist/lib/capture-startup-diagnostics.js.map +1 -1
- package/dist/lib/cursor-session.d.ts +10 -0
- package/dist/lib/cursor-session.d.ts.map +1 -1
- package/dist/lib/cursor-session.js +87 -10
- package/dist/lib/cursor-session.js.map +1 -1
- package/dist/lib/detection.d.ts +2 -1
- package/dist/lib/detection.d.ts.map +1 -1
- package/dist/lib/detection.js +2 -1
- package/dist/lib/detection.js.map +1 -1
- package/dist/lib/hook-logger.cjs +546 -89
- package/dist/lib/hosted-capture.d.ts +4 -3
- package/dist/lib/hosted-capture.d.ts.map +1 -1
- package/dist/lib/hosted-capture.js +52 -25
- package/dist/lib/hosted-capture.js.map +1 -1
- package/dist/lib/hosted-transcripts.d.ts +8 -1
- package/dist/lib/hosted-transcripts.d.ts.map +1 -1
- package/dist/lib/hosted-transcripts.js +89 -21
- package/dist/lib/hosted-transcripts.js.map +1 -1
- package/dist/lib/hosted-watcher.js +28 -4
- package/dist/lib/hosted-watcher.js.map +1 -1
- package/dist/lib/platform.d.ts +5 -2
- package/dist/lib/platform.d.ts.map +1 -1
- package/dist/lib/platform.js +16 -8
- package/dist/lib/platform.js.map +1 -1
- package/dist/lib/portal-launcher.d.ts +3 -0
- package/dist/lib/portal-launcher.d.ts.map +1 -1
- package/dist/lib/portal-launcher.js +40 -9
- package/dist/lib/portal-launcher.js.map +1 -1
- package/dist/lib/practice-handoff.d.ts.map +1 -1
- package/dist/lib/practice-handoff.js +4 -3
- package/dist/lib/practice-handoff.js.map +1 -1
- package/dist/lib/selected-capture-control.d.ts +15 -0
- package/dist/lib/selected-capture-control.d.ts.map +1 -0
- package/dist/lib/selected-capture-control.js +86 -0
- package/dist/lib/selected-capture-control.js.map +1 -0
- package/dist/lib/selected-capture-lease.d.ts +13 -0
- package/dist/lib/selected-capture-lease.d.ts.map +1 -0
- package/dist/lib/selected-capture-lease.js +22 -0
- package/dist/lib/selected-capture-lease.js.map +1 -0
- package/dist/lib/windows-process-scan.d.ts +11 -0
- package/dist/lib/windows-process-scan.d.ts.map +1 -0
- package/dist/lib/windows-process-scan.js +96 -0
- package/dist/lib/windows-process-scan.js.map +1 -0
- package/dist/lib/zip.d.ts.map +1 -1
- package/dist/lib/zip.js +21 -2
- package/dist/lib/zip.js.map +1 -1
- package/dist/program.js +14 -0
- package/dist/program.js.map +1 -1
- package/package.json +1 -1
package/dist/lib/hook-logger.cjs
CHANGED
|
@@ -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
|
*
|
|
@@ -809,6 +902,9 @@ function buildDrainFrame(event, hookEventName) {
|
|
|
809
902
|
for (const k of ["model", "input_tokens", "output_tokens", "cache_read_tokens", "status"]) {
|
|
810
903
|
if (event[k] !== undefined) frame[k] = event[k]
|
|
811
904
|
}
|
|
905
|
+
// ENG-4156: where a prompt's words came from, and a reply whose prompt never arrived.
|
|
906
|
+
if (event.recoveredFrom === "cursor_transcript") frame.recoveredFrom = event.recoveredFrom
|
|
907
|
+
if (event.promptMissing === true) frame.promptMissing = true
|
|
812
908
|
// ENG-2344: the files Cursor's own `afterFileEdit` hook reported the agent
|
|
813
909
|
// editing on this turn, in ENG-2191's `file_writes` shape. Carried whole
|
|
814
910
|
// ahead of the body: the attribution is the part of this record a reader
|
|
@@ -836,9 +932,10 @@ function buildDrainFrame(event, hookEventName) {
|
|
|
836
932
|
frame.text = body
|
|
837
933
|
if (!trimEventToBytes(frame, "text", MAX_DRAIN_FRAME_BYTES)) return null
|
|
838
934
|
}
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
935
|
+
// Trimmed to nothing: a husk with a turn id and no content reads downstream as
|
|
936
|
+
// a captured prompt that said nothing. Send no frame. A stopped Cursor turn
|
|
937
|
+
// (ENG-4157) never had a body; its status is the content.
|
|
938
|
+
if (!frame.text && (body || !cursorStopStatus(event))) return null
|
|
842
939
|
if (frame.text !== body) frame.textTruncated = true
|
|
843
940
|
return JSON.stringify(frame)
|
|
844
941
|
}
|
|
@@ -1003,31 +1100,24 @@ function isResponseEvent(data) {
|
|
|
1003
1100
|
return RESPONSE_HOOK_EVENTS.has(data.hook_event_name)
|
|
1004
1101
|
}
|
|
1005
1102
|
|
|
1006
|
-
function readTranscriptRaw(transcriptPath, endOffset) {
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
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")
|
|
1103
|
+
function readTranscriptRaw(transcriptPath, endOffset, startOffset = 0, expectedIdentity) {
|
|
1104
|
+
if (!Number.isSafeInteger(startOffset) || startOffset < 0) throw new Error("Invalid transcript boundary")
|
|
1105
|
+
if (fs.lstatSync(transcriptPath).isSymbolicLink()) throw new Error("Transcript symlink refused")
|
|
1106
|
+
const fd = fs.openSync(transcriptPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0))
|
|
1107
|
+
try {
|
|
1108
|
+
const stat = fs.fstatSync(fd)
|
|
1109
|
+
if (!stat.isFile() || (expectedIdentity && `${stat.dev}:${stat.ino}` !== expectedIdentity)) throw new Error("Transcript changed")
|
|
1110
|
+
const end = Number.isSafeInteger(endOffset) ? Math.min(stat.size, Math.max(0, endOffset)) : stat.size
|
|
1111
|
+
if (end < startOffset) throw new Error("Transcript truncated")
|
|
1112
|
+
const tail = end - startOffset > MAX_TRANSCRIPT_BYTES
|
|
1113
|
+
const start = tail ? Math.max(startOffset, end - TRANSCRIPT_TAIL_BYTES) : startOffset
|
|
1114
|
+
const buffer = Buffer.alloc(end - start)
|
|
1115
|
+
const count = fs.readSync(fd, buffer, 0, buffer.length, start)
|
|
1116
|
+
let raw = buffer.subarray(0, count).toString("utf8")
|
|
1117
|
+
// A bounded tail can start in the middle of a record. Never parse it.
|
|
1118
|
+
if (tail) { const newline = raw.indexOf("\n"); raw = newline < 0 ? "" : raw.slice(newline + 1) }
|
|
1119
|
+
return raw
|
|
1120
|
+
} finally { fs.closeSync(fd) }
|
|
1031
1121
|
}
|
|
1032
1122
|
|
|
1033
1123
|
/**
|
|
@@ -1119,7 +1209,7 @@ function parseClaudeTranscript(raw) {
|
|
|
1119
1209
|
*/
|
|
1120
1210
|
const TRANSCRIPT_STABLE_READS = 2
|
|
1121
1211
|
|
|
1122
|
-
function readSettledTranscript(transcriptPath, parse) {
|
|
1212
|
+
function readSettledTranscript(transcriptPath, parse, boundary) {
|
|
1123
1213
|
if (typeof transcriptPath !== "string" || !transcriptPath) return null
|
|
1124
1214
|
const deadline = Date.now() + TRANSCRIPT_SETTLE_MS
|
|
1125
1215
|
let lastSize = -1
|
|
@@ -1129,12 +1219,13 @@ function readSettledTranscript(transcriptPath, parse) {
|
|
|
1129
1219
|
for (;;) {
|
|
1130
1220
|
let raw
|
|
1131
1221
|
try {
|
|
1132
|
-
raw = readTranscriptRaw(transcriptPath)
|
|
1222
|
+
raw = readTranscriptRaw(transcriptPath, undefined, boundary?.offset ?? 0, boundary?.identity)
|
|
1133
1223
|
} catch {
|
|
1134
1224
|
return best // vanished or unreadable — keep whatever we already had
|
|
1135
1225
|
}
|
|
1136
1226
|
const text = parse(raw)
|
|
1137
1227
|
if (text) best = text
|
|
1228
|
+
else if (text === false) best = null // the reader saw the answer withdrawn (ENG-4157)
|
|
1138
1229
|
|
|
1139
1230
|
if (raw.length === lastSize) {
|
|
1140
1231
|
stable += 1
|
|
@@ -1153,11 +1244,11 @@ function readSettledTranscript(transcriptPath, parse) {
|
|
|
1153
1244
|
|
|
1154
1245
|
// The whole parse, not just its text: `blocks` carries each block's entry id,
|
|
1155
1246
|
// which is what lets a later Stop send only what this one did not (ENG-2793).
|
|
1156
|
-
function readClaudeTranscriptResponse(transcriptPath) {
|
|
1247
|
+
function readClaudeTranscriptResponse(transcriptPath, boundary) {
|
|
1157
1248
|
return readSettledTranscript(transcriptPath, (raw) => {
|
|
1158
1249
|
const parsed = parseClaudeTranscript(raw)
|
|
1159
1250
|
return parsed.text ? parsed : null
|
|
1160
|
-
})
|
|
1251
|
+
}, boundary)
|
|
1161
1252
|
}
|
|
1162
1253
|
|
|
1163
1254
|
/**
|
|
@@ -1250,15 +1341,30 @@ function readCopilotTranscriptResponse(transcriptPath) {
|
|
|
1250
1341
|
function parseCursorTranscript(raw) {
|
|
1251
1342
|
let lastAnswer = null
|
|
1252
1343
|
let tail = null
|
|
1344
|
+
// ENG-4157: Cursor closes every turn with `{type:"turn_ended", status}`, and
|
|
1345
|
+
// writes a stopped turn's marker BEFORE its user line (measured across this
|
|
1346
|
+
// machine's IDE transcripts: `A turn_ended:success turn_ended:error … U U`).
|
|
1347
|
+
// So anything after a closed turn, without a user line, is a new turn.
|
|
1348
|
+
let closed = false
|
|
1349
|
+
let endedEmpty = false
|
|
1253
1350
|
for (const line of raw.split("\n")) {
|
|
1254
1351
|
const trimmed = line.trim()
|
|
1255
1352
|
if (!trimmed) continue
|
|
1256
1353
|
let entry
|
|
1257
1354
|
try { entry = JSON.parse(trimmed) } catch { continue }
|
|
1355
|
+
if (entry && entry.type === "turn_ended") {
|
|
1356
|
+
if (closed) { lastAnswer = null; endedEmpty = true } // a turn that ended with nothing in it
|
|
1357
|
+
closed = true
|
|
1358
|
+
continue
|
|
1359
|
+
}
|
|
1360
|
+
endedEmpty = false
|
|
1258
1361
|
if (!entry || typeof entry !== "object" || !entry.message) continue
|
|
1259
1362
|
const content = entry.message.content
|
|
1260
|
-
if (entry.role === "user") {
|
|
1363
|
+
if (entry.role === "user" || closed) {
|
|
1261
1364
|
lastAnswer = null // new turn — discard the previous turn's answer
|
|
1365
|
+
closed = false
|
|
1366
|
+
}
|
|
1367
|
+
if (entry.role === "user") {
|
|
1262
1368
|
tail = "prompt"
|
|
1263
1369
|
continue
|
|
1264
1370
|
}
|
|
@@ -1274,13 +1380,18 @@ function parseCursorTranscript(raw) {
|
|
|
1274
1380
|
tail = "tool"
|
|
1275
1381
|
}
|
|
1276
1382
|
}
|
|
1277
|
-
return { text: lastAnswer, tailComplete: tail === "text" }
|
|
1383
|
+
return { text: lastAnswer, tailComplete: tail === "text", endedEmpty }
|
|
1278
1384
|
}
|
|
1279
1385
|
|
|
1280
|
-
function readCursorTranscriptResponse(transcriptPath) {
|
|
1386
|
+
function readCursorTranscriptResponse(transcriptPath, boundary) {
|
|
1281
1387
|
// Cursor acknowledges `stop` can fire before the turn's last lines are
|
|
1282
|
-
// flushed, so wait for quiescence exactly like the Claude reader.
|
|
1283
|
-
|
|
1388
|
+
// flushed, so wait for quiescence exactly like the Claude reader. A read
|
|
1389
|
+
// that ends on a turn closed with nothing in it (a stopped turn's marker
|
|
1390
|
+
// landing mid-wait) withdraws any answer an earlier read found (ENG-4157).
|
|
1391
|
+
return readSettledTranscript(transcriptPath, raw => {
|
|
1392
|
+
const parsed = parseCursorTranscript(raw)
|
|
1393
|
+
return parsed.endedEmpty ? false : parsed.text
|
|
1394
|
+
}, boundary)
|
|
1284
1395
|
}
|
|
1285
1396
|
|
|
1286
1397
|
/**
|
|
@@ -1320,13 +1431,24 @@ function cursorTurnMeta(data) {
|
|
|
1320
1431
|
return Object.keys(meta).length ? meta : null
|
|
1321
1432
|
}
|
|
1322
1433
|
|
|
1434
|
+
/** A Cursor `stop` for a turn that did not complete. An absent status is the
|
|
1435
|
+
* older payload and keeps the old reading. */
|
|
1436
|
+
function cursorTurnStopped(data) {
|
|
1437
|
+
return data?.hook_event_name === "stop" && cursorStopStatus(data)
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
/** True for the statuses Cursor gives a turn that did not complete. */
|
|
1441
|
+
function cursorStopStatus(data) {
|
|
1442
|
+
return typeof data?.status === "string" && data.status !== "" && data.status !== "completed"
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1323
1445
|
/**
|
|
1324
1446
|
* Extract the assistant response from a post-response hook payload. Returns
|
|
1325
1447
|
* `{ text, sessionId }` with text=null when the payload carries no capturable
|
|
1326
1448
|
* response (e.g. a Cursor-translated Stop with no transcript, or a turn that
|
|
1327
1449
|
* produced no assistant text).
|
|
1328
1450
|
*/
|
|
1329
|
-
function extractResponse(data, toolName) {
|
|
1451
|
+
function extractResponse(data, toolName, options = {}) {
|
|
1330
1452
|
// Pick the reader from the payload's OWN event name before trusting
|
|
1331
1453
|
// `toolName`, because `toolName` is the relabeled tool (see effectiveTool in
|
|
1332
1454
|
// main) and the relabel can be wrong for a response.
|
|
@@ -1349,7 +1471,8 @@ function extractResponse(data, toolName) {
|
|
|
1349
1471
|
// Claude Code Stop payload: { session_id, transcript_path, cwd,
|
|
1350
1472
|
// hook_event_name, stop_hook_active }. The response text is not in the
|
|
1351
1473
|
// payload — read it from the transcript.
|
|
1352
|
-
|
|
1474
|
+
if (options.inlineOnly) return { text: typeof data.last_assistant_message === "string" ? data.last_assistant_message : null, sessionId: data.session_id || null }
|
|
1475
|
+
const parsed = readClaudeTranscriptResponse(data.transcript_path, options.boundary)
|
|
1353
1476
|
return {
|
|
1354
1477
|
text: parsed ? parsed.text : null,
|
|
1355
1478
|
blocks: parsed ? parsed.blocks : null,
|
|
@@ -1388,10 +1511,16 @@ function extractResponse(data, toolName) {
|
|
|
1388
1511
|
if (data.hook_event_name === "afterAgentResponse") {
|
|
1389
1512
|
return { ...common, text: typeof data.text === "string" && data.text ? data.text : null }
|
|
1390
1513
|
}
|
|
1514
|
+
// ENG-4157: a turn the candidate stopped (`aborted`) or that failed
|
|
1515
|
+
// (`error`, e.g. offline) has no answer of its own in the transcript yet,
|
|
1516
|
+
// so reading it returns the previous turn's. Neither takes a reply. A
|
|
1517
|
+
// stopped turn is recorded as stopped; a failed one records nothing, since
|
|
1518
|
+
// Cursor's "Try again" answers it later in the same turn.
|
|
1519
|
+
if (cursorTurnStopped(data)) return { ...common, text: null, stopped: data.status === "aborted" }
|
|
1391
1520
|
// `stop` is the CLI's only route: read the transcript it points at.
|
|
1392
1521
|
// Returns null when transcripts are disabled (privacy mode sends
|
|
1393
1522
|
// transcript_path: null), which is a capture gap, not an error.
|
|
1394
|
-
return { ...common, text: readCursorTranscriptResponse(data.transcript_path) }
|
|
1523
|
+
return { ...common, text: options.inlineOnly ? null : readCursorTranscriptResponse(data.transcript_path, options.boundary) }
|
|
1395
1524
|
}
|
|
1396
1525
|
case "copilot": {
|
|
1397
1526
|
// Copilot Stop (both surfaces, via the PascalCase config spelling):
|
|
@@ -1521,14 +1650,36 @@ function pruneTurns() {
|
|
|
1521
1650
|
} catch { /* no dir yet, or unreadable */ }
|
|
1522
1651
|
}
|
|
1523
1652
|
|
|
1653
|
+
// ENG-4156: the turn file also keeps digests of the session's recent prompts,
|
|
1654
|
+
// so a prompt recovered from Cursor's transcript is never one already captured.
|
|
1655
|
+
const RECENT_PROMPT_DIGESTS = 20
|
|
1656
|
+
|
|
1657
|
+
function promptDigest(text) {
|
|
1658
|
+
return crypto.createHash("sha256").update(String(text).replace(/\s+/g, " ").trim()).digest("hex")
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1524
1661
|
/** Mint + persist a turn id for this session's new prompt. */
|
|
1525
|
-
function
|
|
1662
|
+
function captureTranscriptBoundary(file) {
|
|
1663
|
+
if (typeof file !== "string" || !path.isAbsolute(file)) return null
|
|
1664
|
+
let fd
|
|
1665
|
+
try {
|
|
1666
|
+
if (fs.lstatSync(file).isSymbolicLink()) return null
|
|
1667
|
+
fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0))
|
|
1668
|
+
const stat = fs.fstatSync(fd)
|
|
1669
|
+
return stat.isFile() ? { file, offset: stat.size, identity: `${stat.dev}:${stat.ino}` } : null
|
|
1670
|
+
} catch { return null }
|
|
1671
|
+
finally { if (fd !== undefined) fs.closeSync(fd) }
|
|
1672
|
+
}
|
|
1673
|
+
function startTurn(sessionId, generationId, selectionId, transcriptBoundary, promptText, ts = Date.now()) {
|
|
1526
1674
|
if (!sessionId) return null
|
|
1527
1675
|
const turnId = crypto.randomUUID()
|
|
1528
1676
|
try {
|
|
1529
1677
|
fs.mkdirSync(TURNS_DIR, { recursive: true })
|
|
1530
1678
|
pruneTurns()
|
|
1531
|
-
|
|
1679
|
+
const prompts = typeof promptText === "string"
|
|
1680
|
+
? [...currentTurnRecord(sessionId).prompts, promptDigest(promptText)].slice(-RECENT_PROMPT_DIGESTS)
|
|
1681
|
+
: currentTurnRecord(sessionId).prompts
|
|
1682
|
+
fs.writeFileSync(turnFile(sessionId), JSON.stringify({ turnId, ts, ...(typeof generationId === "string" ? { generationId } : {}), ...(typeof selectionId === "string" ? { selectionId } : {}), ...(transcriptBoundary ? { transcriptBoundary } : {}), prompts }))
|
|
1532
1683
|
} catch {
|
|
1533
1684
|
// Unwritable — the event still gets its id, it just can't be paired with
|
|
1534
1685
|
// the response. Better an unpaired pair than a dropped prompt.
|
|
@@ -1544,19 +1695,58 @@ function currentTurn(sessionId) {
|
|
|
1544
1695
|
/** The most recent prompt's turn id AND the instant it was minted, so a
|
|
1545
1696
|
* ledger keyed on the session can be cut at the turn's start. */
|
|
1546
1697
|
function currentTurnRecord(sessionId) {
|
|
1547
|
-
if (!sessionId) return { turnId: null, ts: null }
|
|
1698
|
+
if (!sessionId) return { turnId: null, ts: null, prompts: [] }
|
|
1548
1699
|
try {
|
|
1549
1700
|
const data = JSON.parse(fs.readFileSync(turnFile(sessionId), "utf8"))
|
|
1550
1701
|
return {
|
|
1551
1702
|
generationId: typeof data.generationId === "string" ? data.generationId : null,
|
|
1703
|
+
transcriptBoundary: data.transcriptBoundary && typeof data.transcriptBoundary.file === "string"
|
|
1704
|
+
&& path.isAbsolute(data.transcriptBoundary.file) && Number.isSafeInteger(data.transcriptBoundary.offset)
|
|
1705
|
+
&& data.transcriptBoundary.offset >= 0 && typeof data.transcriptBoundary.identity === "string" ? data.transcriptBoundary : null,
|
|
1706
|
+
selectionId: typeof data.selectionId === "string" ? data.selectionId : null,
|
|
1552
1707
|
turnId: typeof data.turnId === "string" ? data.turnId : null,
|
|
1553
1708
|
ts: typeof data.ts === "number" && Number.isFinite(data.ts) ? data.ts : null,
|
|
1709
|
+
prompts: Array.isArray(data.prompts) ? data.prompts.filter(d => typeof d === "string") : [],
|
|
1710
|
+
// A turn file from a logger before ENG-4156 has no prompt history to compare against.
|
|
1711
|
+
promptHistory: Array.isArray(data.prompts),
|
|
1554
1712
|
}
|
|
1555
1713
|
} catch {
|
|
1556
|
-
return { turnId: null, ts: null }
|
|
1714
|
+
return { turnId: null, ts: null, prompts: [] }
|
|
1557
1715
|
}
|
|
1558
1716
|
}
|
|
1559
1717
|
|
|
1718
|
+
/** The open turn now answers to `generationId` too: Cursor's "Try again" resends
|
|
1719
|
+
* the same prompt under a new generation (ENG-4156). */
|
|
1720
|
+
function adoptGeneration(sessionId, generationId) {
|
|
1721
|
+
if (!sessionId || typeof generationId !== "string" || !generationId) return
|
|
1722
|
+
try {
|
|
1723
|
+
const data = JSON.parse(fs.readFileSync(turnFile(sessionId), "utf8"))
|
|
1724
|
+
fs.writeFileSync(turnFile(sessionId), JSON.stringify({ ...data, generationId }))
|
|
1725
|
+
} catch { /* no open turn: the reply pairs as it did before */ }
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1728
|
+
/**
|
|
1729
|
+
* The words of the newest user line in a Cursor transcript, or null (ENG-4156).
|
|
1730
|
+
* Cursor writes the typed prompt between `<user_query>` tags; a user line
|
|
1731
|
+
* without them is context Cursor added, not a prompt, so it yields null.
|
|
1732
|
+
*/
|
|
1733
|
+
function lastCursorUserQuery(transcriptPath, boundary) {
|
|
1734
|
+
if (typeof transcriptPath !== "string" || !transcriptPath) return null
|
|
1735
|
+
let raw
|
|
1736
|
+
try { raw = readTranscriptRaw(transcriptPath, undefined, boundary?.offset ?? 0, boundary?.identity) } catch { return null }
|
|
1737
|
+
let last = null
|
|
1738
|
+
for (const line of raw.split("\n")) {
|
|
1739
|
+
let entry
|
|
1740
|
+
try { entry = JSON.parse(line) } catch { continue }
|
|
1741
|
+
if (!entry || entry.role !== "user" || !Array.isArray(entry.message?.content)) continue
|
|
1742
|
+
const text = entry.message.content
|
|
1743
|
+
.filter(b => b && b.type === "text" && typeof b.text === "string").map(b => b.text).join("\n")
|
|
1744
|
+
const queries = [...text.matchAll(/<user_query>([\s\S]*?)<\/user_query>/g)]
|
|
1745
|
+
last = queries.length ? queries[queries.length - 1][1].trim() || null : null
|
|
1746
|
+
}
|
|
1747
|
+
return last
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1560
1750
|
// ── What a Stop has already sent (ENG-2793) ──────────────────────────
|
|
1561
1751
|
// The Claude and Copilot readers collect every assistant message since the last
|
|
1562
1752
|
// genuine user entry in the transcript. A Stop that fires again before one is
|
|
@@ -1858,22 +2048,29 @@ function pruneClaims() {
|
|
|
1858
2048
|
*/
|
|
1859
2049
|
const CURSOR_RESPONSE_CLAIM_TTL_MS = 5 * 60 * 1000
|
|
1860
2050
|
|
|
1861
|
-
|
|
2051
|
+
// The claim names the turn it captured (ENG-4157): a stopped turn's `stop` comes
|
|
2052
|
+
// with no `afterAgentResponse` of its own, so the previous turn's claim must not
|
|
2053
|
+
// silence it.
|
|
2054
|
+
function markCursorResponseCaptured(conversationId, turnId) {
|
|
1862
2055
|
if (!conversationId) return
|
|
1863
2056
|
try {
|
|
1864
2057
|
fs.mkdirSync(CLAIM_DIR, { recursive: true })
|
|
1865
2058
|
const safe = String(conversationId).replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 128)
|
|
1866
|
-
fs.writeFileSync(path.join(CLAIM_DIR, `cursor-resp-${safe}`),
|
|
2059
|
+
fs.writeFileSync(path.join(CLAIM_DIR, `cursor-resp-${safe}`), JSON.stringify({ turnId: turnId || null }))
|
|
1867
2060
|
} catch { /* best effort — a duplicate is better than a dropped response */ }
|
|
1868
2061
|
}
|
|
1869
2062
|
|
|
1870
|
-
/** True when a `stop` invocation should stand down (the IDE hook already captured
|
|
1871
|
-
|
|
2063
|
+
/** True when a `stop` invocation should stand down (the IDE hook already captured
|
|
2064
|
+
* this turn). A claim from before the turn field existed counts for any turn. */
|
|
2065
|
+
function cursorResponseAlreadyCaptured(conversationId, turnId) {
|
|
1872
2066
|
if (!conversationId) return false
|
|
1873
2067
|
try {
|
|
1874
2068
|
const safe = String(conversationId).replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 128)
|
|
1875
|
-
const
|
|
1876
|
-
|
|
2069
|
+
const file = path.join(CLAIM_DIR, `cursor-resp-${safe}`)
|
|
2070
|
+
if (Date.now() - fs.statSync(file).mtimeMs >= CURSOR_RESPONSE_CLAIM_TTL_MS) return false
|
|
2071
|
+
let claimed
|
|
2072
|
+
try { claimed = JSON.parse(fs.readFileSync(file, "utf8")) } catch { return true }
|
|
2073
|
+
return !claimed || typeof claimed !== "object" || !("turnId" in claimed) || claimed.turnId === (turnId || null)
|
|
1877
2074
|
} catch {
|
|
1878
2075
|
return false
|
|
1879
2076
|
}
|
|
@@ -1913,8 +2110,107 @@ function claimPrompt(generationId) {
|
|
|
1913
2110
|
* session's) and is the only pointer left once a copied explicit path has
|
|
1914
2111
|
* been rejected.
|
|
1915
2112
|
*/
|
|
1916
|
-
|
|
1917
|
-
|
|
2113
|
+
const SELECTED_CAPTURE_DISCLOSURE = "hosted_local_v3"
|
|
2114
|
+
function captureConversationKey(tool, sessionId) {
|
|
2115
|
+
return crypto.createHash("sha256").update(JSON.stringify([tool, sessionId])).digest("hex")
|
|
2116
|
+
}
|
|
2117
|
+
function validCaptureConversationIdentity(tool, sessionId) {
|
|
2118
|
+
return ["claude", "codex", "cursor", "gemini"].includes(tool) && typeof sessionId === "string"
|
|
2119
|
+
&& sessionId.length > 0 && Buffer.byteLength(sessionId) <= 128
|
|
2120
|
+
&& !/[\u0000-\u001f\u007f\uD800-\uDFFF]/u.test(sessionId)
|
|
2121
|
+
}
|
|
2122
|
+
function captureStopFile(projectDir, captureSetupId) {
|
|
2123
|
+
const key = crypto.createHash("sha256").update(captureSetupId).digest("hex")
|
|
2124
|
+
return path.join(projectDir, ".litmus", "capture-stops", `${key}.json`)
|
|
2125
|
+
}
|
|
2126
|
+
function readCaptureStopId(projectDir, captureSetupId) {
|
|
2127
|
+
let fd
|
|
2128
|
+
try {
|
|
2129
|
+
const file = captureStopFile(projectDir, captureSetupId)
|
|
2130
|
+
if (fs.lstatSync(file).isSymbolicLink()) return null
|
|
2131
|
+
fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0))
|
|
2132
|
+
const stat = fs.fstatSync(fd)
|
|
2133
|
+
if (!stat.isFile() || stat.size > 1024) return null
|
|
2134
|
+
const buffer = Buffer.alloc(1025), count = fs.readSync(fd, buffer, 0, buffer.length, 0)
|
|
2135
|
+
if (count > 1024) return null
|
|
2136
|
+
const value = JSON.parse(buffer.subarray(0, count).toString("utf8"))
|
|
2137
|
+
return value?.captureSetupId === captureSetupId && typeof value.stopId === "string"
|
|
2138
|
+
&& /^[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
|
|
2139
|
+
} catch (error) { return error?.code === "ENOENT" ? "" : null }
|
|
2140
|
+
finally { if (fd !== undefined) fs.closeSync(fd) }
|
|
2141
|
+
}
|
|
2142
|
+
function readCaptureConversationSelection(projectDir, captureSetupId) {
|
|
2143
|
+
const empty = { version: 1, captureSetupId, selected: [] }
|
|
2144
|
+
if (typeof captureSetupId !== "string" || !captureSetupId) return empty
|
|
2145
|
+
let fd
|
|
2146
|
+
try {
|
|
2147
|
+
const file = path.join(projectDir, ".litmus", "capture-selections.json")
|
|
2148
|
+
if (fs.lstatSync(file).isSymbolicLink()) return empty
|
|
2149
|
+
fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0))
|
|
2150
|
+
const stat = fs.fstatSync(fd)
|
|
2151
|
+
if (!stat.isFile() || stat.size > 32768) return empty
|
|
2152
|
+
const buffer = Buffer.alloc(32769), count = fs.readSync(fd, buffer, 0, buffer.length, 0)
|
|
2153
|
+
if (count > 32768) return empty
|
|
2154
|
+
const data = JSON.parse(buffer.subarray(0, count).toString("utf8"))
|
|
2155
|
+
const valid = row => row && validCaptureConversationIdentity(row.tool, row.sessionId)
|
|
2156
|
+
&& row.key === captureConversationKey(row.tool, row.sessionId)
|
|
2157
|
+
&& 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)
|
|
2158
|
+
&& Number.isFinite(row.selectedAt) && row.selectedAt >= 0
|
|
2159
|
+
&& (row.transcript === undefined || (row.transcript && typeof row.transcript.file === "string"
|
|
2160
|
+
&& path.isAbsolute(row.transcript.file) && Number.isSafeInteger(row.transcript.offset)
|
|
2161
|
+
&& row.transcript.offset >= 0 && typeof row.transcript.identity === "string"))
|
|
2162
|
+
if (data?.version !== 1 || data.captureSetupId !== captureSetupId || !Array.isArray(data.selected)
|
|
2163
|
+
|| data.selected.length > 8 || !data.selected.every(valid)
|
|
2164
|
+
|| new Set(data.selected.map(row => row.key)).size !== data.selected.length) return empty
|
|
2165
|
+
const stopId = readCaptureStopId(projectDir, captureSetupId)
|
|
2166
|
+
if (stopId === null || (data.stopId ?? "") !== stopId) return empty
|
|
2167
|
+
return data
|
|
2168
|
+
} catch { return empty }
|
|
2169
|
+
finally { if (fd !== undefined) fs.closeSync(fd) }
|
|
2170
|
+
}
|
|
2171
|
+
function captureSelectionDigest(selection) {
|
|
2172
|
+
const scopes = selection.selected.map(row => ({ tool: row.tool, sessionId: row.sessionId, selectionId: row.selectionId }))
|
|
2173
|
+
.sort((a, b) => a.tool < b.tool ? -1 : a.tool > b.tool ? 1 : a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0)
|
|
2174
|
+
return crypto.createHash("sha256").update(JSON.stringify(scopes)).digest("hex")
|
|
2175
|
+
}
|
|
2176
|
+
function selectedHostedConversation(window, tool, sessionId, now = Date.now()) {
|
|
2177
|
+
if (window?.disclosureVersion !== SELECTED_CAPTURE_DISCLOSURE || !validCaptureConversationIdentity(tool, sessionId)) return null
|
|
2178
|
+
const state = readCaptureConversationSelection(path.dirname(window.litmusDir), window.captureSetupId)
|
|
2179
|
+
return state.selected.find(row => row.tool === tool && row.sessionId === sessionId
|
|
2180
|
+
&& row.selectedAt >= window.startedAt && row.selectedAt <= now) || null
|
|
2181
|
+
}
|
|
2182
|
+
function hostedTurnStorageKey(window, tool, sessionId) {
|
|
2183
|
+
return window?.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
|
|
2184
|
+
? selectedHostedConversation(window, tool, sessionId)?.selectionId || null : sessionId
|
|
2185
|
+
}
|
|
2186
|
+
function recordHostedConversationCandidate(window, tool, sessionId, payload) {
|
|
2187
|
+
if (window?.disclosureVersion !== SELECTED_CAPTURE_DISCLOSURE || !validCaptureConversationIdentity(tool, sessionId)) return
|
|
2188
|
+
const dir = path.join(window.litmusDir, "conversation-candidates")
|
|
2189
|
+
const key = captureConversationKey(tool, sessionId)
|
|
2190
|
+
const location = typeof payload?.cwd === "string" ? payload.cwd
|
|
2191
|
+
: Array.isArray(payload?.workspace_roots) ? payload.workspace_roots.find(value => typeof value === "string") : ""
|
|
2192
|
+
const project = typeof location === "string" ? path.basename(location.replace(/\\/g, "/")).replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 120) : ""
|
|
2193
|
+
const record = { captureSetupId: window.captureSetupId, tool, sessionId, label: project ? `${tool} · ${project}` : `${tool} conversation`, lastActiveAt: Date.now() }
|
|
2194
|
+
let temporary
|
|
2195
|
+
try {
|
|
2196
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
2197
|
+
temporary = path.join(dir, `${key}.${crypto.randomUUID()}.tmp`)
|
|
2198
|
+
fs.writeFileSync(temporary, JSON.stringify(record), { mode: 0o600, flag: "wx" })
|
|
2199
|
+
fs.renameSync(temporary, path.join(dir, `${key}.json`))
|
|
2200
|
+
// Metadata only; never persist prompt/response/transcript_path from payload.
|
|
2201
|
+
const entries = fs.readdirSync(dir).filter(name => /^[a-f0-9]{64}\.json$/.test(name))
|
|
2202
|
+
if (entries.length > 128) {
|
|
2203
|
+
const selected = new Set(readCaptureConversationSelection(path.dirname(window.litmusDir), window.captureSetupId).selected.map(row => `${row.key}.json`))
|
|
2204
|
+
const removable = entries.filter(name => !selected.has(name))
|
|
2205
|
+
.map(name => ({ name, time: fs.lstatSync(path.join(dir, name)).mtimeMs })).sort((a, b) => a.time - b.time)
|
|
2206
|
+
for (const entry of removable.slice(0, entries.length - 128)) fs.unlinkSync(path.join(dir, entry.name))
|
|
2207
|
+
}
|
|
2208
|
+
} catch { /* A metadata failure must neither record a body nor break the AI tool. */ }
|
|
2209
|
+
finally { if (temporary) try { fs.unlinkSync(temporary) } catch {} }
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2212
|
+
// Legacy windows were computer-wide; v3 additionally requires an explicit
|
|
2213
|
+
// conversation selection. Expired authorization never falls back to credentials.
|
|
1918
2214
|
function hostedCaptureWindow(now = Date.now()) {
|
|
1919
2215
|
try {
|
|
1920
2216
|
const window = JSON.parse(fs.readFileSync(path.join(os.homedir(), ".litmus", "hosted-capture.json"), "utf8"))
|
|
@@ -1926,12 +2222,22 @@ function hostedCaptureWindow(now = Date.now()) {
|
|
|
1926
2222
|
const config = readConfig(dir)
|
|
1927
2223
|
if (!config || config.captureMode !== "hosted-local") return null
|
|
1928
2224
|
if (tokenDigest(config.token) !== window.tokenKey) return null
|
|
2225
|
+
if (window.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
|
|
2226
|
+
&& (!window.captureSetupId || window.captureSetupId !== config.captureSetupId
|
|
2227
|
+
|| window.selectionDigest !== captureSelectionDigest(readCaptureConversationSelection(window.projectDir, window.captureSetupId)))) return null
|
|
1929
2228
|
return { ...window, litmusDir: dir }
|
|
1930
2229
|
} catch { return null }
|
|
1931
2230
|
}
|
|
1932
2231
|
|
|
1933
2232
|
function ownedHostedTranscript(window, effectiveTool, id) {
|
|
1934
2233
|
if (!window || !id || !["claude", "codex"].includes(effectiveTool)) return null
|
|
2234
|
+
if (window.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE) {
|
|
2235
|
+
const selected = selectedHostedConversation(window, effectiveTool, id)
|
|
2236
|
+
// The chosen EOF boundary owns this transcript even before the observer's
|
|
2237
|
+
// next poll, so a hook cannot race it into writing a duplicate first turn.
|
|
2238
|
+
return selected?.transcript ? { ...selected.transcript, tool: effectiveTool, sessionId: id,
|
|
2239
|
+
selectionId: selected.selectionId } : null
|
|
2240
|
+
}
|
|
1935
2241
|
try {
|
|
1936
2242
|
const state = JSON.parse(fs.readFileSync(path.join(window.litmusDir, "transcript-observer.json"), "utf8"))
|
|
1937
2243
|
if (state.version !== 1 || state.startedAt !== window.startedAt) return null
|
|
@@ -1951,14 +2257,14 @@ function markHostedClaudeCompletion(window, cursor, parsed) {
|
|
|
1951
2257
|
const finalText = reply.blocks.filter(block => block.id === final?.id).map(block => block.text).join("\n")
|
|
1952
2258
|
if (typeof parsed.last_assistant_message === "string" && finalText !== parsed.last_assistant_message) return null
|
|
1953
2259
|
return final?.id || null
|
|
1954
|
-
})
|
|
2260
|
+
}, window.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE ? cursor : undefined)
|
|
1955
2261
|
if (!entryId || hostedCaptureWindow()?.litmusDir !== window.litmusDir) return
|
|
1956
2262
|
const dir = path.join(window.litmusDir, "transcript-completions")
|
|
1957
2263
|
if (fs.existsSync(dir + ".done")) return false
|
|
1958
2264
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
1959
2265
|
const key = crypto.createHash("sha256").update(JSON.stringify([cursor.sessionId])).digest("hex")
|
|
1960
2266
|
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 })
|
|
2267
|
+
fs.writeFileSync(temp, JSON.stringify({ startedAt: window.startedAt, completedAt: Date.now(), entryId, ...(cursor.selectionId ? { selectionId: cursor.selectionId } : {}) }), { mode: 0o600 })
|
|
1962
2268
|
fs.renameSync(temp, file)
|
|
1963
2269
|
} catch { /* completion metadata is best-effort; terminal transcript rows still work */ }
|
|
1964
2270
|
}
|
|
@@ -1967,7 +2273,11 @@ function resolveAssessmentDir(parsed, workspaceRoots, effectiveTool = tool, self
|
|
|
1967
2273
|
// Copilot retains its assessment-folder hook; it is outside the
|
|
1968
2274
|
// machine-wide disclosure and must never use that routing window.
|
|
1969
2275
|
const hosted = effectiveTool === "copilot" ? null : hostedCaptureWindow()
|
|
1970
|
-
if (hosted && !selftest)
|
|
2276
|
+
if (hosted && !selftest) {
|
|
2277
|
+
if (hosted.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
|
|
2278
|
+
&& !selectedHostedConversation(hosted, effectiveTool, parsed?.session_id || parsed?.sessionId || parsed?.conversation_id)) return null
|
|
2279
|
+
return hosted.litmusDir
|
|
2280
|
+
}
|
|
1971
2281
|
const sessionDirs = [
|
|
1972
2282
|
...(workspaceRoots || []),
|
|
1973
2283
|
...(parsed && typeof parsed.cwd === "string" && parsed.cwd ? [parsed.cwd] : []),
|
|
@@ -2037,6 +2347,13 @@ async function main() {
|
|
|
2037
2347
|
if (earlyLitmusDir && sessionOverMarked(earlyLitmusDir)) return
|
|
2038
2348
|
const hostedWindow = effectiveTool === "copilot" ? null : hostedCaptureWindow()
|
|
2039
2349
|
const hostedAtStart = selftestNonce && hostedWindow?.litmusDir !== earlyLitmusDir ? null : hostedWindow
|
|
2350
|
+
const nativeSessionId = parsed && (parsed.session_id || parsed.sessionId || parsed.conversation_id)
|
|
2351
|
+
const selectionAtStart = selectedHostedConversation(hostedAtStart, effectiveTool, nativeSessionId)
|
|
2352
|
+
if (hostedAtStart?.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE && !selftestNonce) {
|
|
2353
|
+
recordHostedConversationCandidate(hostedAtStart, effectiveTool, nativeSessionId, parsed)
|
|
2354
|
+
// Do not open transcripts, result caches, or edit ledgers for unselected chats.
|
|
2355
|
+
if (!selectionAtStart) return
|
|
2356
|
+
}
|
|
2040
2357
|
const owned = ownedHostedTranscript(hostedAtStart, effectiveTool, parsed && (parsed.session_id || parsed.sessionId))
|
|
2041
2358
|
if (owned && effectiveTool === "claude" && parsed?.hook_event_name === "Stop") {
|
|
2042
2359
|
markHostedClaudeCompletion(hostedAtStart, owned, parsed)
|
|
@@ -2051,8 +2368,9 @@ async function main() {
|
|
|
2051
2368
|
// read/import a transcript for a conversation that predates setup.
|
|
2052
2369
|
if (hostedAtStart && isResponseEvent(parsed)) {
|
|
2053
2370
|
const id = parsed && (parsed.session_id || parsed.sessionId || parsed.conversation_id)
|
|
2054
|
-
const turn = currentTurnRecord(id)
|
|
2371
|
+
const turn = currentTurnRecord(hostedTurnStorageKey(hostedAtStart, effectiveTool, id))
|
|
2055
2372
|
if (!turn || !turn.turnId || turn.ts < hostedAtStart.startedAt) return
|
|
2373
|
+
if (selectionAtStart && (turn.selectionId !== selectionAtStart.selectionId || turn.ts < selectionAtStart.selectedAt)) return
|
|
2056
2374
|
}
|
|
2057
2375
|
|
|
2058
2376
|
// ENG-2477: a capture SELF-TEST probe. `litmus init` (and `litmus doctor`)
|
|
@@ -2090,12 +2408,19 @@ async function main() {
|
|
|
2090
2408
|
// BEFORE the transcript read so the CLI-only path doesn't pay for a poll it
|
|
2091
2409
|
// is going to discard.
|
|
2092
2410
|
const cursorConversation = parsed && (parsed.conversation_id || parsed.session_id)
|
|
2411
|
+
let standDownUnlessNewTurn = false
|
|
2093
2412
|
if (
|
|
2094
2413
|
effectiveTool === "cursor"
|
|
2095
2414
|
&& parsed && parsed.hook_event_name === "stop"
|
|
2096
|
-
&& cursorResponseAlreadyCaptured(cursorConversation)
|
|
2415
|
+
&& cursorResponseAlreadyCaptured(selectionAtStart?.selectionId || cursorConversation, currentTurn(selectionAtStart?.selectionId || parsed.session_id || parsed.conversation_id))
|
|
2097
2416
|
) {
|
|
2098
|
-
|
|
2417
|
+
// ENG-4156: a stop under a generation the open turn never saw may end a turn
|
|
2418
|
+
// whose prompt hook never fired, and the claim it matched is the previous
|
|
2419
|
+
// turn's. The transcript decides (below) before it stands down.
|
|
2420
|
+
const open = currentTurnRecord(selectionAtStart?.selectionId || parsed.session_id || parsed.conversation_id)
|
|
2421
|
+
if (!(open.promptHistory && open.generationId && typeof parsed.generation_id === "string"
|
|
2422
|
+
&& parsed.generation_id && parsed.generation_id !== open.generationId)) return
|
|
2423
|
+
standDownUnlessNewTurn = true
|
|
2099
2424
|
}
|
|
2100
2425
|
|
|
2101
2426
|
// Cursor's transcript omits results. Its post-tool hooks carry the actual
|
|
@@ -2110,10 +2435,11 @@ async function main() {
|
|
|
2110
2435
|
// Gated on the same assessment resolution a prompt gets, so an edit in a
|
|
2111
2436
|
// project that is not the assessment is not written anywhere.
|
|
2112
2437
|
if (effectiveTool === "cursor" && parsed && parsed.hook_event_name === CURSOR_EDIT_EVENT) {
|
|
2438
|
+
if (selectionAtStart && currentTurnRecord(selectionAtStart.selectionId).selectionId !== selectionAtStart.selectionId) return
|
|
2113
2439
|
const roots = Array.isArray(parsed.workspace_roots) ? parsed.workspace_roots : []
|
|
2114
2440
|
const editLitmusDir = resolveAssessmentDir(parsed, roots, effectiveTool)
|
|
2115
2441
|
if (!editLitmusDir || sessionOverMarked(editLitmusDir)) return
|
|
2116
|
-
recordCursorFileEdit(parsed, parsed.session_id || parsed.conversation_id || null,
|
|
2442
|
+
recordCursorFileEdit(parsed, selectionAtStart?.selectionId || parsed.session_id || parsed.conversation_id || null,
|
|
2117
2443
|
path.dirname(editLitmusDir))
|
|
2118
2444
|
return
|
|
2119
2445
|
}
|
|
@@ -2122,17 +2448,24 @@ async function main() {
|
|
|
2122
2448
|
let sessionId = null
|
|
2123
2449
|
let workspaceRoots = []
|
|
2124
2450
|
let responseMeta = null
|
|
2451
|
+
let stoppedTurn = false
|
|
2125
2452
|
// ENG-2793: the entry this reply ends on, recorded once the reply is written.
|
|
2126
2453
|
let repliedEntry = null
|
|
2454
|
+
const responseBoundary = selectionAtStart && responseEvent ? currentTurnRecord(selectionAtStart.selectionId).transcriptBoundary : null
|
|
2455
|
+
const matchingBoundary = responseBoundary?.file === parsed?.transcript_path ? responseBoundary : null
|
|
2127
2456
|
if (responseEvent) {
|
|
2128
|
-
const extracted = extractResponse(parsed, effectiveTool)
|
|
2457
|
+
const extracted = extractResponse(parsed, effectiveTool, selectionAtStart ? { boundary: matchingBoundary, inlineOnly: !matchingBoundary } : {})
|
|
2129
2458
|
content = extracted.text
|
|
2130
2459
|
sessionId = extracted.sessionId
|
|
2131
2460
|
workspaceRoots = extracted.workspaceRoots || []
|
|
2132
2461
|
responseMeta = extracted.meta || null
|
|
2462
|
+
stoppedTurn = extracted.stopped === true
|
|
2463
|
+
// A failed turn records nothing, and leaves its saved tool results for the
|
|
2464
|
+
// reply its "Try again" brings, instead of sealing them here.
|
|
2465
|
+
if (effectiveTool === "cursor" && cursorTurnStopped(parsed) && !stoppedTurn) return
|
|
2133
2466
|
const blocks = extracted.blocks
|
|
2134
2467
|
if (blocks && blocks.length && sessionId && !selftestNonce) {
|
|
2135
|
-
const unsent = unsentBlocks(blocks, lastRepliedEntry(sessionId))
|
|
2468
|
+
const unsent = unsentBlocks(blocks, lastRepliedEntry(selectionAtStart?.selectionId || sessionId))
|
|
2136
2469
|
content = unsent.length ? unsent.map((b) => b.text).join("\n\n") : null
|
|
2137
2470
|
repliedEntry = blocks[blocks.length - 1].id
|
|
2138
2471
|
}
|
|
@@ -2141,30 +2474,38 @@ async function main() {
|
|
|
2141
2474
|
content = extracted.prompt
|
|
2142
2475
|
sessionId = extracted.sessionId
|
|
2143
2476
|
workspaceRoots = extracted.workspaceRoots || []
|
|
2477
|
+
// ENG-4156: Cursor's "Try again" after a failed turn fires this hook with an
|
|
2478
|
+
// empty prompt under a new generation. Nothing is written (it used to be
|
|
2479
|
+
// recorded as the prompt "null"). Which prompt it resends is decided when
|
|
2480
|
+
// its reply arrives, from the transcript (below): the open turn's own, or
|
|
2481
|
+
// one whose hook never fired.
|
|
2482
|
+
if (effectiveTool === "cursor" && !selftestNonce
|
|
2483
|
+
&& !(typeof parsed?.prompt === "string" && parsed.prompt.trim())) return
|
|
2144
2484
|
// Claude's own plumbing arrives on this hook too. It is not a candidate
|
|
2145
2485
|
// prompt, so it is dropped rather than recorded as one — see
|
|
2146
2486
|
// isSystemInjectedPrompt.
|
|
2147
2487
|
if (isSystemInjectedPrompt(content)) return
|
|
2148
2488
|
}
|
|
2489
|
+
const litmusDir = resolveAssessmentDir(parsed, workspaceRoots, effectiveTool, !!selftestNonce)
|
|
2490
|
+
if (!litmusDir) return
|
|
2491
|
+
if (hostedAtStart && hostedCaptureWindow()?.litmusDir !== hostedAtStart.litmusDir) return
|
|
2492
|
+
if (litmusDir !== earlyLitmusDir && sessionOverMarked(litmusDir)) return
|
|
2493
|
+
const captureToken = readConfig(litmusDir)?.token
|
|
2494
|
+
const knownCaptureTokens = captureKnownTokens(captureToken)
|
|
2149
2495
|
let toolTrace = null
|
|
2150
2496
|
const cursorResultsDir = responseEvent && effectiveTool === "cursor" && !selftestNonce
|
|
2151
2497
|
? cursorResultScope({ session_id: sessionId }, hostedAtStart) : null
|
|
2152
|
-
if (responseEvent && !selftestNonce && typeof parsed?.transcript_path === "string"
|
|
2153
|
-
&& (hostedWorkspaceHome || hostedAtStart?.disclosureVersion === "hosted_local_v2")) {
|
|
2154
|
-
try { toolTrace = parseToolEvidence(readTranscriptRaw(parsed.transcript_path), effectiveTool) }
|
|
2498
|
+
if (responseEvent && !selftestNonce && !stoppedTurn && typeof parsed?.transcript_path === "string"
|
|
2499
|
+
&& (hostedWorkspaceHome || hostedAtStart?.disclosureVersion === "hosted_local_v2" || (selectionAtStart && matchingBoundary))) {
|
|
2500
|
+
try { toolTrace = parseToolEvidence(readTranscriptRaw(parsed.transcript_path, undefined, matchingBoundary?.offset ?? 0, matchingBoundary?.identity), effectiveTool, knownCaptureTokens) }
|
|
2155
2501
|
catch { toolTrace = { version: 1, records: [], complete: false, reason: "transcript_unavailable", dropped: 0 } }
|
|
2156
2502
|
}
|
|
2157
|
-
if (responseEvent && effectiveTool === "cursor" && !selftestNonce && hostedAtStart?.disclosureVersion
|
|
2503
|
+
if (responseEvent && effectiveTool === "cursor" && !selftestNonce && ["hosted_local_v2", SELECTED_CAPTURE_DISCLOSURE].includes(hostedAtStart?.disclosureVersion)) {
|
|
2158
2504
|
toolTrace = cursorHookToolTrace(toolTrace, readCursorToolResults(sessionId, hostedAtStart, cursorResultsDir))
|
|
2159
2505
|
}
|
|
2160
|
-
if (!content && !toolTrace?.records?.length) return
|
|
2506
|
+
if (!content && !toolTrace?.records?.length && !stoppedTurn) return
|
|
2161
2507
|
content = content || ""
|
|
2162
2508
|
|
|
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
2509
|
// Claim as LATE as possible — only once we know we have content and somewhere
|
|
2169
2510
|
// to put it. Claiming earlier would let an invocation that then bails (no
|
|
2170
2511
|
// content, no assessment in scope) consume the claim and silence the sibling
|
|
@@ -2172,13 +2513,17 @@ async function main() {
|
|
|
2172
2513
|
// (generation_id is per assistant message, but a prompt and its response
|
|
2173
2514
|
// could conceivably share one) so the two kinds never contend.
|
|
2174
2515
|
if (cursorShaped && parsed && parsed.generation_id) {
|
|
2175
|
-
const
|
|
2516
|
+
const generationKey = selectionAtStart ? `${selectionAtStart.selectionId}:${parsed.generation_id}` : parsed.generation_id
|
|
2517
|
+
const claimKey = responseEvent ? `${generationKey}.resp` : generationKey
|
|
2176
2518
|
if (!claimPrompt(claimKey)) {
|
|
2177
2519
|
return // the sibling hook is writing this same event
|
|
2178
2520
|
}
|
|
2179
2521
|
}
|
|
2180
2522
|
|
|
2181
2523
|
const fullCursorPrompt = !responseEvent && effectiveTool === "cursor"
|
|
2524
|
+
// Redact the full body first: clipping a credential at a character limit
|
|
2525
|
+
// would otherwise prevent exact-value recognition in the final event pass.
|
|
2526
|
+
content = redactCaptureText(content, knownCaptureTokens)
|
|
2182
2527
|
const maxLength = fullCursorPrompt ? Infinity : responseEvent ? MAX_RESPONSE_LENGTH : MAX_PROMPT_LENGTH
|
|
2183
2528
|
const truncated = content.length > maxLength
|
|
2184
2529
|
? content.slice(0, maxLength) + "...[truncated]"
|
|
@@ -2186,8 +2531,46 @@ async function main() {
|
|
|
2186
2531
|
|
|
2187
2532
|
// Pair the two invocations: a prompt opens a turn, its response inherits the
|
|
2188
2533
|
// same id. See the turn-pairing block above.
|
|
2189
|
-
const
|
|
2190
|
-
const
|
|
2534
|
+
const storageKey = selectionAtStart?.selectionId || sessionId
|
|
2535
|
+
const turnRecord = responseEvent && !selftestNonce ? currentTurnRecord(storageKey) : null
|
|
2536
|
+
let turnId = selftestNonce ? null : responseEvent ? turnRecord.turnId
|
|
2537
|
+
: startTurn(storageKey, parsed?.generation_id, selectionAtStart?.selectionId, selectionAtStart ? captureTranscriptBoundary(parsed?.transcript_path) : null, effectiveTool === "cursor" ? content : undefined)
|
|
2538
|
+
|
|
2539
|
+
// ENG-4156: a Cursor reply whose generation is not the open turn's may answer
|
|
2540
|
+
// a prompt `beforeSubmitPrompt` never delivered. Cursor skips that hook when
|
|
2541
|
+
// its hooks are not loaded yet (a remote window still opening), and the reply
|
|
2542
|
+
// was then filed under the previous prompt. A generation alone proves
|
|
2543
|
+
// nothing (3.21 gave `stop` its own), so the transcript's newest typed prompt
|
|
2544
|
+
// decides: the open turn's own words keep the reply there; words never
|
|
2545
|
+
// captured are recovered; words captured for an earlier turn mean this
|
|
2546
|
+
// reply's prompt is missing. With no typed prompt to read, the reply pairs as
|
|
2547
|
+
// before.
|
|
2548
|
+
let recoveredPrompt = null
|
|
2549
|
+
let promptMissing = false
|
|
2550
|
+
// No open turn at all is the same case for a conversation's first prompt.
|
|
2551
|
+
if (responseEvent && effectiveTool === "cursor" && !selftestNonce
|
|
2552
|
+
&& typeof parsed.generation_id === "string" && parsed.generation_id
|
|
2553
|
+
&& (!turnRecord.turnId || (turnRecord.promptHistory && turnRecord.generationId && parsed.generation_id !== turnRecord.generationId))
|
|
2554
|
+
&& typeof parsed.transcript_path === "string"
|
|
2555
|
+
// A selected chat is read only from its open turn's boundary (ENG-4121).
|
|
2556
|
+
&& (!selectionAtStart || matchingBoundary)) {
|
|
2557
|
+
const typed = lastCursorUserQuery(parsed.transcript_path, matchingBoundary)
|
|
2558
|
+
// Redacted like the hooked prompt was, so the digests compare and no secret is recovered.
|
|
2559
|
+
const query = typed ? redactCaptureText(typed, knownCaptureTokens) : null
|
|
2560
|
+
const digest = query ? promptDigest(query) : null
|
|
2561
|
+
if (!digest) {
|
|
2562
|
+
// Nothing typed to read: pair as before.
|
|
2563
|
+
} else if (digest === turnRecord.prompts[turnRecord.prompts.length - 1]) {
|
|
2564
|
+
adoptGeneration(storageKey, parsed.generation_id) // the open turn's own prompt
|
|
2565
|
+
} else {
|
|
2566
|
+
if (!turnRecord.prompts.includes(digest)) recoveredPrompt = query
|
|
2567
|
+
else promptMissing = true
|
|
2568
|
+
// From the open turn's start, so this turn's edits are not called late.
|
|
2569
|
+
turnId = startTurn(storageKey, parsed.generation_id, selectionAtStart?.selectionId, turnRecord.transcriptBoundary, recoveredPrompt ?? undefined, turnRecord.ts ?? Date.now())
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
// Still the claimed turn: its reply is already recorded.
|
|
2573
|
+
if (standDownUnlessNewTurn && !recoveredPrompt && !promptMissing) return
|
|
2191
2574
|
|
|
2192
2575
|
const event = selftestNonce
|
|
2193
2576
|
? {
|
|
@@ -2230,16 +2613,18 @@ async function main() {
|
|
|
2230
2613
|
if (hostedAtStart) {
|
|
2231
2614
|
event.capture_location = "local"
|
|
2232
2615
|
event.capture_receipt = hostedAtStart.receipt
|
|
2616
|
+
if (selectionAtStart && !selftestNonce) event.capture_selection_id = selectionAtStart.selectionId
|
|
2233
2617
|
event.ts = new Date(hostedCapturedAt).toISOString()
|
|
2234
2618
|
}
|
|
2235
2619
|
if (sessionId) event.sessionId = sessionId
|
|
2236
2620
|
if (turnId) event.turnId = turnId
|
|
2621
|
+
if (promptMissing) event.promptMissing = true
|
|
2237
2622
|
// ENG-2344: the files Cursor's `afterFileEdit` hook reported the agent
|
|
2238
2623
|
// editing since this turn's prompt, folded onto its reply. Attached BEFORE
|
|
2239
2624
|
// the byte-cap loop, like the metering, so the body is trimmed around it.
|
|
2240
2625
|
let editLedger = null
|
|
2241
2626
|
if (responseEvent && effectiveTool === "cursor" && !selftestNonce) {
|
|
2242
|
-
editLedger = takeCursorFileEdits(
|
|
2627
|
+
editLedger = takeCursorFileEdits(storageKey, turnRecord ? turnRecord.ts : null)
|
|
2243
2628
|
if (editLedger) event.file_writes = editLedger.writes
|
|
2244
2629
|
}
|
|
2245
2630
|
if (toolTrace) event.tool_calls = { trace: toolTrace }
|
|
@@ -2262,6 +2647,7 @@ async function main() {
|
|
|
2262
2647
|
// Preserve complete Cursor prompts in both the file and upload lanes. Other
|
|
2263
2648
|
// bodies keep their existing serialized budget; the server's size filter is
|
|
2264
2649
|
// still the final storage bound.
|
|
2650
|
+
sanitizeCaptureEvent(event, captureToken)
|
|
2265
2651
|
const MAX_SERIALIZED_BYTES = 60000
|
|
2266
2652
|
const bodyField = responseEvent ? "text" : "prompt"
|
|
2267
2653
|
if (!fullCursorPrompt) trimEventToBytes(event, bodyField, MAX_SERIALIZED_BYTES, toolTrace ? storageBytes : undefined)
|
|
@@ -2270,11 +2656,39 @@ async function main() {
|
|
|
2270
2656
|
// Record that this turn's reply is captured, so the sibling `stop` hook
|
|
2271
2657
|
// doesn't record it a second time (IDE only — see the claim helpers).
|
|
2272
2658
|
if (responseEvent && effectiveTool === "cursor" && parsed.hook_event_name === "afterAgentResponse") {
|
|
2273
|
-
markCursorResponseCaptured(cursorConversation)
|
|
2659
|
+
markCursorResponseCaptured(selectionAtStart?.selectionId || cursorConversation, turnId)
|
|
2274
2660
|
}
|
|
2275
2661
|
|
|
2276
2662
|
// Recheck after transcript reads/settling: teardown may have happened meanwhile.
|
|
2277
2663
|
if (hostedAtStart && hostedCaptureWindow()?.litmusDir !== litmusDir) return
|
|
2664
|
+
if (selectionAtStart && selectedHostedConversation(hostedCaptureWindow(), effectiveTool, sessionId)?.selectionId !== selectionAtStart.selectionId) return
|
|
2665
|
+
|
|
2666
|
+
// ENG-4156: the recovered prompt goes first, down the same lanes a hooked
|
|
2667
|
+
// prompt takes, one millisecond ahead of its reply so it sorts before it.
|
|
2668
|
+
// `recoveredFrom` says where its words came from: Cursor's transcript, a file
|
|
2669
|
+
// under the candidate's home, not the hook payload.
|
|
2670
|
+
if (recoveredPrompt) {
|
|
2671
|
+
const promptEvent = {
|
|
2672
|
+
ts: new Date(Date.parse(event.ts) - 1).toISOString(),
|
|
2673
|
+
type: "ai_prompt",
|
|
2674
|
+
tool: effectiveTool,
|
|
2675
|
+
prompt: recoveredPrompt,
|
|
2676
|
+
recoveredFrom: "cursor_transcript",
|
|
2677
|
+
id: crypto.randomUUID(),
|
|
2678
|
+
...(hostedAtStart ? { capture_location: "local", capture_receipt: hostedAtStart.receipt } : {}),
|
|
2679
|
+
...(selectionAtStart ? { capture_selection_id: selectionAtStart.selectionId } : {}),
|
|
2680
|
+
...(sessionId ? { sessionId } : {}),
|
|
2681
|
+
...(turnId ? { turnId } : {}),
|
|
2682
|
+
}
|
|
2683
|
+
sanitizeCaptureEvent(promptEvent, captureToken)
|
|
2684
|
+
if (!hostedAtStart || trimEventToBytes(promptEvent, "prompt", 6_010_000)) {
|
|
2685
|
+
try { fs.appendFileSync(path.join(litmusDir, "activity.jsonl"), JSON.stringify(promptEvent) + "\n") } catch { /* Non-critical */ }
|
|
2686
|
+
if (!hostedAtStart) {
|
|
2687
|
+
emitToDrain(promptEvent, "beforeSubmitPrompt")
|
|
2688
|
+
await uploadEvent(readConfig(litmusDir), promptEvent)
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
}
|
|
2278
2692
|
|
|
2279
2693
|
// 1. Append to activity.jsonl (for submission ZIP)
|
|
2280
2694
|
const logPath = path.join(litmusDir, "activity.jsonl")
|
|
@@ -2289,7 +2703,7 @@ async function main() {
|
|
|
2289
2703
|
// ENG-2793: the next Stop starts after this reply only once a copy of it is
|
|
2290
2704
|
// on disk. The drain and the upload report no outcome, so a reply whose append
|
|
2291
2705
|
// failed is sent again by the next Stop, and the report folds the repeat.
|
|
2292
|
-
if (repliedEntry && logged) recordRepliedEntry(
|
|
2706
|
+
if (repliedEntry && logged) recordRepliedEntry(storageKey, repliedEntry)
|
|
2293
2707
|
// ENG-2344: the edits this reply carries leave the ledger only now that the
|
|
2294
2708
|
// reply is on disk. An append that failed hands them back for the next reply.
|
|
2295
2709
|
if (editLedger) {
|
|
@@ -2426,8 +2840,23 @@ function storageBytes(value) {
|
|
|
2426
2840
|
|
|
2427
2841
|
const MAX_RECORDS = 128
|
|
2428
2842
|
const MAX_BYTES = 48000
|
|
2429
|
-
function boundedText(value, cap) {
|
|
2430
|
-
|
|
2843
|
+
function boundedText(value, cap, known = []) {
|
|
2844
|
+
// Codex supplies JSON arguments as a STRING, while Claude supplies an object.
|
|
2845
|
+
// Scrub credential keys in either form before stringification or clipping.
|
|
2846
|
+
// Preserve a harmless JSON string's formatting when it needs no redaction.
|
|
2847
|
+
let scrubbed = value
|
|
2848
|
+
if (typeof value === "string") {
|
|
2849
|
+
let parsed
|
|
2850
|
+
try { parsed = JSON.parse(value) } catch { /* ordinary tool output is not necessarily JSON */ }
|
|
2851
|
+
if (parsed && typeof parsed === "object") {
|
|
2852
|
+
const safe = scrubCaptureContent(parsed, known)
|
|
2853
|
+
if (JSON.stringify(safe) !== JSON.stringify(parsed)) scrubbed = JSON.stringify(safe)
|
|
2854
|
+
}
|
|
2855
|
+
}
|
|
2856
|
+
scrubbed = scrubCaptureContent(scrubbed, known)
|
|
2857
|
+
// Hashes/byte counts describe the sanitized evidence, never a retained raw
|
|
2858
|
+
// secret. Both transcript and post-tool-hook writers use this same order.
|
|
2859
|
+
const full = typeof scrubbed === 'string' ? scrubbed : JSON.stringify(scrubbed ?? null)
|
|
2431
2860
|
let text = full
|
|
2432
2861
|
while (storageBytes(text) > cap) text = text.slice(0, Math.floor(text.length * 0.9))
|
|
2433
2862
|
if (text && /[\uD800-\uDBFF]$/.test(text)) text = text.slice(0, -1)
|
|
@@ -2436,8 +2865,8 @@ function boundedText(value, cap) {
|
|
|
2436
2865
|
|
|
2437
2866
|
/** Only the final genuine user turn is in scope. A bounded tail without its
|
|
2438
2867
|
* boundary is unavailable, never a license to import historical tool output. */
|
|
2439
|
-
function parseToolEvidence(raw, tool) {
|
|
2440
|
-
let records = [], boundary = false, seen = new Set(), dropped = 0
|
|
2868
|
+
function parseToolEvidence(raw, tool, known = []) {
|
|
2869
|
+
let records = [], boundary = false, seen = new Set(), dropped = 0, closed = false
|
|
2441
2870
|
for (const [lineIndex, line] of raw.split('\n').entries()) {
|
|
2442
2871
|
let row
|
|
2443
2872
|
try { row = JSON.parse(line) } catch { continue }
|
|
@@ -2451,7 +2880,15 @@ function parseToolEvidence(raw, tool) {
|
|
|
2451
2880
|
if (row.type === 'response_item' && row.payload?.type === 'message' && row.payload.role === 'user'
|
|
2452
2881
|
&& Array.isArray(row.payload.content) && row.payload.content.some(b => b?.type === 'input_text' && isCodexContextualText(b.text))) continue
|
|
2453
2882
|
const codexPrompt = (row.type === 'event_msg' && row.payload?.type === 'user_message') || (row.type === 'response_item' && row.payload?.type === 'message' && row.payload.role === 'user' && Array.isArray(row.payload.content) && row.payload.content.some(b => b?.type === 'input_text'))
|
|
2454
|
-
|
|
2883
|
+
// ENG-4157: Cursor's turn markers bound a turn like a prompt does; a stopped
|
|
2884
|
+
// turn's marker lands before its user line (see parseCursorTranscript).
|
|
2885
|
+
if (row.type === 'turn_ended') {
|
|
2886
|
+
if (closed) { records = []; boundary = true; seen = new Set(); dropped = 0 }
|
|
2887
|
+
closed = true
|
|
2888
|
+
continue
|
|
2889
|
+
}
|
|
2890
|
+
if (prompt || codexPrompt || closed) { records = []; boundary = true; seen = new Set(); dropped = 0; closed = false }
|
|
2891
|
+
if (prompt || codexPrompt) continue
|
|
2455
2892
|
if (!boundary) continue
|
|
2456
2893
|
let candidates = []
|
|
2457
2894
|
if ((row.type === 'assistant' || row.role === 'assistant') && Array.isArray(content)) {
|
|
@@ -2475,7 +2912,7 @@ function parseToolEvidence(raw, tool) {
|
|
|
2475
2912
|
seen.add(key)
|
|
2476
2913
|
if (records.length >= MAX_RECORDS) { dropped++; continue }
|
|
2477
2914
|
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) })
|
|
2915
|
+
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
2916
|
}
|
|
2480
2917
|
}
|
|
2481
2918
|
while (storageBytes(records) > MAX_BYTES) { records.pop(); dropped++ }
|
|
@@ -2514,30 +2951,36 @@ function finishCursorToolResults(dir) {
|
|
|
2514
2951
|
pruneCursorToolResults()
|
|
2515
2952
|
}
|
|
2516
2953
|
function cursorResultScope(data, window) {
|
|
2517
|
-
if (!window || window.disclosureVersion
|
|
2954
|
+
if (!window || !["hosted_local_v2", SELECTED_CAPTURE_DISCLOSURE].includes(window.disclosureVersion)) return null
|
|
2518
2955
|
const session = data?.session_id || data?.conversation_id
|
|
2519
|
-
const turn = currentTurnRecord(session)
|
|
2956
|
+
const turn = currentTurnRecord(hostedTurnStorageKey(window, "cursor", session))
|
|
2520
2957
|
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")
|
|
2958
|
+
const key = crypto.createHash("sha256").update(JSON.stringify([session, turn.turnId, window.startedAt, window.litmusDir, ...(turn.selectionId ? [turn.selectionId] : [])])).digest("hex")
|
|
2522
2959
|
return path.join(cursorResultsRoot(), key)
|
|
2523
2960
|
}
|
|
2524
2961
|
function recordCursorToolResult(data, window) {
|
|
2525
2962
|
pruneCursorToolResults()
|
|
2526
2963
|
const dir = cursorResultScope(data, window)
|
|
2527
2964
|
const failed = data?.hook_event_name === "postToolUseFailure"
|
|
2528
|
-
const
|
|
2965
|
+
const session = data?.session_id || data?.conversation_id
|
|
2966
|
+
const selected = selectedHostedConversation(window, "cursor", session)
|
|
2967
|
+
const observed = currentTurnRecord(hostedTurnStorageKey(window, "cursor", session))
|
|
2968
|
+
if (window?.disclosureVersion === SELECTED_CAPTURE_DISCLOSURE
|
|
2969
|
+
&& (!selected || observed.selectionId !== selected.selectionId || observed.ts < selected.selectedAt)) return false
|
|
2529
2970
|
if (!observed.generationId || data?.generation_id !== observed.generationId) return false
|
|
2530
2971
|
if (!dir || typeof data.tool_use_id !== "string" || !data.tool_use_id || data.tool_use_id.length > 128
|
|
2531
2972
|
|| typeof data.tool_name !== "string" || !data.tool_name || data.tool_name.length > 128
|
|
2532
2973
|
|| data.tool_input === undefined
|
|
2533
2974
|
|| (failed ? typeof data.error_message !== "string" : data.tool_output === undefined)) return false
|
|
2534
2975
|
const id = data.tool_use_id
|
|
2976
|
+
const known = captureKnownTokens(window.litmusDir ? readConfig(window.litmusDir)?.token : undefined)
|
|
2535
2977
|
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) },
|
|
2978
|
+
{ kind: "call", id, name: data.tool_name, input: boundedText(data.tool_input, 40000, known) },
|
|
2979
|
+
{ kind: "result", id, ...(failed ? { ok: false } : {}), output: boundedText(failed ? data.error_message : data.tool_output, 40000, known) },
|
|
2538
2980
|
]
|
|
2539
2981
|
let tmp
|
|
2540
2982
|
try {
|
|
2983
|
+
if (selected && selectedHostedConversation(hostedCaptureWindow(), "cursor", session)?.selectionId !== selected.selectionId) return false
|
|
2541
2984
|
if (fs.existsSync(dir + ".done")) return false
|
|
2542
2985
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
2543
2986
|
if (fs.readdirSync(dir).filter(n => n.endsWith(".json")).length >= MAX_RECORDS / 2) return false
|
|
@@ -2613,6 +3056,20 @@ function cursorHookToolTrace(transcript, hookRecords) {
|
|
|
2613
3056
|
|
|
2614
3057
|
// Exported for unit tests only; every hook invocation runs this file directly.
|
|
2615
3058
|
module.exports = {
|
|
3059
|
+
sanitizeCaptureEvent,
|
|
3060
|
+
captureConversationKey,
|
|
3061
|
+
validCaptureConversationIdentity,
|
|
3062
|
+
readCaptureConversationSelection,
|
|
3063
|
+
selectedHostedConversation,
|
|
3064
|
+
captureSelectionDigest,
|
|
3065
|
+
captureStopFile,
|
|
3066
|
+
readCaptureStopId,
|
|
3067
|
+
captureKnownTokens,
|
|
3068
|
+
redactCaptureText,
|
|
3069
|
+
scrubCaptureContent,
|
|
3070
|
+
CAPTURE_CREDENTIAL_PATTERNS,
|
|
3071
|
+
CAPTURE_CREDENTIAL_KEYS,
|
|
3072
|
+
readCursorTranscriptResponse,
|
|
2616
3073
|
recordCursorToolResult,
|
|
2617
3074
|
readCursorToolResults,
|
|
2618
3075
|
cursorHookToolTrace,
|