imprint-mcp 0.6.4 → 0.6.6
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 +5 -0
- package/package.json +1 -1
- package/prompts/audit-agent.md +3 -3
- package/prompts/auth-compile-agent.md +46 -4
- package/prompts/compile-agent.md +36 -12
- package/prompts/live-verifier-agent.md +15 -5
- package/prompts/request-triage.md +51 -9
- package/prompts/tool-candidate-detection.md +7 -1
- package/prompts/tool-planning.md +1 -1
- package/src/cli.ts +71 -13
- package/src/imprint/audit.ts +23 -5
- package/src/imprint/auth-compile-agent.ts +11 -7
- package/src/imprint/auth-compile-tools.ts +127 -18
- package/src/imprint/auth-verifier.ts +2 -1
- package/src/imprint/backend-ladder.ts +20 -0
- package/src/imprint/build-plan.ts +21 -0
- package/src/imprint/claude-cli-compile.ts +7 -1
- package/src/imprint/codex-cli-compile.ts +6 -0
- package/src/imprint/compile-agent.ts +50 -9
- package/src/imprint/compile-tools.ts +308 -25
- package/src/imprint/compile-verification.ts +11 -2
- package/src/imprint/compile.ts +298 -69
- package/src/imprint/effects.ts +9 -0
- package/src/imprint/live-verifier.ts +455 -34
- package/src/imprint/login.ts +30 -12
- package/src/imprint/mcp-compile-server.ts +56 -5
- package/src/imprint/mcp-live-verifier-server.ts +43 -10
- package/src/imprint/probe-backends.ts +6 -0
- package/src/imprint/recording-request.ts +7 -2
- package/src/imprint/replay-capture.ts +48 -29
- package/src/imprint/request-capture.ts +14 -0
- package/src/imprint/runtime.ts +102 -22
- package/src/imprint/teach-state.ts +162 -21
- package/src/imprint/teach.ts +629 -226
- package/src/imprint/tool-candidates.ts +138 -0
- package/src/imprint/tool-plan.ts +2 -0
- package/src/imprint/triage-selection.ts +44 -0
- package/src/imprint/types.ts +39 -3
package/src/imprint/runtime.ts
CHANGED
|
@@ -19,7 +19,12 @@ import {
|
|
|
19
19
|
readSiteManifest,
|
|
20
20
|
saveSiteCookies,
|
|
21
21
|
} from './credential-store.ts';
|
|
22
|
-
import {
|
|
22
|
+
import {
|
|
23
|
+
captureHeader,
|
|
24
|
+
captureValueMatches,
|
|
25
|
+
jsonpath,
|
|
26
|
+
resolveJsonCapture,
|
|
27
|
+
} from './request-capture.ts';
|
|
23
28
|
import type {
|
|
24
29
|
RequestCapture,
|
|
25
30
|
StateCapability,
|
|
@@ -28,6 +33,7 @@ import type {
|
|
|
28
33
|
Workflow,
|
|
29
34
|
WorkflowRequest,
|
|
30
35
|
} from './types.ts';
|
|
36
|
+
import { persistedCaptureName } from './types.ts';
|
|
31
37
|
|
|
32
38
|
export { splitSetCookieHeader } from './cookie-jar.ts';
|
|
33
39
|
|
|
@@ -154,6 +160,10 @@ interface ExecuteOptions {
|
|
|
154
160
|
workflowPath?: string;
|
|
155
161
|
/** Initial ${state.X} values harvested by fetch-bootstrap. */
|
|
156
162
|
initialState?: Record<string, unknown>;
|
|
163
|
+
/** Caller cancellation for bounded verification work. */
|
|
164
|
+
signal?: AbortSignal;
|
|
165
|
+
/** Disable auth cookie/secret writes during offline request rendering. */
|
|
166
|
+
persistAuthState?: boolean;
|
|
157
167
|
}
|
|
158
168
|
|
|
159
169
|
interface ResponseSlot {
|
|
@@ -555,6 +565,7 @@ async function executeAuthWorkflow(opts: ExecuteOptions): Promise<ToolResult> {
|
|
|
555
565
|
});
|
|
556
566
|
|
|
557
567
|
const persistCookies = async (): Promise<RuntimeErrorResult | undefined> => {
|
|
568
|
+
if (opts.persistAuthState === false) return undefined;
|
|
558
569
|
try {
|
|
559
570
|
await saveSiteCookies(opts.workflow.site, cookieJar.toJSON());
|
|
560
571
|
return undefined;
|
|
@@ -566,6 +577,16 @@ async function executeAuthWorkflow(opts: ExecuteOptions): Promise<ToolResult> {
|
|
|
566
577
|
const executeRequest = async (
|
|
567
578
|
requestIndex: number,
|
|
568
579
|
): Promise<RuntimeResult<ResponseContext | undefined>> => {
|
|
580
|
+
if (opts.signal?.aborted) {
|
|
581
|
+
return {
|
|
582
|
+
ok: false,
|
|
583
|
+
result: fail({
|
|
584
|
+
ok: false,
|
|
585
|
+
error: 'NETWORK',
|
|
586
|
+
message: `Auth action ${JSON.stringify(actionName)} was cancelled.`,
|
|
587
|
+
}),
|
|
588
|
+
};
|
|
589
|
+
}
|
|
569
590
|
const req = opts.workflow.requests[requestIndex];
|
|
570
591
|
if (!req) {
|
|
571
592
|
return {
|
|
@@ -662,6 +683,8 @@ async function executeAuthWorkflow(opts: ExecuteOptions): Promise<ToolResult> {
|
|
|
662
683
|
}
|
|
663
684
|
} else {
|
|
664
685
|
const controller = new AbortController();
|
|
686
|
+
const cancel = (): void => controller.abort();
|
|
687
|
+
opts.signal?.addEventListener('abort', cancel, { once: true });
|
|
665
688
|
responseAbortTimer = setTimeout(() => controller.abort(), timeoutMs);
|
|
666
689
|
try {
|
|
667
690
|
response = await fetchFn(request.url, {
|
|
@@ -683,6 +706,8 @@ async function executeAuthWorkflow(opts: ExecuteOptions): Promise<ToolResult> {
|
|
|
683
706
|
}`,
|
|
684
707
|
},
|
|
685
708
|
};
|
|
709
|
+
} finally {
|
|
710
|
+
opts.signal?.removeEventListener('abort', cancel);
|
|
686
711
|
}
|
|
687
712
|
}
|
|
688
713
|
|
|
@@ -759,7 +784,14 @@ async function executeAuthWorkflow(opts: ExecuteOptions): Promise<ToolResult> {
|
|
|
759
784
|
let matched = !step.repeat;
|
|
760
785
|
|
|
761
786
|
for (let attempt = 0; attempt < (step.repeat?.maxAttempts ?? 1); attempt++) {
|
|
762
|
-
if (attempt > 0 && step.repeat) await sleep(step.repeat.intervalMs);
|
|
787
|
+
if (attempt > 0 && step.repeat) await sleep(step.repeat.intervalMs, opts.signal);
|
|
788
|
+
if (opts.signal?.aborted) {
|
|
789
|
+
return fail({
|
|
790
|
+
ok: false,
|
|
791
|
+
error: 'NETWORK',
|
|
792
|
+
message: `Auth action ${JSON.stringify(actionName)} was cancelled.`,
|
|
793
|
+
});
|
|
794
|
+
}
|
|
763
795
|
const executed = await executeRequest(step.request);
|
|
764
796
|
if (!executed.ok) {
|
|
765
797
|
if (step.onError === 'continue') {
|
|
@@ -828,7 +860,9 @@ async function executeAuthWorkflow(opts: ExecuteOptions): Promise<ToolResult> {
|
|
|
828
860
|
};
|
|
829
861
|
}
|
|
830
862
|
|
|
831
|
-
const missingPersisted = authConfig.persist.filter(
|
|
863
|
+
const missingPersisted = authConfig.persist.filter(
|
|
864
|
+
(name) => !Object.hasOwn(state, persistedCaptureName(authConfig, name)),
|
|
865
|
+
);
|
|
832
866
|
if (missingPersisted.length > 0) {
|
|
833
867
|
return fail({
|
|
834
868
|
ok: false,
|
|
@@ -838,21 +872,33 @@ async function executeAuthWorkflow(opts: ExecuteOptions): Promise<ToolResult> {
|
|
|
838
872
|
}
|
|
839
873
|
const persistedSecrets: Record<string, string> = {};
|
|
840
874
|
for (const name of authConfig.persist) {
|
|
841
|
-
const value = state[name];
|
|
875
|
+
const value = state[persistedCaptureName(authConfig, name)];
|
|
842
876
|
if (value !== undefined && value !== null && String(value) !== '') {
|
|
843
877
|
persistedSecrets[name] = String(value);
|
|
844
878
|
}
|
|
845
879
|
}
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
880
|
+
if (opts.persistAuthState !== false) {
|
|
881
|
+
try {
|
|
882
|
+
await commitSiteAuthState(opts.workflow.site, cookieJar.toJSON(), persistedSecrets);
|
|
883
|
+
} catch (err) {
|
|
884
|
+
return persistenceFailure('authenticated session state', err);
|
|
885
|
+
}
|
|
850
886
|
}
|
|
851
887
|
return { ok: true, data: { authenticated: true } };
|
|
852
888
|
}
|
|
853
889
|
|
|
854
|
-
function sleep(ms: number): Promise<void> {
|
|
855
|
-
|
|
890
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
891
|
+
if (signal?.aborted) return Promise.resolve();
|
|
892
|
+
return new Promise((resolve) => {
|
|
893
|
+
const timer = setTimeout(done, ms);
|
|
894
|
+
const abort = (): void => done();
|
|
895
|
+
function done(): void {
|
|
896
|
+
clearTimeout(timer);
|
|
897
|
+
signal?.removeEventListener('abort', abort);
|
|
898
|
+
resolve();
|
|
899
|
+
}
|
|
900
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
901
|
+
});
|
|
856
902
|
}
|
|
857
903
|
|
|
858
904
|
interface SubstitutedRequest {
|
|
@@ -890,12 +936,7 @@ function substituteRequest(
|
|
|
890
936
|
subbed.headers[k] = headerResult.value;
|
|
891
937
|
}
|
|
892
938
|
if (req.body !== undefined) {
|
|
893
|
-
const
|
|
894
|
-
const ctx: SubstitutionContext = ct.includes('json')
|
|
895
|
-
? 'json-body'
|
|
896
|
-
: ct.includes('urlencoded') || req.body.includes('=')
|
|
897
|
-
? 'form-body'
|
|
898
|
-
: 'opaque-body';
|
|
939
|
+
const ctx = bodySubstitutionContext(req);
|
|
899
940
|
const bodyResult = substituteStringInternal(req.body, requestRuntime, ctx);
|
|
900
941
|
if (!bodyResult.ok) return bodyResult;
|
|
901
942
|
subbed.body = bodyResult.value;
|
|
@@ -907,7 +948,33 @@ const PLACEHOLDER_RE = /\$\{([^}]+)\}/g;
|
|
|
907
948
|
|
|
908
949
|
/** What kind of context the template represents; controls how substituted
|
|
909
950
|
* values are escaped. */
|
|
910
|
-
type SubstitutionContext =
|
|
951
|
+
type SubstitutionContext =
|
|
952
|
+
| 'url'
|
|
953
|
+
| 'legacy-form-body'
|
|
954
|
+
| 'legacy-json-body'
|
|
955
|
+
| 'form-urlencoded-body'
|
|
956
|
+
| 'json-string-body'
|
|
957
|
+
| 'opaque-body'
|
|
958
|
+
| 'header';
|
|
959
|
+
|
|
960
|
+
/**
|
|
961
|
+
* New workflows declare body placeholder encoding explicitly. The fallback is
|
|
962
|
+
* intentionally frozen to the pre-contract behavior so already-emitted sites
|
|
963
|
+
* keep working until they are re-taught; compile verification does not allow
|
|
964
|
+
* newly generated placeholder-bearing bodies to rely on it.
|
|
965
|
+
*/
|
|
966
|
+
function bodySubstitutionContext(req: WorkflowRequest): SubstitutionContext {
|
|
967
|
+
if (req.bodyPlaceholderEncoding === 'raw') return 'opaque-body';
|
|
968
|
+
if (req.bodyPlaceholderEncoding === 'json-string') return 'json-string-body';
|
|
969
|
+
if (req.bodyPlaceholderEncoding === 'form-urlencoded') return 'form-urlencoded-body';
|
|
970
|
+
|
|
971
|
+
const ct = (req.headers['content-type'] ?? req.headers['Content-Type'] ?? '').toLowerCase();
|
|
972
|
+
if (ct.includes('json')) return 'legacy-json-body';
|
|
973
|
+
if (ct.includes('urlencoded') || (req.body?.includes('=') ?? false)) {
|
|
974
|
+
return 'legacy-form-body';
|
|
975
|
+
}
|
|
976
|
+
return 'opaque-body';
|
|
977
|
+
}
|
|
911
978
|
|
|
912
979
|
export function substituteString(
|
|
913
980
|
template: string,
|
|
@@ -1153,7 +1220,9 @@ function preflightStateDependencies(
|
|
|
1153
1220
|
return producer === undefined || producer >= i;
|
|
1154
1221
|
});
|
|
1155
1222
|
if (missingBeforeRequest.length === 0) continue;
|
|
1156
|
-
const hasPriorUnsafe = workflow.requests
|
|
1223
|
+
const hasPriorUnsafe = workflow.requests
|
|
1224
|
+
.slice(0, i)
|
|
1225
|
+
.some((request) => ['unsafe', 'irreversible'].includes(requestEffect(request)));
|
|
1157
1226
|
if (!hasPriorUnsafe) continue;
|
|
1158
1227
|
|
|
1159
1228
|
const name = missingBeforeRequest[0];
|
|
@@ -1177,7 +1246,7 @@ function workflowHasStateFeatures(workflow: Workflow): boolean {
|
|
|
1177
1246
|
);
|
|
1178
1247
|
}
|
|
1179
1248
|
|
|
1180
|
-
function requestEffect(req: WorkflowRequest): 'safe' | 'idempotent' | 'unsafe' {
|
|
1249
|
+
function requestEffect(req: WorkflowRequest): 'safe' | 'idempotent' | 'unsafe' | 'irreversible' {
|
|
1181
1250
|
if (req.effect) return req.effect;
|
|
1182
1251
|
const method = req.method.toUpperCase();
|
|
1183
1252
|
return method === 'GET' || method === 'HEAD' ? 'safe' : 'unsafe';
|
|
@@ -1212,7 +1281,7 @@ function evaluateRequestCaptures(
|
|
|
1212
1281
|
let value: unknown;
|
|
1213
1282
|
switch (capture.source) {
|
|
1214
1283
|
case 'json':
|
|
1215
|
-
value =
|
|
1284
|
+
value = resolveJsonCapture(ctx.parsed, capture.path, capture.decodeJsonPath);
|
|
1216
1285
|
break;
|
|
1217
1286
|
case 'response_header':
|
|
1218
1287
|
value = captureHeader(ctx.headers, capture.header, capture.mode);
|
|
@@ -1337,12 +1406,18 @@ function encodePart(
|
|
|
1337
1406
|
): string {
|
|
1338
1407
|
const s = value === undefined || value === null ? '' : String(value);
|
|
1339
1408
|
|
|
1340
|
-
if (context === 'form-body') {
|
|
1409
|
+
if (context === 'legacy-form-body') {
|
|
1341
1410
|
// Each substituted value sits between `&` and `=` separators; URL-encode
|
|
1342
1411
|
// so a value containing `@` / `&` / `=` doesn't corrupt the body shape.
|
|
1343
1412
|
return encodeURIComponent(s);
|
|
1344
1413
|
}
|
|
1345
|
-
if (context === '
|
|
1414
|
+
if (context === 'form-urlencoded-body') {
|
|
1415
|
+
// WHATWG form-component encoding (not encodeURIComponent): spaces become
|
|
1416
|
+
// `+` and the form encode set is applied exactly. The compile agent owns
|
|
1417
|
+
// the choice and proves round-trip behavior in request.test.ts.
|
|
1418
|
+
return new URLSearchParams([['value', s]]).toString().slice('value='.length);
|
|
1419
|
+
}
|
|
1420
|
+
if (context === 'legacy-json-body') {
|
|
1346
1421
|
// We're substituting INTO a string that will be parsed as JSON. The
|
|
1347
1422
|
// template treats `${credential.X}` as a literal string token, so
|
|
1348
1423
|
// escape characters that would terminate the surrounding JSON string.
|
|
@@ -1352,6 +1427,11 @@ function encodePart(
|
|
|
1352
1427
|
.replace(/\n/g, '\\n')
|
|
1353
1428
|
.replace(/\r/g, '\\r');
|
|
1354
1429
|
}
|
|
1430
|
+
if (context === 'json-string-body') {
|
|
1431
|
+
// JSON.stringify is the complete JSON string escaping algorithm. Remove
|
|
1432
|
+
// only its surrounding quotes because the workflow template owns them.
|
|
1433
|
+
return JSON.stringify(s).slice(1, -1);
|
|
1434
|
+
}
|
|
1355
1435
|
if (context === 'header' || context === 'opaque-body') {
|
|
1356
1436
|
return s;
|
|
1357
1437
|
}
|
|
@@ -33,13 +33,14 @@ import {
|
|
|
33
33
|
type SharedCompileContext,
|
|
34
34
|
SharedCompileContextSchema,
|
|
35
35
|
type ToolCandidate,
|
|
36
|
+
closeCandidateSelection,
|
|
36
37
|
} from './tool-candidates.ts';
|
|
37
38
|
|
|
38
39
|
export const TEACH_STEPS = [
|
|
39
40
|
'record',
|
|
40
41
|
'redact',
|
|
41
|
-
'replay-and-diff',
|
|
42
42
|
'triage',
|
|
43
|
+
'replay-and-diff',
|
|
43
44
|
'detect-candidates',
|
|
44
45
|
'plan-prereqs',
|
|
45
46
|
'generate',
|
|
@@ -55,6 +56,8 @@ export interface WorkflowState {
|
|
|
55
56
|
redactedPath?: string;
|
|
56
57
|
triagedPath?: string;
|
|
57
58
|
classificationsPath?: string;
|
|
59
|
+
/** Hash of the replay classification payload used for candidate/build planning. */
|
|
60
|
+
classificationsHash?: string;
|
|
58
61
|
completedSteps: TeachStep[];
|
|
59
62
|
error?: string;
|
|
60
63
|
startedAt: string;
|
|
@@ -90,6 +93,94 @@ export interface TeachState {
|
|
|
90
93
|
workflows: Record<string, WorkflowState>;
|
|
91
94
|
}
|
|
92
95
|
|
|
96
|
+
/** Candidate-backed resumes must reconstruct the persisted tool set so a
|
|
97
|
+
* downstream tool is never resumed without its upstream dependencies. */
|
|
98
|
+
export function isCandidateBackedResume(
|
|
99
|
+
ws: WorkflowState | undefined,
|
|
100
|
+
): ws is WorkflowState & { candidate: ToolCandidate } {
|
|
101
|
+
return ws?.candidate !== undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Only a fresh detection run supersedes existing tools. A resume may
|
|
105
|
+
* intentionally exclude tools from another recording or an earlier phase. */
|
|
106
|
+
export function staleCompletedToolsForRun(
|
|
107
|
+
completedToolNames: readonly string[],
|
|
108
|
+
incomingToolNames: ReadonlySet<string>,
|
|
109
|
+
cleanupStaleTools: boolean,
|
|
110
|
+
): string[] {
|
|
111
|
+
return cleanupStaleTools ? completedToolNames.filter((name) => !incomingToolNames.has(name)) : [];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Resolve behavior from the actual run chosen by the CLI/TUI, rather than from
|
|
115
|
+
* the presence of a CLI flag. Interactive Continue/Redo must follow the same
|
|
116
|
+
* resume semantics as an explicit `--from-step`. */
|
|
117
|
+
export function resolvedTeachRunPolicy(startFrom: TeachStep, resumesExistingRun: boolean) {
|
|
118
|
+
return {
|
|
119
|
+
cleanupStaleTools: !resumesExistingRun,
|
|
120
|
+
reuseExistingBuildPlan: startFrom !== 'plan-prereqs',
|
|
121
|
+
reviseExistingArtifacts: resumesExistingRun,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function candidatePlanningSignature(candidate: ToolCandidate): string {
|
|
126
|
+
return JSON.stringify(candidate);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Whether re-detection changed the candidate set or any planning-relevant
|
|
130
|
+
* candidate evidence for this recording. A changed graph invalidates prior
|
|
131
|
+
* plan-prereqs/compile progress even when candidate names stayed the same. */
|
|
132
|
+
export function candidateSelectionChanged(
|
|
133
|
+
state: TeachState,
|
|
134
|
+
sessionPath: string,
|
|
135
|
+
selected: ToolCandidate[],
|
|
136
|
+
sharedContext?: SharedCompileContext,
|
|
137
|
+
classificationsHash?: string,
|
|
138
|
+
): boolean {
|
|
139
|
+
const priorWorkflows = Object.values(state.workflows).filter(
|
|
140
|
+
(workflow) => workflow.sessionPath === sessionPath && workflow.candidate,
|
|
141
|
+
);
|
|
142
|
+
if (priorWorkflows.length === 0) return false;
|
|
143
|
+
const prior = priorWorkflows.map((workflow) => workflow.candidate as ToolCandidate);
|
|
144
|
+
const signatures = (candidates: ToolCandidate[]): string[] =>
|
|
145
|
+
candidates.map(candidatePlanningSignature).sort();
|
|
146
|
+
if (JSON.stringify(signatures(prior)) !== JSON.stringify(signatures(selected))) return true;
|
|
147
|
+
const priorContexts = new Set(
|
|
148
|
+
priorWorkflows.map((workflow) => JSON.stringify(workflow.sharedContext ?? null)),
|
|
149
|
+
);
|
|
150
|
+
if (priorContexts.size !== 1 || !priorContexts.has(JSON.stringify(sharedContext ?? null))) {
|
|
151
|
+
return true;
|
|
152
|
+
}
|
|
153
|
+
const priorClassificationHashes = new Set(
|
|
154
|
+
priorWorkflows.map((workflow) => workflow.classificationsHash ?? null),
|
|
155
|
+
);
|
|
156
|
+
return (
|
|
157
|
+
priorClassificationHashes.size !== 1 ||
|
|
158
|
+
!priorClassificationHashes.has(classificationsHash ?? null)
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Remove obsolete candidate state for one recording after a new selection is
|
|
163
|
+
* finalized. Other recordings and pending placeholders remain untouched. */
|
|
164
|
+
export function pruneUnselectedCandidateWorkflows(
|
|
165
|
+
state: TeachState,
|
|
166
|
+
sessionPath: string,
|
|
167
|
+
selectedToolNames: ReadonlySet<string>,
|
|
168
|
+
): string[] {
|
|
169
|
+
const removed: string[] = [];
|
|
170
|
+
for (const [key, workflow] of Object.entries(state.workflows)) {
|
|
171
|
+
if (
|
|
172
|
+
workflow.sessionPath !== sessionPath ||
|
|
173
|
+
!workflow.candidate ||
|
|
174
|
+
selectedToolNames.has(workflow.candidate.toolName)
|
|
175
|
+
) {
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
delete state.workflows[key];
|
|
179
|
+
removed.push(key);
|
|
180
|
+
}
|
|
181
|
+
return removed;
|
|
182
|
+
}
|
|
183
|
+
|
|
93
184
|
export function teachStatePath(site: string): string {
|
|
94
185
|
return pathJoin(localSiteDir(site), '.teach-state.json');
|
|
95
186
|
}
|
|
@@ -106,9 +197,10 @@ export function loadTeachState(site: string): TeachState {
|
|
|
106
197
|
try {
|
|
107
198
|
const state = JSON.parse(readFileSync(loadPath, 'utf8')) as TeachState;
|
|
108
199
|
for (const workflow of Object.values(state.workflows)) {
|
|
109
|
-
if (
|
|
110
|
-
|
|
111
|
-
|
|
200
|
+
if (workflow.sharedContext) {
|
|
201
|
+
const parsed = SharedCompileContextSchema.safeParse(workflow.sharedContext);
|
|
202
|
+
workflow.sharedContext = parsed.success ? parsed.data : undefined;
|
|
203
|
+
}
|
|
112
204
|
}
|
|
113
205
|
return isLegacy ? normalizeLegacyTeachState(site, state) : state;
|
|
114
206
|
} catch {
|
|
@@ -434,8 +526,8 @@ export function resolveStepStartTarget(
|
|
|
434
526
|
return { workflowKey, ws };
|
|
435
527
|
}
|
|
436
528
|
|
|
437
|
-
/** A
|
|
438
|
-
*
|
|
529
|
+
/** A candidate-backed resume reconstructs the prior run's tools from persisted
|
|
530
|
+
* state. Scope it to (a) tools from the SAME recording as the resume
|
|
439
531
|
* target — cross-recording tools have a different session and would otherwise be
|
|
440
532
|
* compiled against the wrong one — and (b) tools whose prior run actually reached
|
|
441
533
|
* `fromStep`'s prerequisites — a tool that failed earlier has no
|
|
@@ -445,13 +537,14 @@ export function resolveStepStartTarget(
|
|
|
445
537
|
interface MultiToolResumeSelection {
|
|
446
538
|
plans: {
|
|
447
539
|
workflowKey: string;
|
|
448
|
-
candidate:
|
|
540
|
+
candidate: ToolCandidate;
|
|
449
541
|
sharedContext: WorkflowState['sharedContext'];
|
|
450
542
|
}[];
|
|
451
543
|
skipped: {
|
|
452
544
|
workflowKey: string;
|
|
453
545
|
reason: 'different-recording' | 'not-resumable' | 'not-in-build-plan';
|
|
454
546
|
}[];
|
|
547
|
+
cycles: string[][];
|
|
455
548
|
}
|
|
456
549
|
|
|
457
550
|
export function selectMultiToolResumePlans(
|
|
@@ -459,13 +552,18 @@ export function selectMultiToolResumePlans(
|
|
|
459
552
|
targetWorkflowKey: string,
|
|
460
553
|
fromStep: TeachStep,
|
|
461
554
|
opts?: {
|
|
462
|
-
|
|
463
|
-
allTools?: boolean;
|
|
555
|
+
primaryTool?: boolean;
|
|
464
556
|
toolName?: string;
|
|
465
557
|
plannedToolNames?: ReadonlySet<string>;
|
|
466
558
|
},
|
|
467
559
|
): MultiToolResumeSelection {
|
|
468
560
|
const target = state.workflows[targetWorkflowKey];
|
|
561
|
+
const persistedPrimary = Object.entries(state.workflows).find(
|
|
562
|
+
([key, workflow]) =>
|
|
563
|
+
!key.startsWith('_pending_') &&
|
|
564
|
+
workflow.candidate?.primary &&
|
|
565
|
+
(!target || workflow.sessionPath === target.sessionPath),
|
|
566
|
+
);
|
|
469
567
|
const plans: MultiToolResumeSelection['plans'] = [];
|
|
470
568
|
const skipped: MultiToolResumeSelection['skipped'] = [];
|
|
471
569
|
for (const [key, ws] of Object.entries(state.workflows)) {
|
|
@@ -484,6 +582,34 @@ export function selectMultiToolResumePlans(
|
|
|
484
582
|
}
|
|
485
583
|
plans.push({ workflowKey: key, candidate: ws.candidate, sharedContext: ws.sharedContext });
|
|
486
584
|
}
|
|
585
|
+
if (target?.candidate && !plans.some((plan) => plan.workflowKey === targetWorkflowKey)) {
|
|
586
|
+
const reason = skipped.find((entry) => entry.workflowKey === targetWorkflowKey)?.reason;
|
|
587
|
+
throw new Error(
|
|
588
|
+
`Cannot resume tool "${target.candidate.toolName}" from "${fromStep}": the target is ${reason ?? 'unavailable'}. Resume an earlier step or re-run from "detect-candidates".`,
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
const closePlans = (rootNames: string[]): Pick<MultiToolResumeSelection, 'plans' | 'cycles'> => {
|
|
592
|
+
const candidatePlans = plans;
|
|
593
|
+
const closure = closeCandidateSelection(
|
|
594
|
+
candidatePlans.map((plan) => plan.candidate),
|
|
595
|
+
rootNames,
|
|
596
|
+
);
|
|
597
|
+
const selectedNames = new Set(closure.selected.map((candidate) => candidate.toolName));
|
|
598
|
+
const eligibleNames = new Set(candidatePlans.map((plan) => plan.candidate.toolName));
|
|
599
|
+
for (const candidate of closure.selected) {
|
|
600
|
+
for (const dependency of candidate.dependsOnTools) {
|
|
601
|
+
if (eligibleNames.has(dependency)) continue;
|
|
602
|
+
throw new Error(
|
|
603
|
+
`Cannot resume tool "${candidate.toolName}" from "${fromStep}": required upstream tool "${dependency}" is unavailable. Re-run from "detect-candidates" to rebuild a complete tool set.`,
|
|
604
|
+
);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
return {
|
|
608
|
+
plans: plans.filter((plan) => selectedNames.has(plan.candidate.toolName)),
|
|
609
|
+
cycles: closure.cycles,
|
|
610
|
+
};
|
|
611
|
+
};
|
|
612
|
+
|
|
487
613
|
if (opts?.toolName) {
|
|
488
614
|
const selected = plans.find(
|
|
489
615
|
(plan) => plan.workflowKey === opts.toolName || plan.candidate?.toolName === opts.toolName,
|
|
@@ -493,35 +619,50 @@ export function selectMultiToolResumePlans(
|
|
|
493
619
|
`Cannot resume tool "${opts.toolName}": it is not resumable from "${fromStep}" in the selected recording.`,
|
|
494
620
|
);
|
|
495
621
|
}
|
|
496
|
-
return {
|
|
622
|
+
return { ...closePlans([selected.candidate.toolName]), skipped };
|
|
497
623
|
}
|
|
498
|
-
if (opts?.
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
624
|
+
if (opts?.primaryTool) {
|
|
625
|
+
if (!persistedPrimary) {
|
|
626
|
+
throw new Error(
|
|
627
|
+
`Cannot resume from "${fromStep}" with --primary-tool: the selected recording has no primary candidate. Re-run from "detect-candidates".`,
|
|
628
|
+
);
|
|
629
|
+
}
|
|
630
|
+
const primary = plans.find((plan) => plan.workflowKey === persistedPrimary[0]);
|
|
631
|
+
if (!primary) {
|
|
632
|
+
const reason = skipped.find((entry) => entry.workflowKey === persistedPrimary[0])?.reason;
|
|
633
|
+
throw new Error(
|
|
634
|
+
`Cannot resume primary tool "${persistedPrimary[1].candidate?.toolName ?? persistedPrimary[0]}" from "${fromStep}": it is ${reason ?? 'unavailable'}. Resume an earlier step or re-run from "detect-candidates".`,
|
|
635
|
+
);
|
|
636
|
+
}
|
|
637
|
+
return {
|
|
638
|
+
...closePlans([primary.candidate.toolName]),
|
|
639
|
+
skipped,
|
|
640
|
+
};
|
|
502
641
|
}
|
|
503
|
-
return {
|
|
642
|
+
return {
|
|
643
|
+
...closePlans(plans.map((plan) => plan.candidate.toolName)),
|
|
644
|
+
skipped,
|
|
645
|
+
};
|
|
504
646
|
}
|
|
505
647
|
|
|
506
|
-
/** True when the `[startIdx, stopIdx]` phase window overlaps the
|
|
507
|
-
* block (replay-and-diff →
|
|
648
|
+
/** True when the `[startIdx, stopIdx]` phase window overlaps the analysis
|
|
649
|
+
* block (triage → replay-and-diff → detect-candidates), i.e. that block must run.
|
|
508
650
|
* Indices are positions in TEACH_STEPS (stopIdx defaults to the last step when no
|
|
509
651
|
* `--to-step` is given). Classic interval-overlap check, extracted so it can be
|
|
510
652
|
* unit-tested independently of teach()'s runtime flow. */
|
|
511
653
|
export function analysisBlockRunsForWindow(startIdx: number, stopIdx: number): boolean {
|
|
512
654
|
return (
|
|
513
|
-
startIdx <= TEACH_STEPS.indexOf('detect-candidates') &&
|
|
514
|
-
stopIdx >= TEACH_STEPS.indexOf('replay-and-diff')
|
|
655
|
+
startIdx <= TEACH_STEPS.indexOf('detect-candidates') && stopIdx >= TEACH_STEPS.indexOf('triage')
|
|
515
656
|
);
|
|
516
657
|
}
|
|
517
658
|
|
|
518
659
|
/** The shared-pipeline steps recorded when the analysis block
|
|
519
|
-
* (replay-and-diff →
|
|
660
|
+
* (triage → replay-and-diff → detect-candidates) completes. */
|
|
520
661
|
export const ANALYSIS_COMPLETED_STEPS: TeachStep[] = [
|
|
521
662
|
'record',
|
|
522
663
|
'redact',
|
|
523
|
-
'replay-and-diff',
|
|
524
664
|
'triage',
|
|
665
|
+
'replay-and-diff',
|
|
525
666
|
'detect-candidates',
|
|
526
667
|
];
|
|
527
668
|
|