@aibyzero/cm-workflow 0.16.4 → 0.16.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/.codex-plugin/plugin.json +1 -1
- package/AGENTS.md +22 -0
- package/CHANGELOG.md +57 -0
- package/README.md +22 -4
- package/THIRD_PARTY_NOTICES.md +9 -0
- package/VERSION +1 -1
- package/docs/architecture.md +43 -0
- package/docs/execution-optimizations.md +33 -0
- package/docs/external-models.md +114 -0
- package/docs/fixes/.reviews/20260929-bootstrap-unchanged-review-r1.md +7 -0
- package/docs/fixes/.reviews/20260930-develop-package-limit-recovery-r4.md +9 -0
- package/docs/fixes/20260929-bootstrap-rule-refresh-conflict.md +22 -0
- package/docs/fixes/20260929-bootstrap-unchanged-review.md +26 -0
- package/docs/fixes/20260930-develop-package-limit-recovery.md +65 -0
- package/docs/human-correction.md +31 -0
- package/docs/installation.md +48 -7
- package/docs/js-workflow-control.md +293 -33
- package/docs/live-evidence-drivers.md +62 -0
- package/docs/next-steps.md +15 -10
- package/docs/runtime-failover.md +1 -1
- package/docs/untested-branches.md +27 -4
- package/docs/user-guide.md +23 -8
- package/install-codex.sh +28 -11
- package/package.json +1 -1
- package/runtime/js/cm-ai/accepted-fix.mjs +23 -5
- package/runtime/js/cm-ai/bootstrap-feature.mjs +15 -0
- package/runtime/js/cm-ai/claude-review-adapter.mjs +7 -4
- package/runtime/js/cm-ai/claude-review-stream.mjs +12 -0
- package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
- package/runtime/js/cm-ai/cm-ai-admission.mjs +115 -41
- package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +3 -2
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +208 -34
- package/runtime/js/cm-ai/cm-ai-learning-handoff-writer.mjs +11 -9
- package/runtime/js/cm-ai/cm-ai-learning-writer.mjs +22 -5
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +181 -57
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +15 -58
- package/runtime/js/cm-ai/codex-config.mjs +3 -2
- package/runtime/js/cm-ai/codex-review-adapter.mjs +56 -17
- package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
- package/runtime/js/cm-ai/developer-adapter.mjs +6 -2
- package/runtime/js/cm-ai/diagnostic-reason.mjs +10 -0
- package/runtime/js/cm-ai/drive-bootstrap.mjs +315 -0
- package/runtime/js/cm-ai/drive-core.mjs +47 -9
- package/runtime/js/cm-ai/durable-runner-state.mjs +413 -56
- package/runtime/js/cm-ai/effect-abandon-log.mjs +19 -0
- package/runtime/js/cm-ai/effect-contract.mjs +44 -2
- package/runtime/js/cm-ai/execution-policy.mjs +58 -0
- package/runtime/js/cm-ai/execution-store-limits.mjs +18 -0
- package/runtime/js/cm-ai/execution-store.mjs +6 -4
- package/runtime/js/cm-ai/external-group-models.mjs +53 -0
- package/runtime/js/cm-ai/external-model-launch.mjs +23 -0
- package/runtime/js/cm-ai/external-models.mjs +52 -0
- package/runtime/js/cm-ai/external-run-guard.mjs +96 -0
- package/runtime/js/cm-ai/fix-code-association.mjs +171 -18
- package/runtime/js/cm-ai/host-bootstrap.mjs +126 -29
- package/runtime/js/cm-ai/host-check.mjs +30 -4
- package/runtime/js/cm-ai/host-conversation-execution.mjs +66 -20
- package/runtime/js/cm-ai/host-handoff.mjs +13 -6
- package/runtime/js/cm-ai/host-progress.mjs +80 -0
- package/runtime/js/cm-ai/host-project-execution.mjs +16 -11
- package/runtime/js/cm-ai/host-qa-executor.mjs +23 -9
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +23 -6
- package/runtime/js/cm-ai/host-qa-policy.mjs +16 -7
- package/runtime/js/cm-ai/host-session.mjs +12 -4
- package/runtime/js/cm-ai/host-tool-bridge.mjs +1 -1
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +16 -5
- package/runtime/js/cm-ai/host.mjs +1 -1
- package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -0
- package/runtime/js/cm-ai/launch-mismatch.mjs +42 -0
- package/runtime/js/cm-ai/legacy-model-run-preview.mjs +24 -0
- package/runtime/js/cm-ai/legacy-model-settings.mjs +59 -0
- package/runtime/js/cm-ai/live-evidence.mjs +96 -0
- package/runtime/js/cm-ai/log-rows.mjs +21 -0
- package/runtime/js/cm-ai/model-configuration-file.mjs +63 -0
- package/runtime/js/cm-ai/model_configuration_write.py +214 -0
- package/runtime/js/cm-ai/native-usage-log.mjs +26 -0
- package/runtime/js/cm-ai/operator-guidance.mjs +86 -0
- package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
- package/runtime/js/cm-ai/project-qa-gate.mjs +84 -0
- package/runtime/js/cm-ai/provider-review-observation.mjs +68 -9
- package/runtime/js/cm-ai/provider-usage.mjs +39 -0
- package/runtime/js/cm-ai/qa-config-revision.mjs +44 -10
- package/runtime/js/cm-ai/review-abandon-log.mjs +21 -0
- package/runtime/js/cm-ai/review-package.mjs +438 -31
- package/runtime/js/cm-ai/review-presentation.mjs +45 -0
- package/runtime/js/cm-ai/review-reconciliation.mjs +20 -0
- package/runtime/js/cm-ai/review-runner.mjs +47 -1
- package/runtime/js/cm-ai/reviewed-deliveries.mjs +97 -0
- package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +104 -10
- package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +42 -3
- package/runtime/js/cm-ai/specification-material.mjs +154 -12
- package/runtime/js/cm-ai/status-projection.mjs +93 -0
- package/runtime/js/cm-ai/task-commit.mjs +2 -2
- package/runtime/js/cm-ai/task-runner.mjs +658 -75
- package/runtime/js/cm-ai/tool-preview.mjs +8 -4
- package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
- package/runtime/js/cm-ai/worker-claude.mjs +63 -19
- package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -9
- package/runtime/js/cm-ai/worker-codex.mjs +45 -19
- package/runtime/js/cm-fix/cause-evidence.mjs +5 -3
- package/runtime/js/cm-fix/cause-invocation.mjs +6 -3
- package/runtime/js/cm-fix/cause-package.mjs +10 -1
- package/runtime/js/cm-fix/execution.mjs +279 -52
- package/runtime/js/cm-fix/final-review.mjs +18 -10
- package/runtime/js/cm-fix/host-review.mjs +32 -9
- package/runtime/js/cm-fix/host.mjs +6 -1
- package/runtime/js/cm-fix/layout.mjs +1 -1
- package/runtime/js/cm-fix/progress.mjs +5 -0
- package/runtime/js/cm-fix/protected-edits.mjs +15 -4
- package/runtime/js/cm-fix/qa-source.mjs +6 -4
- package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
- package/runtime/js/cm-prd/analysis.mjs +2 -1
- package/runtime/js/cm-prd/change.mjs +28 -10
- package/runtime/js/cm-prd/draft.mjs +5 -2
- package/runtime/js/cm-prd/response-recovery.mjs +23 -0
- package/runtime/js/cm-prd/review-preparation.mjs +10 -3
- package/runtime/js/cm-prd/review-publication.mjs +27 -15
- package/runtime/js/cm-prd/review-time.mjs +29 -0
- package/runtime/js/cm-prd/self-check.mjs +6 -3
- package/runtime/js/cm-prd/session.mjs +53 -6
- package/runtime/js/cm-prd/summary.mjs +3 -1
- package/runtime/js/cm-prd/validation-reason.mjs +20 -0
- package/runtime/js/cm-security/finalize.mjs +32 -0
- package/runtime/js/spec-task-line.mjs +117 -0
- package/runtime/js/specs-status.mjs +10 -3
- package/runtime/review.md +5 -0
- package/runtime/task-gates.md +6 -0
- package/runtime/workflow-config.md +10 -1
- package/scripts/cm-ai-abandon-effect-position.test.mjs +201 -0
- package/scripts/cm-ai-admission.mjs +18 -11
- package/scripts/cm-ai-admission.test.mjs +65 -1
- package/scripts/cm-ai-batch-drive.mjs +135 -34
- package/scripts/cm-ai-batch-drive.test.mjs +209 -3
- package/scripts/cm-ai-batch-host.mjs +63 -24
- package/scripts/cm-ai-batch-host.test.mjs +2 -1
- package/scripts/cm-ai-batch-run.mjs +101 -34
- package/scripts/cm-ai-batch-run.test.mjs +56 -5
- package/scripts/cm-ai-bootstrap-driver-preflight.test.mjs +45 -0
- package/scripts/cm-ai-bootstrap-flow.test.mjs +159 -0
- package/scripts/cm-ai-bootstrap-merge.test.mjs +162 -0
- package/scripts/cm-ai-bootstrap.test.mjs +174 -89
- package/scripts/cm-ai-conversation-entry-ops.test.mjs +97 -2
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +924 -0
- package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +468 -0
- package/scripts/cm-ai-drive-timeout.test.mjs +17 -0
- package/scripts/cm-ai-drive.mjs +526 -60
- package/scripts/cm-ai-drive.test.mjs +336 -10
- package/scripts/cm-ai-fix-later-delivery.test.mjs +383 -0
- package/scripts/cm-ai-host.mjs +142 -43
- package/scripts/cm-ai-host.test.mjs +232 -12
- package/scripts/cm-ai-launch-diagnostics.test.mjs +142 -0
- package/scripts/cm-ai-multi-root.test.mjs +9 -3
- package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
- package/scripts/cm-ai-progress.test.mjs +521 -0
- package/scripts/cm-ai-project-qa-gate.test.mjs +308 -0
- package/scripts/cm-ai-qa-config-revision.test.mjs +187 -15
- package/scripts/cm-ai-qa-fingerprint-config.test.mjs +157 -0
- package/scripts/cm-ai-qa-fix-cross-session.test.mjs +27 -2
- package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +400 -0
- package/scripts/cm-ai-review-drift-precedence.test.mjs +90 -0
- package/scripts/cm-ai-review-failure.test.mjs +977 -0
- package/scripts/cm-ai-review-timeout-config.test.mjs +29 -7
- package/scripts/cm-ai-review-timeout.test.mjs +199 -4
- package/scripts/cm-ai-run.mjs +206 -62
- package/scripts/cm-ai-run.test.mjs +6 -4
- package/scripts/cm-ai-runner-error-code-regression.test.mjs +219 -0
- package/scripts/cm-ai-selection-guard.test.mjs +100 -0
- package/scripts/cm-ai-session-chain.test.mjs +7 -3
- package/scripts/cm-ai-spec-rebind.test.mjs +481 -0
- package/scripts/cm-ai-supersede.test.mjs +571 -17
- package/scripts/cm-ai-verification-gate.test.mjs +2 -1
- package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
- package/scripts/cm-capability-gate.test.mjs +21 -2
- package/scripts/cm-check-drive.test.mjs +2 -1
- package/scripts/cm-check-host.test.mjs +1 -1
- package/scripts/cm-check-runtime.sh +12 -1
- package/scripts/cm-claude-developer-worker.test.mjs +3 -1
- package/scripts/cm-claude-install-layout.test.mjs +26 -0
- package/scripts/cm-claude-probe.test.mjs +10 -2
- package/scripts/cm-claude-review-stream.test.mjs +25 -0
- package/scripts/cm-claude-worker.test.mjs +11 -4
- package/scripts/cm-codex-developer-worker.test.mjs +4 -2
- package/scripts/cm-codex-plugin-metadata.py +83 -0
- package/scripts/cm-codex-plugin-metadata.test.mjs +55 -0
- package/scripts/cm-efficiency-checks.test.mjs +37 -0
- package/scripts/cm-efficiency-diagnostics.test.mjs +74 -0
- package/scripts/cm-efficiency-offline.mjs +35 -0
- package/scripts/cm-efficiency-policy.test.mjs +48 -0
- package/scripts/cm-efficiency-presentation.test.mjs +35 -0
- package/scripts/cm-efficiency-response.test.mjs +117 -0
- package/scripts/cm-efficiency-usage.test.mjs +148 -0
- package/scripts/cm-external-batch-host.test.mjs +157 -0
- package/scripts/cm-external-fix-host.test.mjs +281 -0
- package/scripts/cm-external-fix-reconciliation.test.mjs +105 -0
- package/scripts/cm-external-group-models.test.mjs +60 -0
- package/scripts/cm-external-model-host.test.mjs +180 -0
- package/scripts/cm-external-model-recovery.test.mjs +108 -0
- package/scripts/cm-external-models.test.mjs +89 -0
- package/scripts/cm-external-process-cleanup.test.mjs +71 -0
- package/scripts/cm-external-qa-fix.test.mjs +170 -0
- package/scripts/cm-external-review-reconciliation.test.mjs +314 -0
- package/scripts/cm-failover.mjs +8 -8
- package/scripts/cm-fix-abandon.test.mjs +123 -5
- package/scripts/cm-fix-cause-package.test.mjs +2 -0
- package/scripts/cm-fix-drive.mjs +70 -23
- package/scripts/cm-fix-drive.test.mjs +36 -1
- package/scripts/cm-fix-final-review.test.mjs +11 -6
- package/scripts/cm-fix-host.mjs +24 -14
- package/scripts/cm-fix-protected-edits.test.mjs +12 -0
- package/scripts/cm-fix-rediagnosis.test.mjs +168 -0
- package/scripts/cm-fix-review-budget.test.mjs +147 -0
- package/scripts/cm-fixture-process-cleanup.test.mjs +95 -0
- package/scripts/cm-host-check.test.mjs +6 -3
- package/scripts/cm-host-qa-executor.test.mjs +213 -17
- package/scripts/cm-host-session-diagnostic.test.mjs +10 -0
- package/scripts/cm-interactive-qa-diagnostic.test.mjs +53 -0
- package/scripts/cm-knowledge-closeout.test.mjs +160 -0
- package/scripts/cm-live-evidence.test.mjs +64 -0
- package/scripts/cm-log-event.mjs +25 -2
- package/scripts/cm-log-event.py +15 -0
- package/scripts/cm-log-event.test.mjs +31 -0
- package/scripts/cm-model-setup.mjs +79 -0
- package/scripts/cm-prd-completion.test.mjs +75 -0
- package/scripts/cm-prd-draft.test.mjs +14 -0
- package/scripts/cm-prd-drive.mjs +32 -11
- package/scripts/cm-prd-drive.test.mjs +15 -0
- package/scripts/cm-prd-gate-diagnostic.test.mjs +100 -0
- package/scripts/cm-prd-host.mjs +13 -4
- package/scripts/cm-prd-review-gate.mjs +126 -81
- package/scripts/cm-prd-review-gate.test.mjs +105 -1
- package/scripts/cm-prd-review-preparation.test.mjs +15 -0
- package/scripts/cm-prd-review-publication.test.mjs +6 -0
- package/scripts/cm-prd-self-check.test.mjs +6 -0
- package/scripts/cm-prd-summary.test.mjs +9 -0
- package/scripts/cm-release-smoke.sh +5 -1
- package/scripts/cm-review-dependency-snapshot.test.mjs +15 -0
- package/scripts/cm-review-inventory.test.mjs +253 -1
- package/scripts/cm-runtime-i18n.mjs +15 -4
- package/scripts/cm-runtime-install.mjs +8 -4
- package/scripts/cm-runtime.mjs +116 -23
- package/scripts/cm-runtime.test.mjs +121 -12
- package/scripts/cm-security.test.mjs +32 -0
- package/scripts/cm-spec-manifest.mjs +28 -10
- package/scripts/cm-spec-manifest.test.mjs +8 -4
- package/scripts/cm-spec-task-line.test.mjs +138 -0
- package/scripts/cm-specs-status.test.mjs +12 -1
- package/scripts/cm-task-gate-correction.test.mjs +117 -0
- package/scripts/cm-task-gate.mjs +164 -20
- package/scripts/cm-task-gate.py +2 -1
- package/scripts/cm-test-branch-impact.test.mjs +6 -3
- package/scripts/cm-test-drive.mjs +10 -4
- package/scripts/cm-test-drive.test.mjs +14 -1
- package/scripts/cm-tool-preview-context.test.mjs +12 -0
- package/scripts/cm-usage-report.py +22 -3
- package/scripts/cm-workflow-config.mjs +10 -1
- package/scripts/fixtures/bootstrap-review-runner.mjs +102 -0
- package/scripts/fixtures/claude-review-process.mjs +1 -0
- package/scripts/fixtures/live-evidence-driver.mjs +35 -0
- package/scripts/fixtures/process-cleanup.mjs +101 -0
- package/scripts/test-cm-log-event.py +2 -0
- package/scripts/test-cm-native-usage.py +62 -0
- package/scripts/test-cm-prd-review-gate.py +2 -1
- package/scripts/test-external-model-setup.py +91 -0
- package/scripts/test-model-configuration-write.py +201 -0
- package/scripts/test-npm-install.py +11 -2
- package/scripts/test-scan-public-safety.py +1 -1
- package/scripts/test-spec-manifest.py +16 -8
- package/scripts/test-task-gate.py +2 -2
- package/scripts/test-workflow-config.py +1 -0
- package/scripts/validate-public-repo.py +1 -0
- package/skills/cm-ai/SKILL.md +2 -2
- package/skills/cm-ai/references/N1-init.md +1 -1
- package/skills/cm-ai/references/N8-finish.md +5 -0
- package/skills/cm-ai/references/js-host.md +270 -43
- package/skills/cm-ai/references/knowledge-closeout.md +90 -0
- package/skills/cm-fix/SKILL.md +1 -1
- package/skills/cm-fix/references/js-host.md +52 -3
- package/skills/cm-prd/references/js-change-recovery.md +1 -1
- package/skills/cm-prd/references/js-host.md +6 -0
- package/skills/cm-runtime/SKILL.md +29 -6
- package/skills/cm-security/SKILL.md +4 -2
- package/skills/cm-security/references/scan-contract.md +1 -0
- package/templates/cm-workflow.yml +1 -1
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// status, none host.mjs handle status/cancel.
|
|
11
11
|
// cancel
|
|
12
12
|
// host.mjs 自己运行 config.commands 并记录真实退出码;没有 host_request 命令证据。
|
|
13
|
-
// qa_browser
|
|
13
|
+
// qa_browser 由显式 liveEvidence 当前会话执行;未配置时发送前拒绝。
|
|
14
14
|
import fs from 'node:fs';
|
|
15
15
|
import path from 'node:path';
|
|
16
16
|
import {fileURLToPath} from 'node:url';
|
|
@@ -25,6 +25,9 @@ import {inspectDeclaredTestCommand} from '../runtime/js/cm-test/declared-command
|
|
|
25
25
|
import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
26
26
|
import {stderr,stop,readJson,loadPlanFile,requireFields,preflightAnswers,driveHost} from '../runtime/js/cm-ai/drive-core.mjs';
|
|
27
27
|
|
|
28
|
+
import {driverLiveEvidence} from '../runtime/js/cm-ai/live-evidence.mjs';
|
|
29
|
+
|
|
30
|
+
// PLAN.liveEvidence: fresh current-session evidence; see docs/live-evidence-drivers.md.
|
|
28
31
|
const HOST=fileURLToPath(new URL('./cm-test-host.mjs',import.meta.url));
|
|
29
32
|
const KNOWN=new Set(['start','resume','status','cancel']);
|
|
30
33
|
const FILES={change_impact:'change-impact.json',test_cases:'test-cases.json',qa_logic:'qa-logic.json'};
|
|
@@ -34,7 +37,7 @@ const safeFile=file=>fs.existsSync(file)&&fs.lstatSync(file).isFile()&&!fs.lstat
|
|
|
34
37
|
|
|
35
38
|
function main(){
|
|
36
39
|
if(process.argv.length===3&&['--help','-h'].includes(process.argv[2])){
|
|
37
|
-
process.stdout.write('用法: cm-test-drive.mjs --plan PLAN.json <start|resume|status|cancel>\nPLAN: config, answers, sessionDir (resume), resolution:null
|
|
40
|
+
process.stdout.write('用法: cm-test-drive.mjs --plan PLAN.json <start|resume|status|cancel>\nPLAN: config, answers, sessionDir (resume), resolution:null。浏览器执行用 PLAN.liveEvidence {directory,kinds:["qa_browser"],timeoutMs?};未配置时预检拒绝。\n');return;
|
|
38
41
|
}
|
|
39
42
|
const {operation,plan,base}=loadPlanFile({name:'cm-test-drive.mjs',known:KNOWN});
|
|
40
43
|
requireFields(plan,['config']);
|
|
@@ -116,9 +119,12 @@ function main(){
|
|
|
116
119
|
return value;
|
|
117
120
|
};
|
|
118
121
|
const answers=preflightAnswers(asks,loadAnswer);
|
|
122
|
+
let live;
|
|
123
|
+
try{live=driverLiveEvidence(plan,{base,protectedRoots:[admission.project,admission.specs],allowedKinds:['qa_browser']});}
|
|
124
|
+
catch(error){stop(2,error.message);}
|
|
119
125
|
if(['start','resume'].includes(operation)&&admission.operation!=='impact'){
|
|
120
126
|
if(admission.modes.includes('browser')&&(admission.operation==='explore'||contract?.cases?.some(item=>item.kind==='browser')))
|
|
121
|
-
stop(2,'缺少真实执行 runner: qa_browser;不能从静态答案文件应答');
|
|
127
|
+
if(!live.has('qa_browser'))stop(2,'缺少真实执行 runner: qa_browser;不能从静态答案文件应答');
|
|
122
128
|
if(admission.modes.includes('logic')&&contract?.cases?.some(item=>item.kind==='logic'))
|
|
123
129
|
answers.qa_logic=loadAnswer('qa_logic');
|
|
124
130
|
}
|
|
@@ -127,6 +133,6 @@ function main(){
|
|
|
127
133
|
&&(['start','resume'].includes(operation)||operation==='status'&&existingSession)
|
|
128
134
|
?['--session-dir',path.resolve(base,plan.sessionDir)]:[])],
|
|
129
135
|
cwd:admission.project,operation,request:operation==='resume'?{resolution:null}:{},answers,paths:{},
|
|
130
|
-
answerFor:row=>answers[row.kind]??null});
|
|
136
|
+
answerFor:(row,answers,paths,control)=>live.has(row.kind)?live.answer(row,control):answers[row.kind]??null});
|
|
131
137
|
}
|
|
132
138
|
main();
|
|
@@ -6,6 +6,7 @@ import path from 'node:path';
|
|
|
6
6
|
import {spawnSync} from 'node:child_process';
|
|
7
7
|
import {fileURLToPath} from 'node:url';
|
|
8
8
|
import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
|
|
9
|
+
import {runLiveDriver} from './fixtures/live-evidence-driver.mjs';
|
|
9
10
|
const root=fileURLToPath(new URL('..',import.meta.url));
|
|
10
11
|
const driver=path.join(root,'scripts/cm-test-drive.mjs');
|
|
11
12
|
const write=(file,value)=>fs.writeFileSync(file,JSON.stringify(value));
|
|
@@ -27,6 +28,18 @@ function setup(t,kind='logic'){
|
|
|
27
28
|
t.after(()=>fs.rmSync(temp,{recursive:true,force:true}));
|
|
28
29
|
return {temp,project,config,answers,session,planPath,run};
|
|
29
30
|
}
|
|
31
|
+
test('browser live handoff reaches the real host and preserves an unavailable-device BLOCKED observation',async t=>{
|
|
32
|
+
const f=setup(t,'browser');
|
|
33
|
+
write(f.planPath,{config:'config.json',answers:'answers',sessionDir:'session',
|
|
34
|
+
liveEvidence:{directory:'exchange',kinds:['qa_browser'],timeoutMs:1000}});
|
|
35
|
+
const out=await runLiveDriver(driver,f.planPath,'start',row=>{
|
|
36
|
+
assert.equal(row.kind,'qa_browser');assert.equal(row.payload.case.id,'TC-001');
|
|
37
|
+
return {verdict:'BLOCKED',evidence:[],environment:row.payload.environment,cleanup:'not_needed'};
|
|
38
|
+
});
|
|
39
|
+
assert.equal(out.status,0,out.stderr);assert.equal(out.requests.length,1);
|
|
40
|
+
assert.equal(JSON.parse(out.stdout).result.overall,'BLOCKED');
|
|
41
|
+
assert.equal(JSON.parse(out.stdout).result.executionPassed,0);
|
|
42
|
+
});
|
|
30
43
|
test('real host: status is read-only, logic start and historical resume',t=>{
|
|
31
44
|
const f=setup(t);let out=f.run('status');assert.equal(out.status,0,out.stderr);
|
|
32
45
|
assert.equal(JSON.parse(out.stdout).result.stage,'ready');assert.equal(fs.existsSync(f.session),false);
|
|
@@ -72,7 +85,7 @@ test('mutation probes catch static browser answer, omitted schema check, dropped
|
|
|
72
85
|
};
|
|
73
86
|
const browser=setup(t,'browser');let out=browser.run('start');assert.equal(out.status,2);
|
|
74
87
|
const changed=source.replace("if(admission.modes.includes('browser')&&(admission.operation==='explore'||contract?.cases?.some(item=>item.kind==='browser')))","if(false)")
|
|
75
|
-
.replace('answerFor:row=>answers[row.kind]??null',"answerFor:row=>row.kind==='qa_browser'?readJson(path.join(answerRoot,'qa-browser.json'),'qa_browser'):answers[row.kind]??null");
|
|
88
|
+
.replace('answerFor:(row,answers,paths,control)=>live.has(row.kind)?live.answer(row,control):answers[row.kind]??null',"answerFor:row=>row.kind==='qa_browser'?readJson(path.join(answerRoot,'qa-browser.json'),'qa_browser'):answers[row.kind]??null");
|
|
76
89
|
const staticFile=path.join(root,'scripts',`.cm-test-drive-static-mutant-${process.pid}.mjs`);fs.writeFileSync(staticFile,changed);
|
|
77
90
|
t.after(()=>fs.rmSync(staticFile,{force:true}));
|
|
78
91
|
const report=path.join(browser.project,'docs/test-reports','fake.md');fs.mkdirSync(path.dirname(report),{recursive:true});fs.writeFileSync(report,'Fabricated browser result');
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import {skillContext} from '../runtime/js/cm-ai/tool-preview.mjs';
|
|
4
|
+
const retainedPreamble = "Each entry includes a name, description, and location for its `SKILL.md`. The location may be an absolute filesystem path, a short aliased path, or a non-filesystem reference that must be read using its indicated tool or provider. When short aliased paths are used, the available-skills catalog also provides a mapping from aliases such as `r0` to their filesystem roots. Expand the alias before accessing the skill.\n\nThe user's instructions take precedence over guidelines provided in a skill. If explicit user instructions conflict with a skill's instructions, prioritize the user's instructions.\n\nThe first time in a conversation that you decide to apply a skill, inform the user in the commentary channel.\n\nIf a skill causes you to ask for permission or confirmation, pause, or leave requested work unfinished, name the skill and summarize the specific instruction in the skill that led to your decision. Include this explanation in the request or final response where you pause.";
|
|
5
|
+
const input = text => ({input:[{content:[{text}]}]});
|
|
6
|
+
test('Codex 0.159.2 retained empty skill preamble is not a catalog',()=>{
|
|
7
|
+
assert.equal(skillContext(input('<skills_instructions>\n### Available skills\n'+retainedPreamble+'\n</skills_instructions>')).present,false);
|
|
8
|
+
});
|
|
9
|
+
test('real, unresolved and unknown catalogs remain blocked',()=>{
|
|
10
|
+
for(const content of ['- sample (file: /tmp/sample/SKILL.md)','- sample (file: r99/sample/SKILL.md)','Unrecognized catalog content'])
|
|
11
|
+
assert.equal(skillContext(input('<skills_instructions>\n### Available skills\n'+retainedPreamble+'\n'+content+'\n</skills_instructions>')).present,true);
|
|
12
|
+
});
|
|
@@ -179,12 +179,14 @@ def usage_row_error(row: Dict[str, Any]) -> Optional[str]:
|
|
|
179
179
|
return "invalid input count"
|
|
180
180
|
if not is_nonnegative_int(row.get("output_tokens")):
|
|
181
181
|
return "invalid output count"
|
|
182
|
-
for field in ("cache_read_tokens", "cache_write_tokens"):
|
|
182
|
+
for field in ("cache_read_tokens", "cache_write_tokens", "reasoning_tokens"):
|
|
183
183
|
if field in row and not is_nonnegative_int(row[field]):
|
|
184
184
|
return "invalid cache count"
|
|
185
|
+
if "reasoning_tokens" in row and row["reasoning_tokens"] > row["output_tokens"]:
|
|
186
|
+
return "invalid reasoning subset"
|
|
185
187
|
return None
|
|
186
188
|
if usage_state == "unavailable":
|
|
187
|
-
if any(field in row for field in TOKEN_FIELDS):
|
|
189
|
+
if any(field in row for field in TOKEN_FIELDS + ("reasoning_tokens",)):
|
|
188
190
|
return "unavailable row contains token counts"
|
|
189
191
|
return None
|
|
190
192
|
return "invalid usage state"
|
|
@@ -242,6 +244,8 @@ def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
|
|
|
242
244
|
usage_candidates: List[Tuple[RunRef, Path, int, Dict[str, Any]]] = []
|
|
243
245
|
seen_event_ids: Set[str] = set()
|
|
244
246
|
seen_call_ids: Set[Tuple[str, str]] = set()
|
|
247
|
+
native_calls = 0
|
|
248
|
+
native_components = {field: {"tokens": 0, "observed_calls": 0} for field in TOKEN_FIELDS + ("reasoning_tokens",)}
|
|
245
249
|
|
|
246
250
|
for ref in refs:
|
|
247
251
|
log_path = safe_log_path(log_home, ref.log_file)
|
|
@@ -307,7 +311,7 @@ def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
|
|
|
307
311
|
continue
|
|
308
312
|
seen_call_ids.add(call_key)
|
|
309
313
|
claim = claims.get(call_key)
|
|
310
|
-
if row.get("adapter") == "openai-compatible" and claim is None:
|
|
314
|
+
if (row.get("adapter") == "openai-compatible" or row.get("source") == "native-cli-terminal") and claim is None:
|
|
311
315
|
summary["invalid_calls"] += 1
|
|
312
316
|
print(
|
|
313
317
|
f"warning: ignored managed model_usage without prior claim at "
|
|
@@ -333,6 +337,12 @@ def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
|
|
|
333
337
|
stage = str(row["stage"])
|
|
334
338
|
role = str(row["role"])
|
|
335
339
|
usage_state = row.get("usage_state")
|
|
340
|
+
if row.get("source") == "native-cli-terminal":
|
|
341
|
+
native_calls += 1
|
|
342
|
+
for field, component in native_components.items():
|
|
343
|
+
if usage_state == "observed" and field in row:
|
|
344
|
+
component["tokens"] += row[field]
|
|
345
|
+
component["observed_calls"] += 1
|
|
336
346
|
outcome = str(row["outcome"])
|
|
337
347
|
summary["outcomes"][outcome] += 1
|
|
338
348
|
if usage_state == "unavailable":
|
|
@@ -446,6 +456,11 @@ def build_report(log_home: Path, refs: List[RunRef]) -> Dict[str, Any]:
|
|
|
446
456
|
"groups": groups,
|
|
447
457
|
"unavailable_groups": unavailable_groups,
|
|
448
458
|
"unresolved_groups": unresolved_groups,
|
|
459
|
+
**({"native_components": {"calls": native_calls, "reasoning_is_output_subset": True,
|
|
460
|
+
"cache_counts_are_separate": True, "fields": {field: {
|
|
461
|
+
"tokens": value["tokens"] if value["observed_calls"] else None,
|
|
462
|
+
"observed_calls": value["observed_calls"], "unavailable_calls": native_calls - value["observed_calls"]
|
|
463
|
+
} for field, value in native_components.items()}}} if native_calls else {}),
|
|
449
464
|
}
|
|
450
465
|
|
|
451
466
|
|
|
@@ -490,6 +505,10 @@ def print_human(report: Dict[str, Any]) -> None:
|
|
|
490
505
|
f"{group['role']} | {group['adapter']} | "
|
|
491
506
|
f"{group['requested_model']} | claims {group['claims']}"
|
|
492
507
|
)
|
|
508
|
+
if "native_components" in report:
|
|
509
|
+
for field, value in report["native_components"]["fields"].items():
|
|
510
|
+
known = value["tokens"] if value["tokens"] is not None else "unavailable"
|
|
511
|
+
print(f"- native {field}: {known}; observed {value['observed_calls']}, unavailable {value['unavailable_calls']}")
|
|
493
512
|
print(
|
|
494
513
|
"- 缺失 usage 保持 unavailable;未完成 claim 单独报告且不计调用/Token;"
|
|
495
514
|
"未推测缺失用量,也未换算费用。"
|
|
@@ -464,6 +464,15 @@ export function loadUserRuntimes(){
|
|
|
464
464
|
}
|
|
465
465
|
|
|
466
466
|
export function loadConfig(input){
|
|
467
|
+
return loadConfigUsing(input,loadUserRuntimes);
|
|
468
|
+
}
|
|
469
|
+
// Read-only candidate resolution; use the same merge and validation as the real loader.
|
|
470
|
+
// Keep the public loadConfig input and effective-config JSON contracts unchanged.
|
|
471
|
+
export function previewUserRuntimeConfig(input,preset){
|
|
472
|
+
runtimePreset(preset);
|
|
473
|
+
return loadConfigUsing(input,()=>({preset}));
|
|
474
|
+
}
|
|
475
|
+
function loadConfigUsing(input,userDefaults){
|
|
467
476
|
if(!object(input)||!Object.hasOwn(input,'projectRoot')
|
|
468
477
|
||Object.keys(input).some(key=>!['projectRoot','configPath','text'].includes(key)))throw new ConfigError('invalid config input');
|
|
469
478
|
const root=realDirectory(input.projectRoot,'project root');
|
|
@@ -486,7 +495,7 @@ export function loadConfig(input){
|
|
|
486
495
|
const raw=parseDocument(configPath,text);walkForSecrets(raw);validateRaw(raw);
|
|
487
496
|
const normalizedRaw={...raw,version:Number(raw.version)};
|
|
488
497
|
const projectDeclared=raw.runtimes?.available!==undefined;
|
|
489
|
-
const user=projectDeclared?null:
|
|
498
|
+
const user=projectDeclared?null:userDefaults();
|
|
490
499
|
const defaults=user?deepMerge(DEFAULT_CONFIG,runtimePreset(user.preset)):DEFAULT_CONFIG;
|
|
491
500
|
const effective=deepMerge(defaults,normalizedRaw),policy=effective.roles.external_expert.model_policy;
|
|
492
501
|
RUNTIME_SOURCES.set(effective,projectDeclared?'project':user?'user':'none');
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import {buildManifest} from '../cm-spec-manifest.mjs';
|
|
2
|
+
import {after} from 'node:test';
|
|
3
|
+
import assert from 'node:assert/strict';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import {fileURLToPath} from 'node:url';
|
|
8
|
+
import {createHostBootstrap} from '../../runtime/js/cm-ai/host-bootstrap.mjs';
|
|
9
|
+
import {cmInitRuleTargets} from '../../runtime/js/cm-init/draft-generation.mjs';
|
|
10
|
+
import {createTaskRunner} from '../../runtime/js/cm-ai/task-runner.mjs';
|
|
11
|
+
import {openTaskExecutionStore} from '../../runtime/js/cm-ai/task-owner.mjs';
|
|
12
|
+
import {createDeveloperRun} from '../../runtime/js/cm-ai/developer-adapter.mjs';
|
|
13
|
+
import {inspectCmAiTaskLearningInput} from '../../runtime/js/cm-ai/cm-ai-context-refresh.mjs';
|
|
14
|
+
import {digest} from '../../runtime/js/cm-ai/effect-contract.mjs';
|
|
15
|
+
import {createHostCheck} from '../../runtime/js/cm-ai/host-check.mjs';
|
|
16
|
+
import {reviewPaths} from '../../runtime/js/cm-ai/review-runner.mjs';
|
|
17
|
+
|
|
18
|
+
// Keep runtime declarations and log mirrors independent of the invoking user's home.
|
|
19
|
+
const isolatedWorkflowHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-ai-bootstrap-home-'));
|
|
20
|
+
process.env.CM_WORKFLOW_HOME=path.join(isolatedWorkflowHome,'user');
|
|
21
|
+
process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedWorkflowHome,'logs');
|
|
22
|
+
after(()=>fs.rmSync(isolatedWorkflowHome,{recursive:true,force:true}));
|
|
23
|
+
|
|
24
|
+
export const workflowRoot=fileURLToPath(new URL('../..',import.meta.url)).replace(/\/$/,'');
|
|
25
|
+
export const selection={versionControl:'none',modules:['frontend'],analysis:'Approved synthetic JavaScript project'};
|
|
26
|
+
const checks=()=>Object.fromEntries(['commands','globs','file_references','constraint_preservation','rule_applicability']
|
|
27
|
+
.map(name=>[name,{status:'verified',evidence:'Synthetic semantic report for the local fixture'}]));
|
|
28
|
+
export function fixture(t){
|
|
29
|
+
const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-bootstrap-')));
|
|
30
|
+
t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
|
|
31
|
+
const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs');
|
|
32
|
+
fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,'0.bootstrap'),{recursive:true});fs.mkdirSync(path.join(specsDir,'.reviews'));
|
|
33
|
+
fs.writeFileSync(path.join(specsDir,'0.bootstrap','requirements.md'),'# Requirements\nSynthetic approved scaffold and project instructions.\n');
|
|
34
|
+
fs.writeFileSync(path.join(specsDir,'0.bootstrap','design.md'),'# Design\nJavaScript; no Git; frontend module.\n');
|
|
35
|
+
fs.writeFileSync(path.join(specsDir,'0.bootstrap','tasks.md'),'- [ ] T-001: 生成项目骨架 scaffold\n- [ ] T-002: 生成 .claude/ 规范(cm-init)\n');
|
|
36
|
+
fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:['0.bootstrap'],specFiles:buildManifest(specsDir)}));
|
|
37
|
+
return {root,codeProject,specsDir,calls:[],reviews:[],businessCalls:0};
|
|
38
|
+
}
|
|
39
|
+
export function definition(f,taskId){
|
|
40
|
+
return {version:1,codeProject:f.codeProject,specsDir:f.specsDir,feature:'0.bootstrap',
|
|
41
|
+
identity:{repositoryId:'bootstrap-fixture',runId:'run-'+taskId,taskId,attempt:1},
|
|
42
|
+
scope:taskId==='T-001'?['app.mjs']:[...cmInitRuleTargets(selection)],requirements:[]};
|
|
43
|
+
}
|
|
44
|
+
export function reply(f,kind,payload){
|
|
45
|
+
f.calls.push(kind);
|
|
46
|
+
if(kind==='init_generate')return {status:'generated',documents:payload.targets.map(file=>({path:file,
|
|
47
|
+
content:file==='AGENTS.md'&&fs.existsSync(path.join(f.codeProject,file))?fs.readFileSync(path.join(f.codeProject,file),'utf8'):
|
|
48
|
+
file==='.claude/CLAUDE.md'?'# Fixture instructions\n'+payload.targets.filter(p=>p.startsWith('.claude/rules/'))
|
|
49
|
+
.map(p=>'@rules/'+path.basename(p)).join('\n')+'\n':'# Fixture instructions\nUse approved scope.\n'
|
|
50
|
+
// A revision must change the rejected bytes (develop_unchanged_after_review).
|
|
51
|
+
+(payload.bootstrap?.priorReview?'Revised for the review findings.\n':'')}))};
|
|
52
|
+
if(kind==='init_verify')return {checks:checks(),constraintChanges:[],application:{status:'no_relevant_lesson',note:null},
|
|
53
|
+
retrospective:f.lesson&&f.calls.filter(kind=>kind==='init_verify').length===1
|
|
54
|
+
?{status:'lesson_candidate',candidates:[{classification:'structured',trigger:'Bootstrap recovery',
|
|
55
|
+
action:'Preserve reviewed instruction lessons across attempts',evidence:['app.mjs']}],reason:null}
|
|
56
|
+
:{status:'no_new_lesson',candidates:[],reason:null}};
|
|
57
|
+
assert.fail('unexpected host call '+kind);
|
|
58
|
+
}
|
|
59
|
+
export function open(f,taskId,mode='create',overrides={}){
|
|
60
|
+
const d=definition(f,taskId),bridge={call:async(kind,payload)=>overrides.reply?overrides.reply(kind,payload):reply(f,kind,payload)};
|
|
61
|
+
const bootstrap=createHostBootstrap({definition:d,workflowRoot,selection:taskId==='T-001'?null:selection,bridge,
|
|
62
|
+
allowWrite:overrides.allowWrite??true});
|
|
63
|
+
const store=openTaskExecutionStore({tasksPath:path.join(f.specsDir,'0.bootstrap','tasks.md'),feature:'bootstrap',specsRoot:f.specsDir,
|
|
64
|
+
identity:{repositoryId:d.identity.repositoryId,runId:d.identity.runId},
|
|
65
|
+
fingerprints:{workflow:digest('bootstrap-test'),config:digest({d,bootstrap:bootstrap.configuration}),inputs:digest(taskId)},create:mode==='create'});
|
|
66
|
+
const developer={provider:'codex',requestedModel:'synthetic',contextId:'scaffold-author',run:createDeveloperRun({provider:'codex',requestedModel:'synthetic',worker:async request=>{
|
|
67
|
+
f.businessCalls++;assert(!request.prompt.includes('"scope":["AGENTS.md"'));
|
|
68
|
+
assert(request.prompt.includes(Buffer.from('JavaScript; no Git; frontend module.').toString('base64').slice(0,12))
|
|
69
|
+
||request.prompt.includes('0.bootstrap/design.md'));
|
|
70
|
+
fs.writeFileSync(path.join(f.codeProject,'app.mjs'),'export const fixture = true;\n');
|
|
71
|
+
return {status:'succeeded',value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
|
|
72
|
+
retrospective:{status:'no_new_lesson',candidates:[],reason:null}}};
|
|
73
|
+
}})};
|
|
74
|
+
const hostCheck=createHostCheck({cwd:f.codeProject,timeoutMs:1000,commands:[{id:'syntax',command:[process.execPath,'--check','app.mjs']}]});
|
|
75
|
+
const runner=createTaskRunner({root:f.codeProject,identity:d.identity,scope:d.scope,requirements:d.requirements,bootstrap,
|
|
76
|
+
taskLearning:{feature:'0.bootstrap',hostHandoff:true},developer,excludedContexts:['main'],timeoutMs:5000,
|
|
77
|
+
reviewers:[{id:'reviewer',adapterId:'codex-review-adapter',provider:'codex',requestedModel:'synthetic-review',allowed:true,available:true,contexts:['review-one','review-two'],
|
|
78
|
+
run:async(request,{onEvent})=>{f.reviews.push(request.payload.reviewPackage);
|
|
79
|
+
onEvent({event:'thread.started',provider_thread:'actual-review-'+request.identity.attempt});
|
|
80
|
+
onEvent({event:'turn.started',item_type:null});onEvent({event:'item.completed',item_type:'agent_message'});
|
|
81
|
+
onEvent({event:'turn.completed',item_type:null});onEvent({event:'process_closed',exit_code:0,signal:null,timed_out:false});
|
|
82
|
+
const revise=f.requestRevision&&taskId==='T-002'&&request.identity.attempt===1;
|
|
83
|
+
return {status:'succeeded',value:{verdict:revise?'changes_requested':'approved',packageDigest:request.payload.reviewPackage.packageDigest,
|
|
84
|
+
examinedPaths:reviewPaths(request.payload.reviewPackage),findings:revise?[{id:'F1',severity:'P2',path:'AGENTS.md',
|
|
85
|
+
message:'Reverify instruction applicability',evidence:'Synthetic revision fixture'}]:[],summary:'Synthetic independent review'}};}}],
|
|
86
|
+
reviewInvocation:{developerThreadId:'scaffold-author',excludedThreadIds:['main'],authorize:(request,{authorizationAt})=>{
|
|
87
|
+
const body={version:1,kind:'cm-review-dispatch-grant',grantId:'grant-'+request.identity.attempt,adapterId:'codex-review-adapter',
|
|
88
|
+
invocationId:request.invocationId,requestDigest:request.requestDigest,identity:request.identity,reviewerId:'reviewer',
|
|
89
|
+
logicalContextId:request.contextId,packageDigest:request.payload.reviewPackage.packageDigest,hostContextId:'main',
|
|
90
|
+
decisionId:'decision-'+request.identity.attempt,decision:'approved',issuedAt:authorizationAt,expiresAt:authorizationAt+60000};
|
|
91
|
+
return {...body,grantDigest:digest(body)};
|
|
92
|
+
}},
|
|
93
|
+
check:overrides.afterCheck?async (input,control)=>{const result=await hostCheck(input,control);overrides.afterCheck();return result;}:hostCheck,
|
|
94
|
+
taskCompletion:{reviewsDir:path.join(f.specsDir,'.reviews'),handoffs:[1,2].map(a=>path.join(f.specsDir,'.reviews',`bootstrap-${taskId}-a${a}-handoff.json`))},
|
|
95
|
+
persistence:{store,mode,version:3}});
|
|
96
|
+
return {runner,store,definition:d,close:()=>store.close(),effect:(kind,suffix='')=>{
|
|
97
|
+
const identity=runner.status().identity;
|
|
98
|
+
return runner.executeEffect({version:1,id:kind+'-'+identity.attempt+suffix,kind,identity,...(kind==='develop'?{
|
|
99
|
+
learningInput:inspectCmAiTaskLearningInput({specsDir:f.specsDir,codeProject:f.codeProject,feature:'0.bootstrap',identity,
|
|
100
|
+
applicableAgentFiles:[]},{admission:runner.inspectBootstrapAdmission()})}:{})});
|
|
101
|
+
}};
|
|
102
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Synthetic stdout protocol fixture only, never a model-generated review.
|
|
3
3
|
import {randomUUID} from 'node:crypto';
|
|
4
|
+
if(process.argv.includes('--version')){process.stdout.write('2.1.274 (Claude Code)\n');process.exit(0);}
|
|
4
5
|
let prompt='';for await(const part of process.stdin)prompt+=part;
|
|
5
6
|
if(process.env.ANTHROPIC_API_KEY==='cm-synthetic-local-probe'){
|
|
6
7
|
const base=process.env.ANTHROPIC_BASE_URL;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Local fixture responder for the actual driver/host transport. No provider,
|
|
2
|
+
// account or browser is contacted; each test supplies its synthetic observation.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import {spawn} from 'node:child_process';
|
|
5
|
+
export function runLiveDriver(driver,plan,operation,respond,{env=process.env,timeoutMs=30000}={}){
|
|
6
|
+
return new Promise((resolve,reject)=>{
|
|
7
|
+
const child=spawn(process.execPath,[driver,'--plan',plan,operation],{env,stdio:['ignore','pipe','pipe']});
|
|
8
|
+
let stdout='',stderr='',buffer='',failure=null;const requests=[];
|
|
9
|
+
const startedAt=Date.now();
|
|
10
|
+
const timer=setTimeout(()=>{
|
|
11
|
+
failure=Object.assign(Error('fixture driver timeout'),{code:'fixture_driver_timeout',
|
|
12
|
+
diagnostic:{timeoutMs,elapsedMs:Date.now()-startedAt,requestCount:requests.length,
|
|
13
|
+
stdoutBytes:Buffer.byteLength(stdout),stderrBytes:Buffer.byteLength(stderr)}});
|
|
14
|
+
child.kill();
|
|
15
|
+
},timeoutMs);
|
|
16
|
+
child.stdout.on('data',chunk=>{stdout+=chunk;});
|
|
17
|
+
child.stderr.on('data',chunk=>{
|
|
18
|
+
stderr+=chunk;buffer+=chunk;
|
|
19
|
+
let at;while((at=buffer.indexOf('\n'))!==-1){
|
|
20
|
+
const line=buffer.slice(0,at);buffer=buffer.slice(at+1);
|
|
21
|
+
if(!line.startsWith('[drive] live_evidence_request: '))continue;
|
|
22
|
+
const file=line.slice('[drive] live_evidence_request: '.length);
|
|
23
|
+
try{
|
|
24
|
+
const row=JSON.parse(fs.readFileSync(file,'utf8'));requests.push(row);
|
|
25
|
+
const result=respond(row),target=file.replace('.request.json','.result.json');
|
|
26
|
+
fs.writeFileSync(target+'.tmp',JSON.stringify({type:'host_result',sessionId:row.sessionId,
|
|
27
|
+
callId:row.callId,requestDigest:row.requestDigest,result}),{flag:'wx',mode:0o600});
|
|
28
|
+
fs.renameSync(target+'.tmp',target);
|
|
29
|
+
}catch(error){failure=error;child.kill();}
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
child.on('error',error=>{clearTimeout(timer);reject(error);});
|
|
33
|
+
child.on('close',status=>{clearTimeout(timer);if(failure)reject(failure);else resolve({status,stdout,stderr,requests});});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Test-only process hygiene for synthetic CLI fixtures. Runtime code never
|
|
2
|
+
// imports this module.
|
|
3
|
+
//
|
|
4
|
+
// Timeout fixtures deliberately stay busy (setInterval) and are often spawned
|
|
5
|
+
// detached by the host under test, so killing the host or losing the test
|
|
6
|
+
// process used to orphan them for good. Two independent guards apply:
|
|
7
|
+
// 1. ownerGuardSource(): the fixture itself exits once the *test process*
|
|
8
|
+
// that created it is gone, or after a hard ceiling. It watches the test
|
|
9
|
+
// process rather than its direct parent, so an orphan caused by a
|
|
10
|
+
// production cleanup regression stays observable while the test runs.
|
|
11
|
+
// 2. killFixtureProcesses(): the test kills the processes that provably belong
|
|
12
|
+
// to its temp dir (see fixtureProcesses), plus the groups they lead.
|
|
13
|
+
import {spawnSync} from 'node:child_process';
|
|
14
|
+
|
|
15
|
+
export const FIXTURE_MAX_LIFETIME_MS=300000;
|
|
16
|
+
export const ownerTag=(ownerPid=process.pid)=>`cm-fixture-owner:${ownerPid}`;
|
|
17
|
+
|
|
18
|
+
// Valid as the first statement of CommonJS, `node -e` and ESM sources.
|
|
19
|
+
export function ownerGuardSource({ownerPid=process.pid,maxLifetimeMs=FIXTURE_MAX_LIFETIME_MS}={}){
|
|
20
|
+
if(!Number.isSafeInteger(ownerPid)||ownerPid<1||!Number.isSafeInteger(maxLifetimeMs)||maxLifetimeMs<1)
|
|
21
|
+
throw Error('invalid_owner_guard');
|
|
22
|
+
return `;(()=>{/*${ownerTag(ownerPid)}*/const owner=${ownerPid},deadline=Date.now()+${maxLifetimeMs};`
|
|
23
|
+
+`const stop=()=>{try{process.kill(process.pid,'SIGKILL');}catch{process.exit(137);}};`
|
|
24
|
+
+`const timer=setInterval(()=>{let alive=true;try{process.kill(owner,0);}catch(error){alive=error?.code==='EPERM';}`
|
|
25
|
+
+`if(!alive||Date.now()>=deadline)stop();},200);timer.unref?.();})();\n`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Insert the guard after an optional shebang line.
|
|
29
|
+
export function guardFixtureSource(source,options){
|
|
30
|
+
const guard=ownerGuardSource(options);
|
|
31
|
+
if(!source.startsWith('#!'))return guard+source;
|
|
32
|
+
const newline=source.indexOf('\n');
|
|
33
|
+
return newline===-1?`${source}\n${guard}`:source.slice(0,newline+1)+guard+source.slice(newline+1);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function listProcesses(){
|
|
37
|
+
const listed=spawnSync('ps',['-axww','-o','pid=,ppid=,pgid=,command='],{encoding:'utf8',maxBuffer:64*1024*1024});
|
|
38
|
+
if(listed.status!==0)throw Object.assign(Error('fixture process listing failed'),{
|
|
39
|
+
code:'fixture_process_listing_failed',diagnostic:{command:'ps',status:listed.status??null,
|
|
40
|
+
signal:listed.signal??null,systemCode:listed.error?.code??null}});
|
|
41
|
+
const rows=[];
|
|
42
|
+
for(const line of listed.stdout.split('\n')){
|
|
43
|
+
const match=line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
|
|
44
|
+
if(!match)continue;
|
|
45
|
+
const [pid,ppid,pgid]=match.slice(1,4).map(Number);rows.push({pid,ppid,pgid,command:match[4]});
|
|
46
|
+
}
|
|
47
|
+
return rows;
|
|
48
|
+
}
|
|
49
|
+
const interpreters=new Set([process.execPath,'node','/bin/sh','sh']);
|
|
50
|
+
|
|
51
|
+
// Only processes that provably belong to this test, never one that merely
|
|
52
|
+
// mentions the root (a user's grep/tail/lsof of a fixture path survives):
|
|
53
|
+
// - a descendant of this test process whose command line carries the root
|
|
54
|
+
// (hosts and drivers the test spawned), or
|
|
55
|
+
// - a program run from inside the root: argv[0] under it, or node/sh running
|
|
56
|
+
// a script under it (fake CLIs, which may be orphaned by a killed host).
|
|
57
|
+
// Fixture roots come from mkdtemp and contain no whitespace.
|
|
58
|
+
export function fixtureProcesses(root){
|
|
59
|
+
if(typeof root!=='string'||!root.startsWith('/')||root.length<8||/\s/.test(root))throw Error('invalid_fixture_marker');
|
|
60
|
+
if(process.platform==='win32')return [];
|
|
61
|
+
const rows=listProcesses(),parents=new Map(rows.map(row=>[row.pid,row.ppid]));
|
|
62
|
+
const descends=pid=>{
|
|
63
|
+
for(let current=parents.get(pid),hops=0;current>1&&hops<4096;current=parents.get(current),hops++)
|
|
64
|
+
if(current===process.pid)return true;
|
|
65
|
+
return false;
|
|
66
|
+
};
|
|
67
|
+
const inside=value=>typeof value==='string'&&value.startsWith(root+'/');
|
|
68
|
+
return rows.filter(row=>{
|
|
69
|
+
if(row.pid===process.pid||!row.command.includes(root))return false;
|
|
70
|
+
const [program,script]=row.command.split(/\s+/);
|
|
71
|
+
return inside(program)||(interpreters.has(program)&&inside(script))||descends(row.pid);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function ownProcessGroup(){
|
|
76
|
+
const row=listProcesses().find(entry=>entry.pid===process.pid);
|
|
77
|
+
return row?.pgid??process.pid;
|
|
78
|
+
}
|
|
79
|
+
const pause=ms=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms);
|
|
80
|
+
|
|
81
|
+
// Synchronous so it also fits finally blocks, t.after and watchdog callbacks.
|
|
82
|
+
export function killFixtureProcesses(root,{waitMs=5000}={}){
|
|
83
|
+
const found=fixtureProcesses(root);
|
|
84
|
+
const own=found.length?ownProcessGroup():null;
|
|
85
|
+
for(const row of found){
|
|
86
|
+
// Only a group whose leader is itself a fixture process (spawned detached by
|
|
87
|
+
// the host under test) is taken whole; never this test's own group.
|
|
88
|
+
if(row.pgid===row.pid&&row.pgid!==own)try{process.kill(-row.pgid,'SIGKILL');}catch{}
|
|
89
|
+
try{process.kill(row.pid,'SIGKILL');}catch{}
|
|
90
|
+
}
|
|
91
|
+
const deadline=Date.now()+waitMs;
|
|
92
|
+
let remaining=found.length?fixtureProcesses(root):[];
|
|
93
|
+
while(remaining.length&&Date.now()<deadline){pause(50);remaining=fixtureProcesses(root);}
|
|
94
|
+
if(remaining.length)throw Error(`fixture processes survived SIGKILL: ${remaining.map(row=>row.pid).join(',')}`);
|
|
95
|
+
return found;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function killProcessGroup(pid){
|
|
99
|
+
if(!Number.isSafeInteger(pid)||pid<2)return;
|
|
100
|
+
try{process.kill(-pid,'SIGKILL');}catch{}
|
|
101
|
+
}
|
|
@@ -32,6 +32,7 @@ def invoke(
|
|
|
32
32
|
cwd=ROOT,
|
|
33
33
|
env=env,
|
|
34
34
|
text=True,
|
|
35
|
+
encoding="utf-8",
|
|
35
36
|
capture_output=True,
|
|
36
37
|
check=False,
|
|
37
38
|
)
|
|
@@ -1082,6 +1083,7 @@ def main() -> int:
|
|
|
1082
1083
|
cwd=ROOT,
|
|
1083
1084
|
env=concurrent_env,
|
|
1084
1085
|
text=True,
|
|
1086
|
+
encoding="utf-8",
|
|
1085
1087
|
stdout=subprocess.PIPE,
|
|
1086
1088
|
stderr=subprocess.PIPE,
|
|
1087
1089
|
)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Local native usage accounting fixture. Synthetic logs only; no providers."""
|
|
3
|
+
import contextlib
|
|
4
|
+
import datetime
|
|
5
|
+
import importlib.util
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
import unittest
|
|
12
|
+
|
|
13
|
+
spec = importlib.util.spec_from_file_location("native_usage_report", Path(__file__).with_name("cm-usage-report.py"))
|
|
14
|
+
reporter = importlib.util.module_from_spec(spec)
|
|
15
|
+
sys.modules[spec.name] = reporter
|
|
16
|
+
spec.loader.exec_module(reporter)
|
|
17
|
+
|
|
18
|
+
class NativeUsage(unittest.TestCase):
|
|
19
|
+
def report(self, usages):
|
|
20
|
+
with tempfile.TemporaryDirectory(prefix="cm-native-usage-") as directory:
|
|
21
|
+
root = Path(directory).resolve()
|
|
22
|
+
now = datetime.datetime.now(datetime.timezone.utc)
|
|
23
|
+
ref = reporter.RunRef("native-fixture-run", "cm-ai", "fixture", "done", now, now.isoformat(), "events.jsonl")
|
|
24
|
+
rows = []
|
|
25
|
+
for index, usage in enumerate(usages):
|
|
26
|
+
common = {"workflow": "cm-ai", "runtime": "codex", "stage": "review", "role": "reviewer",
|
|
27
|
+
"adapter": "codex-cli", "requested_model": "fixture", "source": "native-cli-terminal",
|
|
28
|
+
"purpose": "workflow-execution", "run_id": ref.run_id, "call_id": "call-" + str(index)}
|
|
29
|
+
claim = {**common, "event": "model_call", "phase": "claimed"}
|
|
30
|
+
row = {**common, "event": "model_usage", "phase": "complete", "outcome": "success", **usage}
|
|
31
|
+
rows.extend([claim, row, row]) # Exact repeated log bytes must not add tokens.
|
|
32
|
+
(root / "events.jsonl").write_text("".join(json.dumps(row) + "\n" for row in rows))
|
|
33
|
+
with contextlib.redirect_stderr(io.StringIO()):
|
|
34
|
+
return reporter.build_report(root, [ref])
|
|
35
|
+
|
|
36
|
+
def test_subsets_not_added_and_missing_components_are_null(self):
|
|
37
|
+
result = self.report([{"usage_state": "observed", "input_tokens": 100, "output_tokens": 20,
|
|
38
|
+
"cache_read_tokens": 70, "reasoning_tokens": 5},
|
|
39
|
+
{"usage_state": "observed", "input_tokens": 10, "output_tokens": 2},
|
|
40
|
+
{"usage_state": "unavailable"}])
|
|
41
|
+
self.assertEqual(result["summary"]["input_tokens"], 110)
|
|
42
|
+
self.assertEqual(result["summary"]["output_tokens"], 22)
|
|
43
|
+
self.assertEqual(result["summary"]["observed_calls"], 2)
|
|
44
|
+
self.assertEqual(result["summary"]["unavailable_calls"], 1)
|
|
45
|
+
fields = result["native_components"]["fields"]
|
|
46
|
+
self.assertEqual(fields["reasoning_tokens"], {"tokens": 5, "observed_calls": 1, "unavailable_calls": 2})
|
|
47
|
+
self.assertEqual(fields["cache_write_tokens"]["tokens"], None)
|
|
48
|
+
self.assertEqual(fields["cache_write_tokens"]["unavailable_calls"], 3)
|
|
49
|
+
|
|
50
|
+
def test_bad_reasoning_subset_and_unavailable_counts_are_rejected(self):
|
|
51
|
+
result = self.report([{"usage_state": "observed", "input_tokens": 1, "output_tokens": 2, "reasoning_tokens": 3},
|
|
52
|
+
{"usage_state": "unavailable", "reasoning_tokens": 0}])
|
|
53
|
+
self.assertEqual(result["summary"]["observed_calls"], 0)
|
|
54
|
+
self.assertNotIn("native_components", result)
|
|
55
|
+
|
|
56
|
+
def test_unknown_reasoning_is_not_inferred_from_output(self):
|
|
57
|
+
result = self.report([{"usage_state": "observed", "input_tokens": 100, "output_tokens": 20}])
|
|
58
|
+
self.assertEqual(result["native_components"]["fields"]["reasoning_tokens"]["tokens"], None)
|
|
59
|
+
self.assertEqual(result["native_components"]["fields"]["cache_read_tokens"]["tokens"], None)
|
|
60
|
+
|
|
61
|
+
if __name__ == "__main__":
|
|
62
|
+
unittest.main()
|
|
@@ -24,6 +24,7 @@ def invoke(*args: str, expected_exit: int = 0) -> dict[str, object]:
|
|
|
24
24
|
[os.environ.get("CM_NODE_BIN", "node") if SCRIPT.suffix == ".mjs" else sys.executable, str(SCRIPT), *args],
|
|
25
25
|
cwd=ROOT,
|
|
26
26
|
text=True,
|
|
27
|
+
encoding="utf-8",
|
|
27
28
|
capture_output=True,
|
|
28
29
|
check=False,
|
|
29
30
|
)
|
|
@@ -41,7 +42,7 @@ def invoke(*args: str, expected_exit: int = 0) -> dict[str, object]:
|
|
|
41
42
|
command = [sys.executable if other.suffix == ".py" else os.environ.get("CM_NODE_BIN", "node"), str(other), "inspect"]
|
|
42
43
|
for flag in ("--stage", "--feature", "--evidence", "--receipt"):
|
|
43
44
|
command.extend([flag, args[args.index(flag) + 1]])
|
|
44
|
-
checked = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, check=False)
|
|
45
|
+
checked = subprocess.run(command, cwd=ROOT, text=True, encoding="utf-8", capture_output=True, check=False)
|
|
45
46
|
if checked.returncode != 0 or json.loads(checked.stdout).get("outcome") != "completed":
|
|
46
47
|
raise AssertionError(f"cross-runtime receipt rejected: {checked.stderr}")
|
|
47
48
|
return json.loads(result.stdout) if result.stdout.strip() else {"stderr": result.stderr}
|