@aibyzero/cm-workflow 0.16.5 → 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 +14 -0
- package/CHANGELOG.md +7 -0
- package/README.md +11 -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 +48 -0
- 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-conversation-entry.mjs +79 -20
- package/runtime/js/cm-ai/cm-ai-qa-log.mjs +1 -4
- 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/drive-bootstrap.mjs +20 -10
- package/runtime/js/cm-ai/drive-core.mjs +9 -3
- package/runtime/js/cm-ai/durable-runner-state.mjs +117 -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 +50 -16
- 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 +2 -2
- 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/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/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 +171 -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/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/progress.mjs +4 -0
- package/runtime/js/cm-fix/review-reconciliation.mjs +64 -0
- package/runtime/js/cm-prd/response-recovery.mjs +23 -0
- 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/review.md +5 -0
- package/runtime/task-gates.md +6 -0
- package/runtime/workflow-config.md +10 -1
- package/scripts/cm-ai-batch-drive.mjs +50 -21
- package/scripts/cm-ai-batch-drive.test.mjs +47 -2
- package/scripts/cm-ai-batch-host.mjs +37 -14
- package/scripts/cm-ai-batch-run.mjs +71 -27
- 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 +59 -25
- package/scripts/cm-ai-drive.test.mjs +97 -1
- package/scripts/cm-ai-host.mjs +64 -24
- package/scripts/cm-ai-operator-guidance.test.mjs +94 -0
- package/scripts/cm-ai-progress.test.mjs +521 -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 +58 -14
- 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-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 +21 -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 +8 -2
- 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 +13 -4
- package/scripts/cm-release-smoke.sh +5 -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-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-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/N8-finish.md +5 -0
- package/skills/cm-ai/references/js-host.md +13 -5
- 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-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
|
@@ -7,7 +7,7 @@ import {fileURLToPath} from 'node:url';
|
|
|
7
7
|
import {loadConfig,resolveRole} from '../../../scripts/cm-workflow-config.mjs';
|
|
8
8
|
import {validateTestCases} from '../../../scripts/validate-test-cases.mjs';
|
|
9
9
|
import {inspectCmAiAdmission,inspectCmAiQaTaskContext,identifyApprovedBootstrapFeature} from './cm-ai-admission.mjs';
|
|
10
|
-
import {createHostCheck} from './host-check.mjs';
|
|
10
|
+
import {createHostCheck,reportHostCheckProgress} from './host-check.mjs';
|
|
11
11
|
import {specsPermissionArgs} from './codex-config.mjs';
|
|
12
12
|
import {resolveCodeProjects,codeProjectPaths} from './code-projects.mjs';
|
|
13
13
|
import {findCmAiQaDecision,readCmAiQaRunRound,reportFile} from './cm-ai-qa-log.mjs';
|
|
@@ -184,7 +184,7 @@ export function createHostQaExecutor(options) {
|
|
|
184
184
|
for(const command of plan.commands){
|
|
185
185
|
notCancelled();
|
|
186
186
|
const check=createHostCheck({cwd:roots?command.codeProject:configuration.codeProject,commands:[{id:command.id,command:command.command}],
|
|
187
|
-
timeoutMs:configuration.timeoutMs,specsRoot:configuration.specsRoot??null});
|
|
187
|
+
timeoutMs:configuration.timeoutMs,specsRoot:configuration.specsRoot??null,onProgress:reportHostCheckProgress});
|
|
188
188
|
const resource={resource_id:`qa-command-${digest({testRunId:binding.testRunId,command:command.id}).slice(0,48)}`,
|
|
189
189
|
resource_kind:'qa_command'};
|
|
190
190
|
logStep(configuration,binding,'resource','acquired',{...resource,cleanup_required:true},'QA command resource acquired');
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import {selectExternalModels} from './external-models.mjs';
|
|
2
|
+
import {readExecutionPolicy} from './execution-policy.mjs';
|
|
1
3
|
// Serial child host. Existing owners retain lifecycle and action authority.
|
|
2
4
|
import fs from 'node:fs';
|
|
3
5
|
import path from 'node:path';
|
|
@@ -6,11 +8,11 @@ import {createFixHost} from '../cm-fix/host.mjs';
|
|
|
6
8
|
import {bindQaFixDefinition} from './qa-fix-definition.mjs';
|
|
7
9
|
import {digest,id,json,need,shape,validIdentity,hex} from './effect-contract.mjs';
|
|
8
10
|
|
|
9
|
-
export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHostContextId,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={}}){
|
|
11
|
+
export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHostContextId,fix=null,template=null,allowStart=false,autoFix=false,fixExecution={},fixPermissions=[],fixAuthorities={},externalModels=null,executionPolicy=null}){
|
|
10
12
|
id(hostContextId);id(parentHostContextId);
|
|
11
13
|
need((fix===null)!==(template===null),'invalid_fix_config');
|
|
12
14
|
let definition=null;
|
|
13
|
-
|
|
15
|
+
let fixedTemplate=template===null?null:json(template,64*1024);
|
|
14
16
|
if(fixedTemplate){
|
|
15
17
|
shape(fixedTemplate,['specsRoot','feature','identity','configuration']);validIdentity(fixedTemplate.identity);
|
|
16
18
|
need(!Object.hasOwn(fixedTemplate.configuration,'qaSource'),'invalid_fix_template');
|
|
@@ -18,6 +20,21 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
|
|
|
18
20
|
shape(fix,['specsRoot','identity','configuration']);definition=json(fix,64*1024);
|
|
19
21
|
validIdentity(definition.identity);need(definition.configuration.qaSource,'qa_fix_source_required');
|
|
20
22
|
}
|
|
23
|
+
if(executionPolicy){
|
|
24
|
+
const selected=readExecutionPolicy(executionPolicy),target=fixedTemplate??definition;
|
|
25
|
+
if(!fixedTemplate&&!target.configuration.executionPolicy)need(false,'execution_policy_legacy_child_inheritance_forbidden');
|
|
26
|
+
if(target.configuration.executionPolicy)need(digest(target.configuration.executionPolicy)===digest(selected),'execution_policy_child_conflict');
|
|
27
|
+
const inherited={...target,configuration:{...target.configuration,executionPolicy:selected}};
|
|
28
|
+
if(fixedTemplate)fixedTemplate=inherited;else definition=inherited;
|
|
29
|
+
}
|
|
30
|
+
if(externalModels){
|
|
31
|
+
const target=fixedTemplate??definition,runtime=target.configuration.runtime??'codex';
|
|
32
|
+
const selected=selectExternalModels(externalModels,[runtime]);
|
|
33
|
+
if(!fixedTemplate&&!target.configuration.externalModels)need(false,'external_model_legacy_child_inheritance_forbidden');
|
|
34
|
+
if(target.configuration.externalModels)need(digest(target.configuration.externalModels)===digest(selected),'external_model_pair_conflict');
|
|
35
|
+
const inherited={...target,configuration:{...target.configuration,externalModels:selected}};
|
|
36
|
+
if(fixedTemplate)fixedTemplate=inherited;else definition=inherited;
|
|
37
|
+
}
|
|
21
38
|
need(typeof allowStart==='boolean','invalid_input');
|
|
22
39
|
need(typeof autoFix==='boolean'&&(!autoFix||(allowStart&&fixedTemplate!==null)),'qa_fix_auto_authorization_required');
|
|
23
40
|
need(typeof reopenParent==='function','invalid_input');
|
|
@@ -43,7 +60,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
|
|
|
43
60
|
busy=true;try{return await current.host.handle(request);}finally{busy=false;}
|
|
44
61
|
}
|
|
45
62
|
const value=json(request);shape(value,['version','requestId','operation','identity','packageDigest','testRunId',
|
|
46
|
-
...(request.operation==='fix_action'?['fixOperation',...(['abandon_step','abandon_review'].includes(request.fixOperation)&&Object.hasOwn(request,'reason')?['reason']:[])]:[])]);
|
|
63
|
+
...(request.operation==='fix_action'?['fixOperation',...(request.fixOperation==='reconcile_review'?['invocationId']:[]),...(['abandon_step','abandon_review'].includes(request.fixOperation)&&Object.hasOwn(request,'reason')?['reason']:[])]:[])]);
|
|
47
64
|
need(value.version===1,'invalid_input');id(value.requestId);validIdentity(value.identity);hex(value.packageDigest);id(value.testRunId);
|
|
48
65
|
if(fixedTemplate)definition=bindQaFixDefinition({template:fixedTemplate,identity:value.identity,
|
|
49
66
|
packageDigest:value.packageDigest,testRunId:value.testRunId});
|
|
@@ -55,7 +72,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
|
|
|
55
72
|
const acting=value.operation==='fix_action';
|
|
56
73
|
if(acting)need(['red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback',
|
|
57
74
|
'handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression',
|
|
58
|
-
'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review','abandon_step','abandon_review'].includes(value.fixOperation),'fix_operation_unavailable');
|
|
75
|
+
'publish_dossier','walkthrough','finish','prepare_revision','cause_review_package','cause_review','reconcile_review','abandon_step','abandon_review'].includes(value.fixOperation),'fix_operation_unavailable');
|
|
59
76
|
need(!(advancing||acting)||allowStart,'qa_fix_start_authorization_required');
|
|
60
77
|
busy=true;let child=null,released=false,result;
|
|
61
78
|
try{
|
|
@@ -75,7 +92,7 @@ export function createQaFixOwnerHost({parent,reopenParent,hostContextId,parentHo
|
|
|
75
92
|
runtime:definition.configuration.runtime??'codex',permissions:[...permissions,'--allow-reproduction'],...fixAuthorities});
|
|
76
93
|
actionResult=running?await host.run(value.requestId)
|
|
77
94
|
:await host.handle({requestId:value.requestId,operation:advancing?'advance':value.fixOperation,
|
|
78
|
-
...(['abandon_step','abandon_review'].includes(value.fixOperation)?{reason:value.reason}:{})});
|
|
95
|
+
...(value.fixOperation==='reconcile_review'?{invocationId:value.invocationId}:{}),...(['abandon_step','abandon_review'].includes(value.fixOperation)?{reason:value.reason}:{})});
|
|
79
96
|
}
|
|
80
97
|
// Original observation/escalation finish intentionally closes its owner. Preserve
|
|
81
98
|
// that successful incomplete exit without reading a closed store.
|
|
@@ -13,7 +13,7 @@ export function parseHostInputLimit(raw){
|
|
|
13
13
|
&&value>=LIMIT&&value<=4*1024*1024,'invalid_arguments');
|
|
14
14
|
return value;
|
|
15
15
|
}
|
|
16
|
-
const operationNames=new Set(['replace_inputs','read_batch','recover_final_review','abandon_step','abandon_review','abandon_effect','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
|
|
16
|
+
const operationNames=new Set(['repair_review_response','reconcile_review','rediagnose','replace_inputs','read_batch','recover_final_review','abandon_step','abandon_review','abandon_effect','bootstrap_review_recover','advance','start','plan_design','promote_design','select_design_reviews','status','fix_status','fix_advance','fix_action','fix_run','decision','complete','qa','qa_result','prepare_revision','prepare_save',
|
|
17
17
|
'context_refresh','finish','completion_evidence','run_finalize','review_findings','review_disposition','save_draft','save_design','correct_findings','prepare_summary','publish_summary','inspect_correction','resume_correction','cancel','resume','prepare_judge_revision','cause_review_package','cause_review','red_test','baseline','author_tests','repair','regression','retrospective','learning_writeback','handoff','final_review_package','final_review','publish_review','check_n5','post_review_regression','publish_dossier','walkthrough']);
|
|
18
18
|
|
|
19
19
|
// Which contract codes may reach the peer is a deliberate boundary: the host
|
|
@@ -50,7 +50,9 @@ export function readHostWorkflowConfiguration(file){
|
|
|
50
50
|
|
|
51
51
|
export function validateHostWorkflowConfiguration(raw){
|
|
52
52
|
const config=json(raw);
|
|
53
|
-
shape(config,['qa','documentationPaths','applicableAgentFiles'
|
|
53
|
+
shape(config,['qa','documentationPaths','applicableAgentFiles',
|
|
54
|
+
...(Object.hasOwn(config,'knowledgeCloseout')?['knowledgeCloseout']:[])]);
|
|
55
|
+
if(Object.hasOwn(config,'knowledgeCloseout'))need(typeof config.knowledgeCloseout==='boolean','invalid_workflow_config');
|
|
54
56
|
for(const key of ['documentationPaths','applicableAgentFiles'])
|
|
55
57
|
need(Array.isArray(config[key])&&config[key].length<=256&&config[key].every(item=>typeof item==='string'),'invalid_workflow_config');
|
|
56
58
|
if(config.qa!==null){
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Advisory read-only closeout over the original documentation inspection.
|
|
2
|
+
// A report is neither a Review receipt nor authority to change files or finish.
|
|
3
|
+
import {freeze,json,need,shape} from './effect-contract.mjs';
|
|
4
|
+
|
|
5
|
+
export const CLOSEOUT_VERSION=1;
|
|
6
|
+
export const CLOSEOUT_AREAS=Object.freeze(['code','runtime','documentation','rules','memory','residue']);
|
|
7
|
+
export function readCloseoutPolicy(raw){
|
|
8
|
+
const value=json(raw);shape(value,['version','enabled']);
|
|
9
|
+
need(value.version===CLOSEOUT_VERSION&&typeof value.enabled==='boolean','closeout_policy_unsupported');
|
|
10
|
+
return freeze(value);
|
|
11
|
+
}
|
|
12
|
+
export function closeoutPolicyCandidates(execution,mode,snapshot=null){
|
|
13
|
+
if(!execution?.documentationProvider&&!execution?.documentationResult)return [null];
|
|
14
|
+
const workflow=execution.configuration.workflow?.configuration??execution.configuration.workflow;
|
|
15
|
+
const explicit=workflow&&Object.hasOwn(workflow,'knowledgeCloseout');
|
|
16
|
+
const requested=readCloseoutPolicy({version:CLOSEOUT_VERSION,enabled:explicit?workflow.knowledgeCloseout:true});
|
|
17
|
+
if(mode==='create')return [requested];
|
|
18
|
+
const init=snapshot?.records.find(row=>row.payload.type==='init');
|
|
19
|
+
if(init){
|
|
20
|
+
const saved=init.payload.config.knowledgeCloseout;
|
|
21
|
+
if(saved===undefined){need(!explicit,'closeout_policy_changed');return [null];}
|
|
22
|
+
const policy=readCloseoutPolicy(saved);
|
|
23
|
+
need(!explicit||policy.enabled===requested.enabled,'closeout_policy_changed');
|
|
24
|
+
return [policy];
|
|
25
|
+
}
|
|
26
|
+
// An interrupted empty initializer has no init record. Only an exact original
|
|
27
|
+
// fingerprint may select one of these supported configurations; never guess.
|
|
28
|
+
return explicit?[requested]:[requested,readCloseoutPolicy({version:CLOSEOUT_VERSION,enabled:false}),null];
|
|
29
|
+
}
|
|
30
|
+
export function readCloseoutReport(raw){
|
|
31
|
+
const report=json(raw,16*1024);shape(report,['version','items']);
|
|
32
|
+
need(report.version===CLOSEOUT_VERSION&&Array.isArray(report.items)
|
|
33
|
+
&&report.items.length===CLOSEOUT_AREAS.length,'closeout_report_invalid');
|
|
34
|
+
const seen=new Set();
|
|
35
|
+
const string=(value,max)=>need(typeof value==='string'&&value.trim().length>0
|
|
36
|
+
&&Buffer.byteLength(value,'utf8')<=max&&!/[\x00-\x1f\x7f]/.test(value),'closeout_report_invalid');
|
|
37
|
+
for(const item of report.items){
|
|
38
|
+
shape(item,['area','status','evidence','detail']);
|
|
39
|
+
need(CLOSEOUT_AREAS.includes(item.area)&&!seen.has(item.area),'closeout_report_invalid');seen.add(item.area);
|
|
40
|
+
need(['checked','issues','unverified','out_of_scope','not_applicable'].includes(item.status),'closeout_report_invalid');
|
|
41
|
+
string(item.detail,1000);
|
|
42
|
+
need(Array.isArray(item.evidence)&&item.evidence.length<=8,'closeout_report_invalid');
|
|
43
|
+
item.evidence.forEach(value=>string(value,1000));
|
|
44
|
+
need(!['checked','issues'].includes(item.status)||item.evidence.length>0,'closeout_report_invalid');
|
|
45
|
+
}
|
|
46
|
+
return freeze(report);
|
|
47
|
+
}
|
|
48
|
+
export function closeoutSummary(policy,documentation=null,reason='report_not_provided'){
|
|
49
|
+
if(policy===null)return {};
|
|
50
|
+
readCloseoutPolicy(policy);
|
|
51
|
+
const report=policy.enabled&&documentation?.closeout?readCloseoutReport(documentation.closeout):null;
|
|
52
|
+
return {knowledgeCloseout:{...policy,status:!policy.enabled?'disabled':report?'reported':'not_completed',
|
|
53
|
+
reason:!policy.enabled?'explicitly_disabled':report?'advisory_only':reason,
|
|
54
|
+
...(documentation?{identity:documentation.identity,packageDigest:documentation.packageDigest,
|
|
55
|
+
contextDigest:documentation.contextDigest,syncId:documentation.syncId}:{}),items:report?.items??[]}};
|
|
56
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Historical experimental snapshots remain immutable and need their original executor.
|
|
2
|
+
import {digest,json,need,shape,validIdentity} from './effect-contract.mjs';
|
|
3
|
+
import {externalPair} from './external-models.mjs';
|
|
4
|
+
export function previewLegacyModelRun(raw){
|
|
5
|
+
const value=json(raw,64*1024),{snapshotDigest,...body}=value;
|
|
6
|
+
const experimental=value.schemaVersion===1&&value.kind==='cm-model-run-snapshot'&&value.population==='experimental-model-v1';
|
|
7
|
+
const policy=value.version===2&&value.kind==='cm-model-policy-snapshot'&&value.resolverVersion==='model-policy-resolver-v1';
|
|
8
|
+
need((experimental||policy)&&value.locked===true&&digest(body)===snapshotDigest,'legacy_model_snapshot_invalid');
|
|
9
|
+
shape(value,experimental?['schemaVersion','kind','population','locked','definition','selection','snapshotDigest']:
|
|
10
|
+
['version','kind','resolverVersion','definition','selection','locked','snapshotDigest',...(Object.hasOwn(value,'modelPolicyFix')?['modelPolicyFix']:[])]);
|
|
11
|
+
validIdentity(value.definition.identity);
|
|
12
|
+
need(value.definition.version===2&&value.definition.population===(experimental?'experimental-model-v1':'model-policy-v2'),'legacy_model_snapshot_invalid');
|
|
13
|
+
const {previewDigest,...selection}=value.selection;
|
|
14
|
+
need(selection.schemaVersion===1&&selection.kind==='cm-model-preview'&&selection.executionAvailable===false
|
|
15
|
+
&&digest(selection)===previewDigest,'legacy_model_preview_invalid');
|
|
16
|
+
const stages=Object.fromEntries(Object.entries(selection.stages).map(([stage,choice])=>{
|
|
17
|
+
need(['developer','reviewer','test_analysis'].includes(stage),'legacy_model_preview_invalid');
|
|
18
|
+
const {provider,...pair}=choice.tuple;
|
|
19
|
+
return [stage,{provider,...externalPair(provider,pair),mode:choice.mode,source:choice.source}];
|
|
20
|
+
}));
|
|
21
|
+
return {readOnly:true,validation:'snapshot and selection digest; not execution ownership',
|
|
22
|
+
identity:value.definition.identity,population:value.definition.population,snapshotDigest,stages,
|
|
23
|
+
effectiveModel:'unknown',providerConfirmed:false,resume:'original executor required; no migration'};
|
|
24
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Read-only compatibility. These historical defaults never select a new run.
|
|
2
|
+
import {digest,json,need,shape} from './effect-contract.mjs';
|
|
3
|
+
import {externalPair} from './external-models.mjs';
|
|
4
|
+
const defaults={codex:{general:'gpt-6-astra',code:'gpt-6.1-sol'},claude:{general:'claude-fable-5',code:'claude-opus-5-5'}};
|
|
5
|
+
const tuple=(provider,raw)=>{
|
|
6
|
+
const value=json(raw);shape(value,['provider','model','effort']);need(value.provider===provider,'legacy_provider_conflict');
|
|
7
|
+
return externalPair(provider,{model:value.model,effort:value.effort});
|
|
8
|
+
};
|
|
9
|
+
function choices(raw){
|
|
10
|
+
const value=json(raw);shape(value,['schemaVersion','presetVersion','choices']);
|
|
11
|
+
need([1,2].includes(value.schemaVersion)&&value.presetVersion==='two-tier-v1','legacy_schema_unsupported');
|
|
12
|
+
const result={};
|
|
13
|
+
for(const provider of ['codex','claude'])result[provider]={developer:{model:defaults[provider].code,effort:'high'},reviewer:{model:defaults[provider].code,effort:'high'}};
|
|
14
|
+
if(value.schemaVersion===1){
|
|
15
|
+
shape(value.choices,['codex','claude']);
|
|
16
|
+
for(const provider of ['codex','claude']){
|
|
17
|
+
shape(value.choices[provider],['general','code']);
|
|
18
|
+
for(const entry of Object.values(value.choices[provider]))need(tuple(provider,entry).effort==='high','legacy_effort_invalid');
|
|
19
|
+
result[provider]={developer:tuple(provider,value.choices[provider].code),reviewer:tuple(provider,value.choices[provider].code)};
|
|
20
|
+
}
|
|
21
|
+
}else{
|
|
22
|
+
shape(value.choices,Object.keys(value.choices));
|
|
23
|
+
for(const [provider,stages] of Object.entries(value.choices)){
|
|
24
|
+
need(Object.hasOwn(defaults,provider),'invalid_external_provider');shape(stages,Object.keys(stages));
|
|
25
|
+
for(const [stage,entry] of Object.entries(stages)){
|
|
26
|
+
need(['general','developer','reviewer'].includes(stage),'legacy_stage_invalid');
|
|
27
|
+
shape(entry,Object.keys(entry));need(Object.keys(entry).length>0&&Object.keys(entry).every(key=>['provider','model','effort'].includes(key)),'legacy_tuple_invalid');
|
|
28
|
+
const selected=tuple(provider,{provider,model:defaults[provider][stage==='general'?'general':'code'],effort:'high',...entry});
|
|
29
|
+
if(stage!=='general')result[provider][stage]=selected;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
export function previewLegacyExternalModels({settings,task=null,project=null,global=null}){
|
|
36
|
+
const base=choices(settings);
|
|
37
|
+
for(const layer of [task,project,global])if(layer!==null){
|
|
38
|
+
shape(layer,['schemaVersion','stages']);need(layer.schemaVersion===1,'legacy_schema_unsupported');
|
|
39
|
+
shape(layer.stages,Object.keys(layer.stages));
|
|
40
|
+
for(const [stage,row] of Object.entries(layer.stages)){
|
|
41
|
+
need(['developer','reviewer','test_analysis'].includes(stage),'legacy_stage_invalid');
|
|
42
|
+
need(['manual','recommended'].includes(row?.mode),'legacy_mode_invalid');
|
|
43
|
+
shape(row,['mode',...(row.mode==='manual'?['provider','model','effort']:[])]);
|
|
44
|
+
if(row.mode==='manual'){const {mode,...raw}=row;tuple(raw.provider,raw);}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const selected=Object.fromEntries(['developer','reviewer'].map(stage=>{
|
|
48
|
+
const row=[task,project,global].map(layer=>layer?.stages[stage]).find(value=>value!==undefined);
|
|
49
|
+
if(row===undefined)return [stage,null];
|
|
50
|
+
need(row.mode==='manual','legacy_recommendation_requires_explicit_choice');
|
|
51
|
+
shape(row,['mode','provider','model','effort']);const {mode,...raw}=row;
|
|
52
|
+
return [stage,{provider:raw.provider,pair:tuple(raw.provider,raw)}];
|
|
53
|
+
}));
|
|
54
|
+
return Object.fromEntries(Object.keys(base).map(provider=>{
|
|
55
|
+
const effective=Object.fromEntries(['developer','reviewer'].map(stage=>[stage,selected[stage]?.provider===provider?selected[stage].pair:base[provider][stage]]));
|
|
56
|
+
const conflict=digest(effective.developer)!==digest(effective.reviewer);
|
|
57
|
+
return [provider,{...effective,conflict,pair:conflict?null:effective.developer}];
|
|
58
|
+
}));
|
|
59
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Current-session execution transport. The host owns evidence semantics;
|
|
2
|
+
// this responder only binds a fresh reply to its original live request.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {randomUUID} from 'node:crypto';
|
|
6
|
+
import {setTimeout as delay} from 'node:timers/promises';
|
|
7
|
+
|
|
8
|
+
const KINDS=new Set(['qa_logic','qa_browser','verification_precheck','prd_materials']);
|
|
9
|
+
const fail=code=>{throw Error(code);};
|
|
10
|
+
const inside=(root,file)=>file===root||file.startsWith(root+path.sep);
|
|
11
|
+
function resolvedFutureRoot(file){
|
|
12
|
+
let existing=path.resolve(file);const tail=[];
|
|
13
|
+
while(!fs.existsSync(existing)){
|
|
14
|
+
const parent=path.dirname(existing);if(parent===existing)break;
|
|
15
|
+
tail.unshift(path.basename(existing));existing=parent;
|
|
16
|
+
}
|
|
17
|
+
return path.join(fs.realpathSync(existing),...tail);
|
|
18
|
+
}
|
|
19
|
+
function ordinaryAncestors(file){
|
|
20
|
+
let current=path.parse(file).root;
|
|
21
|
+
for(const part of file.slice(current.length).split(path.sep).filter(Boolean)){
|
|
22
|
+
current=path.join(current,part);
|
|
23
|
+
try{const stat=fs.lstatSync(current);
|
|
24
|
+
if(!stat.isDirectory()||stat.isSymbolicLink())fail('live_evidence_unsafe_directory');
|
|
25
|
+
}catch(error){if(error.code!=='ENOENT')throw error;}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function createLiveEvidence(config,{base,protectedRoots=[],notify=()=>{},maxBytes=65536,allowedKinds=[...KINDS]}={}){
|
|
29
|
+
if(config===undefined)return {has:()=>false,answer:async()=>null};
|
|
30
|
+
if(!config||typeof config!=='object'||Array.isArray(config)
|
|
31
|
+
||Object.keys(config).some(key=>!['directory','kinds','timeoutMs'].includes(key))
|
|
32
|
+
||typeof config.directory!=='string'||!config.directory.trim()
|
|
33
|
+
||!Array.isArray(config.kinds)||!config.kinds.length
|
|
34
|
+
||new Set(config.kinds).size!==config.kinds.length
|
|
35
|
+
||!config.kinds.every(kind=>KINDS.has(kind)&&allowedKinds.includes(kind)))fail('live_evidence_invalid_config');
|
|
36
|
+
const timeout=config.timeoutMs??900000;
|
|
37
|
+
if(!Number.isSafeInteger(timeout)||timeout<1||timeout>3600000
|
|
38
|
+
||!Number.isSafeInteger(maxBytes)||maxBytes<1||maxBytes>4194304)fail('live_evidence_invalid_limit');
|
|
39
|
+
const directory=path.resolve(base??process.cwd(),config.directory);
|
|
40
|
+
const validateDirectory=()=>{
|
|
41
|
+
ordinaryAncestors(directory);
|
|
42
|
+
for(const root of protectedRoots.filter(Boolean)){
|
|
43
|
+
const resolved=resolvedFutureRoot(root),lexical=path.resolve(root);
|
|
44
|
+
if([resolved,lexical].some(value=>inside(value,directory)||inside(directory,value)))fail('live_evidence_protected_directory');
|
|
45
|
+
}
|
|
46
|
+
if(fs.existsSync(directory)){
|
|
47
|
+
const stat=fs.lstatSync(directory);
|
|
48
|
+
if((stat.mode&0o077)!==0||typeof process.getuid==='function'&&stat.uid!==process.getuid())
|
|
49
|
+
fail('live_evidence_directory_not_private');
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
validateDirectory();
|
|
53
|
+
const kinds=new Set(config.kinds),seen=new Set();let exchange=null;
|
|
54
|
+
return {has:kind=>kinds.has(kind),async answer(row,{signal}={}){
|
|
55
|
+
if(!kinds.has(row.kind))return null;
|
|
56
|
+
if(signal?.aborted)fail('live_evidence_cancelled');
|
|
57
|
+
if(row.type!=='host_request'||!row.sessionId||!row.callId
|
|
58
|
+
||typeof row.requestDigest!=='string'||!/^[a-f0-9]{64}$/.test(row.requestDigest))fail('live_evidence_invalid_request');
|
|
59
|
+
const key=JSON.stringify([row.sessionId,row.callId]);
|
|
60
|
+
if(seen.has(key))fail('live_evidence_duplicate_call');
|
|
61
|
+
seen.add(key);validateDirectory();
|
|
62
|
+
if(exchange===null){
|
|
63
|
+
fs.mkdirSync(directory,{recursive:true,mode:0o700});validateDirectory();
|
|
64
|
+
exchange=path.join(directory,randomUUID());fs.mkdirSync(exchange,{mode:0o700});
|
|
65
|
+
}
|
|
66
|
+
// File names never contain caller-controlled identifiers.
|
|
67
|
+
const stem=path.join(exchange,randomUUID()),requestFile=stem+'.request.json',resultFile=stem+'.result.json';
|
|
68
|
+
fs.writeFileSync(requestFile,JSON.stringify(row)+'\n',{flag:'wx',mode:0o600});
|
|
69
|
+
notify(requestFile);const end=Date.now()+timeout;
|
|
70
|
+
while(true){
|
|
71
|
+
if(signal?.aborted)fail('live_evidence_cancelled');
|
|
72
|
+
let fd;
|
|
73
|
+
try{
|
|
74
|
+
fd=fs.openSync(resultFile,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);
|
|
75
|
+
const before=fs.fstatSync(fd);
|
|
76
|
+
if(!before.isFile()||before.nlink!==1||before.size>maxBytes)fail('live_evidence_unsafe_result');
|
|
77
|
+
const bytes=fs.readFileSync(fd),after=fs.fstatSync(fd);
|
|
78
|
+
if(bytes.length>maxBytes||before.size!==after.size||before.mtimeMs!==after.mtimeMs)fail('live_evidence_result_changed');
|
|
79
|
+
let value;try{value=JSON.parse(bytes.toString('utf8'));}catch{fail('live_evidence_invalid_json');}
|
|
80
|
+
if(!value||Array.isArray(value)||Object.keys(value).sort().join(',')!=='callId,requestDigest,result,sessionId,type'
|
|
81
|
+
||value.type!=='host_result'||value.sessionId!==row.sessionId||value.callId!==row.callId
|
|
82
|
+
||value.requestDigest!==row.requestDigest)fail('live_evidence_binding_mismatch');
|
|
83
|
+
return value.result;
|
|
84
|
+
}catch(error){if(error.code!=='ENOENT')throw error;}
|
|
85
|
+
finally{if(fd!==undefined)fs.closeSync(fd);}
|
|
86
|
+
if(Date.now()>=end)fail('live_evidence_timeout');
|
|
87
|
+
try{await delay(Math.min(100,end-Date.now()),undefined,{signal});}
|
|
88
|
+
catch(error){if(error.name==='AbortError')fail('live_evidence_cancelled');throw error;}
|
|
89
|
+
}
|
|
90
|
+
}};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function driverLiveEvidence(plan,options){
|
|
94
|
+
return createLiveEvidence(plan.liveEvidence,{...options,notify:file=>process.stderr.write(
|
|
95
|
+
`[drive] live_evidence_request: ${file}\n[drive] Read the live request, execute its task, then atomically write the matching .result.json host_result.\n`)});
|
|
96
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Local bounded declarative JSON. No global state, secrets, or store migrations.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {createHash} from 'node:crypto';
|
|
5
|
+
import {spawnSync} from 'node:child_process';
|
|
6
|
+
import {fileURLToPath} from 'node:url';
|
|
7
|
+
import {need,digest} from './effect-contract.mjs';
|
|
8
|
+
const LIMIT=64*1024;
|
|
9
|
+
const RUN_DIRECTORIES=new Set(['.reviews','.cm-model-runtime-v1','.cm-model-reviews-v1','.cm-model-runtime-v2','.cm-model-reviews-v2','.cm-model-fix-runtime-v1','.cm-external-models-v1']);
|
|
10
|
+
const RUN_FILES=new Set(['.cm-task-owner.json','.cm-model-code-owner-v1.json','.cm-model-project-owner-v2.json','.cm-model-snapshot-v1.json','.cm-model-fix-owner-v1.json']);
|
|
11
|
+
export function parseModelJson(text){
|
|
12
|
+
need(typeof text==='string'&&Buffer.byteLength(text)<=LIMIT,'model_configuration_too_large');
|
|
13
|
+
let value;try{value=JSON.parse(text);}catch{need(false,'invalid_model_json');}
|
|
14
|
+
const tokens=text.match(/"(?:\\[\s\S]|[^"\\])*"|[{}\[\]:,]|[^\s{}\[\]:,]+/g)??[];let index=0;
|
|
15
|
+
const walk=depth=>{
|
|
16
|
+
need(depth<=32,'model_configuration_too_deep');const token=tokens[index++];
|
|
17
|
+
if(token==='{'){
|
|
18
|
+
const keys=new Set();if(tokens[index]==='}'){index++;return;}
|
|
19
|
+
for(;;){const key=JSON.parse(tokens[index++]);need(!keys.has(key),'duplicate_model_json_key');keys.add(key);index++;walk(depth+1);
|
|
20
|
+
if(tokens[index++]==='}')return;}
|
|
21
|
+
}
|
|
22
|
+
if(token==='['){if(tokens[index]===']'){index++;return;}for(;;){walk(depth+1);if(tokens[index++]===']')return;}}
|
|
23
|
+
};
|
|
24
|
+
walk(0);return value;
|
|
25
|
+
}
|
|
26
|
+
const match=(a,b)=>['dev','ino','size','mtimeMs','ctimeMs','nlink'].every(k=>a[k]===b[k]);
|
|
27
|
+
export function readModelJsonRecord(file){
|
|
28
|
+
const before=fs.lstatSync(file);need(before.isFile()&&!before.isSymbolicLink()&&before.nlink===1&&before.size<=LIMIT,'invalid_model_configuration_file');
|
|
29
|
+
const fd=fs.openSync(file,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);
|
|
30
|
+
try{
|
|
31
|
+
need(match(before,fs.fstatSync(fd)),'model_configuration_changed');const bytes=fs.readFileSync(fd);const text=bytes.toString('utf8');
|
|
32
|
+
need(bytes.equals(Buffer.from(text))&&match(before,fs.fstatSync(fd))&&match(before,fs.lstatSync(file)),'model_configuration_changed');
|
|
33
|
+
return {value:parseModelJson(text),sha256:createHash('sha256').update(bytes).digest('hex')};
|
|
34
|
+
}finally{fs.closeSync(fd);}
|
|
35
|
+
}
|
|
36
|
+
export const readModelJson=file=>readModelJsonRecord(file).value;
|
|
37
|
+
export function assertModelOutputPath(file){
|
|
38
|
+
const target=path.resolve(file);
|
|
39
|
+
need(!target.split(path.sep).some(segment=>RUN_DIRECTORIES.has(segment.toLowerCase()))
|
|
40
|
+
&&!RUN_FILES.has(path.basename(target).toLowerCase()),'model_output_run_path_forbidden');
|
|
41
|
+
return target;
|
|
42
|
+
}
|
|
43
|
+
export function writeModelJson(file,value,{expectedDigest,expectedSha256,replace=true,createParents=false,sourceGuard=null}={}){
|
|
44
|
+
const target=assertModelOutputPath(file);
|
|
45
|
+
need(path.basename(target).toLowerCase()!=='.cm-model-config.lock','model_output_run_path_forbidden');
|
|
46
|
+
// No downgrade to a path-based writer if the platform/helper is unavailable.
|
|
47
|
+
need(process.platform!=='win32'&&fs.existsSync('/usr/bin/python3'),'model_secure_write_unavailable');
|
|
48
|
+
let before=null;
|
|
49
|
+
try{const info=fs.lstatSync(target);need(info.isFile()&&!info.isSymbolicLink()&&info.nlink===1,'invalid_model_configuration_file');
|
|
50
|
+
need(replace,'model_configuration_exists');before=readModelJsonRecord(target);
|
|
51
|
+
}catch(e){if(e.code!=='ENOENT')throw e;}
|
|
52
|
+
if(expectedDigest!==undefined)need(expectedDigest===null?before===null:before!==null&&digest(before.value)===expectedDigest,'model_configuration_changed');
|
|
53
|
+
if(expectedSha256!==undefined)need((before?.sha256??null)===expectedSha256,'model_configuration_changed');
|
|
54
|
+
const bytes=Buffer.from(JSON.stringify(value,null,2)+'\n');need(bytes.length<=LIMIT,'model_configuration_too_large');
|
|
55
|
+
const request={target,bytes:bytes.toString('base64'),expectedSha256:before?.sha256??null,replace,createParents,sourceGuard};
|
|
56
|
+
const helper=fileURLToPath(new URL('./model_configuration_write.py',import.meta.url));
|
|
57
|
+
const result=spawnSync('/usr/bin/python3',['-I','-B',helper],{input:JSON.stringify(request),encoding:'utf8',
|
|
58
|
+
env:{PATH:'/usr/bin:/bin',LANG:'C.UTF-8'},timeout:10000,maxBuffer:4096,shell:false});
|
|
59
|
+
// A started helper may already have published before timeout/response loss.
|
|
60
|
+
if(result.error||result.signal)need(false,result.error?.code==='ENOENT'?'model_secure_write_unavailable':'model_configuration_write_unknown');
|
|
61
|
+
let response;try{response=JSON.parse(result.stdout);}catch{need(false,'model_configuration_write_unknown');}
|
|
62
|
+
need(response?.ok===true&&result.status===0,response?.ok===false&&/^model_|^invalid_model_|^unsupported_model_/.test(response.code)?response.code:'model_configuration_write_unknown');
|
|
63
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""POSIX publication only: pinned directories, cooperative lock, byte CAS.
|
|
3
|
+
|
|
4
|
+
The containing directory must be owned by the caller and not group/world writable.
|
|
5
|
+
This does not sandbox a same-UID actor that can move that directory or ignore locks.
|
|
6
|
+
"""
|
|
7
|
+
import base64
|
|
8
|
+
import errno
|
|
9
|
+
import hashlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import stat
|
|
13
|
+
import sys
|
|
14
|
+
import uuid
|
|
15
|
+
|
|
16
|
+
LIMIT = 64 * 1024
|
|
17
|
+
RUN_DIRECTORIES = {'.cm-external-models-v1', '.reviews', '.cm-model-runtime-v1', '.cm-model-reviews-v1',
|
|
18
|
+
'.cm-model-runtime-v2', '.cm-model-reviews-v2', '.cm-model-fix-runtime-v1'}
|
|
19
|
+
RUN_FILES = {'.cm-task-owner.json', '.cm-model-code-owner-v1.json',
|
|
20
|
+
'.cm-model-project-owner-v2.json', '.cm-model-snapshot-v1.json',
|
|
21
|
+
'.cm-model-fix-owner-v1.json'}
|
|
22
|
+
LOCK = '.cm-model-config.lock'
|
|
23
|
+
SECURE_PLATFORM = (os.name == 'posix' and hasattr(os, 'O_NOFOLLOW') and hasattr(os, 'O_DIRECTORY')
|
|
24
|
+
and all(function in os.supports_dir_fd for function in
|
|
25
|
+
(os.open, os.mkdir, os.stat, os.link, os.unlink, os.rename)))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Refusal(Exception):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def require(condition, code):
|
|
33
|
+
if not condition:
|
|
34
|
+
raise Refusal(code)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def validate_target(target):
|
|
38
|
+
require(isinstance(target, str) and os.path.isabs(target)
|
|
39
|
+
and os.path.normpath(target) == target, 'unsupported_model_path')
|
|
40
|
+
require(not any(part.lower() in RUN_DIRECTORIES for part in target.split(os.sep))
|
|
41
|
+
and os.path.basename(target).lower() not in RUN_FILES | {LOCK},
|
|
42
|
+
'model_output_run_path_forbidden')
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def open_parent(target, create):
|
|
46
|
+
"""Never resolve an ancestor through a symlink, including during mkdir."""
|
|
47
|
+
flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
|
48
|
+
current = os.open(os.sep, flags)
|
|
49
|
+
try:
|
|
50
|
+
for part in os.path.dirname(target).split(os.sep)[1:]:
|
|
51
|
+
try:
|
|
52
|
+
child = os.open(part, flags, dir_fd=current)
|
|
53
|
+
except FileNotFoundError:
|
|
54
|
+
require(create, 'unsupported_model_path')
|
|
55
|
+
try:
|
|
56
|
+
os.mkdir(part, 0o700, dir_fd=current)
|
|
57
|
+
os.fsync(current)
|
|
58
|
+
except FileExistsError:
|
|
59
|
+
pass
|
|
60
|
+
child = os.open(part, flags, dir_fd=current)
|
|
61
|
+
os.close(current)
|
|
62
|
+
current = child
|
|
63
|
+
info = os.fstat(current)
|
|
64
|
+
require(info.st_uid == os.geteuid() and not info.st_mode & 0o022,
|
|
65
|
+
'model_configuration_untrusted_directory')
|
|
66
|
+
return current
|
|
67
|
+
except BaseException:
|
|
68
|
+
os.close(current)
|
|
69
|
+
raise
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def file_hash(parent, name):
|
|
73
|
+
try:
|
|
74
|
+
fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
|
|
75
|
+
except FileNotFoundError:
|
|
76
|
+
return None
|
|
77
|
+
try:
|
|
78
|
+
before = os.fstat(fd)
|
|
79
|
+
require(stat.S_ISREG(before.st_mode) and before.st_nlink == 1
|
|
80
|
+
and before.st_size <= LIMIT, 'invalid_model_configuration_file')
|
|
81
|
+
with os.fdopen(os.dup(fd), 'rb') as stream:
|
|
82
|
+
content = stream.read(LIMIT + 1)
|
|
83
|
+
after = os.stat(name, dir_fd=parent, follow_symlinks=False)
|
|
84
|
+
identity = lambda info: (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns,
|
|
85
|
+
info.st_ctime_ns, info.st_nlink)
|
|
86
|
+
require(len(content) <= LIMIT and identity(before) == identity(os.fstat(fd)) and identity(before) == identity(after),
|
|
87
|
+
'model_configuration_changed')
|
|
88
|
+
return hashlib.sha256(content).hexdigest()
|
|
89
|
+
finally:
|
|
90
|
+
os.close(fd)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def publish(request):
|
|
94
|
+
require(SECURE_PLATFORM, 'model_secure_write_unavailable')
|
|
95
|
+
import fcntl
|
|
96
|
+
require(set(request) == {'target', 'bytes', 'expectedSha256', 'replace', 'createParents', 'sourceGuard'},
|
|
97
|
+
'invalid_model_write_request')
|
|
98
|
+
target = request['target']
|
|
99
|
+
validate_target(target)
|
|
100
|
+
require(type(request['replace']) is bool and type(request['createParents']) is bool,
|
|
101
|
+
'invalid_model_write_request')
|
|
102
|
+
content = base64.b64decode(request['bytes'], validate=True)
|
|
103
|
+
require(len(content) <= LIMIT, 'model_configuration_too_large')
|
|
104
|
+
expected = request['expectedSha256']
|
|
105
|
+
require(expected is None or isinstance(expected, str) and len(expected) == 64
|
|
106
|
+
and all(c in '0123456789abcdef' for c in expected), 'invalid_model_write_request')
|
|
107
|
+
guard = request['sourceGuard']
|
|
108
|
+
if guard is not None:
|
|
109
|
+
require(isinstance(guard, dict) and set(guard) == {'file', 'sha256'}
|
|
110
|
+
and isinstance(guard['file'], str)
|
|
111
|
+
and isinstance(guard['sha256'], str) and len(guard['sha256']) == 64
|
|
112
|
+
and all(c in '0123456789abcdef' for c in guard['sha256'])
|
|
113
|
+
and os.path.dirname(guard['file']) == os.path.dirname(target),
|
|
114
|
+
'invalid_model_write_request')
|
|
115
|
+
validate_target(guard['file'])
|
|
116
|
+
parent = open_parent(target, request['createParents'])
|
|
117
|
+
lock = None
|
|
118
|
+
temporary = None
|
|
119
|
+
published = False
|
|
120
|
+
try:
|
|
121
|
+
try:
|
|
122
|
+
lock = os.open(LOCK, os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent)
|
|
123
|
+
except FileExistsError:
|
|
124
|
+
try:
|
|
125
|
+
lock = os.open(LOCK, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
|
|
126
|
+
except FileNotFoundError:
|
|
127
|
+
raise Refusal('model_configuration_busy')
|
|
128
|
+
info = os.fstat(lock)
|
|
129
|
+
require(stat.S_ISREG(info.st_mode) and info.st_nlink == 1 and info.st_uid == os.geteuid()
|
|
130
|
+
and not info.st_mode & 0o077, 'invalid_model_configuration_lock')
|
|
131
|
+
try:
|
|
132
|
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
133
|
+
except BlockingIOError:
|
|
134
|
+
raise Refusal('model_configuration_busy')
|
|
135
|
+
# Persistent lock inode: never unlink it, including after crash or success.
|
|
136
|
+
require(os.stat(LOCK, dir_fd=parent, follow_symlinks=False).st_ino == info.st_ino,
|
|
137
|
+
'invalid_model_configuration_lock')
|
|
138
|
+
name = os.path.basename(target)
|
|
139
|
+
actual = file_hash(parent, name)
|
|
140
|
+
require(request['replace'] or actual is None, 'model_configuration_exists')
|
|
141
|
+
require(actual == expected, 'model_configuration_changed')
|
|
142
|
+
if guard is not None:
|
|
143
|
+
require(file_hash(parent, os.path.basename(guard['file'])) == guard['sha256'],
|
|
144
|
+
'model_configuration_changed')
|
|
145
|
+
temporary = '.cm-model-' + uuid.uuid4().hex + '.tmp'
|
|
146
|
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=parent)
|
|
147
|
+
with os.fdopen(fd, 'wb') as stream:
|
|
148
|
+
stream.write(content)
|
|
149
|
+
stream.flush()
|
|
150
|
+
os.fsync(stream.fileno())
|
|
151
|
+
require(file_hash(parent, name) == expected, 'model_configuration_changed')
|
|
152
|
+
if actual is None:
|
|
153
|
+
try:
|
|
154
|
+
os.link(temporary, name, src_dir_fd=parent, dst_dir_fd=parent, follow_symlinks=False)
|
|
155
|
+
except FileExistsError:
|
|
156
|
+
raise Refusal('model_configuration_changed')
|
|
157
|
+
published = True
|
|
158
|
+
os.unlink(temporary, dir_fd=parent)
|
|
159
|
+
else:
|
|
160
|
+
os.replace(temporary, name, src_dir_fd=parent, dst_dir_fd=parent)
|
|
161
|
+
published = True
|
|
162
|
+
temporary = None
|
|
163
|
+
os.fsync(parent)
|
|
164
|
+
# A renamed pinned directory cannot redirect the write, but the named
|
|
165
|
+
# configuration may no longer refer to it. Do not report success then.
|
|
166
|
+
named_parent = open_parent(target, False)
|
|
167
|
+
try:
|
|
168
|
+
pinned, named = os.fstat(parent), os.fstat(named_parent)
|
|
169
|
+
require((pinned.st_dev, pinned.st_ino) == (named.st_dev, named.st_ino),
|
|
170
|
+
'model_configuration_write_unknown')
|
|
171
|
+
finally:
|
|
172
|
+
os.close(named_parent)
|
|
173
|
+
except BaseException:
|
|
174
|
+
if published:
|
|
175
|
+
raise Refusal('model_configuration_write_unknown')
|
|
176
|
+
raise
|
|
177
|
+
finally:
|
|
178
|
+
cleanup_error = None
|
|
179
|
+
if temporary is not None:
|
|
180
|
+
try:
|
|
181
|
+
os.unlink(temporary, dir_fd=parent)
|
|
182
|
+
except FileNotFoundError:
|
|
183
|
+
pass
|
|
184
|
+
except OSError as error:
|
|
185
|
+
cleanup_error = error
|
|
186
|
+
for descriptor in (lock, parent):
|
|
187
|
+
if descriptor is not None:
|
|
188
|
+
try:
|
|
189
|
+
os.close(descriptor)
|
|
190
|
+
except OSError as error:
|
|
191
|
+
cleanup_error = error
|
|
192
|
+
if cleanup_error is not None:
|
|
193
|
+
if published:
|
|
194
|
+
raise Refusal('model_configuration_write_unknown')
|
|
195
|
+
raise cleanup_error
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def main():
|
|
199
|
+
try:
|
|
200
|
+
data = sys.stdin.buffer.read(192 * 1024 + 1)
|
|
201
|
+
require(len(data) <= 192 * 1024, 'model_configuration_too_large')
|
|
202
|
+
publish(json.loads(data))
|
|
203
|
+
print(json.dumps({'ok': True}))
|
|
204
|
+
except Exception as error:
|
|
205
|
+
code = str(error) if isinstance(error, Refusal) else (
|
|
206
|
+
'unsupported_model_path' if isinstance(error, OSError) and error.errno in (errno.ELOOP, errno.ENOTDIR)
|
|
207
|
+
else 'model_configuration_write_failed')
|
|
208
|
+
print(json.dumps({'ok': False, 'code': code}))
|
|
209
|
+
return 1
|
|
210
|
+
return 0
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
if __name__ == '__main__':
|
|
214
|
+
sys.exit(main())
|