ravensight-playtest 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -0
- package/docs/MOBILE.md +1 -1
- package/package.json +3 -3
- package/src/api/client.js +10 -1
- package/src/cli.js +29 -2
- package/src/commands/hosted.js +15 -0
- package/src/commands/run.js +89 -8
- package/src/run/anygame/index.js +1 -1
- package/src/run/args.js +24 -0
- package/src/run/budgetReserve.js +70 -8
- package/src/run/choiceCheck.js +26 -7
- package/src/run/drivers/web.js +118 -5
- package/src/run/livesite/browser.js +316 -0
- package/src/run/livesite/hosts.js +107 -0
- package/src/run/livesite/network.js +117 -0
- package/src/run/livesite/options.js +167 -0
- package/src/run/livesite/resolver.js +78 -0
- package/src/run/livesite/run.js +113 -0
- package/src/run/personaLoop.js +207 -24
- package/src/run/proxyClient.js +5 -1
- package/src/run/redaction.js +191 -0
- package/src/run/report.js +5 -2
- package/src/run/resume.js +30 -3
- package/src/run/state.js +3 -1
- package/src/run/tooFast.js +116 -0
- package/src/run/transcript.js +3 -1
- package/src/run/usage.js +3 -1
package/src/run/personaLoop.js
CHANGED
|
@@ -6,14 +6,16 @@ import { prepareMessages, repairLastTurn, frozenEnds, frozenEnd, createCacheLayo
|
|
|
6
6
|
import { callStepWithRetry, ProxyError, STEPS } from './model.js';
|
|
7
7
|
import { RUN_FILES } from './paths.js';
|
|
8
8
|
import { requestBytes, reserveDecision } from './budgetReserve.js';
|
|
9
|
-
import { measureActInput } from './inputMeasurement.js';
|
|
9
|
+
import { measureActInput, supportsImageMeasurement } from './inputMeasurement.js';
|
|
10
10
|
import { completionClaim, completionCriteria, completionPrompt, completionRepairPrompt, MAX_COMPLETION_TEXT } from './completion.js';
|
|
11
11
|
import { createScreenshotKeeper } from './screenshots.js';
|
|
12
|
-
import { checkBriefChoice, screensForCheck, writeChoiceIntoMarkdown, CHOICE_CHECK_FILE } from './choiceCheck.js';
|
|
12
|
+
import { checkBriefChoice, choiceCheckRequest, insertUnderHeading, screensForCheck, writeChoiceIntoMarkdown, CHOICE_CHECK_FILE, CHOICE_CHECK_MAX_TOKENS } from './choiceCheck.js';
|
|
13
|
+
import { thinkingTime, timerExpiryClaim, tooFastLine, tooFastNote } from './tooFast.js';
|
|
13
14
|
import { declinedAnswer, declinedPrompt, declinedStopDetail, NEUTRAL_RESTATEMENT } from './refusal.js';
|
|
14
15
|
import { createPlayClock, clockStopDetail, timeLeftAside } from './playClock.js';
|
|
15
16
|
import { appendNormalisedMarkdown, checkEvidence, createReportValidator, lintMarkdownSections, normaliseEnums, normaliseEvidence, normaliseReproSteps, repairInstruction, REQUIRED_MARKDOWN_SECTIONS, stampReport, stripTrailingToolMarkup, writeReportFiles } from './report.js';
|
|
16
17
|
import { assertNoSecrets, scanForSecrets } from './secretScan.js';
|
|
18
|
+
import { redactText } from './redaction.js';
|
|
17
19
|
import { ACTION_TOOLS, NEW_TOOL_NAMES, REPORT_TOOLS, executeTool, expectationOf, modelFrameOf, toolResult, toolsFor, NEWEST_TOOL_NAMES } from './tools.js';
|
|
18
20
|
import {
|
|
19
21
|
CAPABILITY_HEADING, DIALOGS_HEADING, EVIDENCE_HEADING, MAX_WIN_CONTINUES, RUNNER_FINDINGS_HEADING, WIN_TEXT,
|
|
@@ -37,7 +39,7 @@ import { claimShape, judgeIssue, legacyIssue, impressionOf } from './judge.js';
|
|
|
37
39
|
import { EVENTS_RULE, eventsBlock, eventsReportLines, eventsUsage, withEventEvidence } from './events.js';
|
|
38
40
|
import { memoryBlock, extractLocalNotes, gameMemoryBody } from './gameMemory.js';
|
|
39
41
|
import { CLAIM_SYSTEM, CLAIM_WIRE, claimText, claimRead, claimMessage } from './claimwords.js';
|
|
40
|
-
import { claimCheckSystem, claimReply, claimFormatRepair, MAX_CLAIM_REPLY_TEXT } from './claimProtocol.js';
|
|
42
|
+
import { CLAIM_FAULT_SYSTEM, claimCheckSystem, claimReply, claimFormatRepair, MAX_CLAIM_REPLY_TEXT } from './claimProtocol.js';
|
|
41
43
|
import { captureNotes, createCaptureWatch, rewriteStaleEvidence, staleSentence } from './captureCheck.js';
|
|
42
44
|
import { gameRefusal } from './gameRefusal.js';
|
|
43
45
|
import { BUILT_IN_NOISE, expectedNoiseForPrompt, isExpectedNoise } from './noise.js';
|
|
@@ -317,7 +319,7 @@ export async function runPersona(args) {
|
|
|
317
319
|
// not send, findings it watched happen, dialogs and their answers, and the
|
|
318
320
|
// edge behaviour checks. Kept out here so a report written from the step
|
|
319
321
|
// log after a failure still carries them.
|
|
320
|
-
const honesty = { capability: createCapabilityLedger(), findings: [], dialogs: [], edge: null, video: null, traceSteps: new Map(), tester: createTesterLedger() };
|
|
322
|
+
const honesty = { capability: createCapabilityLedger(), findings: [], dialogs: [], edge: null, video: null, traceSteps: new Map(), tester: createTesterLedger(), timing: createTiming() };
|
|
321
323
|
let imageBudget = maxImages;
|
|
322
324
|
|
|
323
325
|
await mkdir(path.join(runDirectory, 'screenshots'), { recursive: true });
|
|
@@ -543,7 +545,8 @@ export async function runPersona(args) {
|
|
|
543
545
|
// them, they may be symptoms of the crash, and what report.json holds
|
|
544
546
|
// becomes findings, analyst memory and graph nodes on the server.
|
|
545
547
|
findings: [],
|
|
546
|
-
|
|
548
|
+
// A live site that did not load or refused the sign-in already says what happened and what to change.
|
|
549
|
+
reason: error && error.plainReason ? detail : `The run stopped on an error before its report was written: ${detail}`,
|
|
547
550
|
bareReason: 'The run stopped on an error before its report was written.'
|
|
548
551
|
});
|
|
549
552
|
}
|
|
@@ -768,6 +771,53 @@ export function aboutRunnerLimit(finding) {
|
|
|
768
771
|
return RUNNER_LIMIT_TEXT.test(`${(finding && finding.title) || ''}\n${(finding && finding.description) || ''}`);
|
|
769
772
|
}
|
|
770
773
|
|
|
774
|
+
/* ------------------------------------- a game timer the playtester's own thinking ran out (./tooFast.js) */
|
|
775
|
+
|
|
776
|
+
/** Why the runner moves a finding to the [too_fast] capability note; see ./tooFast.js. */
|
|
777
|
+
export const TOO_FAST_REASON = 'a game timer that ran out while the playtester was still deciding, a limit of the runner [too_fast], not the game';
|
|
778
|
+
|
|
779
|
+
/** The run's record of the turns the game kept running through while the model thought. */
|
|
780
|
+
export function createTiming() {
|
|
781
|
+
return { running: 0, thinkMs: [] };
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/**
|
|
785
|
+
* Whether the game kept running while the playtester thought: a native run, a
|
|
786
|
+
* web page that is not a frozen canvas, --realtime. On such a run a game timer
|
|
787
|
+
* can run out between two inputs however they are played.
|
|
788
|
+
*
|
|
789
|
+
* @param {Object|null} honesty
|
|
790
|
+
* @returns {boolean}
|
|
791
|
+
*/
|
|
792
|
+
export function realTimeRun(honesty) {
|
|
793
|
+
return Boolean(honesty && honesty.timing && honesty.timing.running > 0);
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/** A note of the persona's that says a game timer ran out on it (praise and the runner's own lines aside). */
|
|
797
|
+
export function timerNote(note) {
|
|
798
|
+
return Boolean(note && !note.automatic && note.kind !== 'good' && timerExpiryClaim(note.text));
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/** What the report step is told on a run whose game kept running while the playtester thought. */
|
|
802
|
+
export function tooFastPrompt(timing) {
|
|
803
|
+
const pace = timing && timing.turns > 0 && timing.medianSeconds !== null ? `: about ${timing.medianSeconds} s a turn, up to ${timing.maxSeconds} s` : '';
|
|
804
|
+
return `The game kept running while you decided${pace}. A game timer or countdown that ran out between your inputs (a "Time is up" screen, a question, a life or a round lost to the clock, a timing window too tight to answer in) is a limit of this runner, not of the game: write it in "What this run didn't cover" as a line starting with [too_fast], never as a finding of any severity or category. The runner moves a finding that says so.`;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/**
|
|
808
|
+
* Say what was moved as the [too_fast] capability note: a line under "What
|
|
809
|
+
* this run didn't cover" (which `run` prints with its fix) and the runner's own
|
|
810
|
+
* capability list.
|
|
811
|
+
*
|
|
812
|
+
* @returns {string} the markdown with the line
|
|
813
|
+
*/
|
|
814
|
+
function sayTooFast({ markdown, moved, honesty, transcript = null }) {
|
|
815
|
+
const timing = thinkingTime(honesty && honesty.timing ? honesty.timing.thinkMs : []);
|
|
816
|
+
const note = tooFastNote(timing);
|
|
817
|
+
if (honesty && honesty.capability && honesty.capability.add(note) && transcript) transcript.write({ kind: 'capability_note', input: note.input, reason: note.reason });
|
|
818
|
+
return insertUnderHeading(String(markdown || ''), "## What this run didn't cover", tooFastLine(moved, timing));
|
|
819
|
+
}
|
|
820
|
+
|
|
771
821
|
async function playLoop({
|
|
772
822
|
// The observation and action lines of the transcript, kept for the report
|
|
773
823
|
// step's "Actions you took" list and for a partial report.
|
|
@@ -816,6 +866,8 @@ async function playLoop({
|
|
|
816
866
|
log = () => {}
|
|
817
867
|
}) {
|
|
818
868
|
const system = buildSystem({ skill, persona, brief, localBrief, intentNotes, driverName, target, maxActions, runId });
|
|
869
|
+
// How long the model thought on each turn the game kept running through (./tooFast.js).
|
|
870
|
+
const timing = honesty.timing || (honesty.timing = createTiming());
|
|
819
871
|
const identity = runIdentity({ persona, runId });
|
|
820
872
|
const secrets = secretsOf(localBrief);
|
|
821
873
|
const noisePatterns = (localBrief && Array.isArray(localBrief.expected_noise)) ? localBrief.expected_noise : [];
|
|
@@ -922,22 +974,34 @@ async function playLoop({
|
|
|
922
974
|
const recentActUnits = [];
|
|
923
975
|
|
|
924
976
|
/**
|
|
925
|
-
* Whether the next act turn would leave too little for the report.
|
|
926
|
-
* from the act request about to be sent and the report
|
|
927
|
-
* be built now
|
|
977
|
+
* Whether the next act turn would leave too little for the report phase.
|
|
978
|
+
* Sized from the act request about to be sent and the report phase's
|
|
979
|
+
* requests as they would be built now: the brief choice check, the report
|
|
980
|
+
* request (sent twice when report.md and report.json come in two turns) and
|
|
981
|
+
* a claim check for each issue noted so far; see ./budgetReserve.js.
|
|
928
982
|
*/
|
|
929
983
|
const reserveCheck = () => {
|
|
930
984
|
const spend = modelBudgetUsd ? ledger.spendEstimate() : null;
|
|
931
985
|
if (!spend) return { stop: false, known: false, figures: {} };
|
|
932
986
|
const prepared = withPlayCacheBreakpoint(prepareMessages(messages, { maxImages: imageBudget, keepObservations, layout: cacheLayout }), cacheLayout);
|
|
933
987
|
const measured = measureActInput({ messages: prepared, max_tokens: ACT_MAX_TOKENS, stream: true, system, tools: completionRepairPending ? [] : playTools }, inputMeasurement, { controller });
|
|
988
|
+
const actionLog = actionLogFrom(actionRecords);
|
|
934
989
|
const reportRequest = buildReportRequest({
|
|
935
990
|
skill: reportSkill || skill, schemas, persona, brief, localBrief, intentNotes, driverName, target, runId, jobId,
|
|
936
|
-
play: { actionsTaken: actions, quitReason: 'budget_exhausted', quitDetail: RESERVE_STOP_DETAIL, actionLog
|
|
991
|
+
play: { actionsTaken: actions, quitReason: 'budget_exhausted', quitDetail: RESERVE_STOP_DETAIL, actionLog, records: actionRecords,
|
|
937
992
|
completionClaim: completionAccount, completionAttempts },
|
|
938
|
-
notes, observations, screenshots
|
|
993
|
+
notes, observations, screenshots, honesty
|
|
939
994
|
});
|
|
940
995
|
const reportChars = requestBytes({ messages: reportRequest.messages, max_tokens: REPORT_MAX_TOKENS, stream: true, system: reportRequest.system, tools: REPORT_TOOLS });
|
|
996
|
+
// The choice check and a claim check each send one picture: sized with the newest one play has, at the server's
|
|
997
|
+
// advertised image reserve. Without that rule (an older server, a controller with its own catalog) a picture would
|
|
998
|
+
// be counted as its encoded length, which no call of the report phase was ever reserved at; they are sized without
|
|
999
|
+
// it there, as before 0.13.0, and a refused check still costs only the check.
|
|
1000
|
+
const frame = controller === 'standard' && supportsImageMeasurement(inputMeasurement) ? newestFrame(prepared) : null;
|
|
1001
|
+
const choiceRequest = brief ? choiceCheckRequest({ briefText: choiceBriefText({ brief, intentNotes, secrets }), actionText: scrubSecrets(actionLogLines(actionLog), secrets), records: actionRecords, frame }) : null;
|
|
1002
|
+
const choice = choiceRequest ? measureActInput({ ...choiceRequest, max_tokens: CHOICE_CHECK_MAX_TOKENS, stream: true }, inputMeasurement, { controller }) : null;
|
|
1003
|
+
const claimCount = claimChecksAhead(notes, { realTime: realTimeRun(honesty) });
|
|
1004
|
+
const claim = claimCount > 0 ? measureActInput(claimCheckSizingRequest(frame), inputMeasurement, { controller }) : null;
|
|
941
1005
|
const decision = reserveDecision({
|
|
942
1006
|
usdMax: modelBudgetUsd,
|
|
943
1007
|
spend,
|
|
@@ -948,7 +1012,9 @@ async function playLoop({
|
|
|
948
1012
|
// The tools-free completion repair turn cannot read the cached prompt.
|
|
949
1013
|
actUncached: completionRepairPending,
|
|
950
1014
|
reportChars,
|
|
951
|
-
reportMaxTokens: REPORT_MAX_TOKENS
|
|
1015
|
+
reportMaxTokens: REPORT_MAX_TOKENS,
|
|
1016
|
+
choice: choice ? { chars: choice.chars, imageUnits: choice.imageUnits, maxTokens: CHOICE_CHECK_MAX_TOKENS } : null,
|
|
1017
|
+
claims: claim ? { count: claimCount, chars: claim.chars, imageUnits: claim.imageUnits, maxTokens: CLAIM_CHECK_MAX_TOKENS } : null
|
|
952
1018
|
});
|
|
953
1019
|
if (decision.known) Object.assign(decision.figures, { act_measurement: measured.measurement, act_images: measured.images, act_image_units: measured.imageUnits });
|
|
954
1020
|
return decision;
|
|
@@ -1134,7 +1200,13 @@ async function playLoop({
|
|
|
1134
1200
|
ledger.record({ model: answer.model, usage: answer.usage, ms: Date.now() - askedAt });
|
|
1135
1201
|
transcript.write({ kind: 'usage', step: 'act', turn: turns, ...usageLine(answer.usage) });
|
|
1136
1202
|
// The time the model took is play time only when the game ran through it.
|
|
1137
|
-
|
|
1203
|
+
const thoughtMs = Date.now() - askedAt;
|
|
1204
|
+
const frozenWhileThinking = Boolean(driver && driver.frozenBetweenActions);
|
|
1205
|
+
clock.thought(thoughtMs, frozenWhileThinking);
|
|
1206
|
+
if (!frozenWhileThinking) {
|
|
1207
|
+
timing.running += 1;
|
|
1208
|
+
timing.thinkMs.push(thoughtMs);
|
|
1209
|
+
}
|
|
1138
1210
|
recentActUnits.push(ledger.lastCallUnits || 0);
|
|
1139
1211
|
if (recentActUnits.length > 3) recentActUnits.shift();
|
|
1140
1212
|
// The warn turn is a turn the developer paid for, so its tool calls are
|
|
@@ -1842,7 +1914,7 @@ async function reportPhase({
|
|
|
1842
1914
|
client,
|
|
1843
1915
|
jobId,
|
|
1844
1916
|
runId,
|
|
1845
|
-
briefText:
|
|
1917
|
+
briefText: choiceBriefText({ brief, intentNotes, secrets }),
|
|
1846
1918
|
actionText: scrubSecrets(actionLogLines(play.actionLog), secrets),
|
|
1847
1919
|
records: play.records || [],
|
|
1848
1920
|
frame: play.finalFrame || null,
|
|
@@ -1882,6 +1954,12 @@ async function reportPhase({
|
|
|
1882
1954
|
// still fits.
|
|
1883
1955
|
const escalate = shouldEscalate(persona) && !play.budgetWarned && !play.budgetExceeded && !play.reserveStopped;
|
|
1884
1956
|
let maxTokens = REPORT_MAX_TOKENS;
|
|
1957
|
+
// A warned run has a fifth of its budget left at most. A first report cut off
|
|
1958
|
+
// at the ceiling spends most of that and leaves no room to ask again
|
|
1959
|
+
// (pt_run_e4b5ec8995a5ae70ef74: cut off at 4096, then only 2229 fit, so the
|
|
1960
|
+
// report came from the notes and the run read as out of budget). So the
|
|
1961
|
+
// first ask already says how much room there is.
|
|
1962
|
+
if (play.budgetWarned) askWithinBudget(messages, maxTokens);
|
|
1885
1963
|
let shrunk = false;
|
|
1886
1964
|
let lastCandidate = null;
|
|
1887
1965
|
// The largest output ceiling a turn has already been cut off at. A retry
|
|
@@ -2011,7 +2089,7 @@ async function reportPhase({
|
|
|
2011
2089
|
? { ...reproFixed.report, partial: true, quit_reason: 'cost_cap', quit_detail: play.quitDetail }
|
|
2012
2090
|
: reproFixed.report;
|
|
2013
2091
|
const capped = normalised ? capNetworkOnlyFindings(stampReport(reportCandidate, facts), { notes, screenshots }) : null;
|
|
2014
|
-
const runnerDrop = capped ? dropRunnerRejectedFindings(capped, { notes, observations }) : { report: null, dropped: [] };
|
|
2092
|
+
const runnerDrop = capped ? dropRunnerRejectedFindings(capped, { notes, observations, realTime: realTimeRun(honesty) }) : { report: null, dropped: [] };
|
|
2015
2093
|
for (const entry of runnerDrop.dropped) {
|
|
2016
2094
|
transcript.write({ kind: 'finding_dropped', id: entry.finding.id, severity: entry.finding.severity, title: entry.finding.title, reason: entry.reason });
|
|
2017
2095
|
}
|
|
@@ -2177,6 +2255,9 @@ async function reportPhase({
|
|
|
2177
2255
|
markdown = rewriteMarkdown(markdown, droppedByRunner.map(entry => entry.finding), report.findings || [], RUNNER_DROPPED_SECTION);
|
|
2178
2256
|
log(`dropped ${droppedByRunner.length} finding(s) the runner's evidence rules refuse: ${droppedByRunner.map(entry => `${entry.finding.id} (${entry.reason})`).join(', ')}`);
|
|
2179
2257
|
}
|
|
2258
|
+
// A game timer the playtester's own thinking ran out is said as the [too_fast] capability note it is.
|
|
2259
|
+
const timerMoved = droppedByRunner.filter(entry => entry.reason === TOO_FAST_REASON).map(entry => ({ id: entry.finding.id, title: entry.finding.title }));
|
|
2260
|
+
if (timerMoved.length > 0) markdown = sayTooFast({ markdown, moved: timerMoved, honesty, transcript });
|
|
2180
2261
|
// The uploaded pair agree: report.md says the severity report.json does.
|
|
2181
2262
|
if (downgradedByRunner.length > 0) markdown = rewriteDowngradedMarkdown(markdown, downgradedByRunner);
|
|
2182
2263
|
// A claim the checks turned away, or kept as an impression, leaves every part of report.md that stood on it as an issue.
|
|
@@ -2344,6 +2425,74 @@ export const CLAIM_SEVERITIES = Object.freeze(['blocker', 'major', 'minor', 'cos
|
|
|
2344
2425
|
/** Output ceiling for one claim check: the answer is a few words ("as designed" may quote the game's message). */
|
|
2345
2426
|
export const CLAIM_CHECK_MAX_TOKENS = 32;
|
|
2346
2427
|
|
|
2428
|
+
/* The report phase's calls as the budget reserve sizes them during play (./budgetReserve.js reportPhaseUnits). */
|
|
2429
|
+
|
|
2430
|
+
/** The brief as the choice check is shown it (./choiceCheck.js): the brief and its design intent notes, the brief's secrets taken out. */
|
|
2431
|
+
export function choiceBriefText({ brief, intentNotes, secrets = [] }) {
|
|
2432
|
+
return scrubSecrets(`${briefForPrompt(brief)}\n${intentNotesForPrompt(brief, intentNotes)}`, secrets);
|
|
2433
|
+
}
|
|
2434
|
+
|
|
2435
|
+
/**
|
|
2436
|
+
* The newest picture in a request's messages, as a frame (`{data, mediaType}`), or null when it has none: what
|
|
2437
|
+
* the choice check and a claim check are sized with during play, one picture each, as they send.
|
|
2438
|
+
*
|
|
2439
|
+
* @param {Array<Object>} messages
|
|
2440
|
+
* @returns {{data: string, mediaType: string}|null}
|
|
2441
|
+
*/
|
|
2442
|
+
export function newestFrame(messages) {
|
|
2443
|
+
const pictureOf = block => (block && block.type === 'image' && block.source && block.source.type === 'base64' && typeof block.source.data === 'string'
|
|
2444
|
+
? { data: block.source.data, mediaType: block.source.media_type || 'image/png' } : null);
|
|
2445
|
+
for (const message of [...(Array.isArray(messages) ? messages : [])].reverse()) {
|
|
2446
|
+
for (const block of [...(Array.isArray(message && message.content) ? message.content : [])].reverse()) {
|
|
2447
|
+
const found = pictureOf(block) || (block && block.type === 'tool_result' && Array.isArray(block.content) ? [...block.content].reverse().map(pictureOf).find(Boolean) : null);
|
|
2448
|
+
if (found) return found;
|
|
2449
|
+
}
|
|
2450
|
+
}
|
|
2451
|
+
return null;
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
/**
|
|
2455
|
+
* How many claim checks the report phase can be expected to make: one for each issue the persona noted (a bug,
|
|
2456
|
+
* something confusing, a suggestion), at most MAX_CLAIM_CHECKS. The report's issues come from those notes; a
|
|
2457
|
+
* repeated note counts again, which only keeps more back. Console lines, expected noise and waiting notes are
|
|
2458
|
+
* never asked about, and on a run whose game kept running while the model thought nor is a timer the
|
|
2459
|
+
* playtester ran out: the runner moves it to the [too_fast] note before any check.
|
|
2460
|
+
*
|
|
2461
|
+
* @param {Array<Object>} notes
|
|
2462
|
+
* @param {{realTime?: boolean}} [options]
|
|
2463
|
+
* @returns {number}
|
|
2464
|
+
*/
|
|
2465
|
+
export function claimChecksAhead(notes = [], { realTime = false } = {}) {
|
|
2466
|
+
const issues = (Array.isArray(notes) ? notes : []).filter(note => note && !note.automatic && !note.expected_noise && ['bug', 'confusing', 'suggestion'].includes(note.kind)
|
|
2467
|
+
&& !(realTime && timerNote(note)));
|
|
2468
|
+
return Math.min(MAX_CLAIM_CHECKS, issues.length);
|
|
2469
|
+
}
|
|
2470
|
+
|
|
2471
|
+
/** The widest claim a check asks about: the longest title and description claimText keeps, and three facts. */
|
|
2472
|
+
const WIDEST_CLAIM = Object.freeze({ severity: 'blocker', title: 'x'.repeat(160), description: 'x'.repeat(1200), facts: ['x'.repeat(100), 'x'.repeat(100), 'x'.repeat(100)] });
|
|
2473
|
+
|
|
2474
|
+
/**
|
|
2475
|
+
* One claim check's request at its largest, for the budget reserve: the longest question claimText asks (of each
|
|
2476
|
+
* kind it asks), the longer system prompt, and one picture.
|
|
2477
|
+
*
|
|
2478
|
+
* @param {{data: string, mediaType: string}|null} frame
|
|
2479
|
+
* @returns {Object} a request body
|
|
2480
|
+
*/
|
|
2481
|
+
export function claimCheckSizingRequest(frame) {
|
|
2482
|
+
const questions = [{ cls: 'absence', fault: true }, { cls: 'other', fault: true }, { cls: 'layout', fault: false }, { cls: 'other', fault: false }].map(moment => claimText(WIDEST_CLAIM, moment));
|
|
2483
|
+
const question = questions.reduce((longest, text) => (text.length > longest.length ? text : longest), '');
|
|
2484
|
+
const system = [CLAIM_SYSTEM, CLAIM_FAULT_SYSTEM].reduce((longest, text) => (text.length > longest.length ? text : longest), '');
|
|
2485
|
+
return {
|
|
2486
|
+
messages: [{ role: 'user', content: [
|
|
2487
|
+
...(frame && frame.data ? [{ type: 'image', source: { type: 'base64', media_type: frame.mediaType || 'image/png', data: frame.data } }] : []),
|
|
2488
|
+
{ type: 'text', text: question }
|
|
2489
|
+
] }],
|
|
2490
|
+
max_tokens: CLAIM_CHECK_MAX_TOKENS,
|
|
2491
|
+
stream: true,
|
|
2492
|
+
system
|
|
2493
|
+
};
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2347
2496
|
/**
|
|
2348
2497
|
* The screenshot a finding's claim is checked against: of those it cites, the
|
|
2349
2498
|
* one taken nearest after the latest observation it cites (the later of two on
|
|
@@ -2599,6 +2748,7 @@ export function buildReportRequest({ skill, schemas = [], persona, brief, localB
|
|
|
2599
2748
|
...(honesty && honesty.anygame ? [...honesty.anygame.reportLines(), ''] : []),
|
|
2600
2749
|
CAPABILITY_NOTES_INSTRUCTION,
|
|
2601
2750
|
...(capabilityPrompt(driverName, honesty ? honesty.capability.list() : []) ? ['', capabilityPrompt(driverName, honesty ? honesty.capability.list() : [])] : []),
|
|
2751
|
+
...(realTimeRun(honesty) ? ['', tooFastPrompt(thinkingTime(honesty.timing.thinkMs))] : []),
|
|
2602
2752
|
...(honesty && honesty.findings.length > 0 ? ['', `The runner itself saw these happen and adds them to the report as its own findings, with their steps and evidence. Do not write a finding of your own for the same thing; you may refer to them in "Top issues" by their title:\n${honesty.findings.map(finding => `- [${finding.severity}] ${finding.title}: ${finding.description}`).join('\n')}`] : []),
|
|
2603
2753
|
'Notes of kind dialog record a browser dialog the game opened and how it was answered. They are context: a finding only when what the game did after the answer was wrong.',
|
|
2604
2754
|
play.completionClaim
|
|
@@ -2640,6 +2790,21 @@ export function shorterReportInstruction(maxTokens) {
|
|
|
2640
2790
|
+ 'and a report.md of about 250 words that keeps its four sections. Write the files in one turn and do not restate the notes.';
|
|
2641
2791
|
}
|
|
2642
2792
|
|
|
2793
|
+
/** What a warned run's first report request says: the room it has, before anything is cut off. */
|
|
2794
|
+
export function withinBudgetReportInstruction(maxTokens) {
|
|
2795
|
+
return `This run is near its model budget, so the report has to fit in ${maxTokens} output tokens. Keep it short: at most 5 findings, each description and repro step one or two short sentences, `
|
|
2796
|
+
+ 'and a report.md of about 250 words that keeps its four sections. Write the files in one turn and do not restate the notes.';
|
|
2797
|
+
}
|
|
2798
|
+
|
|
2799
|
+
function askWithinBudget(messages, maxTokens) {
|
|
2800
|
+
const last = messages[messages.length - 1];
|
|
2801
|
+
if (!last || last.role !== 'user') return;
|
|
2802
|
+
const text = withinBudgetReportInstruction(maxTokens);
|
|
2803
|
+
const content = typeof last.content === 'string' ? [{ type: 'text', text: last.content }] : [...(last.content || [])];
|
|
2804
|
+
if (content.some(block => block && block.type === 'text' && block.text === text)) return;
|
|
2805
|
+
messages[messages.length - 1] = { ...last, content: [...content, { type: 'text', text }] };
|
|
2806
|
+
}
|
|
2807
|
+
|
|
2643
2808
|
/** Add the shorter-report instruction to the last user message, which is the next request's question. */
|
|
2644
2809
|
function askShorter(messages, maxTokens) {
|
|
2645
2810
|
const last = messages[messages.length - 1];
|
|
@@ -3095,9 +3260,10 @@ function completionReportNote(play) {
|
|
|
3095
3260
|
* screenshot list and says plainly that it is partial, rather than
|
|
3096
3261
|
* inventing a persona verdict nobody gave.
|
|
3097
3262
|
*/
|
|
3098
|
-
export function renderFallbackMarkdown({ persona, driverName, target, notes, screenshots, actions = [], actionRecords = [], play, reason, usage = null }) {
|
|
3263
|
+
export function renderFallbackMarkdown({ persona, driverName, target, notes, screenshots, actions = [], actionRecords = [], play, reason, usage = null, leftOut = [] }) {
|
|
3099
3264
|
const good = notes.filter(note => note.kind === 'good');
|
|
3100
|
-
|
|
3265
|
+
// `leftOut`: notes that are not issues of the game (a timer the playtester ran out, ./tooFast.js), said elsewhere.
|
|
3266
|
+
const bad = notes.filter(note => (note.kind === 'bug' || note.kind === 'confusing') && !leftOut.includes(note));
|
|
3101
3267
|
const network = notes.filter(note => note.automatic && note.url);
|
|
3102
3268
|
const list = entries => (entries.length > 0
|
|
3103
3269
|
? entries.map(note => `- **${note.kind}${note.severity ? `/${note.severity}` : ''}**: ${note.text}`).join('\n')
|
|
@@ -3309,8 +3475,13 @@ async function writePartialReport({ outcome, runDirectory, persona, driverName,
|
|
|
3309
3475
|
// is the scale's midpoint when it wrote none. `partial` still tells a reader
|
|
3310
3476
|
// that no report step judged it.
|
|
3311
3477
|
const mood = moodFromNotes(notes);
|
|
3478
|
+
// On a run whose game kept running while the playtester thought, a timer it ran out is the [too_fast] capability
|
|
3479
|
+
// note, never a finding: A1 of the November 19 mobile proofs ended here with its timer notes as major findings.
|
|
3480
|
+
const timerNotes = realTimeRun(honesty) ? notes.filter(timerNote) : [];
|
|
3481
|
+
const timing = thinkingTime(honesty && honesty.timing ? honesty.timing.thinkMs : []);
|
|
3482
|
+
if (timerNotes.length > 0 && honesty && honesty.capability) honesty.capability.add(tooFastNote(timing));
|
|
3312
3483
|
const report = stampReport({
|
|
3313
|
-
findings: findings || notesToFindings(notes, screenshots),
|
|
3484
|
+
findings: findings || notesToFindings(notes.filter(note => !timerNotes.includes(note)), screenshots),
|
|
3314
3485
|
sentiment: mood.sentiment,
|
|
3315
3486
|
would_continue: mood.wouldContinue,
|
|
3316
3487
|
partial: true
|
|
@@ -3338,13 +3509,18 @@ async function writePartialReport({ outcome, runDirectory, persona, driverName,
|
|
|
3338
3509
|
actionRecords,
|
|
3339
3510
|
play,
|
|
3340
3511
|
reason,
|
|
3341
|
-
usage: ledger.toReportUsage()
|
|
3512
|
+
usage: ledger.toReportUsage(),
|
|
3513
|
+
leftOut: timerNotes
|
|
3342
3514
|
});
|
|
3343
|
-
const
|
|
3515
|
+
const combined = preservedMarkdown
|
|
3344
3516
|
? ['# Playtest (partial report draft)', '',
|
|
3345
3517
|
'The run reached its model budget before this draft could be completed and checked. It is preserved below for review.',
|
|
3346
3518
|
'', preservedMarkdown, '', '---', '', fallbackMarkdown].join('\n')
|
|
3347
3519
|
: fallbackMarkdown;
|
|
3520
|
+
// The [too_fast] line goes in the first "What this run didn't cover", the one `run` reads its capability notes from.
|
|
3521
|
+
const markdown = timerNotes.length > 0
|
|
3522
|
+
? insertUnderHeading(combined, "## What this run didn't cover", tooFastLine(timerNotes.map(note => ({ id: `note ${notes.indexOf(note) + 1}`, title: note.text })), timing))
|
|
3523
|
+
: combined;
|
|
3348
3524
|
// What the runner saw happen is kept even in a report nobody reviewed: a
|
|
3349
3525
|
// crash it watched is true whatever became of the report step.
|
|
3350
3526
|
const honest = writeHonesty({ report, markdown, honesty, driverName, notes, screenshots, observations });
|
|
@@ -3395,7 +3571,7 @@ async function writeSomeReport({ log, bareReason = BUDGET_PARTIAL_REASON, ...rep
|
|
|
3395
3571
|
}
|
|
3396
3572
|
|
|
3397
3573
|
async function writePartialMarkdown({ runDirectory, persona, driverName, target, notes, screenshots, play, reason }) {
|
|
3398
|
-
const markdown = stampGeneratedAt(renderFallbackMarkdown({ persona, driverName, target, notes, screenshots, play, reason }), new Date().toISOString(), reportFacts({ persona, driverName, target, play }));
|
|
3574
|
+
const markdown = redactText(stampGeneratedAt(renderFallbackMarkdown({ persona, driverName, target, notes, screenshots, play, reason }), new Date().toISOString(), reportFacts({ persona, driverName, target, play })));
|
|
3399
3575
|
assertNoSecrets('report.md', markdown);
|
|
3400
3576
|
await writeFile(path.join(runDirectory, RUN_FILES.reportMd), markdown, 'utf8');
|
|
3401
3577
|
}
|
|
@@ -3594,7 +3770,7 @@ export function observationTitle(observation) {
|
|
|
3594
3770
|
/** How report.md lists what the runner dropped. */
|
|
3595
3771
|
export const RUNNER_DROPPED_SECTION = Object.freeze({
|
|
3596
3772
|
heading: '## Dropped by the runner (driver errors, runner limits, waiting notes or expected noise only)',
|
|
3597
|
-
explanation: 'The runner removes a blocker or major whose only cited observations are driver errors (the runner could not carry out an action; the game did nothing wrong), a finding that is about a limit of the runner itself (what its screen text did not show, a target it could not find), and any finding cited only by waiting notes or by console noise the brief says to expect. They are not sent to the server. They are kept here so you can judge them yourself.',
|
|
3773
|
+
explanation: 'The runner removes a blocker or major whose only cited observations are driver errors (the runner could not carry out an action; the game did nothing wrong), a finding that is about a limit of the runner itself (what its screen text did not show, a target it could not find, a game timer that ran out while it was still deciding), and any finding cited only by waiting notes or by console noise the brief says to expect. They are not sent to the server. They are kept here so you can judge them yourself.',
|
|
3598
3774
|
emptyNote: '- Nothing here that the runner kept. See the dropped findings below.'
|
|
3599
3775
|
});
|
|
3600
3776
|
|
|
@@ -3607,14 +3783,18 @@ export const RUNNER_DROPPED_SECTION = Object.freeze({
|
|
|
3607
3783
|
* Texas run filed "the season loop is fully blocked" from three strict mode
|
|
3608
3784
|
* failures, with a screenshot of the screen working.
|
|
3609
3785
|
* - Any finding whose transcript evidence is only waiting notes.
|
|
3786
|
+
* - On a run whose game kept running while the model thought (`realTime`), a
|
|
3787
|
+
* finding that says a game timer ran out or left too little time
|
|
3788
|
+
* (./tooFast.js): the playtester was slower than a player, which is the
|
|
3789
|
+
* [too_fast] capability note (TOO_FAST_REASON), never a finding.
|
|
3610
3790
|
*
|
|
3611
3791
|
* A finding with no transcript evidence is left to the other checks.
|
|
3612
3792
|
*
|
|
3613
3793
|
* @param {Object} report
|
|
3614
|
-
* @param {{notes?: Array, observations?: Array}} context
|
|
3794
|
+
* @param {{notes?: Array, observations?: Array, realTime?: boolean}} context
|
|
3615
3795
|
* @returns {{report: Object, dropped: Array<{finding: Object, reason: string}>}}
|
|
3616
3796
|
*/
|
|
3617
|
-
export function dropRunnerRejectedFindings(report, { notes = [], observations = [] } = {}) {
|
|
3797
|
+
export function dropRunnerRejectedFindings(report, { notes = [], observations = [], realTime = false } = {}) {
|
|
3618
3798
|
if (!report || !Array.isArray(report.findings)) return { report, dropped: [] };
|
|
3619
3799
|
const byIndex = new Map(observations.map(entry => [entry.index, entry]));
|
|
3620
3800
|
// The runner's console-error screenshot of a moment whose every console
|
|
@@ -3662,7 +3842,10 @@ export function dropRunnerRejectedFindings(report, { notes = [], observations =
|
|
|
3662
3842
|
for (const finding of report.findings) {
|
|
3663
3843
|
// Praise is never about a limit; anything else that talks about the
|
|
3664
3844
|
// runner's own tools is a capability note the persona filed as a finding.
|
|
3665
|
-
const reason = finding ?
|
|
3845
|
+
const reason = !finding ? null
|
|
3846
|
+
: finding.severity !== 'praise' && aboutRunnerLimit(finding) ? 'about a limit of the runner, not the game'
|
|
3847
|
+
: finding.severity !== 'praise' && realTime && timerExpiryClaim(`${finding.title || ''}\n${finding.description || ''}`) ? TOO_FAST_REASON
|
|
3848
|
+
: verdict(finding);
|
|
3666
3849
|
if (reason) dropped.push({ finding, reason });
|
|
3667
3850
|
else findings.push(finding);
|
|
3668
3851
|
}
|
package/src/run/proxyClient.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { redactText } from './redaction.js';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* The one HTTP client for Ravensight's model proxy.
|
|
3
5
|
*
|
|
@@ -138,7 +140,9 @@ export function createProxyClient({ baseURL, authToken, timeoutMs = 300000, fetc
|
|
|
138
140
|
response = await fetchImpl(url, {
|
|
139
141
|
method: 'POST',
|
|
140
142
|
headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream', Authorization: `Bearer ${authToken}`, ...headers },
|
|
141
|
-
|
|
143
|
+
// A live URL run's sign-in secrets are replaced as the very last step (./redaction.js), so a
|
|
144
|
+
// site that prints the test account on screen still never shows it to the model.
|
|
145
|
+
body: redactText(JSON.stringify(body)),
|
|
142
146
|
signal: controller.signal
|
|
143
147
|
});
|
|
144
148
|
} catch (error) {
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { readdir, readFile, stat, writeFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The run's redaction list: the sign-in secrets of a live URL playtest (the
|
|
6
|
+
* test account's email and password, each session cookie value, the session
|
|
7
|
+
* header value), held in this process only and never written anywhere.
|
|
8
|
+
*
|
|
9
|
+
* A secret joins the list the moment the CLI reads it, before any other use,
|
|
10
|
+
* with the forms it can take on the way out of a browser: as typed, URL
|
|
11
|
+
* encoded (both `%20` and form `+` spellings), escaped inside a JSON string,
|
|
12
|
+
* and in base64 and base64url at each of the three byte alignments (a Basic
|
|
13
|
+
* authorization value carries `email:password`, so the password sits part way
|
|
14
|
+
* into the encoded string). Every writer that can carry page or model text
|
|
15
|
+
* (log lines, the step log, report.md, report.json, usage.json, the journal)
|
|
16
|
+
* and the model request body pass through `redactText` as their last step,
|
|
17
|
+
* and the run directory is scanned again before upload (`redactDirectory`).
|
|
18
|
+
*
|
|
19
|
+
* With nothing on the list every function here returns its input unchanged,
|
|
20
|
+
* so runs that are not live URL runs are not touched.
|
|
21
|
+
*
|
|
22
|
+
* A value shorter than MIN_SECRET_CHARS is not added: replacing two or three
|
|
23
|
+
* characters everywhere would also rewrite ordinary words and the base64 of
|
|
24
|
+
* every screenshot sent to the model. The CLI refuses such a password before
|
|
25
|
+
* anything is registered; a short cookie value is not a credential.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** What a secret is replaced with. */
|
|
29
|
+
export const REDACTED = '[redacted]';
|
|
30
|
+
|
|
31
|
+
/** The shortest value or form that is redacted. */
|
|
32
|
+
export const MIN_SECRET_CHARS = 6;
|
|
33
|
+
|
|
34
|
+
/** @type {Map<string, boolean>} form -> case insensitive */
|
|
35
|
+
const forms = new Map();
|
|
36
|
+
let insensitivePattern = null;
|
|
37
|
+
let sensitivePattern = null;
|
|
38
|
+
|
|
39
|
+
const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
40
|
+
|
|
41
|
+
function rebuild() {
|
|
42
|
+
const build = (wanted, flags) => {
|
|
43
|
+
const list = [...forms].filter(([, insensitive]) => insensitive === wanted).map(([form]) => form).sort((a, b) => b.length - a.length);
|
|
44
|
+
return list.length > 0 ? new RegExp(list.map(escape).join('|'), flags) : null;
|
|
45
|
+
};
|
|
46
|
+
insensitivePattern = build(true, 'gi');
|
|
47
|
+
sensitivePattern = build(false, 'g');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The base64 characters that depend only on the secret's own bytes, when it
|
|
52
|
+
* starts `offset` bytes into a longer value.
|
|
53
|
+
*/
|
|
54
|
+
function base64Cores(value) {
|
|
55
|
+
const bytes = Buffer.from(value, 'utf8');
|
|
56
|
+
const out = [];
|
|
57
|
+
for (let offset = 0; offset < 3; offset += 1) {
|
|
58
|
+
const padded = Buffer.concat([Buffer.alloc(offset), bytes]);
|
|
59
|
+
const encoded = padded.toString('base64');
|
|
60
|
+
const start = Math.ceil((8 * offset) / 6);
|
|
61
|
+
const end = Math.floor((8 * (offset + bytes.length)) / 6);
|
|
62
|
+
const core = encoded.slice(start, end);
|
|
63
|
+
out.push(core, core.replace(/\+/g, '-').replace(/\//g, '_'));
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Add a secret and its encoded forms to the list.
|
|
70
|
+
*
|
|
71
|
+
* @param {unknown} value
|
|
72
|
+
* @param {{insensitive?: boolean}} [options] true for an email address, which a page may print in any case
|
|
73
|
+
* @returns {boolean} whether it was added
|
|
74
|
+
*/
|
|
75
|
+
export function addSecret(value, { insensitive = false } = {}) {
|
|
76
|
+
if (typeof value !== 'string' || value.length < MIN_SECRET_CHARS) return false;
|
|
77
|
+
const textForms = new Set([value, encodeURIComponent(value), new URLSearchParams({ v: value }).toString().slice(2), JSON.stringify(value).slice(1, -1)]);
|
|
78
|
+
for (const form of textForms) if (form.length >= MIN_SECRET_CHARS) forms.set(form, insensitive || forms.get(form) === true);
|
|
79
|
+
for (const form of base64Cores(value)) if (form.length >= MIN_SECRET_CHARS && !forms.has(form)) forms.set(form, false);
|
|
80
|
+
rebuild();
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Whether any secret is on the list. */
|
|
85
|
+
export function hasSecrets() {
|
|
86
|
+
return forms.size > 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Every form on the list (for tests that read files back). */
|
|
90
|
+
export function secretForms() {
|
|
91
|
+
return [...forms.keys()];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Empty the list (tests only). */
|
|
95
|
+
export function resetSecrets() {
|
|
96
|
+
forms.clear();
|
|
97
|
+
rebuild();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The text with every form of every secret replaced.
|
|
102
|
+
*
|
|
103
|
+
* @param {string} text
|
|
104
|
+
* @returns {string}
|
|
105
|
+
*/
|
|
106
|
+
export function redactText(text) {
|
|
107
|
+
if (forms.size === 0 || typeof text !== 'string') return text;
|
|
108
|
+
let out = text;
|
|
109
|
+
if (insensitivePattern) out = out.replace(insensitivePattern, REDACTED);
|
|
110
|
+
if (sensitivePattern) out = out.replace(sensitivePattern, REDACTED);
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* How many secret forms the text holds.
|
|
116
|
+
*
|
|
117
|
+
* @param {string} text
|
|
118
|
+
* @returns {number}
|
|
119
|
+
*/
|
|
120
|
+
export function countSecrets(text) {
|
|
121
|
+
if (forms.size === 0 || typeof text !== 'string') return 0;
|
|
122
|
+
let count = 0;
|
|
123
|
+
let rest = text;
|
|
124
|
+
if (insensitivePattern) {
|
|
125
|
+
count += (rest.match(insensitivePattern) || []).length;
|
|
126
|
+
rest = rest.replace(insensitivePattern, REDACTED);
|
|
127
|
+
}
|
|
128
|
+
if (sensitivePattern) count += (rest.match(sensitivePattern) || []).length;
|
|
129
|
+
return count;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Every string in a value redacted, through arrays and plain objects. Other
|
|
134
|
+
* values (buffers, dates, class instances) are returned as they are.
|
|
135
|
+
*
|
|
136
|
+
* @param {any} value
|
|
137
|
+
* @returns {any}
|
|
138
|
+
*/
|
|
139
|
+
export function redactValue(value) {
|
|
140
|
+
if (forms.size === 0) return value;
|
|
141
|
+
if (typeof value === 'string') return redactText(value);
|
|
142
|
+
if (Array.isArray(value)) return value.map(redactValue);
|
|
143
|
+
if (value && typeof value === 'object' && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) {
|
|
144
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, redactValue(entry)]));
|
|
145
|
+
}
|
|
146
|
+
return value;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** A log function whose every line is redacted first. */
|
|
150
|
+
export function redactingLog(log) {
|
|
151
|
+
return message => log(typeof message === 'string' ? redactText(message) : message);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const BINARY = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.webm', '.mp4', '.mov', '.zip', '.gz', '.br', '.wasm', '.pck']);
|
|
155
|
+
const MAX_SCAN_FILE_BYTES = 64 * 1024 * 1024;
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Scan every text file under a directory for the secrets, rewrite each one that
|
|
159
|
+
* holds any with them redacted, and count the hits. Binaries (pictures, video,
|
|
160
|
+
* archives, and any file with a NUL byte near its start) are left alone.
|
|
161
|
+
*
|
|
162
|
+
* @param {string} directory
|
|
163
|
+
* @returns {Promise<{redactions: number, files: Array<string>}>} files relative to the directory
|
|
164
|
+
*/
|
|
165
|
+
export async function redactDirectory(directory) {
|
|
166
|
+
const result = { redactions: 0, files: [] };
|
|
167
|
+
if (forms.size === 0) return result;
|
|
168
|
+
async function walk(dir) {
|
|
169
|
+
let entries;
|
|
170
|
+
try { entries = await readdir(dir, { withFileTypes: true }); } catch { return; }
|
|
171
|
+
for (const entry of entries) {
|
|
172
|
+
const full = path.join(dir, entry.name);
|
|
173
|
+
if (entry.isDirectory()) { await walk(full); continue; }
|
|
174
|
+
if (!entry.isFile() || BINARY.has(path.extname(entry.name).toLowerCase())) continue;
|
|
175
|
+
const info = await stat(full).catch(() => null);
|
|
176
|
+
if (!info || info.size > MAX_SCAN_FILE_BYTES) continue;
|
|
177
|
+
const bytes = await readFile(full).catch(() => null);
|
|
178
|
+
if (!bytes || bytes.subarray(0, 8000).includes(0)) continue;
|
|
179
|
+
const text = bytes.toString('utf8');
|
|
180
|
+
const hits = countSecrets(text);
|
|
181
|
+
if (hits === 0) continue;
|
|
182
|
+
await writeFile(full, redactText(text), 'utf8');
|
|
183
|
+
result.redactions += hits;
|
|
184
|
+
result.files.push(path.relative(directory, full).split(path.sep).join('/'));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
await walk(directory);
|
|
188
|
+
return result;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export default { addSecret, hasSecrets, redactText, redactValue, countSecrets, redactDirectory, redactingLog, resetSecrets, secretForms, REDACTED };
|
package/src/run/report.js
CHANGED
|
@@ -4,6 +4,7 @@ import Ajv2020 from 'ajv/dist/2020.js';
|
|
|
4
4
|
import addFormats from 'ajv-formats';
|
|
5
5
|
import { RUN_FILES } from './paths.js';
|
|
6
6
|
import { assertNoSecrets } from './secretScan.js';
|
|
7
|
+
import { redactText } from './redaction.js';
|
|
7
8
|
|
|
8
9
|
/**
|
|
9
10
|
* `report.json` and `report.md`: validated here before they are written,
|
|
@@ -543,8 +544,10 @@ export async function checkEvidence(report, runDirectory) {
|
|
|
543
544
|
* @param {Object} args.report
|
|
544
545
|
* @returns {Promise<{markdownPath: string, reportPath: string}>}
|
|
545
546
|
*/
|
|
546
|
-
export async function writeReportFiles({ runDirectory, markdown, report }) {
|
|
547
|
-
|
|
547
|
+
export async function writeReportFiles({ runDirectory, markdown: written, report }) {
|
|
548
|
+
// A live URL run's sign-in secrets are replaced as the last step (./redaction.js).
|
|
549
|
+
const markdown = redactText(written);
|
|
550
|
+
const json = redactText(`${JSON.stringify(report, null, 2)}\n`);
|
|
548
551
|
assertNoSecrets('report.md', markdown);
|
|
549
552
|
assertNoSecrets('report.json', json);
|
|
550
553
|
const markdownPath = path.join(runDirectory, RUN_FILES.reportMd);
|