@aibyzero/cm-workflow 0.16.5 → 0.16.7
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 +14 -0
- package/CHANGELOG.md +19 -1
- package/README.md +17 -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 +28 -7
- package/docs/js-workflow-control.md +96 -6
- package/docs/live-evidence-drivers.md +62 -0
- package/docs/next-steps.md +15 -10
- 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/claude-review-adapter.mjs +7 -4
- package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -4
- package/runtime/js/cm-ai/cm-ai-admission.mjs +34 -10
- package/runtime/js/cm-ai/cm-ai-context-refresh.mjs +9 -5
- package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +111 -34
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +93 -31
- package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +13 -57
- package/runtime/js/cm-ai/codex-config.mjs +3 -2
- package/runtime/js/cm-ai/codex-review-adapter.mjs +34 -15
- package/runtime/js/cm-ai/committed-rule-basis.mjs +76 -0
- package/runtime/js/cm-ai/developer-adapter.mjs +8 -5
- package/runtime/js/cm-ai/drive-bootstrap.mjs +22 -12
- package/runtime/js/cm-ai/drive-core.mjs +9 -3
- package/runtime/js/cm-ai/durable-runner-state.mjs +146 -14
- package/runtime/js/cm-ai/effect-contract.mjs +1 -1
- package/runtime/js/cm-ai/execution-policy.mjs +58 -0
- 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/host-bootstrap.mjs +70 -20
- package/runtime/js/cm-ai/host-check.mjs +30 -4
- package/runtime/js/cm-ai/host-conversation-execution.mjs +59 -17
- package/runtime/js/cm-ai/host-documentation.mjs +2 -2
- 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 +54 -8
- package/runtime/js/cm-ai/host-qa-fix-owner.mjs +22 -5
- package/runtime/js/cm-ai/host-session.mjs +1 -1
- package/runtime/js/cm-ai/host-workflow-capabilities.mjs +3 -1
- package/runtime/js/cm-ai/knowledge-closeout.mjs +56 -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 +36 -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 +89 -0
- package/runtime/js/cm-ai/owned-process-cleanup.mjs +22 -0
- package/runtime/js/cm-ai/provider-review-observation.mjs +15 -0
- package/runtime/js/cm-ai/provider-usage.mjs +39 -0
- package/runtime/js/cm-ai/review-package.mjs +11 -0
- 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/status-projection.mjs +93 -0
- package/runtime/js/cm-ai/task-runner.mjs +176 -25
- 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 +183 -40
- package/runtime/js/cm-fix/final-review.mjs +18 -10
- package/runtime/js/cm-fix/finish.mjs +2 -19
- package/runtime/js/cm-fix/host-review.mjs +25 -6
- package/runtime/js/cm-fix/host.mjs +4 -1
- package/runtime/js/cm-fix/layout.mjs +1 -1
- package/runtime/js/cm-fix/log-events.mjs +29 -0
- package/runtime/js/cm-fix/metrics.mjs +3 -2
- package/runtime/js/cm-fix/progress.mjs +4 -0
- package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
- package/runtime/js/cm-prd/analysis.mjs +5 -2
- package/runtime/js/cm-prd/response-recovery.mjs +23 -0
- package/runtime/js/cm-prd/review-host.mjs +2 -1
- package/runtime/js/cm-prd/review-publication.mjs +23 -13
- package/runtime/js/cm-prd/review-time.mjs +29 -0
- package/runtime/js/cm-prd/session.mjs +53 -6
- package/runtime/js/cm-security/finalize.mjs +32 -0
- package/runtime/js/cm-test/recovery.mjs +4 -4
- package/runtime/review.md +5 -0
- package/runtime/task-gates.md +6 -0
- package/runtime/workflow-config.md +10 -1
- package/scripts/cm-ai-admission.mjs +14 -3
- package/scripts/cm-ai-batch-drive.mjs +52 -23
- package/scripts/cm-ai-batch-drive.test.mjs +47 -2
- package/scripts/cm-ai-batch-host.mjs +44 -16
- package/scripts/cm-ai-batch-run.mjs +77 -29
- package/scripts/cm-ai-bootstrap-flow.test.mjs +3 -2
- package/scripts/cm-ai-bootstrap-merge.test.mjs +118 -1
- package/scripts/cm-ai-bootstrap.test.mjs +80 -87
- package/scripts/cm-ai-conversation-entry-ops.test.mjs +15 -0
- package/scripts/cm-ai-develop-driver-gaps.test.mjs +102 -0
- package/scripts/cm-ai-drive-bootstrap-rules.test.mjs +2 -2
- package/scripts/cm-ai-drive.mjs +73 -28
- package/scripts/cm-ai-drive.test.mjs +119 -1
- package/scripts/cm-ai-feature-selection.test.mjs +178 -0
- package/scripts/cm-ai-host.mjs +79 -27
- package/scripts/cm-ai-host.test.mjs +88 -0
- package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
- package/scripts/cm-ai-progress.test.mjs +521 -0
- package/scripts/cm-ai-protected-scope.test.mjs +194 -0
- package/scripts/cm-ai-qa-config-revision.test.mjs +21 -0
- package/scripts/cm-ai-review-failure.test.mjs +71 -11
- package/scripts/cm-ai-run.mjs +94 -19
- package/scripts/cm-ai-run.test.mjs +2 -1
- package/scripts/cm-bootstrap-review-recovery.test.mjs +70 -0
- package/scripts/cm-check-drive.test.mjs +1 -0
- package/scripts/cm-check-runtime.sh +11 -0
- package/scripts/cm-claude-install-layout.test.mjs +26 -0
- package/scripts/cm-claude-probe.test.mjs +1 -1
- 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-fix-drive.mjs +28 -13
- package/scripts/cm-fix-final-review.test.mjs +11 -6
- package/scripts/cm-fix-host.mjs +17 -10
- package/scripts/cm-fix-large-log.test.mjs +113 -0
- 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 +7 -1
- package/scripts/cm-host-qa-executor.test.mjs +329 -3
- package/scripts/cm-knowledge-closeout.test.mjs +160 -0
- package/scripts/cm-live-evidence.test.mjs +64 -0
- package/scripts/cm-log-event.mjs +34 -7
- package/scripts/cm-log-event.py +15 -0
- package/scripts/cm-model-setup.mjs +79 -0
- package/scripts/cm-prd-drive.mjs +32 -11
- package/scripts/cm-prd-drive.test.mjs +15 -0
- package/scripts/cm-prd-host.mjs +26 -6
- package/scripts/cm-prd-host.test.mjs +4 -0
- package/scripts/cm-prd-review-host.test.mjs +17 -0
- package/scripts/cm-prd-session-recovery.test.mjs +44 -2
- package/scripts/cm-prd-task-grouping.test.mjs +206 -0
- package/scripts/cm-release-smoke.sh +5 -1
- package/scripts/cm-review-scope-recovery.test.mjs +5 -3
- 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-task-gate-correction.test.mjs +117 -0
- package/scripts/cm-task-gate.mjs +146 -10
- package/scripts/cm-task-gate.py +1 -0
- package/scripts/cm-test-branch-impact.test.mjs +11 -0
- 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/live-evidence-driver.mjs +35 -0
- package/scripts/fixtures/process-cleanup.mjs +3 -1
- package/scripts/test-cm-native-usage.py +62 -0
- package/scripts/test-external-model-setup.py +91 -0
- package/scripts/test-model-configuration-write.py +201 -0
- package/scripts/test-npm-install.py +10 -1
- 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 +16 -7
- 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 +30 -2
- package/skills/cm-prd/SKILL.md +5 -4
- package/skills/cm-prd/references/spec-self-check.md +3 -1
- 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
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -35,7 +35,9 @@ export function guardFixtureSource(source,options){
|
|
|
35
35
|
|
|
36
36
|
function listProcesses(){
|
|
37
37
|
const listed=spawnSync('ps',['-axww','-o','pid=,ppid=,pgid=,command='],{encoding:'utf8',maxBuffer:64*1024*1024});
|
|
38
|
-
if(listed.status!==0)throw Error(
|
|
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}});
|
|
39
41
|
const rows=[];
|
|
40
42
|
for(const line of listed.stdout.split('\n')){
|
|
41
43
|
const match=line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/);
|
|
@@ -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()
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Real terminal setup: no installed providers, network, auth, or model calls."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import pty
|
|
6
|
+
import select
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
import tempfile
|
|
10
|
+
import time
|
|
11
|
+
import unittest
|
|
12
|
+
|
|
13
|
+
SCRIPT = Path(__file__).resolve().with_name('cm-model-setup.mjs')
|
|
14
|
+
NODE = shutil.which('node')
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TerminalSetup(unittest.TestCase):
|
|
18
|
+
def setUp(self):
|
|
19
|
+
self.temp = tempfile.TemporaryDirectory(prefix='cm-external-terminal-')
|
|
20
|
+
self.addCleanup(self.temp.cleanup)
|
|
21
|
+
self.root = Path(self.temp.name).resolve()
|
|
22
|
+
self.settings = self.root / 'external-models-v1.json'
|
|
23
|
+
|
|
24
|
+
def interact(self, arguments, steps):
|
|
25
|
+
master, slave = pty.openpty()
|
|
26
|
+
process = subprocess.Popen([NODE, str(SCRIPT)] + arguments,
|
|
27
|
+
stdin=slave, stdout=slave, stderr=slave,
|
|
28
|
+
env=dict(os.environ, CM_WORKFLOW_HOME=str(self.root)))
|
|
29
|
+
os.close(slave)
|
|
30
|
+
output = b''
|
|
31
|
+
try:
|
|
32
|
+
for prompt, answer, before in steps:
|
|
33
|
+
deadline = time.monotonic() + 5
|
|
34
|
+
while prompt.encode() not in output:
|
|
35
|
+
if time.monotonic() > deadline:
|
|
36
|
+
self.fail('missing prompt: ' + prompt + '\n' + output.decode(errors='replace'))
|
|
37
|
+
if select.select([master], [], [], 0.1)[0]:
|
|
38
|
+
output += os.read(master, 65536)
|
|
39
|
+
if before:
|
|
40
|
+
before()
|
|
41
|
+
os.write(master, answer.encode() + b'\r')
|
|
42
|
+
output = b''
|
|
43
|
+
# Drain the terminal while waiting: TTY writes can block without a reader.
|
|
44
|
+
deadline = time.monotonic() + 5
|
|
45
|
+
while process.poll() is None and time.monotonic() < deadline:
|
|
46
|
+
if select.select([master], [], [], 0.1)[0]:
|
|
47
|
+
try:
|
|
48
|
+
output += os.read(master, 65536)
|
|
49
|
+
except OSError:
|
|
50
|
+
break
|
|
51
|
+
return process.wait(timeout=1)
|
|
52
|
+
finally:
|
|
53
|
+
if process.poll() is None:
|
|
54
|
+
process.kill()
|
|
55
|
+
process.wait(timeout=5)
|
|
56
|
+
os.close(master)
|
|
57
|
+
|
|
58
|
+
def test_codex_free_model_and_default_effort(self):
|
|
59
|
+
status = self.interact(['configure', '--provider', 'codex'], [
|
|
60
|
+
('codex external model ID:', 'fixture-codex', None),
|
|
61
|
+
('Effort (Enter = adapter default):', '', None),
|
|
62
|
+
('Save this provider pair?', 'y', None)])
|
|
63
|
+
self.assertEqual(status, 0)
|
|
64
|
+
self.assertEqual(json.loads(self.settings.read_text())['providers']['codex'],
|
|
65
|
+
dict(model='fixture-codex', effort='high'))
|
|
66
|
+
|
|
67
|
+
def test_claude_optional_effort_is_not_sent(self):
|
|
68
|
+
status = self.interact(['configure', '--provider', 'claude'], [
|
|
69
|
+
('claude external model ID:', 'fixture-claude', None),
|
|
70
|
+
('Effort (Enter = adapter default):', '', None),
|
|
71
|
+
('Save this provider pair?', 'yes', None)])
|
|
72
|
+
self.assertEqual(status, 0)
|
|
73
|
+
self.assertIsNone(json.loads(self.settings.read_text())['providers']['claude']['effort'])
|
|
74
|
+
|
|
75
|
+
def test_cancel_keeps_absent_file(self):
|
|
76
|
+
self.assertEqual(self.interact(['configure', '--provider', 'codex', '--model', 'fixture'],
|
|
77
|
+
[('Save this provider pair?', 'n', None)]), 0)
|
|
78
|
+
self.assertFalse(self.settings.exists())
|
|
79
|
+
|
|
80
|
+
def test_confirmation_cannot_overwrite_concurrent_bytes(self):
|
|
81
|
+
old = dict(schemaVersion=1, providers=dict(codex=dict(model='old', effort='high')))
|
|
82
|
+
self.settings.write_text(json.dumps(old))
|
|
83
|
+
changed = json.dumps(old, indent=4).encode()
|
|
84
|
+
status = self.interact(['configure', '--provider', 'codex', '--model', 'new'],
|
|
85
|
+
[('Save this provider pair?', 'y', lambda: self.settings.write_bytes(changed))])
|
|
86
|
+
self.assertEqual(status, 1)
|
|
87
|
+
self.assertEqual(self.settings.read_bytes(), changed)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
if __name__ == '__main__':
|
|
91
|
+
unittest.main()
|