@aibyzero/cm-workflow 0.21.2 → 0.21.4

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.
Files changed (45) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +9 -0
  3. package/README.md +7 -1
  4. package/VERSION +1 -1
  5. package/docs/installation.md +1 -1
  6. package/docs/js-workflow-control.md +6 -1
  7. package/package.json +1 -1
  8. package/runtime/js/cm-ai/call-timeout.mjs +21 -0
  9. package/runtime/js/cm-ai/checkpoint-package-material.mjs +3 -2
  10. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +5 -1
  11. package/runtime/js/cm-ai/durable-runner-state.mjs +19 -4
  12. package/runtime/js/cm-ai/fix-code-association.mjs +5 -5
  13. package/runtime/js/cm-ai/host-conversation-execution.mjs +22 -15
  14. package/runtime/js/cm-ai/host-documentation.mjs +4 -3
  15. package/runtime/js/cm-ai/host-handoff.mjs +3 -2
  16. package/runtime/js/cm-ai/host-project-execution.mjs +11 -9
  17. package/runtime/js/cm-ai/host-qa-executor.mjs +3 -2
  18. package/runtime/js/cm-ai/host-replay.mjs +28 -8
  19. package/runtime/js/cm-ai/review-package.mjs +101 -33
  20. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  21. package/runtime/js/cm-ai/reviewed-integration.mjs +1 -1
  22. package/runtime/js/cm-ai/symlink-material.mjs +153 -0
  23. package/runtime/js/cm-ai/task-commit.mjs +6 -3
  24. package/runtime/js/cm-ai/task-runner.mjs +12 -5
  25. package/runtime/js/cm-ai/worker-claude-developer.mjs +19 -7
  26. package/runtime/js/cm-fix/protected-edits.mjs +57 -36
  27. package/scripts/ci-test-weights.json +1 -0
  28. package/scripts/cm-ai-batch-drive.mjs +9 -5
  29. package/scripts/cm-ai-call-timeout.test.mjs +85 -0
  30. package/scripts/cm-ai-control-launch.test.mjs +18 -0
  31. package/scripts/cm-ai-drive.mjs +141 -42
  32. package/scripts/cm-ai-host.mjs +15 -3
  33. package/scripts/cm-ai-host.test.mjs +3 -1
  34. package/scripts/cm-ai-launch-diagnostics.test.mjs +23 -0
  35. package/scripts/cm-ai-run.mjs +2 -1
  36. package/scripts/cm-ai-scope-revision.test.mjs +35 -3
  37. package/scripts/cm-ai-supersede.test.mjs +51 -3
  38. package/scripts/cm-ai-symlink.test.mjs +481 -0
  39. package/scripts/cm-skill-hints.mjs +40 -16
  40. package/scripts/cm-skill-hints.test.mjs +91 -0
  41. package/scripts/cm-start-check.mjs +53 -15
  42. package/scripts/cm-start-check.test.mjs +41 -2
  43. package/scripts/cm-task-gate.mjs +42 -13
  44. package/scripts/cm-task-gate.test.mjs +33 -0
  45. package/skills/cm-ai/references/js-host.md +1 -0
@@ -8,6 +8,7 @@ import fs from 'node:fs';
8
8
  import os from 'node:os';
9
9
  import path from 'node:path';
10
10
  import {createHostCheck} from './host-check.mjs';
11
+ import {assertRealParents,readSymlinkRecord} from './symlink-material.mjs';
11
12
  import {need,json,validIdentity} from './effect-contract.mjs';
12
13
 
13
14
  const FILE_LIMIT=1024*1024,ENTRY_LIMIT=200000,EVIDENCE_LIMIT=1500;
@@ -16,15 +17,20 @@ export const HOST_REPLAY_EVIDENCE_PREFIX='cm-host-replay-v1: ';
16
17
  // Scope file state before development: {bytes,mode}, or null for a file that does
17
18
  // not exist yet. Anything else (a link, a directory, an oversized file) makes the
18
19
  // snapshot unavailable, never a partial one.
19
- export function captureBeforeSnapshot(codeProject,scope){
20
+ export function captureBeforeSnapshot(codeProject,scope,{allowSymlinks=false}={}){
20
21
  const files=new Map();
21
22
  for(const file of scope){
23
+ if(allowSymlinks){
24
+ try{files.set(file,currentState(codeProject,file,true));}
25
+ catch(error){return {unavailable:error.code==='replay_scope_link'?'snapshot_unsupported_file':'snapshot_unreadable'};}
26
+ continue;
27
+ }
22
28
  const target=path.join(codeProject,file);let stat;
23
29
  try{stat=fs.lstatSync(target);}catch(error){if(error.code==='ENOENT'){files.set(file,null);continue;}return {unavailable:'snapshot_unreadable'};}
24
30
  if(!stat.isFile()||stat.size>FILE_LIMIT)return {unavailable:'snapshot_unsupported_file'};
25
31
  files.set(file,{bytes:fs.readFileSync(target),mode:stat.mode&0o777});
26
32
  }
27
- return {files};
33
+ return {files,...(allowSymlinks?{allowSymlinks}:{})};
28
34
  }
29
35
 
30
36
  const summarize=rows=>{
@@ -65,7 +71,7 @@ function copyProject(codeProject,specsDir){
65
71
  if(real===null||!copied(codeProject,specsDir,real))continue;
66
72
  if(realOrNull(path.join(project,link))!==path.join(project,path.relative(codeProject,real)))throw replayError('replay_internal_link');
67
73
  }
68
- return {root,project};
74
+ return {root,project,links};
69
75
  }catch(error){removeCopy(root);throw error;}
70
76
  }
