@aibyzero/cm-workflow 0.21.4 → 0.21.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/CHANGELOG.md +13 -0
- package/README.md +7 -2
- package/VERSION +1 -1
- package/docs/installation.md +1 -1
- package/docs/js-workflow-control.md +1 -0
- package/install.ps1 +3 -0
- package/install.sh +2 -0
- package/package.json +1 -1
- package/runtime/js/cm-ai/host-session.mjs +1 -1
- package/runtime/js/cm-check/host.mjs +37 -8
- package/runtime/js/cm-prd/accepted-design.mjs +4 -0
- package/runtime/js/cm-prd/disposition-plan.mjs +4 -2
- package/runtime/js/cm-prd/narrow-review.mjs +210 -0
- package/runtime/js/cm-prd/review-correction.mjs +161 -8
- package/runtime/js/cm-prd/review-disposition.mjs +8 -1
- package/runtime/js/cm-prd/review-findings.mjs +8 -0
- package/runtime/js/notify.mjs +1 -0
- package/scripts/ci-test-weights.json +1 -0
- package/scripts/cm-check-doc-links.mjs +29 -0
- package/scripts/cm-check-host.test.mjs +46 -0
- package/scripts/cm-check-runtime.sh +15 -0
- package/scripts/cm-claude-install-layout.test.mjs +12 -0
- package/scripts/cm-doc-links-shared.mjs +139 -0
- package/scripts/cm-doc-links.test.mjs +110 -0
- package/scripts/cm-prd-design-phase.test.mjs +36 -4
- package/scripts/cm-prd-drive.mjs +12 -6
- package/scripts/cm-prd-host.mjs +15 -5
- package/scripts/cm-prd-narrow-review.test.mjs +429 -0
- package/scripts/cm-prd-review-gate.mjs +3 -0
- package/scripts/cm-rewrite-doc-links.mjs +34 -0
- package/skills/cm-ai/references/N1-init.md +1 -1
- package/skills/cm-check/SKILL.md +1 -1
- package/skills/cm-prd/SKILL.md +1 -0
- package/skills/cm-prd/references/js-change-recovery.md +2 -0
- package/skills/cm-prd/references/js-host.md +17 -2
|
@@ -4,7 +4,7 @@ import fs from 'node:fs';
|
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import {createHash,randomUUID} from 'node:crypto';
|
|
6
6
|
import {TextDecoder} from 'node:util';
|
|
7
|
-
import {inspectPrdFindings} from './review-findings.mjs';
|
|
7
|
+
import {inspectPrdFindings,readPrdReviewAuthor} from './review-findings.mjs';
|
|
8
8
|
import {inspectPrdDispositionPlan} from './disposition-plan.mjs';
|
|
9
9
|
import {checkPrdDraftMechanics} from './self-check.mjs';
|
|
10
10
|
import {prdTaskScopeOptions} from './task-scope-record.mjs';
|
|
@@ -12,6 +12,8 @@ import {inspectPrdDesignDraft} from './draft.mjs';
|
|
|
12
12
|
import {readCmInitSource} from '../cm-init/draft-inspection.mjs';
|
|
13
13
|
import {writeReviewEvidence} from '../cm-ai/review-evidence-file.mjs';
|
|
14
14
|
import {need,json,shape,digest} from '../cm-ai/effect-contract.mjs';
|
|
15
|
+
import {inspectPrdNarrowState,narrowPublicState,narrowNames,narrowCorrectionBytes,recordPrdNarrowReview,
|
|
16
|
+
PRD_NARROW_MAX_ROUNDS} from './narrow-review.mjs';
|
|
15
17
|
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
16
18
|
const archiveBytes=value=>Buffer.from('# Original review correction proposal\n\nNot review approval or completion. Private host-attested material.\n```json\n'
|
|
17
19
|
+JSON.stringify(value)+'\n```\n');
|
|
@@ -51,8 +53,13 @@ export function createPrdCorrectionOwner({correct}){
|
|
|
51
53
|
need(review.gate.outcome==='resume_disposition'&&review.verdict!=='blocked'&&review.findings.length>0,
|
|
52
54
|
'prd_correction_not_ready');
|
|
53
55
|
const archiveName=`prd-${feature.replace(/^\d+\./,'')}-${stage}-correction.md`;
|
|
54
|
-
if(readCmInitSource(specs,`.reviews/${archiveName}`)!==null)
|
|
55
|
-
|
|
56
|
+
if(readCmInitSource(specs,`.reviews/${archiveName}`)!==null){
|
|
57
|
+
// Design only: the saved original correction continues through recorded narrow review rounds.
|
|
58
|
+
if(stage==='design'&&prdNarrowCorrectionFlow({specs,stage,feature}))
|
|
59
|
+
return narrowCorrection({specs,feature,correct,attempts,signal});
|
|
60
|
+
return json({status:'correction_recovery_required',
|
|
61
|
+
archive:`.reviews/${archiveName}`,next:'inspect_original_correction_archive_without_regeneration',completionAuthorized:false});
|
|
62
|
+
}
|
|
56
63
|
const read=file=>readCorrectionFile(specs,file);
|
|
57
64
|
const before=review.reviewedArtifacts.map(item=>{
|
|
58
65
|
const bytes=read(item.path);need(sha(bytes)===item.sha256,'prd_correction_inputs_changed');
|
|
@@ -70,7 +77,8 @@ export function createPrdCorrectionOwner({correct}){
|
|
|
70
77
|
for(const item of before)need(sha(read(item.path))===item.sha256,'prd_correction_inputs_changed');
|
|
71
78
|
};
|
|
72
79
|
current();
|
|
73
|
-
|
|
80
|
+
// design archives written by this version opt the run into narrow review rounds; older archives stay legacy
|
|
81
|
+
const archive=archiveBytes({version:1,packageDigest:review.packageDigest,stage,feature,before,proposal,...(stage==='design'?{narrowReview:1}:{})});
|
|
74
82
|
// Archive original bytes and per-finding decisions before replacing any spec.
|
|
75
83
|
writeReviewEvidence({reviewsDir:path.join(specs,'.reviews'),name:archiveName,bytes:archive,
|
|
76
84
|
validate:file=>need((fs.lstatSync(file).mode&0o777)===0o600,'prd_correction_archive_permissions')});
|
|
@@ -111,14 +119,15 @@ export function replacePrdDocument({specs,relative,content,current}){
|
|
|
111
119
|
}finally{if(fd!==undefined)fs.closeSync(fd);try{fs.unlinkSync(temp);}catch(error){if(error.code!=='ENOENT')throw error;}}
|
|
112
120
|
}
|
|
113
121
|
|
|
114
|
-
function loadCorrection({specs,stage,feature}){
|
|
115
|
-
const review=inspectPrdFindings({specs,stage,feature});
|
|
122
|
+
function loadCorrection({specs,stage,feature,pendingSplit=null}){
|
|
123
|
+
const review=inspectPrdFindings({specs,stage,feature,pendingSplit});
|
|
116
124
|
need(review.verdict!=='blocked'&&['resume_disposition','completed'].includes(review.gate.outcome),'prd_correction_not_ready');
|
|
117
125
|
const archiveName=`prd-${feature.replace(/^\d+\./,'')}-${stage}-correction.md`;
|
|
118
126
|
const bytes=readCorrectionFile(specs,`.reviews/${archiveName}`);
|
|
119
127
|
const match=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes).match(/\n```json\n([^\n]+)\n```\n$/);
|
|
120
128
|
need(match,'prd_correction_archive_invalid');const value=json(JSON.parse(match[1]),256*1024);
|
|
121
|
-
shape(value,['version','packageDigest','stage','feature','before','proposal']);
|
|
129
|
+
shape(value,['version','packageDigest','stage','feature','before','proposal',...(Object.hasOwn(value,'narrowReview')?['narrowReview']:[])]);
|
|
130
|
+
need(!Object.hasOwn(value,'narrowReview')||(value.narrowReview===1&&stage==='design'),'prd_correction_archive_invalid');
|
|
122
131
|
need(value.version===1&&value.packageDigest===review.packageDigest&&value.stage===stage&&value.feature===feature
|
|
123
132
|
&&archiveBytes(value).equals(bytes)&&Array.isArray(value.before),'prd_correction_archive_invalid');
|
|
124
133
|
const originals=new Map(review.reviewedArtifacts.map(item=>[item.path,item.sha256])),seen=new Set();
|
|
@@ -140,7 +149,7 @@ function loadCorrection({specs,stage,feature}){
|
|
|
140
149
|
return {...item,sha256:currentHash};
|
|
141
150
|
});
|
|
142
151
|
return {specs,stage,feature,review,archiveName,archiveHash:sha(bytes),evidenceHash:sha(readCmInitSource(specs,review.evidence)),
|
|
143
|
-
before,proposal:value.proposal,after,plan,states};
|
|
152
|
+
before,proposal:value.proposal,after,plan,states,narrowEnabled:value.narrowReview===1};
|
|
144
153
|
}
|
|
145
154
|
|
|
146
155
|
export function inspectPrdCorrectionRecovery(input){
|
|
@@ -167,3 +176,147 @@ export function resumePrdCorrection(input,signal){
|
|
|
167
176
|
if(value.states.some(item=>item.status==='needs_correction'))need(value.review.gate.outcome==='resume_disposition','prd_correction_not_ready');
|
|
168
177
|
return writeCorrection({...value,current},signal);
|
|
169
178
|
}
|
|
179
|
+
|
|
180
|
+
// ---- Design-stage narrow review rounds (see narrow-review.mjs) ----
|
|
181
|
+
const designPath=feature=>`${feature}/design.md`;
|
|
182
|
+
// After the design receipt is written the design is frozen at the receipt's bytes; a later saved split correction
|
|
183
|
+
// legitimately changes the file. Callers past that point pass the receipt's design sha (and the saved split plan).
|
|
184
|
+
function narrowFound({specs,feature,pendingSplit=null,designSha256=null}){
|
|
185
|
+
need(typeof feature==='string'&&/^[1-9]\d*\.[a-z0-9]+(?:-[a-z0-9]+)*$/.test(feature),'prd_review_feature_invalid');
|
|
186
|
+
if(readCmInitSource(specs,`.reviews/prd-${feature.replace(/^\d+\./,'')}-design-correction.md`)===null)return null;
|
|
187
|
+
const value=loadCorrection({specs,stage:'design',feature,pendingSplit}),design=designPath(feature);
|
|
188
|
+
if(!value.narrowEnabled)return null; // run started before narrow rounds: unchanged legacy flow
|
|
189
|
+
const state=inspectPrdNarrowState({specs,feature,packageDigest:value.review.packageDigest,
|
|
190
|
+
base:{designSha256:value.after.find(item=>item.path===design).sha256,archiveSha256:value.archiveHash,
|
|
191
|
+
originalDesignSha256:value.review.reviewedArtifacts.find(item=>item.path===design).sha256,
|
|
192
|
+
requirementsSha256:value.review.reviewedArtifacts.find(item=>item.path===`${feature}/requirements.md`).sha256,
|
|
193
|
+
authorContextId:readPrdReviewAuthor({specs,stage:'design',feature})},
|
|
194
|
+
currentDesignSha256:designSha256??sha(readCorrectionFile(specs,design))});
|
|
195
|
+
return {value,state};
|
|
196
|
+
}
|
|
197
|
+
// True only when the original correction is fully saved (or a narrow round already exists),
|
|
198
|
+
// so an unfinished original write still goes through the original recovery.
|
|
199
|
+
export function prdNarrowCorrectionFlow({specs,stage,feature}){
|
|
200
|
+
if(stage!=='design')return false;
|
|
201
|
+
if(readCmInitSource(specs,`.reviews/${narrowNames(feature).review(1)}`)!==null)return true;
|
|
202
|
+
const value=loadCorrection({specs,stage,feature});
|
|
203
|
+
return value.narrowEnabled&&value.states.every(item=>item.status==='matches_correction');
|
|
204
|
+
}
|
|
205
|
+
export const prdNarrowChainStarted=({specs,feature})=>readCmInitSource(specs,`.reviews/${narrowNames(feature).review(1)}`)!==null;
|
|
206
|
+
// For drivers that pre-check a prd_correct answer: the review the answer must resolve, or null (use the original).
|
|
207
|
+
export function narrowCorrectionReview({specs,stage,feature}){
|
|
208
|
+
if(stage!=='design'||!prdNarrowChainStarted({specs,feature}))return null;
|
|
209
|
+
const found=narrowFound({specs,feature});
|
|
210
|
+
if(found===null||found.state.phase.status!=='awaiting_correction')return null;
|
|
211
|
+
return {stage,feature,findings:found.state.rounds.at(-1).review.findings,reviewedArtifacts:found.value.review.reviewedArtifacts.map(item=>
|
|
212
|
+
({path:item.path,sha256:sha(readCorrectionFile(specs,item.path))}))};
|
|
213
|
+
}
|
|
214
|
+
export function inspectPrdNarrowReview(input){
|
|
215
|
+
const found=narrowFound(input);
|
|
216
|
+
return found===null?json({status:'narrow_not_started',next:'correct_findings',completionAuthorized:false}):json(narrowPublicState(found.state));
|
|
217
|
+
}
|
|
218
|
+
export function recordPrdNarrowReviewHost({specs,feature,packageDigest,input,authorContextId,writeEnabled}){
|
|
219
|
+
assertPrdBatchActive(specs,[feature]);
|
|
220
|
+
const found=narrowFound({specs,feature});need(found,'prd_narrow_requires_original_correction');
|
|
221
|
+
need(found.value.review.gate.outcome==='resume_disposition','prd_narrow_closed');
|
|
222
|
+
need(packageDigest===found.value.review.packageDigest,'prd_narrow_package_changed');
|
|
223
|
+
recordPrdNarrowReview({specs,feature,packageDigest,state:found.state,input,authorContextId,
|
|
224
|
+
originalAuthorContextId:readPrdReviewAuthor({specs,stage:'design',feature}),writeEnabled});
|
|
225
|
+
const after=narrowFound({specs,feature}),row=after.state.rounds.at(-1);
|
|
226
|
+
const blocking=row.review.findings.filter(item=>item.severity!=='minor'||['security','dataLoss','silentFailure','violatesWrittenRule'].some(flag=>item[flag]));
|
|
227
|
+
return json({...narrowPublicState(after.state),status:'narrow_review_recorded',round:row.round,verdict:row.review.verdict,
|
|
228
|
+
reviewDigest:row.reviewDigest,degradedReview:row.review.reviewer==='self-degraded',backlog:row.review.findings.filter(item=>!blocking.includes(item)).map(item=>({id:item.id,message:item.message}))});
|
|
229
|
+
}
|
|
230
|
+
// Original disposition gate: once a narrow round exists the design must have been approved by it.
|
|
231
|
+
export function assertPrdNarrowDispositionReady({specs,feature,pendingSplit=null,designSha256=null}){
|
|
232
|
+
if(readCmInitSource(specs,`.reviews/${narrowNames(feature).review(1)}`)===null)return {used:false};
|
|
233
|
+
const found=narrowFound({specs,feature,pendingSplit,designSha256});need(found,'prd_narrow_requires_original_correction');
|
|
234
|
+
const status=found.state.phase.status;
|
|
235
|
+
need(status!=='awaiting_user_decision','prd_narrow_awaiting_user_decision');
|
|
236
|
+
need(status==='approved','prd_narrow_review_pending');
|
|
237
|
+
return {used:true,designPath:designPath(feature),originalDecisions:found.value.plan.decisions};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function narrowCorrection({specs,feature,correct,attempts,signal}){
|
|
241
|
+
const found=narrowFound({specs,feature}),{state,value}=found,phase=state.phase,names=narrowNames(feature);
|
|
242
|
+
// A saved correction whose result was lost before the session commit: answer again from the archive, never regenerate.
|
|
243
|
+
const lastRow=state.rounds.at(-1);
|
|
244
|
+
const resumed=phase.status==='awaiting_review'&&lastRow?.correction&&phase.round===lastRow.round+1;
|
|
245
|
+
need(phase.status!=='awaiting_review'||resumed,'prd_narrow_review_required');
|
|
246
|
+
need(phase.status!=='approved','prd_narrow_already_approved');
|
|
247
|
+
need(phase.status!=='awaiting_user_decision','prd_narrow_awaiting_user_decision');
|
|
248
|
+
const round=resumed?lastRow.round:phase.round,archive=`.reviews/${names.correction(round)}`;
|
|
249
|
+
const designRelative=designPath(feature),packageDigest=value.review.packageDigest;
|
|
250
|
+
const current=()=>{
|
|
251
|
+
need(!signal.aborted,'cancelled');const latest=narrowFound({specs,feature});
|
|
252
|
+
need(latest.value.review.packageDigest===packageDigest&&latest.value.review.gate.outcome==='resume_disposition'
|
|
253
|
+
&&['awaiting_correction','correction_incomplete'].includes(latest.state.phase.status)&&latest.state.phase.round===round,
|
|
254
|
+
'prd_narrow_state_changed');
|
|
255
|
+
};
|
|
256
|
+
const finish=row=>{
|
|
257
|
+
const doc=row.correction.proposal.documents.find(item=>item.path===designRelative);
|
|
258
|
+
const written=[];
|
|
259
|
+
try{
|
|
260
|
+
if(row.correction.beforeSha256!==row.correction.afterSha256&&sha(readCorrectionFile(specs,designRelative))===row.correction.beforeSha256){
|
|
261
|
+
current();replacePrdDocument({specs,relative:designRelative,content:doc.content,current});written.push(designRelative);
|
|
262
|
+
}
|
|
263
|
+
const after=narrowFound({specs,feature});
|
|
264
|
+
need(after.state.phase.status==='awaiting_review'&&after.state.phase.round===round+1,'prd_narrow_state_changed');
|
|
265
|
+
return json({...narrowPublicState(after.state),status:'correction_saved',narrow:true,round,packageDigest,
|
|
266
|
+
decisions:row.correction.proposal.decisions,
|
|
267
|
+
artifacts:row.correction.before.map(item=>({path:item.path,sha256:item.path===designRelative?row.correction.afterSha256:item.sha256})),
|
|
268
|
+
archive});
|
|
269
|
+
}catch{return json({status:'correction_save_unknown',archive,round,observedWritten:written,
|
|
270
|
+
next:'rerun_correct_findings_to_resume_from_archive_without_regeneration',completionAuthorized:false});}
|
|
271
|
+
};
|
|
272
|
+
if(phase.status==='correction_incomplete'||resumed)return finish(state.rounds[round-1]);
|
|
273
|
+
const narrow=state.rounds[round-1];
|
|
274
|
+
const read=file=>readCorrectionFile(specs,file);
|
|
275
|
+
const before=value.review.reviewedArtifacts.map(item=>{
|
|
276
|
+
const bytes=read(item.path);
|
|
277
|
+
return {path:item.path,sha256:sha(bytes),content:new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes)};
|
|
278
|
+
});
|
|
279
|
+
// Requirements are frozen after the original review; a user edit must be undone before a narrow archive is written,
|
|
280
|
+
// otherwise the saved archive could never be read back (nothing is written or asked until then).
|
|
281
|
+
for(const item of value.review.reviewedArtifacts)
|
|
282
|
+
if(item.path!==designRelative)need(before.find(row=>row.path===item.path)?.sha256===item.sha256,'prd_correction_inputs_changed');
|
|
283
|
+
const key=digest({specs,packageDigest,round});need(!attempts.has(key),'prd_correction_already_attempted');attempts.add(key);
|
|
284
|
+
const pseudo={stage:'design',feature,findings:narrow.review.findings,
|
|
285
|
+
reviewedArtifacts:before.map(({path:file,sha256})=>({path:file,sha256}))};
|
|
286
|
+
const proposal=json(await correct(json({review:{stage:'design',feature,packageDigest,narrowRound:round,
|
|
287
|
+
maxNarrowRounds:PRD_NARROW_MAX_ROUNDS,verdict:narrow.review.verdict,findings:narrow.review.findings,
|
|
288
|
+
summary:narrow.review.summary,narrowReviewDigest:narrow.reviewDigest},documents:before,
|
|
289
|
+
instructions:'Resolve only the findings of this recorded narrow design review round. Return {decisions:[{id,status:applied|escalated,evidence:[reason],changedPaths:[path]}],documents:[{path,content}]} covering every finding id and the complete unchanged path inventory. Only design.md may change. Escalate disagreement or unprovable changes; do not invent human approval. Do not write files, change task status, call another reviewer/provider or retry. The corrected design needs another recorded narrow review (at most two rounds in total).'}),signal),256*1024);
|
|
290
|
+
need(!signal.aborted,'cancelled');
|
|
291
|
+
const {after,plan}=inspectProposal(specs,pseudo,proposal);
|
|
292
|
+
current();for(const item of before)need(sha(read(item.path))===item.sha256,'prd_correction_inputs_changed');
|
|
293
|
+
const afterDesign=after.find(item=>item.path===designRelative).sha256;
|
|
294
|
+
const record={version:1,kind:'prd_design_narrow_correction',feature,packageDigest,round,narrowReviewDigest:narrow.reviewDigest,
|
|
295
|
+
beforeSha256:state.tipDesignSha256,afterSha256:afterDesign,before,proposal:{decisions:plan.decisions,documents:proposal.documents}};
|
|
296
|
+
// Archive the answered review's per-finding decisions and original bytes before any spec write.
|
|
297
|
+
writeReviewEvidence({reviewsDir:path.join(specs,'.reviews'),name:names.correction(round),bytes:narrowCorrectionBytes(json(record,256*1024)),
|
|
298
|
+
exclusive:true,validate:file=>need((fs.lstatSync(file).mode&0o777)===0o600,'prd_correction_archive_permissions')});
|
|
299
|
+
return finish({correction:record});
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// Receipt writers outside the host (cm-prd-review-gate record) get the same full chain validation as the host:
|
|
303
|
+
// any narrow review/correction file present means the chain must be valid, approved, and keep the original
|
|
304
|
+
// decision counts. Fails closed with fixed prd_narrow_* codes (never raw system errors or paths).
|
|
305
|
+
export function assertNarrowReceiptAllowed({specs,slug,findingCount,unresolvedCount}){
|
|
306
|
+
const invalid=()=>Object.assign(new Error('prd_narrow_record_invalid'),{code:'prd_narrow_record_invalid'});
|
|
307
|
+
if(typeof slug!=='string'||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug))return; // not a PRD feature slug: nothing narrow to check
|
|
308
|
+
const names=narrowNames(`1.${slug}`);
|
|
309
|
+
const present=[names.review(1),names.review(2),names.correction(1)].some(name=>{
|
|
310
|
+
try{fs.lstatSync(path.join(specs,'.reviews',name));return true;}catch(error){if(error.code==='ENOENT')return false;return true;}
|
|
311
|
+
});
|
|
312
|
+
if(!present)return;
|
|
313
|
+
try{
|
|
314
|
+
const dirs=fs.readdirSync(specs).filter(name=>new RegExp(`^[1-9]\\d*\\.${slug}$`).test(name));
|
|
315
|
+
need(dirs.length===1,'prd_narrow_record_invalid');
|
|
316
|
+
const found=narrowFound({specs,feature:dirs[0]});need(found,'prd_narrow_requires_original_correction');
|
|
317
|
+
need(found.state.phase.status==='approved','prd_narrow_review_pending');
|
|
318
|
+
const decisions=found.value.plan.decisions;
|
|
319
|
+
need(findingCount===decisions.length&&unresolvedCount===decisions.filter(item=>item.status==='escalated').length,
|
|
320
|
+
'prd_narrow_disposition_decisions_changed');
|
|
321
|
+
}catch(error){throw typeof error?.code==='string'&&error.code.startsWith('prd_narrow_')?error:invalid();}
|
|
322
|
+
}
|
|
@@ -11,6 +11,7 @@ import {inspectPrdDispositionPlan} from './disposition-plan.mjs';
|
|
|
11
11
|
import {checkPrdDraftMechanics,inspectPrdContextCheck} from './self-check.mjs';
|
|
12
12
|
import {prdTaskScopeOptions} from './task-scope-record.mjs';
|
|
13
13
|
import {correctionCheckStore} from './correction-check.mjs';
|
|
14
|
+
import {assertPrdNarrowDispositionReady} from './review-correction.mjs';
|
|
14
15
|
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
15
16
|
|
|
16
17
|
export function recordPrdHostDisposition(input){return disposition(input);}
|
|
@@ -21,7 +22,11 @@ function disposition({specs,stage,feature,packageDigest,decisions,artifacts,writ
|
|
|
21
22
|
const review=inspectPrdFindings({specs,stage,feature});
|
|
22
23
|
need(review.packageDigest===packageDigest,'prd_disposition_package_changed');
|
|
23
24
|
need(review.verdict!=='blocked','prd_disposition_review_blocked');
|
|
24
|
-
|
|
25
|
+
// Design only: a recorded narrow review chain must have approved the exact saved design first.
|
|
26
|
+
const narrow=stage==='design'?assertPrdNarrowDispositionReady({specs,feature}):{used:false};
|
|
27
|
+
const plan=inspectPrdDispositionPlan(review,decisions,artifacts,{alsoChanged:narrow.used?[narrow.designPath]:[]});
|
|
28
|
+
// Narrow rounds never reopen the original per-finding decisions: they must equal the archived ones.
|
|
29
|
+
if(narrow.used)need(digest(plan.decisions)===digest(narrow.originalDecisions),'prd_narrow_disposition_decisions_changed');
|
|
25
30
|
({decisions,artifacts}=plan);const {changed,unresolved}=plan;
|
|
26
31
|
for(const item of artifacts){
|
|
27
32
|
const bytes=readCmInitSource(specs,item.path);
|
|
@@ -60,6 +65,8 @@ function disposition({specs,stage,feature,packageDigest,decisions,artifacts,writ
|
|
|
60
65
|
const gate=inspectPrdReview(args);
|
|
61
66
|
need(gate.outcome==='completed'&&gate.disposition===disposition&&gate.package_sha256===packageDigest,
|
|
62
67
|
'prd_disposition_write_unknown');
|
|
68
|
+
// The receipt writer reads the files again: bytes that changed since the check above are not what was reviewed.
|
|
69
|
+
for(const item of selected){const bytes=readCmInitSource(specs,item.path);need(bytes!==null&&sha(bytes)===item.sha256,'prd_disposition_write_unknown');}
|
|
63
70
|
return json({status:'disposition_recorded',outcome:recorded.outcome,gate,decisions,artifacts,
|
|
64
71
|
unresolvedFindings:review.findings.filter(item=>decisions.some(decision=>decision.id===item.id&&(failedCheck||decision.status==='escalated'))),
|
|
65
72
|
next:failedCheck?'prepare_human_summary_with_failed_checks':unresolved?'include_unresolved_in_human_summary':stage==='design'?'continue_task_generation':'prepare_human_summary',
|
|
@@ -35,3 +35,11 @@ export function inspectPrdFindings({specs,stage,feature,pendingSplit=null,approv
|
|
|
35
35
|
result.findings.length?'resolve_original_findings':'record_no_findings_after_artifacts_saved',
|
|
36
36
|
dispatchAuthorized:false,writeAuthorized:false,completionAuthorized:false});
|
|
37
37
|
}
|
|
38
|
+
|
|
39
|
+
// Declared author of the original r1 attempt; separate so review results keep their exact shape.
|
|
40
|
+
export function readPrdReviewAuthor({specs,stage,feature}){
|
|
41
|
+
const match=feature.match(/^[1-9]\d*\.([a-z0-9]+(?:-[a-z0-9]+)*)$/);need(match,'prd_review_feature_invalid');
|
|
42
|
+
const bytes=readCmInitSource(specs,`.reviews/prd-${match[1]}-${stage}-r1.md`);need(bytes!==null,'prd_review_archive_unavailable');
|
|
43
|
+
const line=new TextDecoder('utf-8',{fatal:true}).decode(bytes).match(/\n```json\n([^\n]+)\n```\n$/);need(line,'prd_review_archive_unavailable');
|
|
44
|
+
return JSON.parse(line[1]).authorContextId;
|
|
45
|
+
}
|
package/runtime/js/notify.mjs
CHANGED
|
@@ -901,6 +901,7 @@ const CLASSIFY={
|
|
|
901
901
|
if(stage==='change_check_failed'&&Number(r.round)>=2)return 'stuck';
|
|
902
902
|
if(/^change_(requirements|design|tasks|check)$/.test(stage??'')&&text(r.question))return 'ask';
|
|
903
903
|
if(status&&(/_unknown$/.test(status)||['correction_recovery_required','correction_recovery_conflict','disposition_details_need_verification'].includes(status)))return 'stuck';
|
|
904
|
+
if(status==='narrow_review_recorded'&&r.userDecisionRequired===true)return 'stuck';
|
|
904
905
|
if(status==='human_summary_prepared'&&r.readyForAwaitingReview===false)return 'stuck';
|
|
905
906
|
if(status==='review_findings_ready'&&r.verdict==='blocked')return 'stuck';
|
|
906
907
|
if(['review_unknown','review_cancelled'].includes(review.status)||review.verdict==='blocked'
|
|
@@ -175,6 +175,7 @@
|
|
|
175
175
|
"cm-prd-host.test.mjs": 26,
|
|
176
176
|
"cm-prd-inputs-replaced.test.mjs": 5,
|
|
177
177
|
"cm-prd-materials.test.mjs": 1,
|
|
178
|
+
"cm-prd-narrow-review.test.mjs": 1,
|
|
178
179
|
"cm-prd-review-claim.test.mjs": 1,
|
|
179
180
|
"cm-prd-review-disposition.test.mjs": 5,
|
|
180
181
|
"cm-prd-review-gate.test.mjs": 1,
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 校验本包技能 *.md 里指向 docs 的相对引用(Markdown 链接和反引号路径)在当前安装布局下可达。
|
|
3
|
+
// 插件/源码布局 docs 在根目录;Claude 兼容布局在 cm-workflow/docs(安装时已改写)。
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import { dirname, relative, resolve } from 'node:path';
|
|
6
|
+
import { pathToFileURL } from 'node:url';
|
|
7
|
+
import { listDocRefs, makeBoundedReader, managedSkillMarkdown, mapOutsideFences } from './cm-doc-links-shared.mjs';
|
|
8
|
+
|
|
9
|
+
export function findBrokenDocLinks(root) {
|
|
10
|
+
const broken = [];
|
|
11
|
+
const read = makeBoundedReader();
|
|
12
|
+
for (const file of managedSkillMarkdown(root)) {
|
|
13
|
+
mapOutsideFences(read(file), (part) => {
|
|
14
|
+
for (const m of listDocRefs(part)) {
|
|
15
|
+
const target = m.up + (m.done || '') + m.rest;
|
|
16
|
+
if (!existsSync(resolve(dirname(file), target))) broken.push(`${relative(root, file)} -> ${target}`);
|
|
17
|
+
}
|
|
18
|
+
return part;
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
return broken;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
25
|
+
let broken;
|
|
26
|
+
try { broken = findBrokenDocLinks(resolve(process.argv[2] || '.')); } catch (e) { console.error(`broken docs link: ${e.message}`); process.exit(1); }
|
|
27
|
+
for (const b of broken) console.error(`broken docs link: ${b}`);
|
|
28
|
+
process.exit(broken.length ? 1 : 0);
|
|
29
|
+
}
|
|
@@ -49,6 +49,52 @@ test('actual JSONL CLI runs fixture checker once then eight groups; optional deg
|
|
|
49
49
|
assert.equal(result.mechanical.output,'original checker output\noriginal stderr\n');assert.equal(result.result.completionAuthorized,false);
|
|
50
50
|
assert.deepEqual(fs.readdirSync(f.input.project),[]);
|
|
51
51
|
});
|
|
52
|
+
test('snapshot 遇到超过 1MB 的非 CM 技能文本只记大小,不阻断检查',{timeout:5000},async t=>{
|
|
53
|
+
const f=fixture(t);const big=path.join(f.dir,'skills/other-skill/assets/vendor/babel.min.js');
|
|
54
|
+
fs.mkdirSync(path.dirname(big),{recursive:true});fs.writeFileSync(big,Buffer.alloc(1048576+1024,97));
|
|
55
|
+
const host=createCmCheckHost(f.input,{call:async(kind,payload)=>kind==='check_runtime'?mechanical(payload):assessment(payload)});
|
|
56
|
+
const value=await host.handle({requestId:'start',operation:'start'});
|
|
57
|
+
assert.equal(value.result.overall,'PASSED',JSON.stringify(value));
|
|
58
|
+
});
|
|
59
|
+
test('超过 1MB 的 CM 文本在检查期间被等长改一个字节仍判为源码漂移;读失败的阻断带文件路径',{timeout:8000},async t=>{
|
|
60
|
+
const f=fixture(t);const big=path.join(f.dir,'skills/cm-check/big.md');fs.writeFileSync(big,Buffer.alloc(1048576+1024,97));
|
|
61
|
+
const host=createCmCheckHost(f.input,{call:async(kind,payload)=>{
|
|
62
|
+
if(kind==='check_runtime')return mechanical(payload);
|
|
63
|
+
const bytes=fs.readFileSync(big);bytes[10]=98;fs.writeFileSync(big,bytes);return assessment(payload);}});
|
|
64
|
+
const drift=await host.handle({requestId:'start',operation:'start'});
|
|
65
|
+
assert.equal(drift.result.overall,'BLOCKED',JSON.stringify(drift));
|
|
66
|
+
const g=fixture(t);const locked=path.join(g.dir,'skills/cm-check/locked.md');fs.writeFileSync(locked,'x');fs.chmodSync(locked,0o000);
|
|
67
|
+
t.after(()=>{try{fs.chmodSync(locked,0o644);}catch{}});
|
|
68
|
+
if(process.getuid?.()!==0){
|
|
69
|
+
const blocked=await createCmCheckHost(g.input,{call:async()=>{throw Error('must not run');}}).handle({requestId:'start',operation:'start'});
|
|
70
|
+
assert.equal(blocked.result.overall,'BLOCKED');assert.equal(blocked.result.file,'skills/cm-check/locked.md');
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
test('大文件的读取计入 64MiB 预算;超 16MB 的文本等长改写(ctime 变)也判漂移;漂移与目录读失败的阻断带路径;大文件可作证据',{timeout:30000},async t=>{
|
|
74
|
+
const run=async(f,mutate)=>createCmCheckHost(f.input,{call:async(kind,payload)=>{if(kind==='check_runtime')return mechanical(payload);mutate?.(payload);return assessment(payload);}}).handle({requestId:'start',operation:'start'});
|
|
75
|
+
const f=fixture(t);for(let i=0;i<5;i++)fs.writeFileSync(path.join(f.dir,`skills/cm-check/b${i}.md`),Buffer.alloc(14*1024*1024,97));
|
|
76
|
+
assert.equal((await run(f)).result.reason,'check_inventory_limit');
|
|
77
|
+
const g=fixture(t);const huge=path.join(g.dir,'skills/cm-check/huge.md');fs.writeFileSync(huge,Buffer.alloc(17*1024*1024,97));
|
|
78
|
+
const d=await run(g,()=>{const b=fs.readFileSync(huge);b[5]=98;fs.writeFileSync(huge,b);});
|
|
79
|
+
assert.equal(d.result.reason,'check_source_changed');assert.equal(d.result.file,'skills/cm-check/huge.md');
|
|
80
|
+
const h=fixture(t);const mid=path.join(h.dir,'skills/cm-check/mid.md');fs.writeFileSync(mid,Buffer.alloc(1048576+10,97));
|
|
81
|
+
const ok=createCmCheckHost(h.input,{call:async(kind,payload)=>{if(kind==='check_runtime')return mechanical(payload);const v=assessment(payload);v.checks[0].evidence=[{path:'skills/cm-check/mid.md',line:1}];return v;}});
|
|
82
|
+
assert.equal((await ok.handle({requestId:'start',operation:'start'})).result.overall,'PASSED');
|
|
83
|
+
if(process.getuid?.()!==0){
|
|
84
|
+
const k=fixture(t);const dir=path.join(k.dir,'skills/cm-check/locked');fs.mkdirSync(dir);fs.chmodSync(dir,0o000);
|
|
85
|
+
try{assert.equal((await run(k)).result.file,'skills/cm-check/locked');}finally{fs.chmodSync(dir,0o755);}
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
test('docs 目录进入快照:检查期间删掉被技能链接指向的文档会被判漂移',{timeout:8000},async t=>{
|
|
89
|
+
const f=fixture(t);fs.mkdirSync(path.join(f.dir,'docs'));const doc=path.join(f.dir,'docs/user-guide.md');fs.writeFileSync(doc,'x');
|
|
90
|
+
const r=await createCmCheckHost(f.input,{call:async(kind,payload)=>{if(kind==='check_runtime')return mechanical(payload);fs.unlinkSync(doc);return assessment(payload);}}).handle({requestId:'start',operation:'start'});
|
|
91
|
+
assert.equal(r.result.reason,'check_source_changed');
|
|
92
|
+
});
|
|
93
|
+
test('范围清单进入快照:检查期间改它(改变受管范围)会被判漂移',{timeout:8000},async t=>{
|
|
94
|
+
const f=fixture(t);fs.mkdirSync(path.join(f.dir,'cm-workflow'));const scope=path.join(f.dir,'cm-workflow/doc-links-scope.txt');fs.writeFileSync(scope,'# cm-workflow doc-links scope v1 count=0\n');
|
|
95
|
+
const r=await createCmCheckHost(f.input,{call:async(kind,payload)=>{if(kind==='check_runtime')return mechanical(payload);fs.writeFileSync(scope,'# cm-workflow doc-links scope v1 count=1\nskills/x/SKILL.md\n');return assessment(payload);}}).handle({requestId:'start',operation:'start'});
|
|
96
|
+
assert.equal(r.result.reason,'check_source_changed');
|
|
97
|
+
});
|
|
52
98
|
test('mechanical failure stops semantics, repeated start never retries',async t=>{
|
|
53
99
|
const f=fixture(t,7);let calls=0;const host=createCmCheckHost(f.input,{call:async(kind,payload)=>{calls++;assert.equal(kind,'check_runtime');return mechanical(payload);}});
|
|
54
100
|
const value=await host.handle({requestId:'start',operation:'start'});assert.equal(value.result.overall,'FAILED');assert.equal(value.result.semanticChecked,false);
|
|
@@ -360,6 +360,12 @@ for correction_command in prepare-human-correction publish-human-correction-revi
|
|
|
360
360
|
grep -Fq "$correction_command" "$ROOT/$HUMAN_CORRECTION_DOC" ||
|
|
361
361
|
fail "human correction command/document pair incomplete: $correction_command"
|
|
362
362
|
done
|
|
363
|
+
# Skill docs links must resolve in this layout (0.21.5: claude-compat links pointed at a missing ~/.claude/docs).
|
|
364
|
+
if [ -n "$NODE_BIN" ] && [ -f "$ROOT/scripts/cm-check-doc-links.mjs" ]; then
|
|
365
|
+
"$NODE_BIN" "$ROOT/scripts/cm-check-doc-links.mjs" "$ROOT" || fail "skills docs links do not resolve in $MODE layout (see broken docs link lines above)"
|
|
366
|
+
else
|
|
367
|
+
fail "missing scripts/cm-check-doc-links.mjs or node for docs link check"
|
|
368
|
+
fi
|
|
363
369
|
require_file "scripts/cm-workflow-config.mjs"
|
|
364
370
|
require_file "scripts/cm-workflow-config.test.mjs"
|
|
365
371
|
# Group 4: user runtimes.yml producers <-> authoritative consumer.
|
|
@@ -708,6 +714,15 @@ for name in cm-challenge cm-idea cm-init cm-prd cm-ai cm-test cm-security cm-fix
|
|
|
708
714
|
fi
|
|
709
715
|
done
|
|
710
716
|
|
|
717
|
+
# cm-check 第 2 组口径:除独立配置工具 cm-notify 外,核心 Skill 必须用链接或反引号路径引用真实存在的 runtime/ 合同。
|
|
718
|
+
for name in cm-idea cm-init cm-prd cm-ai cm-test cm-security cm-fix cm-refactor cm-check cm-runtime; do
|
|
719
|
+
runtime_ref_ok=0
|
|
720
|
+
for ref in $(grep -oE '(\]\(\.\./\.\./runtime/[A-Za-z0-9._/-]+\.(md|json|mjs)[)#]|`\.\./\.\./runtime/[A-Za-z0-9._/-]+\.(md|json|mjs)[`#])' "$ROOT/skills/$name/SKILL.md" | sed -E 's/^(\]\(|`)//; s/.$//'); do
|
|
721
|
+
[ -f "$ROOT/skills/$name/$ref" ] && runtime_ref_ok=1
|
|
722
|
+
done
|
|
723
|
+
[ "$runtime_ref_ok" -eq 1 ] || fail "core skill has no resolvable runtime/ contract reference: skills/$name/SKILL.md"
|
|
724
|
+
done
|
|
725
|
+
|
|
711
726
|
for reference in \
|
|
712
727
|
skills/cm-idea/references/idea-to-prd.md \
|
|
713
728
|
skills/cm-idea/references/example-prd.md \
|
|
@@ -12,12 +12,24 @@ test('real isolated Claude install checks correction docs at its installed layou
|
|
|
12
12
|
t.after(()=>fs.rmSync(home,{recursive:true,force:true}));
|
|
13
13
|
const target=path.join(home,'.claude'),env={...process.env,HOME:home,CLAUDE_HOME:target,
|
|
14
14
|
CM_WORKFLOW_HOME:path.join(home,'user'),CM_WORKFLOW_LOG_HOME:path.join(home,'logs'),CM_MATT_SKILLS_INSTALL:'off'};
|
|
15
|
+
// 用户自装、带断链的技能(首次安装时目标里已存在)不得让安装的自检失败或回滚。
|
|
16
|
+
fs.mkdirSync(path.join(target,'skills/cm-user-own'),{recursive:true});
|
|
17
|
+
fs.writeFileSync(path.join(target,'skills/cm-user-own/SKILL.md'),'---\nname: cm-user-own\ndescription: 用户自装技能\n---\n[x](../../docs/none.md)\n');
|
|
15
18
|
const installed=spawnSync('/bin/bash',[path.join(source,'install.sh'),'--yes'],{cwd:source,env,encoding:'utf8',timeout:120000,maxBuffer:4*1024*1024});
|
|
16
19
|
assert.equal(installed.status,0,installed.stdout+installed.stderr);
|
|
17
20
|
assert.match(installed.stdout,/cm runtime check: PASSED \(claude-compat v/);
|
|
18
21
|
const doc=path.join(target,'cm-workflow/docs/human-correction.md');
|
|
19
22
|
assert.equal(fs.readFileSync(doc,'utf8'),fs.readFileSync(path.join(source,'docs/human-correction.md'),'utf8'));
|
|
20
23
|
assert.equal(fs.existsSync(path.join(target,'docs/human-correction.md')),false);
|
|
24
|
+
const notify=fs.readFileSync(path.join(target,'skills/cm-notify/SKILL.md'),'utf8');
|
|
25
|
+
assert.match(notify,/\.\.\/\.\.\/cm-workflow\/docs\/user-guide\.md/);
|
|
26
|
+
assert.equal(fs.readFileSync(path.join(source,'skills/cm-notify/SKILL.md'),'utf8').includes('../../cm-workflow/docs/'),false);
|
|
27
|
+
const scope=fs.readFileSync(path.join(target,'cm-workflow/doc-links-scope.txt'),'utf8');
|
|
28
|
+
assert.match(scope,/skills\/cm-notify\/SKILL\.md/);
|
|
29
|
+
assert.equal(scope.includes('cm-user-own'),false);
|
|
30
|
+
assert.equal(fs.readFileSync(path.join(target,'skills/cm-user-own/SKILL.md'),'utf8'),'---\nname: cm-user-own\ndescription: 用户自装技能\n---\n[x](../../docs/none.md)\n');
|
|
31
|
+
const links=spawnSync(process.execPath,[path.join(target,'scripts/cm-check-doc-links.mjs'),target],{encoding:'utf8'});
|
|
32
|
+
assert.equal(links.status,0,links.stderr);
|
|
21
33
|
fs.unlinkSync(doc);
|
|
22
34
|
const rejected=spawnSync('/bin/bash',[path.join(target,'scripts/cm-check-runtime.sh'),'--project',source],{cwd:source,env,encoding:'utf8',timeout:120000,maxBuffer:4*1024*1024});
|
|
23
35
|
assert.notEqual(rejected.status,0);
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// 改写与检查共用同一套“哪些是指向本包 docs 的相对引用”的识别规则,避免两边漂移。
|
|
2
|
+
import { closeSync, existsSync, lstatSync, openSync, readSync, readdirSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
// 范围清单:安装器在暂存目录生成、随包装入 <根>/cm-workflow/,列出本包自带的 skills/**/*.md。
|
|
6
|
+
// 检查只看清单里的文件,所以用户自装的技能(含同样以 cm- 开头的)不会被误判;
|
|
7
|
+
// 两个安装器(含不生成安装清单的 PowerShell)用同一份,不依赖安装清单的发布时机。
|
|
8
|
+
export const SCOPE_FILE = 'cm-workflow/doc-links-scope.txt';
|
|
9
|
+
const SCOPE_HEADER = '# cm-workflow doc-links scope v1';
|
|
10
|
+
// 单个技能文档读取上限;超过按错误处理,不整份读进内存(与快照的预算同口径)。
|
|
11
|
+
export const MAX_DOC_BYTES = 1024 * 1024;
|
|
12
|
+
export const MAX_TOTAL_BYTES = 64 * 1024 * 1024;
|
|
13
|
+
|
|
14
|
+
// 只认两种写法:Markdown 链接目标 ](…) 和整段反引号路径 `…`,且路径后必须紧跟收尾符:
|
|
15
|
+
// 链接:) 或 # 或 空白+标题;反引号:` 或 #。
|
|
16
|
+
// 外链(https://x/?next=../../docs/y)、普通文字、带命令行后缀的反引号(`../docs/g.md --dry-run`)都不算。
|
|
17
|
+
// 兼容安装已改写形态 ../cm-workflow/docs/ 也要认,检查才能发现它指向的文档被删。
|
|
18
|
+
const PATH = String.raw`((?:\.\.\/)+)(cm-workflow\/)?(docs\/[^\s)\`'"#>\]]*)`;
|
|
19
|
+
const DOC_REF = new RegExp(
|
|
20
|
+
String.raw`(?<=\]\()` + PATH + String.raw`(?=[)#]|\s+["'(])|(?<=\`)` + PATH + String.raw`(?=[\`#])`,
|
|
21
|
+
'g',
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
// 统一成 (上级前缀, 已含 cm-workflow/ 否, docs 路径) 回调;返回值替换原匹配。
|
|
25
|
+
export function replaceDocRefs(text, fn) {
|
|
26
|
+
return text.replace(DOC_REF, (...a) => fn(a[1] ?? a[4], a[2] ?? a[5], a[3] ?? a[6], a[0]));
|
|
27
|
+
}
|
|
28
|
+
export function listDocRefs(text) {
|
|
29
|
+
const out = [];
|
|
30
|
+
replaceDocRefs(text, (up, done, rest, whole) => { out.push({ up, done, rest }); return whole; });
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// 围栏代码块(``` 或 ~~~,可缩进 0–3 格、可在引用块 > 内,结束围栏可更长,未闭合则到文末)里的示例不改、不查。
|
|
35
|
+
// 逐行判断:引用块层数(> 的个数)比开围栏时少,说明引用块已结束,围栏随之结束,该行按正文处理;
|
|
36
|
+
// 结束围栏必须与开围栏同字符、不短于它、层数相同、后面只有空白。
|
|
37
|
+
// 缩进总共至多 3 格:无引用块时只认开头的缩进;有引用块时 > 之后允许再缩进至多 3 格。
|
|
38
|
+
const LINE_PREFIX = /^(?:[ ]{0,3}((?:>[ \t]?)+)[ ]{0,3}|[ ]{0,3})/; // 缩进只数空格:Tab 占 4 列,已超上限
|
|
39
|
+
export function mapOutsideFences(text, fn) {
|
|
40
|
+
let out = '';
|
|
41
|
+
let plain = '';
|
|
42
|
+
let fence = null; // {ch, len, depth}
|
|
43
|
+
for (const line of text.split(/(?<=\n)/)) {
|
|
44
|
+
const pm = line.match(LINE_PREFIX);
|
|
45
|
+
const depth = ((pm[1] || '').match(/>/g) || []).length;
|
|
46
|
+
const rest = line.slice(pm[0].length);
|
|
47
|
+
if (fence && depth < fence.depth) fence = null;
|
|
48
|
+
if (fence) {
|
|
49
|
+
const close = rest.match(/^(`{3,}|~{3,})[ \t]*\r?\n?$/);
|
|
50
|
+
if (depth === fence.depth && close && close[1][0] === fence.ch && close[1].length >= fence.len) fence = null;
|
|
51
|
+
out += line;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const open = rest.match(/^(`{3,}|~{3,})/);
|
|
55
|
+
if (open) {
|
|
56
|
+
out += fn(plain) + line;
|
|
57
|
+
plain = '';
|
|
58
|
+
fence = { ch: open[1][0], len: open[1].length, depth };
|
|
59
|
+
} else plain += line;
|
|
60
|
+
}
|
|
61
|
+
return out + fn(plain);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function walk(dir, out) {
|
|
65
|
+
for (const name of readdirSync(dir).sort()) {
|
|
66
|
+
const p = join(dir, name);
|
|
67
|
+
const st = lstatSync(p);
|
|
68
|
+
if (st.isSymbolicLink()) continue;
|
|
69
|
+
if (st.isDirectory()) walk(p, out);
|
|
70
|
+
else if (name.endsWith('.md')) out.push(p);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// 暂存目录里 skills/ 全是本包的:改写与生成范围清单用它。
|
|
75
|
+
export function stagedSkillMarkdown(stageRoot) {
|
|
76
|
+
const out = [];
|
|
77
|
+
walk(join(stageRoot, 'skills'), out);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function scopeText(stageRoot) {
|
|
82
|
+
const rel = stagedSkillMarkdown(stageRoot).map((p) => p.slice(stageRoot.length + 1).split('\\').join('/'));
|
|
83
|
+
return `${SCOPE_HEADER} count=${rel.length}\n${rel.join('\n')}\n`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 本包管理的技能文档。
|
|
87
|
+
// - 有范围清单:只取清单里的文件;头部数量与实际行数不符(被截断)、清单为空、清单里的文件缺失,都抛错,不静默跳过。
|
|
88
|
+
// - 无清单且根下有 cm-workflow/docs(兼容安装布局;源码与插件根没有 cm-workflow/,与用户自己的 docs/ 无关):抛错,因为无法区分本包与用户自装技能。
|
|
89
|
+
// - 其余(源码、插件、安装暂存目录):skills/ 全是本包的。
|
|
90
|
+
export function managedSkillMarkdown(root) {
|
|
91
|
+
const scope = join(root, SCOPE_FILE);
|
|
92
|
+
if (existsSync(scope)) {
|
|
93
|
+
const lines = readBounded(scope, MAX_DOC_BYTES).split('\n').filter((l) => l !== '');
|
|
94
|
+
const head = lines[0] && lines[0].match(/^# cm-workflow doc-links scope v1 count=(\d+)$/);
|
|
95
|
+
const files = lines.slice(1);
|
|
96
|
+
if (!head || Number(head[1]) !== files.length || files.length === 0) {
|
|
97
|
+
throw new Error(`范围清单损坏或被截断: ${SCOPE_FILE}`);
|
|
98
|
+
}
|
|
99
|
+
return files.map((rel) => {
|
|
100
|
+
if (!/^skills\/.+\.md$/.test(rel) || rel.includes('\\') || rel.split('/').some((seg) => seg === '' || seg === '.' || seg === '..')) throw new Error(`范围清单含非法路径: ${rel}`);
|
|
101
|
+
const p = join(root, rel);
|
|
102
|
+
if (!existsSync(p)) throw new Error(`范围清单里的文件不存在: ${rel}`);
|
|
103
|
+
return p;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
if (existsSync(join(root, 'cm-workflow', 'docs'))) {
|
|
107
|
+
throw new Error(`兼容安装缺少范围清单 ${SCOPE_FILE},无法区分本包技能与自装技能;请重新安装`);
|
|
108
|
+
}
|
|
109
|
+
const out = [];
|
|
110
|
+
walk(join(root, 'skills'), out);
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 限量读取:最多读 limit+1 字节,超过 limit 即抛错;不依赖先 stat 再读(文件可能在两步之间变大)。
|
|
115
|
+
function readBuffer(file, limit) {
|
|
116
|
+
const fd = openSync(file, 'r');
|
|
117
|
+
try {
|
|
118
|
+
const buf = Buffer.alloc(limit + 1);
|
|
119
|
+
let n = 0;
|
|
120
|
+
for (;;) {
|
|
121
|
+
const got = readSync(fd, buf, n, buf.length - n, null);
|
|
122
|
+
if (got === 0) break;
|
|
123
|
+
n += got;
|
|
124
|
+
if (n > limit) throw new Error(`文件超过 ${limit} 字节上限: ${file}`);
|
|
125
|
+
}
|
|
126
|
+
return buf.subarray(0, n);
|
|
127
|
+
} finally { closeSync(fd); }
|
|
128
|
+
}
|
|
129
|
+
export function readBounded(file, limit) { return readBuffer(file, limit).toString('utf8'); }
|
|
130
|
+
|
|
131
|
+
// 技能文档读取:单文件 MAX_DOC_BYTES,累计 MAX_TOTAL_BYTES,均按实际读到的字节算。
|
|
132
|
+
export function makeBoundedReader() {
|
|
133
|
+
let total = 0;
|
|
134
|
+
return (file) => {
|
|
135
|
+
const buf = readBuffer(file, Math.min(MAX_DOC_BYTES, MAX_TOTAL_BYTES - total));
|
|
136
|
+
total += buf.length; // 实际读到的字节数,不是解码后的字符数
|
|
137
|
+
return buf.toString('utf8');
|
|
138
|
+
};
|
|
139
|
+
}
|