71
77
  function removeCopy(root){
@@ -74,7 +80,7 @@ function removeCopy(root){
74
80
  }
75
81
  // Writes only through real directories inside the copy: every ancestor and the
76
82
  // target itself are checked without following links, before any byte is written.
77
- function place(project,file,state){
83
+ function place(project,file,state,allowSymlinks){
78
84
  let current=project;
79
85
  for(const part of file.split('/').slice(0,-1)){
80
86
  current=path.join(current,part);let stat;
@@ -84,14 +90,17 @@ function place(project,file,state){
84
90
  const target=path.join(project,file);
85
91
  let existing=null;
86
92
  try{existing=fs.lstatSync(target);}catch(error){if(error.code!=='ENOENT')throw error;}
87
- if(existing!==null){if(!existing.isFile())throw replayError('replay_scope_link');fs.unlinkSync(target);}
93
+ if(existing!==null){if(!existing.isFile()&&!(allowSymlinks&&existing.isSymbolicLink()))throw replayError('replay_scope_link');fs.unlinkSync(target);}
88
94
  if(state===null)return;
95
+ if(allowSymlinks&&Object.hasOwn(state,'symlink')){fs.symlinkSync(state.symlink,target);return;}
89
96
  const fd=fs.openSync(target,fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|fs.constants.O_NOFOLLOW,state.mode);
90
97
  try{fs.writeFileSync(fd,state.bytes);fs.fchmodSync(fd,state.mode);}finally{fs.closeSync(fd);}
91
98
  }
92
- const currentState=(codeProject,file)=>{
99
+ const currentState=(codeProject,file,allowSymlinks)=>{
100
+ if(allowSymlinks)assertRealParents(codeProject,file);
93
101
  const target=path.join(codeProject,file);let stat;
94
102
  try{stat=fs.lstatSync(target);}catch(error){if(error.code==='ENOENT')return null;throw error;}
103
+ if(allowSymlinks&&stat.isSymbolicLink())return {symlink:readSymlinkRecord(codeProject,file).target};
95
104
  if(!stat.isFile()||stat.size>FILE_LIMIT)throw replayError('replay_scope_link');
96
105
  return {bytes:fs.readFileSync(target),mode:stat.mode&0o777};
97
106
  };
@@ -106,6 +115,7 @@ export async function replayDelivery({codeProject,specsDir,snapshot,scope,tests,
106
115
  // A path added to the scope after the snapshot has no known prior state.
107
116
  if(!scope.every(file=>snapshot.files.has(file)))return skipped('snapshot_scope_changed');
108
117
  if(!Array.isArray(checkCommands)||checkCommands.length===0)return skipped('no_host_checks');
118
+ const allowSymlinks=snapshot.allowSymlinks===true;
109
119
  const testFiles=(tests??[]).filter(file=>scope.includes(file));
110
120
  const commands=checkCommands.map(({id,command})=>({id,command}));
111
121
  // A command that names the project by absolute path would run the real project, not the copy.
@@ -115,7 +125,17 @@ export async function replayDelivery({codeProject,specsDir,snapshot,scope,tests,
115
125
  need(!signal?.aborted,'cancelled');
116
126
  const copy=copyProject(codeProject,specsDir);
117
127
  try{
118
- for(const file of scope)place(copy.project,file,states(file));
128
+ for(const file of scope)place(copy.project,file,states(file),allowSymlinks);
129
+ if(allowSymlinks)for(const link of new Set([...copy.links,...scope])){
130
+ const target=path.join(copy.project,link);
131
+ let stat;
132
+ try{stat=fs.lstatSync(target);}catch(error){if(error.code==='ENOENT'||error.code==='ENOTDIR')continue;throw error;}
133
+ if(!stat.isSymbolicLink())continue;
134
+ const literal=path.resolve(path.dirname(target),readSymlinkRecord(copy.project,link).target);
135
+ const resolved=realOrNull(target);
136
+ const pointsBack=p=>p!==null&&(p===codeProject||p.startsWith(codeProject+path.sep));
137
+ if(pointsBack(literal)||pointsBack(resolved))throw replayError('replay_internal_link');
138
+ }
119
139
  // The same sandbox as the task's own checks: the copy is the workspace, specs stay read-only.
120
140
  return summarize(await makeCheck({cwd:copy.project,commands,timeoutMs,specsRoot:specsDir})({identity},{signal}));
121
141
  }finally{removeCopy(copy.root);}
@@ -125,7 +145,7 @@ export async function replayDelivery({codeProject,specsDir,snapshot,scope,tests,
125
145
  const baseline=await run(before);
126
146
  let red={skipped:'no_test_files'};
127
147
  if(testFiles.length){
128
- const delivered=new Map(testFiles.map(file=>[file,currentState(codeProject,file)]));
148
+ const delivered=new Map(testFiles.map(file=>[file,currentState(codeProject,file,allowSymlinks)]));
129
149
  red=await run(file=>delivered.has(file)?delivered.get(file):before(file));
130
150
  }
131
151
  return {version:1,status:'replayed',baseline,red,green};
@@ -10,6 +10,8 @@ import {captureSpecificationMaterial,readSpecificationMaterial,verifySpecificati
10
10
  import {resolveCodeProjects,validateCodeProjectPaths,
11
11
  codeProjectInstructionPaths,assertCodeProjectSelections} from './code-projects.mjs';
12
12
  import {identifyApprovedBootstrapFeature} from './bootstrap-feature.mjs';
13
+ import {SYMLINK_BASELINE_VERSION,reviewPackageVersion,readSymlinkRecord,validateSymlinkRecord,symlinkRecord,projectedPathStat,
14
+ assertRealParents,lstatOrMissing,resolveSymlinkTarget} from './symlink-material.mjs';
13
15
 
14
16
  const FILE_LIMIT=1024*1024, SNAPSHOT_LIMIT=2*1024*1024, FILE_COUNT=256;
15
17
  // Read-only view for callers that must refuse an oversized delivery before it is written.
@@ -327,14 +329,16 @@ export function reviewSpecsPath(root,specsRoot) {
327
329
  need(root!==specsRoot&&!root.startsWith(specsRoot+path.sep),'overlapping_roots');
328
330
  return specsRoot.startsWith(root+path.sep)?filePath(path.relative(root,specsRoot).split(path.sep).join('/')):null;
329
331
  }
330
- function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selected=null,policy=null,inventoryOnly=false) {
332
+ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selected=null,policy=null,inventoryOnly=false,allowSymlinks=false) {
331
333
  if(specsPath!==null){
332
334
  const target=path.join(root,specsPath);
333
335
  need(fs.realpathSync(target)===target&&fs.lstatSync(target).isDirectory(),'unsupported_path');
334
336
  }
335
337
  const files=[],seen=new Set(); let total=0,materialBytes=0,materialCount=0,visitedSpecs=false;
336
338
  function add(p,s){
337
- if(!s.isFile()||s.isSymbolicLink()||s.nlink!==1)throw diagnostic('unsupported_file',p);
339
+ const link=s.isSymbolicLink();
340
+ if(link?(!allowSymlinks||p.split('/').at(-1)==='AGENTS.md'):(!s.isFile()||s.nlink!==1))
341
+ throw diagnostic('unsupported_file',p);
338
342
  const includeContent=!inventoryOnly&&(selected===null||materialPath(p,selected));
339
343
  const countLimit=selected===null&&!inventoryOnly?FILE_COUNT:INVENTORY_COUNT;
340
344
  const byteLimit=selected===null&&!inventoryOnly?SNAPSHOT_LIMIT:INVENTORY_LIMIT;
@@ -344,7 +348,7 @@ function snapshot(root,specsPath=null,projectPaths=null,retainedPaths=[],selecte
344
348
  throw diagnostic('limit_exceeded',p,`material file count > ${FILE_COUNT}`);
345
349
  if(includeContent&&materialBytes+s.size>SNAPSHOT_LIMIT)
346
350
  throw diagnostic('limit_exceeded',p,`material bytes ${materialBytes}+${s.size} > ${SNAPSHOT_LIMIT}; scope, requirements and AGENTS.md content count`);
347
- const f=readFile(root,p,includeContent,includeContent?Math.min(FILE_LIMIT,SNAPSHOT_LIMIT-materialBytes):byteLimit-total);
351
+ const f=link?readSymlinkRecord(root,p):readFile(root,p,includeContent,includeContent?Math.min(FILE_LIMIT,SNAPSHOT_LIMIT-materialBytes):byteLimit-total);
348
352
  total+=f.size;
349
353
  if(includeContent){materialBytes+=f.size;materialCount++;}
350
354
  files.push(f);
@@ -431,8 +435,8 @@ export function captureReviewInventory(root,baseline,{withMode=false}={}){
431
435
  const policy=stable?stableSnapshotPolicy(root,baseline.ignorePolicy)
432
436
  :Object.hasOwn(baseline,'ignorePolicy')?ignorePolicy(root):null;
433
437
  return snapshot(root,baseline.specsPath??null,baseline.codeProjectPaths??null,
434
- stable?[]:baseline.files.map(file=>file.path),new Set(),policy)
435
- .map(file=>withMode?({path:file.path,type:file.type,mode:file.mode,sha256:file.sha256})
438
+ stable?[]:baseline.files.map(file=>file.path),new Set(),policy,false,baseline.version===SYMLINK_BASELINE_VERSION)
439
+ .map(file=>withMode?(file.type==='symlink'?file:({path:file.path,type:file.type,mode:file.mode,sha256:file.sha256}))
436
440
  :({path:file.path,sha256:file.sha256}));
437
441
  }
438
442
  // withMode also reports permission-only changes; the mode is part of a reviewed
@@ -446,8 +450,8 @@ export function compareReviewInventoryToBaseline(root,baseline,{withMode=false,p
446
450
  :Object.hasOwn(baseline,'ignorePolicy')?ignorePolicy(root):null;
447
451
  const before=stable?comparableFiles(baseline.files,policy,new Set([...baseline.scope,...baseline.requirements])):baseline.files;
448
452
  const after=snapshot(root,baseline.specsPath??null,baseline.codeProjectPaths??null,
449
- stable?[]:baseline.files.map(file=>file.path),new Set(),policy);
450
- const key=file=>withMode?`${file.sha256}:${file.mode}`:file.sha256;
453
+ stable?[]:baseline.files.map(file=>file.path),new Set(),policy,false,baseline.version===SYMLINK_BASELINE_VERSION);
454
+ const key=file=>withMode?`${file.sha256}:${file.mode??null}`:file.sha256;
451
455
  const previous=new Map(before.map(file=>[file.path,key(file)]));
452
456
  const current=new Map(after.map(file=>[file.path,key(file)]));
453
457
  const records=new Map(after.map(file=>[file.path,file]));
@@ -483,7 +487,8 @@ const sealed = (data,key) => {
483
487
  export function captureReviewBaseline(options,legacy=false,policyVersion=2,baselinePolicy=null,acceptance=true) {
484
488
  const v=plain(options); keys(v,['root','identity','scope','requirements',
485
489
  ...['specsRoot','codeProjectPaths','bootstrapRequirements','specification','version','scopeRevisionPaths'].filter(key=>Object.hasOwn(v,key))]); identityCheck(v.identity);
486
- const version=v.version??2;need([1,2].includes(version));
490
+ const version=v.version??2;need([1,2,SYMLINK_BASELINE_VERSION].includes(version));
491
+ const allowSymlinks=version===SYMLINK_BASELINE_VERSION;
487
492
  const bootstrap=Object.hasOwn(v,'bootstrapRequirements')?v.bootstrapRequirements:null;
488
493
  if(bootstrap!==null){
489
494
  validBootstrapRequirements(bootstrap);
@@ -497,6 +502,10 @@ export function captureReviewBaseline(options,legacy=false,policyVersion=2,basel
497
502
  specification=captureSpecificationMaterial({...v.specification,taskId:v.identity.taskId,acceptance});
498
503
  }
499
504
  const scope=paths(v.scope), requirements=requirementPaths(v.requirements,bootstrap!==null||specification!==null),root=rootPath(v.root);
505
+ if(allowSymlinks){
506
+ for(const p of [...scope,...requirements])assertRealParents(root,p);
507
+ need(!lstatOrMissing(path.join(root,'.git'))?.isSymbolicLink(),'unsupported_path');
508
+ }
500
509
  need(![...scope,...requirements].some(p=>inDependencyDirectory(p)||inCocoaPodsTree(root,p)),'excluded_snapshot_path');
501
510
  const projectPaths=Object.hasOwn(v,'codeProjectPaths')?validateCodeProjectPaths(v.codeProjectPaths):null;
502
511
  if(projectPaths!==null)resolveCodeProjects(v.root,projectPaths.map(prefix=>path.join(root,prefix)));
@@ -511,13 +520,21 @@ export function captureReviewBaseline(options,legacy=false,policyVersion=2,basel
511
520
  const policy=legacy||version===1?null:policyVersion===1?ignorePolicy(root)
512
521
  :stableIgnorePolicy(root,baselinePolicy?.mode==='builtin_limit');
513
522
  const snapshotPolicy=baselinePolicy===null?policy:stableSnapshotPolicy(root,baselinePolicy,policy);
514
- const files=snapshot(root,specsPath,projectPaths,[],version===1?null:new Set([...scope,...requirements]),snapshotPolicy);
523
+ const files=snapshot(root,specsPath,projectPaths,[],version===1?null:new Set([...scope,...requirements]),snapshotPolicy,false,allowSymlinks);
515
524
  need(requirements.every(p=>files.some(f=>f.path===p)),'read_failed');
525
+ if(allowSymlinks)for(const p of requirements)
526
+ need(files.find(f=>f.path===p).type==='file','unsupported_file');
516
527
  for(const p of scope) {
517
528
  const absolute=path.join(root,p);
529
+ if(allowSymlinks){
530
+ const stat=lstatOrMissing(absolute);
531
+ need(stat===null||stat.isFile()||stat.isSymbolicLink(),'unsupported_file');
532
+ continue;
533
+ }
518
534
  if(fs.existsSync(absolute)) need(fs.lstatSync(absolute).isFile(),'unsupported_file');
519
535
  }
520
536
  return sealed({version,kind:'cm-review-baseline',identity:v.identity,rootDigest:sha(root),
537
+ ...(allowSymlinks?{symlinkPolicy:1}:{}),
521
538
  scope,requirements,files,...(Object.hasOwn(v,'scopeRevisionPaths')?{scopeRevisionPaths:paths(v.scopeRevisionPaths)}:{}),...(specsPath===null?{}:{specsPath}),
522
539
  ...(projectPaths===null?{}:{codeProjectPaths:projectPaths}),
523
540
  ...(bootstrap===null?{}:{bootstrapRequirements:bootstrap}),
@@ -539,7 +556,7 @@ export const readReviewScope=value=>paths(value);
539
556
  // Pods can be missing from the creation inventory without a Git-ignore row;
540
557
  // this narrow recovery API never opens a parent directory named Pods.
541
558
  function scopeRevisionAdditions(b,scope){
542
- need(b.version===2&&b.ignorePolicy?.version!==1,'scope_revision_unsupported_baseline');
559
+ need(b.version>=2&&b.ignorePolicy?.version!==1,'scope_revision_unsupported_baseline');
543
560
  const additions=paths(scope).filter(p=>!b.scope.includes(p));
544
561
  const ignoredPaths=new Set((b.ignorePolicy?.ignoredPaths??[]).map(p=>p.toLowerCase()));
545
562
  const ignoredDirectories=(b.ignorePolicy?.ignoredDirectories??[]).map(p=>p.toLowerCase());
@@ -558,7 +575,7 @@ export function extendReviewBaseline(raw,scope,files){
558
575
  need(b.scope.filter(p=>p!=='AGENTS.md').every(p=>desired.includes(p)),'scope_revision_shrink');
559
576
  need(Array.isArray(files)&&files.length<=additions.length,'invalid_input');
560
577
  const supplied=new Map();
561
- for(const file of files){fileRecord(file);need(additions.includes(file.path)&&!supplied.has(file.path),'invalid_input');supplied.set(file.path,file);}
578
+ for(const file of files){scopeRecord(file,b.version===SYMLINK_BASELINE_VERSION);need(additions.includes(file.path)&&!supplied.has(file.path),'invalid_input');supplied.set(file.path,file);}
562
579
  const inventory=new Map(b.files.map(file=>[file.path,file]));
563
580
  const aliases=new Set(b.files.map(file=>file.path.toLowerCase()));
564
581
  for(const p of additions){
@@ -589,7 +606,8 @@ export function captureScopeRevisionSources(root,baseline,scope){
589
606
  catch(error){if(error.code==='ENOENT')break;throw error;}
590
607
  }
591
608
  const old=b.files.find(file=>file.path===p);
592
- if(old)files.push(readFile(real,p));
609
+ if(old)files.push(b.version===SYMLINK_BASELINE_VERSION&&lstatOrMissing(path.join(real,p))?.isSymbolicLink()
610
+ ?readSymlinkRecord(real,p):readFile(real,p));
593
611
  else{
594
612
  try{fs.lstatSync(path.join(real,p));need(false,'scope_revision_source_changed');}
595
613
  catch(error){if(error.code!=='ENOENT')throw error;}
@@ -639,6 +657,13 @@ function fileRecord(f) {
639
657
  const bytes=Buffer.from(f.contentBase64,'base64');
640
658
  need(bytes.toString('base64')===f.contentBase64 && bytes.length===f.size && sha(bytes)===f.sha256);
641
659
  }
660
+ function scopeRecord(file,allowSymlinks) {
661
+ if(allowSymlinks&&file.type==='symlink'){
662
+ filePath(file.path);
663
+ need(file.path.split('/').at(-1)!=='AGENTS.md','unsupported_file');
664
+ validateSymlinkRecord(file);
665
+ }else fileRecord(file);
666
+ }
642
667
  function fileList(files) {
643
668
  need(Array.isArray(files) && files.length>0 && files.length<=FILE_COUNT);
644
669
  files.forEach(fileRecord);
@@ -650,12 +675,16 @@ function fileList(files) {
650
675
  function inventoryList(b) {
651
676
  const files=b.files,selected=new Set([...b.scope,...b.requirements]);
652
677
  need(Array.isArray(files)&&files.length<=INVENTORY_COUNT);
653
- const material=[];let total=0,previous=null;const aliases=new Set();
678
+ let materialSize=0,materialCount=0,total=0,previous=null;const aliases=new Set();
654
679
  for(const f of files){
655
680
  // Legacy dependency records retain their original full bytes and drift checks.
656
681
  // Ordinary sparse inventory entries still reject unsolicited bodies.
657
682
  const legacyDependency=!Object.hasOwn(b,'specification')&&inDependencyDirectory(f.path)&&Object.hasOwn(f,'contentBase64');
658
- if(materialPath(f.path,selected)||legacyDependency){fileRecord(f);material.push(f);}
683
+ const hasMaterial=materialPath(f.path,selected)||legacyDependency;
684
+ if(b.version===SYMLINK_BASELINE_VERSION&&f.type==='symlink'){
685
+ need(!b.requirements.includes(f.path));
686
+ scopeRecord(f,true);
687
+ }else if(hasMaterial)fileRecord(f);
659
688
  else{
660
689
  keys(f,['path','type','mode','size','sha256']);filePath(f.path);
661
690
  need(f.type==='file'&&Number.isInteger(f.mode)&&f.mode>=0&&f.mode<=0o7777);
@@ -664,8 +693,11 @@ function inventoryList(b) {
664
693
  need(previous===null||previous<f.path);previous=f.path;
665
694
  need(!aliases.has(f.path.toLowerCase()));aliases.add(f.path.toLowerCase());
666
695
  total+=f.size;need(total<=INVENTORY_LIMIT);
696
+ if(hasMaterial){
697
+ materialCount++;materialSize+=f.size;
698
+ need(materialCount<=FILE_COUNT&&materialSize<=SNAPSHOT_LIMIT,'limit_exceeded');
699
+ }
667
700
  }
668
- if(material.length)fileList(material);
669
701
  need(Buffer.byteLength(JSON.stringify(b))<=8*1024*1024,'limit_exceeded');
670
702
  }
671
703
  const bootstrapPaths=feature=>[`${feature}/design.md`,`${feature}/requirements.md`];
@@ -691,8 +723,11 @@ export function readReviewSourceRecords(raw){
691
723
  function validBaseline(b) {
692
724
  try {
693
725
  keys(b,['version','kind','identity','rootDigest','scope','requirements','files','baselineDigest',
726
+ ...(b.version===SYMLINK_BASELINE_VERSION?['symlinkPolicy']:[]),
694
727
  ...['specsPath','codeProjectPaths','bootstrapRequirements','specification','specificationRoot','ignorePolicy','scopeRevisionPaths'].filter(key=>Object.hasOwn(b,key))]);
695
- need([1,2].includes(b.version) && b.kind==='cm-review-baseline'); identityCheck(b.identity); hex(b.rootDigest);
728
+ need([1,2,SYMLINK_BASELINE_VERSION].includes(b.version) && b.kind==='cm-review-baseline');
729
+ if(b.version===SYMLINK_BASELINE_VERSION)need(b.symlinkPolicy===1);
730
+ identityCheck(b.identity); hex(b.rootDigest);
696
731
  if(Object.hasOwn(b,'ignorePolicy')){
697
732
  if(b.ignorePolicy.version===2)validateStablePolicy(b.ignorePolicy);
698
733
  else{
@@ -716,7 +751,7 @@ function validBaseline(b) {
716
751
  need(digest(b.scopeRevisionPaths)===digest(paths(b.scopeRevisionPaths))
717
752
  &&b.scopeRevisionPaths.every(p=>b.scope.includes(p)),'invalid_baseline');
718
753
  }
719
- if(b.version===2)inventoryList(b);
754
+ if(b.version>=2)inventoryList(b);
720
755
  else if(!bootstrap||b.files.length)fileList(b.files);else need(Array.isArray(b.files));
721
756
  need(b.requirements.every(p=>b.files.some(f=>f.path===p)));
722
757
  if(Object.hasOwn(b,'specsPath'))validateSpecsSelection(b.specsPath,[...b.scope,...b.requirements,...b.files.map(f=>f.path)]);
@@ -763,14 +798,14 @@ const packagePolicy=(root,b)=>b.ignorePolicy?.version===2?stableSnapshotPolicy(r
763
798
  function packageSnapshot(root,b,policy){
764
799
  const selected=b.version===1?null:new Set([...b.scope,...b.requirements,
765
800
  ...b.files.filter(f=>Object.hasOwn(f,'contentBase64')).map(f=>f.path)]);
766
- return snapshot(root,b.specsPath??null,b.codeProjectPaths??null,b.ignorePolicy?.version===2?[]:b.files.map(f=>f.path),selected,policy);
801
+ return snapshot(root,b.specsPath??null,b.codeProjectPaths??null,b.ignorePolicy?.version===2?[]:b.files.map(f=>f.path),selected,policy,false,b.version===SYMLINK_BASELINE_VERSION);
767
802
  }
768
803
  // Read-only: path and size of every material body a package built from the
769
804
  // current tree would carry. Callers use it to refuse a delivery before writing it.
770
805
  export function reviewMaterialSizes(options){
771
806
  const v=plain(options);keys(v,['root','baseline']);const b=v.baseline;validBaseline(b);
772
807
  const root=rootPath(v.root);need(sha(root)===b.rootDigest,'invalid_baseline');
773
- return freeze(packageSnapshot(root,b,packagePolicy(root,b)).filter(f=>Object.hasOwn(f,'contentBase64'))
808
+ return freeze(packageSnapshot(root,b,packagePolicy(root,b)).filter(f=>Object.hasOwn(f,'contentBase64')||f.type==='symlink'&&b.scope.includes(f.path))
774
809
  .map(f=>({path:f.path,size:f.size})));
775
810
  }
776
811
  // Validation, specification, policy and bootstrap material a package is built
@@ -789,7 +824,10 @@ function packageContext(v){
789
824
  if(bootstrap!==null)need(reviewSpecsPath(root,b.bootstrapRequirements.specsRoot)===(b.specsPath??null),'bootstrap_requirements_mismatch');
790
825
  return {b,root,stable,policy,specification,bootstrap};
791
826
  }
792
- function assemblePackage({b,stable,policy,specification,bootstrap},files,checks,handoff){
827
+ export const unchangedScopeRecord=(baseline,file)=>baseline.scopeRevisionPaths?.includes(file.path)||file.type==='symlink'
828
+ ?file:{path:file.path,sha256:file.sha256};
829
+ function assemblePackage({b,root,stable,policy,specification,bootstrap},files,checks,handoff,
830
+ stat=relative=>lstatOrMissing(path.join(root,relative))){
793
831
  const protectedPaths=new Set([...b.scope,...b.requirements]);
794
832
  const before=new Map((stable?comparableFiles(b.files,policy,protectedPaths):b.files).map(f=>[f.path,f]));
795
833
  const after=new Map(files.map(f=>[f.path,f]));
@@ -807,11 +845,26 @@ function assemblePackage({b,stable,policy,specification,bootstrap},files,checks,
807
845
  throw error;
808
846
  }
809
847
  need(changes.length>0,'empty_changes');
848
+ for(const change of changes){
849
+ if(change.after?.type!=='symlink')continue;
850
+ const prefix=b.codeProjectPaths?.find(p=>change.path.startsWith(p+'/'));
851
+ const codeRoot=prefix===undefined?root:path.join(root,prefix);
852
+ const local=prefix===undefined?change.path:change.path.slice(prefix.length+1);
853
+ resolveSymlinkTarget(codeRoot,local,change.after.target,{
854
+ specsRoot:b.specsPath===undefined?null:path.join(root,b.specsPath),
855
+ stat:file=>{
856
+ const name=prefix===undefined?file:prefix+'/'+file;
857
+ if(after.get(name)?.type==='symlink'||(before.has(name)&&!after.has(name)))return null;
858
+ return stat(name);
859
+ },
860
+ });
861
+ }
810
862
  const changedPaths=new Set(changes.map(change=>change.path));
811
863
  const unchangedScope=b.scope.filter(p=>!changedPaths.has(p)&&after.has(p))
812
- .map(p=>b.scopeRevisionPaths?.includes(p)?after.get(p):({path:p,sha256:after.get(p).sha256}));
813
- const requirements=b.requirements.map(p=>{ need(after.has(p),'read_failed'); return after.get(p); });
814
- const pkg=sealed({version:1,kind:'cm-review-package',identity:b.identity,rootDigest:b.rootDigest,
864
+ .map(p=>unchangedScopeRecord(b,after.get(p)));
865
+ const requirements=b.requirements.map(p=>{ need(after.has(p),'read_failed'); const file=after.get(p);fileRecord(file);return file; });
866
+ const pkg=sealed({version:reviewPackageVersion(b),kind:'cm-review-package',identity:b.identity,rootDigest:b.rootDigest,
867
+ ...(b.version===SYMLINK_BASELINE_VERSION?{symlinkPolicy:b.symlinkPolicy}:{}),
815
868
  baseIdentity:b.baselineDigest,scope:b.scope,changes,unchangedScope,requirements,checks,
816
869
  ...(Object.hasOwn(b,'codeProjectPaths')?{codeProjectPaths:b.codeProjectPaths,
817
870
  instructions:files.filter(file=>file.path.split('/').at(-1)==='AGENTS.md')}:{}),
@@ -837,12 +890,23 @@ export function projectedReviewPackage(options){
837
890
  const v=plain(options);keys(v,['root','baseline','checks','scopeFiles',...(Object.hasOwn(v,'handoff')?['handoff']:[])]);
838
891
  const context=packageContext(v);need(Array.isArray(v.scopeFiles),'invalid_input');
839
892
  const files=new Map(packageSnapshot(context.root,context.b,context.policy).map(file=>[file.path,file]));
893
+ const projectedPaths=new Map();
840
894
  for(const item of v.scopeFiles){
841
- keys(item,['path','contentBase64','mode']);need(context.b.scope.includes(item.path),'out_of_scope');
842
- if(item.contentBase64===null){need(item.mode===null);files.delete(item.path);continue;}
895
+ need(context.b.scope.includes(item.path),'out_of_scope');
896
+ if(Object.hasOwn(item,'symlink')){
897
+ keys(item,['path','symlink']);
898
+ const record=symlinkRecord(item.path,item.symlink);
899
+ scopeRecord(record,context.b.version===SYMLINK_BASELINE_VERSION);
900
+ files.set(item.path,record);
901
+ projectedPaths.set(item.path,'symlink');
902
+ continue;
903
+ }
904
+ keys(item,['path','contentBase64','mode']);
905
+ if(item.contentBase64===null){need(item.mode===null);files.delete(item.path);projectedPaths.set(item.path,null);continue;}
843
906
  need(typeof item.contentBase64==='string'&&Number.isInteger(item.mode)&&item.mode>=0&&item.mode<=0o7777);
844
907
  const bytes=Buffer.from(item.contentBase64,'base64');need(bytes.toString('base64')===item.contentBase64);
845
908
  files.set(item.path,{path:item.path,type:'file',mode:item.mode,size:bytes.length,sha256:sha(bytes),contentBase64:item.contentBase64});
909
+ projectedPaths.set(item.path,'file');
846
910
  }
847
911
  // A projected handoff ({name,contentBase64,mode}) takes the record shape the
848
912
  // package reads back from the published file.
@@ -854,12 +918,14 @@ export function projectedReviewPackage(options){
854
918
  const record={path:name,type:'file',mode:v.handoff.mode,size:bytes.length,sha256:sha(bytes),contentBase64:v.handoff.contentBase64};
855
919
  handoff=()=>record;
856
920
  }
857
- return assemblePackage(context,[...files.values()].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0),v.checks,handoff);
921
+ return assemblePackage(context,[...files.values()].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0),v.checks,handoff,
922
+ projectedPathStat(context.root,projectedPaths));
858
923
  }
859
924
  function validPackage(p) {
860
925
  try {
861
926
  keys(p,['version','kind','identity','rootDigest','baseIdentity','scope','changes','requirements',
862
927
  'checks','artifactDigest','requirementsDigest','checksDigest','packageDigest',
928
+ ...(p.version===2?['symlinkPolicy']:[]),
863
929
  ...(Object.hasOwn(p,'unchangedScope')?['unchangedScope']:[]),
864
930
  ...(Object.hasOwn(p,'specification')?['specification']:[]),
865
931
  ...(Object.hasOwn(p,'handoff')?['handoff']:[]),
@@ -879,7 +945,8 @@ function validPackage(p) {
879
945
  if(Object.hasOwn(p,'handoff')) {
880
946
  fileRecord(p.handoff);need(!p.handoff.path.includes('/')&&p.handoff.size<=256*1024);
881
947
  }
882
- need(p.version===1 && p.kind==='cm-review-package'); identityCheck(p.identity);
948
+ need([1,2].includes(p.version) && p.kind==='cm-review-package'); identityCheck(p.identity);
949
+ if(p.version===2)need(p.symlinkPolicy===1);
883
950
  if(Object.hasOwn(p,'specification'))readSpecificationMaterial(p.specification,p.identity.taskId);
884
951
  [p.rootDigest,p.baseIdentity,p.artifactDigest,p.requirementsDigest,p.checksDigest,p.packageDigest].forEach(hex);
885
952
  need(digest(p.scope)===digest(paths(p.scope)));
@@ -888,7 +955,7 @@ function validPackage(p) {
888
955
  for(const change of p.changes) {
889
956
  keys(change,['path','before','after']); filePath(change.path); need(p.scope.includes(change.path));
890
957
  names.push(change.path); need(change.before!==null || change.after!==null);
891
- for(const f of [change.before,change.after]) if(f!==null) { fileRecord(f); need(f.path===change.path); }
958
+ for(const f of [change.before,change.after]) if(f!==null) { scopeRecord(f,p.version===2); need(f.path===change.path); }
892
959
  need(digest(change.before)!==digest(change.after));
893
960
  }
894
961
  need(digest(names)===digest(paths(names)));
@@ -897,10 +964,11 @@ function validPackage(p) {
897
964
  if(p.requirements.length)fileList(p.requirements);else need(Array.isArray(p.requirements));
898
965
  }else if(p.requirements.length||!Object.hasOwn(p,'specification'))fileList(p.requirements);
899
966
  else need(Array.isArray(p.requirements));
967
+ if(p.version===2)need(Object.hasOwn(p,'unchangedScope'));
900
968
  if(Object.hasOwn(p,'unchangedScope')){
901
969
  need(Array.isArray(p.unchangedScope)&&p.unchangedScope.length<=FILE_COUNT);
902
970
  for(const file of p.unchangedScope){
903
- if(Object.hasOwn(file,'contentBase64'))fileRecord(file);
971
+ if(Object.hasOwn(file,'contentBase64')||file.type==='symlink')scopeRecord(file,p.version===2);
904
972
  else{keys(file,['path','sha256']);filePath(file.path);hex(file.sha256);}
905
973
  need(p.scope.includes(file.path)&&!names.includes(file.path));
906
974
  for(const material of [...p.requirements,...(p.instructions??[])])
@@ -931,14 +999,14 @@ export function verifyReviewPackage(options) {
931
999
  const v=plain(options); keys(v,['root','baseline','checks','reviewPackage','expectedDigest',
932
1000
  ...(Object.hasOwn(v,'handoffPath')?['handoffPath']:[])]);
933
1001
  hex(v.expectedDigest); validBaseline(v.baseline); validPackage(v.reviewPackage);
934
- need(v.reviewPackage.packageDigest===v.expectedDigest,'package_mismatch');
1002
+ need(v.reviewPackage.version===reviewPackageVersion(v.baseline)&&v.reviewPackage.packageDigest===v.expectedDigest,'package_mismatch');
935
1003
  need(Object.hasOwn(v.reviewPackage,'specification')===Object.hasOwn(v.baseline,'specification'),'package_mismatch');
936
1004
  need(Object.hasOwn(v.reviewPackage,'handoff')===Object.hasOwn(v,'handoffPath'),'package_mismatch');
937
1005
  need(digest(v.reviewPackage.ignorePolicy??null)===digest(v.baseline.ignorePolicy??null),'package_mismatch');
938
1006
  let current=createReviewPackage({root:v.root,baseline:v.baseline,checks:v.checks,
939
1007
  ...(Object.hasOwn(v,'handoffPath')?{handoffPath:v.handoffPath}:{})});
940
1008
  // Rebuild the historical representation for legacy receipts, without rewriting them.
941
- if(!Object.hasOwn(v.reviewPackage,'unchangedScope')){
1009
+ if(v.reviewPackage.version===1&&!Object.hasOwn(v.reviewPackage,'unchangedScope')){
942
1010
  const {unchangedScope,packageDigest,...legacy}=current;
943
1011
  current=sealed(legacy,'packageDigest');
944
1012
  }
@@ -952,13 +1020,13 @@ export function verifyCompletionReviewPackage(options) {
952
1020
  const v=plain(options);keys(v,['root','baseline','checks','reviewPackage','expectedDigest',
953
1021
  ...(Object.hasOwn(v,'handoffPath')?['handoffPath']:[])]);
954
1022
  hex(v.expectedDigest);validBaseline(v.baseline);validPackage(v.reviewPackage);
955
- need(v.reviewPackage.packageDigest===v.expectedDigest,'package_mismatch');
1023
+ need(v.reviewPackage.version===reviewPackageVersion(v.baseline)&&v.reviewPackage.packageDigest===v.expectedDigest,'package_mismatch');
956
1024
  need(Object.hasOwn(v.reviewPackage,'specification')===Object.hasOwn(v.baseline,'specification'),'package_mismatch');
957
1025
  need(Object.hasOwn(v.reviewPackage,'handoff')===Object.hasOwn(v,'handoffPath'),'package_mismatch');
958
1026
  need(digest(v.reviewPackage.ignorePolicy??null)===digest(v.baseline.ignorePolicy??null),'package_mismatch');
959
1027
  let current=createReviewPackage({root:v.root,baseline:v.baseline,checks:v.checks,
960
1028
  ...(Object.hasOwn(v,'handoffPath')?{handoffPath:v.handoffPath}:{})});
961
- if(!Object.hasOwn(v.reviewPackage,'unchangedScope')){
1029
+ if(v.reviewPackage.version===1&&!Object.hasOwn(v.reviewPackage,'unchangedScope')){
962
1030
  const {unchangedScope,packageDigest,...legacy}=current;
963
1031
  current=sealed(legacy,'packageDigest');
964
1032
  }
@@ -25,7 +25,7 @@ const driftInstruction='这些文件与直接前驱运行开工前的基线不
25
25
 
26
26
  function verifyOldCodeBaseline(codeProject,rawBaseline){
27
27
  // Legacy journals without a complete V2 inventory cannot prove code drift.
28
- if(rawBaseline?.version!==2)return [];
28
+ if(![2,3].includes(rawBaseline?.version))return [];
29
29
  const baseline=readReviewBaseline(rawBaseline);
30
30
  let current;
31
31
  try{
@@ -60,7 +60,7 @@ export function readIntegrationPlan(raw){
60
60
 
61
61
  function bindTarget(plan,baseline,parentPackage,records){
62
62
  const base=readReviewBaseline(baseline),pkg=readReviewPackage(parentPackage),target=plan.target;
63
- need(base.version===2&&pkg.baseIdentity===base.baselineDigest&&pkg.rootDigest===base.rootDigest,'integration_binding_mismatch');
63
+ need(base.version>=2&&pkg.baseIdentity===base.baselineDigest&&pkg.rootDigest===base.rootDigest,'integration_binding_mismatch');
64
64
  equal(pkg.identity,base.identity);equal(target.identity,pkg.identity);
65
65
  need(target.rootDigest===base.rootDigest&&target.baselineDigest===base.baselineDigest
66
66
  &&target.packageDigest===pkg.packageDigest&&target.recordCount===records.length
@@ -0,0 +1,153 @@
1
+ // Link material binds the directory entry itself. It never opens the referent.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {createHash} from 'node:crypto';
5
+ import {need,shape,hex} from './effect-contract.mjs';
6
+
7
+ export const SYMLINK_BASELINE_VERSION=3;
8
+ export const reviewPackageVersion=baseline=>baseline.version===SYMLINK_BASELINE_VERSION?2:1;
9
+ const utf8=new TextDecoder('utf8',{fatal:true,ignoreBOM:true});
10
+ const inside=(root,file)=>file===root||file.startsWith(root+path.sep);
11
+ const validTargetText=target=>typeof target==='string'&&target.length>0&&!target.includes('\0')
12
+ &&utf8.decode(Buffer.from(target))===target;
13
+
14
+ export function symlinkRecord(file,target){
15
+ need(validTargetText(target),'unsupported_file');
16
+ return {path:file,type:'symlink',target,size:Buffer.byteLength(target),
17
+ sha256:createHash('sha256').update('symlink\0').update(target).digest('hex')};
18
+ }
19
+
20
+ export function readSymlinkRecord(root,file){
21
+ const absolute=path.join(root,file);
22
+ const stat=()=>fs.lstatSync(absolute,{bigint:true});
23
+ const key=s=>[s.dev,s.ino,s.mode,s.size,s.ctimeNs,s.mtimeNs].join(':');
24
+ const before=stat();
25
+ need(before.isSymbolicLink(),'snapshot_changed');
26
+ const bytes=fs.readlinkSync(absolute,{encoding:'buffer'});
27
+ need(key(before)===key(stat())&&BigInt(bytes.length)===before.size,'snapshot_changed');
28
+ let target;
29
+ try{target=utf8.decode(bytes);}catch{need(false,'unsupported_file');}
30
+ return symlinkRecord(file,target);
31
+ }
32
+
33
+ export function validateSymlinkRecord(file){
34
+ shape(file,['path','type','target','size','sha256']);
35
+ const expected=symlinkRecord(file.path,file.target);
36
+ need(file.type===expected.type&&file.size===expected.size&&file.sha256===expected.sha256);
37
+ }
38
+
39
+ export function lstatOrMissing(file){
40
+ try{return fs.lstatSync(file);}catch(error){if(error.code==='ENOENT')return null;throw error;}
41
+ }
42
+
43
+ // Root-to-leaf checks also see dangling links and stop before probing their children.
44
+ export function assertRealParents(root,file,stat=relative=>lstatOrMissing(path.join(root,relative))){
45
+ const parts=file.split('/');
46
+ need(parts.every(part=>part&&part!=='.'&&part!=='..'&&!/[\\\0]/.test(part)),'unsupported_path');
47
+ let cursor='';
48
+ for(const part of parts.slice(0,-1)){
49
+ cursor=cursor?cursor+'/'+part:part;
50
+ const info=stat(cursor);
51
+ if(info===null)return;
52
+ need(info.isDirectory(),'unsupported_path');
53
+ }
54
+ }
55
+
56
+ const projectedFile=Object.freeze({isFile:()=>true,isDirectory:()=>false});
57
+ const projectedDirectory=Object.freeze({isFile:()=>false,isDirectory:()=>true});
58
+ const projectedLink=Object.freeze({isFile:()=>false,isDirectory:()=>false});
59
+
60
+ // Overlay known file states on the disk. A write also creates missing parents.
61
+ export function projectedPathStat(root,paths){
62
+ const parents=new Set();
63
+ for(const [file,type] of paths){
64
+ if(type===null)continue;
65
+ const parts=file.split('/');
66
+ while(parts.length>1){parts.pop();parents.add(parts.join('/'));}
67
+ }
68
+ return file=>{
69
+ if(paths.has(file)){
70
+ const type=paths.get(file);
71
+ return type===null?null:type==='symlink'?projectedLink:projectedFile;
72
+ }
73
+ return lstatOrMissing(path.join(root,file))??(parents.has(file)?projectedDirectory:null);
74
+ };
75
+ }
76
+
77
+ // Two proposed file entries cannot also make one of them the other's parent.
78
+ export function assertDisjointEditPaths(files){
79
+ const names=new Set(files.map(file=>file.toLowerCase()));
80
+ for(const file of names){
81
+ const parts=file.split('/');
82
+ while(parts.length>1){
83
+ parts.pop();
84
+ need(!names.has(parts.join('/')),'unsupported_path');
85
+ }
86
+ }
87
+ }
88
+
89
+ export function validateSymlinkTargetText(target){
90
+ need(validTargetText(target)&&Buffer.byteLength(target)<=1024&&!target.includes('\\')
91
+ &&!path.posix.isAbsolute(target)&&!path.win32.isAbsolute(target)&&!/^[a-z]:/i.test(target),'invalid_symlink_target');
92
+ }
93
+
94
+ // Resolve POSIX link text one component at a time. Checking components before
95
+ // applying ".." prevents normalization from hiding a link or protected directory.
96
+ export function resolveSymlinkTarget(root,file,target,{specsRoot=null,stat=null}={}){
97
+ const validateTarget=stat!==null;
98
+ if(validateTarget)validateSymlinkTargetText(target);
99
+ else need(validTargetText(target)&&!path.posix.isAbsolute(target)&&!path.win32.isAbsolute(target)
100
+ &&!/^[a-z]:/i.test(target),'symlink_outside_root');
101
+ const parts=file.split('/').slice(0,-1);
102
+ const protectedSpecs=specsRoot?.toLowerCase();
103
+ const checkLocation=relative=>{
104
+ const absolute=path.join(root,relative);
105
+ need(!parts.some(name=>['.git','.reviews'].includes(name.toLowerCase()))
106
+ &&!(protectedSpecs&&inside(protectedSpecs,absolute.toLowerCase()))
107
+ &&relative.toLowerCase()!==file.toLowerCase(),'invalid_symlink_target');
108
+ };
109
+ const segments=target.split('/');
110
+ for(const [index,part] of segments.entries()){
111
+ if(part==='..'){
112
+ need(parts.length>0,validateTarget?'invalid_symlink_target':'symlink_outside_root');
113
+ parts.pop();
114
+ }else if(part&&part!=='.'){
115
+ parts.push(part);
116
+ if(validateTarget){
117
+ const relative=parts.join('/');
118
+ checkLocation(relative);
119
+ const info=stat(relative);
120
+ need(info&&(info.isDirectory()||info.isFile()),'invalid_symlink_target');
121
+ if(!info.isDirectory())need(index===segments.length-1,'invalid_symlink_target');
122
+ }
123
+ }
124
+ }
125
+ const relative=parts.join('/');
126
+ if(validateTarget){
127
+ checkLocation(relative);
128
+ const info=relative===''?fs.lstatSync(root):stat(relative);
129
+ need(info&&(info.isDirectory()||info.isFile()),'invalid_symlink_target');
130
+ }
131
+ return path.join(root,relative);
132
+ }
133
+
134
+
135
+ export function validateProtectedEdit(edit,allowSymlinks=false){
136
+ if(Object.hasOwn(edit,'symlink')){
137
+ need(allowSymlinks,'protected_edit_invalid');
138
+ shape(edit,['path','beforeSha256','symlink']);
139
+ validateSymlinkTargetText(edit.symlink);
140
+ }else{
141
+ shape(edit,['path','beforeSha256','content',...(Object.hasOwn(edit,'mode')?['mode']:[])]);
142
+ need(!Object.hasOwn(edit,'mode')||edit.content!==null&&['0644','0755'].includes(edit.mode),'protected_edit_invalid');
143
+ need(edit.content===null||typeof edit.content==='string','protected_edit_invalid');
144
+ need(edit.content===null||Buffer.byteLength(edit.content)<=1024*1024,'limit_exceeded');
145
+ need(edit.content!==null||edit.beforeSha256!==null,'protected_edit_invalid');
146
+ }
147
+ if(edit.beforeSha256!==null)hex(edit.beforeSha256);
148
+ }
149
+
150
+ export function protectedEditDigest(edit){
151
+ if(Object.hasOwn(edit,'symlink'))return symlinkRecord(edit.path,edit.symlink).sha256;
152
+ return edit.content===null?null:createHash('sha256').update(edit.content).digest('hex');
153
+ }