@tnunamak/dalan 0.8.5 → 0.9.0

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.
@@ -438,8 +438,9 @@ export function validateNamedCheckTargets(namedPaths, scan, outputSet) {
438
438
  throw namedCheckError(`entry ${index+1}: pin a revision with the regular test file, or declare a new file in output_paths`,index+1);
439
439
  }
440
440
  }
441
- export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanInput,warnings=null,excludeSensitive=false,review=false,worker}={}) {
441
+ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanInput,warnings=null,excludeSensitive=false,review=false,worker,inheritedExclusions=[],allowPagedReadScope=false,pagedReadPrior=null}={}) {
442
442
  const warn=message=>{if(warnings&&!warnings.includes(message)) warnings.push(message);};
443
+ if(assignment&&Object.hasOwn(assignment,'paged_read_scope')) throw new Error('only the bridge can record a paged read scope');
443
444
  let p;
444
445
  try { p=loadPolicy(); } catch(error) { throw infrastructureError(error.message); }
445
446
  let rendered=renderAssignment(assignment);
@@ -451,7 +452,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
451
452
  const total=instructionBytes(r);
452
453
  if(total>submissionLimits.instructions) throw Object.assign(new Error(`task instructions: ${total} UTF-8 bytes exceeds ${submissionLimits.instructions}; cut at least ${total-submissionLimits.instructions} bytes`),{expandedPayload:r});
453
454
  };
454
- checkInstructionSize(rendered);
455
+ checkInstructionSize(pagedReadPrior?{...rendered,scope_paths:[]}:rendered);
455
456
  if([authority,grantedAuthority].some(pattern=>pattern.test([rendered.brief,rendered.expected_output,scopeText].join('\n')))) throw new Error('live-slot or expanded-authority claim in instructions');
456
457
  if(hasSecretContent(rendered)) throw new Error('hard sensitive content exclusion');
457
458
  // Labelled values are medium precision: every output sink masks them, so intake warns instead of refusing.
@@ -487,9 +488,14 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
487
488
  const rule=entry?'owner sensitive_paths entry '+entry:'soft sensitive name: '+(/auth/i.test(base)?'auth':/secret/i.test(base)?'secret':/credential/i.test(base)?'credential':/(?:^|[_.-])sign(?:ing|ature)?(?=[_.-]|$)/i.test(base)?'signing':'credential-style token name');
488
489
  return sensitivePathError(`sensitive scope path: ${file}; ${rule}; rename the file or redact it and give it a name that does not look like a secret, or leave it out of scope_paths`,file);
489
490
  };
491
+ const priorOmittedPaths=new Set(inheritedExclusions.map(entry=>entry.path));
492
+ const priorExcluded=new Set([...priorOmittedPaths].map(outputPathKeys[3]));
490
493
  function inspectPath(file) {
491
494
  // A router group cannot hide a sensitive name: `(x).env` is also checked as `.env`.
492
495
  if(hardSensitive(file)) throw sensitivePathError(`hard sensitive path exclusion: ${file}`,file);
496
+ const parts=outputPathKeys[3](file).split('/');
497
+ if(priorExcluded.size&&parts.some((_,i)=>priorExcluded.has(parts.slice(0,i+1).join('/'))))
498
+ throw sensitivePathError(`sensitive scope path: ${file}; the prior assignment excluded this path`,file);
493
499
  if((softName(file)||policyEntry(file))&&(!exception||file!==exception.path)) throw sensitiveRefusal(file);
494
500
  }
495
501
  for(const file of scope) inspectPath(file);
@@ -505,6 +511,23 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
505
511
  }
506
512
  }
507
513
  const outputSet=new Set(outputs);
514
+ const canPage=allowPagedReadScope&&excludeSensitive&&sensitiveScopeOverride===null&&rendered.execution_scope==='read-only'&&
515
+ !outputs.length&&input&&input.input_patch===undefined&&(!input.head_sha||input.head_sha===input.base_sha);
516
+ if(pagedReadPrior) {
517
+ const prior=assignmentInput(pagedReadPrior),priorFiles=new Set(pagedReadPrior.scope_paths);
518
+ if(!canPage||input.github_repo!==prior.github_repo||input.base_sha!==prior.base_sha||scope.some(file=>!priorFiles.has(file))) {
519
+ throw new Error('a correction must keep the pinned revision and stay within the prior paged read scope');
520
+ }
521
+ }
522
+ const paged=(files)=>{
523
+ const note='Use list_files to see the approved files. Use read_file to read them at the pinned revision.';
524
+ const brief=rendered.brief.includes(note)?rendered.brief:`${rendered.brief}\n\n${note}`;
525
+ cap(brief,submissionLimits.brief,'brief');
526
+ const result={...rendered,brief,scope_paths:files,paged_read_scope:true,
527
+ ...(rendered.read_list!==undefined?{read_list:files}:{}),...(rendered.read_paths!==undefined?{read_paths:files}:{})};
528
+ checkInstructionSize({...result,scope_paths:[]});
529
+ return result;
530
+ };
508
531
  const namedPaths=submissionNamedCheckPaths(rendered,{review,policyPaths:p.sensitive_paths});
509
532
  // Unified-diff /dev/null markers are sentinels, not filesystem requests. An exact exclusion diagnostic grants no
510
533
  // read permission. Keep scanning its content for secrets above and checking scope/diff paths below; remove only
@@ -541,7 +564,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
541
564
  // Every implementation directory keeps its write grant while withholding sensitive files.
542
565
  // This must not depend on an opt-in: the worker receives no access to hard or soft secret paths.
543
566
  const withholdImplementation=rendered.execution_scope==='implementation';
544
- const dropped=[];let narrowedScope=null;
567
+ const dropped=input?[...inheritedExclusions]:[];let narrowedScope=null;
545
568
  const firstPass=mentionedPaths(text,scope);
546
569
  for(const file of firstPass) {
547
570
  const bare=bareToken(file)&&!firstPass.explicit.has(file);
@@ -566,7 +589,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
566
589
  // A free-form read-only or review assignment may grow its scope by the files its own brief names and its PR changes: the
567
590
  // submitter asked for them, each still passes inspectPath, and the workspace enforces the result. Implementation work,
568
591
  // structured briefs and explicit read lists keep the scope exactly as declared.
569
- const growable=(rendered.execution_scope==='read-only'||review)&&rendered.objective===undefined&&rendered.read_paths===undefined&&rendered.read_list===undefined&&!scope.includes('.');
592
+ const growable=!pagedReadPrior&&(rendered.execution_scope==='read-only'||review)&&rendered.objective===undefined&&rendered.read_paths===undefined&&rendered.read_list===undefined&&!scope.includes('.');
570
593
  const added=[],undeclared=[],fixable=[],ambiguous=[],mentionedAs=new Map();
571
594
  // Review mode cannot write (apply_patch refuses review submissions), so growing a review assignment's scope adds read access only.
572
595
  const maxGrowth=200;
@@ -695,6 +718,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
695
718
  // sensitive files. Read-only directory scopes are narrowed to exclude them.
696
719
  // Named paths and patch paths still refuse above and below.
697
720
  for(const file of scan.files.filter(f=>within(f,scope)&&!scope.includes(f))) {
721
+ if(priorOmittedPaths.has(file)) continue;
698
722
  if(withholdImplementation&&withheldRepoPath(file,p.sensitive_paths)) {
699
723
  dropped.push({path:file,reason:isSensitiveRepoPath(file,p.sensitive_paths)?sensitiveReason(file):'sensitive ancestor directory (withheld)'});continue;
700
724
  }
@@ -719,9 +743,18 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
719
743
  if(!dropped.some(d=>d.path===file)) dropped.push({path:file,reason:'symlink (the workspace never follows symlinks)'});
720
744
  }
721
745
  }
722
- // A scope whose narrowing needs more than maxNarrowedEntries entries is refused (fail closed): keeping the broad scope
723
- // would rest on an exact-path exclusion that a case or Unicode alias on a case-insensitive filesystem can miss.
724
- if(dropped.length) narrowedScope=withholdImplementation?scope:narrowScope(scope,[...new Set([...scan.files,...scan.diffFiles])],dropped.map(d=>d.path));
746
+ if(dropped.length) {
747
+ try {
748
+ narrowedScope=withholdImplementation?scope:narrowScope(scope,[...new Set([...scan.files,...scan.diffFiles])],dropped.map(d=>d.path));
749
+ } catch(error) {
750
+ if(error.code!=='scope_representation_limit'||!canPage||scan.diff||scan.diffFiles.length||!Array.isArray(scan.regularFiles)) throw error;
751
+ // Persist exact approved files in the ordinary scope field. Older bridge
752
+ // binaries can enforce those paths without understanding paging.
753
+ const files=pagedReadFiles(scan.regularFiles,scope,dropped);
754
+ if(!files?.length) throw error;
755
+ return paged(files);
756
+ }
757
+ }
725
758
  for(const file of scan.symlinks||[]) if(within(file,narrowedScope??scope)&&!dropped.some(d=>d.path===file)) throw new Error(`symlink in repository scope: ${file}`);
726
759
  const inspectPatchPath=file=>{
727
760
  inspectPath(file);
@@ -751,6 +784,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
751
784
  if(input.input_patch&&!/^diff --git /m.test(input.input_patch)) throw new Error('incomplete input patch');
752
785
  } else if(scope.length) throw new Error('scope_paths require pinned repository input');
753
786
  // Persist exactly the normalized scope used above, including the no-growth path.
787
+ if(pagedReadPrior) return paged(scope);
754
788
  const stored=rendered.scope_paths,same=Array.isArray(stored)&&stored.length===scope.length&&stored.every((path,i)=>path===scope[i]);
755
789
  const normalized=!same&&(stored!==undefined||scope.length>0)?{...rendered,scope_paths:[...scope]}:rendered;
756
790
  if(!dropped.length) {const done=withOutputPaths(withAllowList(normalized,warn));checkInstructionSize(done);return done;}
@@ -772,6 +806,23 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
772
806
  // The scope entries that cover every file under `scope` except `bad`: a directory with no bad file below it stays whole, one with
773
807
  // a bad file is replaced by its children. Throws when that needs more entries than a scope should hold.
774
808
  const maxNarrowedEntries=200;
809
+ function pagedReadFiles(regularFiles,scope,dropped) {
810
+ const key=path=>path.normalize('NFC').toLowerCase();
811
+ const excluded=new Set(dropped.map(entry=>key(entry.path)));
812
+ const parents=new Set();
813
+ for(const path of excluded) {
814
+ for(let i=path.indexOf('/');i>=0;i=path.indexOf('/',i+1)) parents.add(path.slice(0,i));
815
+ }
816
+ const matchesExcluded=path=>{
817
+ if(parents.has(path)||excluded.has(path)) return true;
818
+ for(let i=path.indexOf('/');i>=0;i=path.indexOf('/',i+1)) if(excluded.has(path.slice(0,i))) return true;
819
+ return false;
820
+ };
821
+ const files=regularFiles.filter(path=>within(path,scope)&&!matchesExcluded(key(path)));
822
+ if(files.some(path=>!isLiteralScopePath(path)||path.split('/').some(part=>part.toLowerCase()==='.git')||hasSecretContent(path))) return null;
823
+ // Bound the persisted and machine-readable list independently of the brief.
824
+ return bytes(JSON.stringify(files))<=256*1024?files:null;
825
+ }
775
826
  export function narrowScope(scope,files,bad) {
776
827
  const badSet=new Set(bad),badDirs=new Set(),children=new Map(),add=(dir,child)=>{if(!children.has(dir)) children.set(dir,new Set());children.get(dir).add(child);};
777
828
  for(const file of files) {
@@ -789,7 +840,7 @@ export function narrowScope(scope,files,bad) {
789
840
  for(const entry of scope) visit(entry==='.'?'':entry);
790
841
  const narrowed=[...new Set(out)];
791
842
  if(!narrowed.length) throw sensitivePathError(`sensitive scope path: ${bad[0]} (every file in the scope is sensitive)`,bad[0]);
792
- if(narrowed.length>maxNarrowedEntries) throw new Error(`sensitive scope path: ${bad[0]} (too many files to exclude from ${scope.map(s=>`"${s}"`).join(', ')}: dropping ${bad.length} sensitive file(s) would need ${narrowed.length} scope entries, over the ${maxNarrowedEntries} limit; submit a narrower scope that avoids them)`);
843
+ if(narrowed.length>maxNarrowedEntries) throw Object.assign(new Error(`sensitive scope path: ${bad[0]} (too many files to exclude from ${scope.map(s=>`"${s}"`).join(', ')}: dropping ${bad.length} sensitive file(s) would need ${narrowed.length} scope entries, over the ${maxNarrowedEntries} limit; submit a narrower scope that avoids them)`),{code:'scope_representation_limit'});
793
844
  const unnameable=narrowed.find(entry=>{try{paths([entry],'scope_paths');return false;}catch{return true;}});
794
845
  if(unnameable!==undefined) throw new Error(`sensitive scope path: ${bad[0]} (cannot narrow the scope: ${unnameable} has a name that scope_paths cannot hold; exclude it or name the files you want)`);
795
846
  return paths(narrowed,'scope_paths');
@@ -249,6 +249,8 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
249
249
  if (keyError) done('invalid_arguments', new RegistryError('invalid_arguments', keyError));
250
250
  const config = JSON.parse(row.handler);
251
251
  const impl = handlers[config.kind];
252
+ if (impl?.requireCurrentRead && key !== undefined)
253
+ done('invalid_arguments', new RegistryError('invalid_arguments', 'omit idempotency_key for live reads'));
252
254
  const call = { tool: row.name, worker: name, args, config, now, idempotencyKey: key, context };
253
255
  const assertArguments = () => {
254
256
  const errors = validateValue(JSON.parse(row.input_schema), args);
@@ -272,6 +274,8 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
272
274
  if (authority.error || binding === undefined) return authority;
273
275
  const scoped = claimAuthority();
274
276
  if (scoped.error || scoped.binding === binding) return scoped;
277
+ if (impl.requireCurrentRead)
278
+ return { outcome: 'authorization_failed', error: new RegistryError('authorization_failed', 'the claim changed during the read') };
275
279
  return { outcome: 'idempotency_conflict', error: new RegistryError('idempotency_conflict', 'the call no longer belongs to the same claim authority') };
276
280
  };
277
281
  const mayRetakePending = callClass === 'read' || (impl?.recoverPendingWrite === true && binding !== undefined);
@@ -358,6 +362,8 @@ export function createToolRegistry({ store, now = store.nowMs, handlers = {}, au
358
362
  settle({ ok: false, code: 'handler_failed', message, retryable: error?.notDelivered === true });
359
363
  done('handler_failed', new RegistryError('handler_failed', message));
360
364
  }
365
+ // Replies containing current private data may not outlive the grant that permitted the read.
366
+ if (impl?.requireCurrentRead) deny(latestAuthority());
361
367
  const capped = capResult(result);
362
368
  settle({ ok: true, result: capped });
363
369
  done('ok');
package/src/workspace.mjs CHANGED
@@ -114,7 +114,7 @@ function closedWorkspace(a,requestId,claimId,claimEpoch,currentEpoch) {
114
114
  }
115
115
  const CHECK_GUIDANCE='run_check runs a listed check in the bridge sandbox on this claim\'s workspace, with your applied patches. It does not run on your machine. Call run_check with check_id (not check or name) after apply_patch and before finish. Its receipt is bridge-verified evidence; a test you ran yourself is not. available_check_details says what each id runs. If you finish with a patch and have not run the default check on it, the bridge runs default itself before it stores your report.';
116
116
  function git(args,opts={}) { const r=spawnSync('git',args,{encoding:'utf8',timeout:10000,maxBuffer:12*1024*1024,...opts,env:gitEnv(opts.env)}); if(r.error||r.status!==0) throw new Error(`git failed: ${(r.stderr||r.error?.message||'').slice(0,300)}`); return r.stdout; }
117
- function relative(p,allowDot=false) { if (allowDot && (p===undefined||p==='')) return ''; if(typeof p!=='string'||!p||Buffer.byteLength(p)>1024||p.includes('\0')||path.isAbsolute(p)||p.split('/').some(x=>!x||x==='.'||x==='..'||x==='.git'||x.includes('\\'))) throw new Error('invalid project-relative path'); return p; }
117
+ function relative(p,allowDot=false) { if (allowDot && (p===undefined||p==='')) return ''; if(typeof p!=='string'||!p||Buffer.byteLength(p)>1024||p.includes('\0')||path.isAbsolute(p)||p.split('/').some(x=>!x||x==='.'||x==='..'||x.toLowerCase()==='.git'||x.includes('\\'))) throw new Error('invalid project-relative path'); return p; }
118
118
  function safePath(dir,p,existing=false) { p=relative(p); let cursor=dir; for(const part of p.split('/')) { cursor=path.join(cursor,part); try { if(fs.lstatSync(cursor).isSymbolicLink()) throw new Error('symlink traversal denied'); } catch(e) { if(e.code!=='ENOENT') throw e; if(existing) throw new Error('file not found'); } } return cursor; }
119
119
  // scope_paths is the assignment's read/write allow-list (submission-policy `within`). No scope_paths, or the repo-wide
120
120
  // scope ".", means unrestricted, as before. Entries are normalised the same way submission-policy normalises them.
@@ -127,6 +127,15 @@ export const isExcludedPath=(p,excluded)=>{const parts=canonicalPath(p).split('/
127
127
  function scopeOf(assignment) {
128
128
  const raw=assignment.scope_paths, excluded=new Set((assignment.scope_excluded||[]).map(d=>canonicalPath(d.path)));
129
129
  const scope=Array.isArray(raw)&&raw.length?raw.map(p=>String(p).replace(/^\.\//,'').replace(/\/$/,'')):[];
130
+ if(assignment.paged_read_scope===true) {
131
+ const files=new Set(scope),dirs=new Set();
132
+ for(const file of files) {
133
+ for(let i=file.indexOf('/');i>=0;i=file.indexOf('/',i+1)) dirs.add(file.slice(0,i));
134
+ }
135
+ const sensitive=sensitivePolicyPaths();
136
+ if(sensitive.error) throw new Error('sensitive_policy_unavailable');
137
+ return {files,dirs,excluded,outputs:new Set(),sensitive};
138
+ }
130
139
  const paths=!scope.length||scope.includes('.')?null:scope;
131
140
  const outputs=outputsOf(assignment);
132
141
  const sensitive=assignment.execution_scope==='implementation'&&excluded.size?sensitivePolicyPaths():null;
@@ -144,9 +153,10 @@ function existsAtHead(dir,file) {
144
153
  if(r.error||r.status!==0) throw new Error(`git ls-tree failed: ${(r.stderr||r.error?.message||'').slice(0,200)}`);
145
154
  return r.stdout.length>0;
146
155
  }
147
- const inScope=(p,scope)=>!scope||(!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded)&&(!scope.sensitive||scope.paths?.includes(p)||!isSensitiveRepoPath(p,scope.sensitive.paths));
156
+ const inScope=(p,scope)=>!scope||(scope.files?scope.files.has(p):!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded)&&(!scope.sensitive||scope.paths?.includes(p)||!isSensitiveRepoPath(p,scope.sensitive.paths));
148
157
  // A directory that holds a scope entry may be listed so the walk can reach it.
149
- const leadsToScope=(p,scope)=>!scope||!scope.paths||inScope(p,scope)||scope.paths.some(s=>s.startsWith(`${p}/`))||[...scope.outputs].some(o=>o.startsWith(`${p}/`));
158
+ const leadsToScope=(p,scope)=>!scope||!isExcludedPath(p,scope.excluded)&&
159
+ (scope.files?scope.dirs.has(p)||inScope(p,scope):!scope.paths||inScope(p,scope)||scope.paths.some(s=>s.startsWith(`${p}/`))||[...scope.outputs].some(o=>o.startsWith(`${p}/`)));
150
160
  function outputDirectoryHint(file,outputs) {
151
161
  const parent=[...outputs].find(p=>file.startsWith(`${p}/`));
152
162
  return parent?` output_paths entry ${parent} names one new file, not a directory. List each new file in output_paths (for example ${file}); ask the owner to resubmit with the exact file paths.`:'';
@@ -157,7 +167,7 @@ function realRelative(dir,file,fallback) { try { const rel=path.relative(fs.real
157
167
  function requireScope(p,scope) { if(!inScope(p,scope)) throw new Error(`path outside scope_paths: ${p}${outputDirectoryHint(p,scope?.outputs??[])}`); }
158
168
  // Walk from `start` and stop at `max` files. Large repos used to throw 'file tree limit' on every call,
159
169
  // so the worker could not list anything; now it gets the first `max` files and truncated:true.
160
- export function guardedFiles(dir,start='',max=2000,scope=null,after='') { const out=[];let truncated=false,passed=!after; function walk(base,depth) { if(out.length>=max) { truncated=true; return; } if(depth>16) { truncated=true; return; } const entries=fs.readdirSync(path.join(dir,base),{withFileTypes:true}).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0); for(const ent of entries) { if(out.length>=max) { truncated=true; return; } if(ent.name==='.git') continue; const rel=base?`${base}/${ent.name}`:ent.name; if(ent.isSymbolicLink()) continue; if(ent.isDirectory()) { if(leadsToScope(rel,scope)) walk(rel,depth+1); } else if(ent.isFile()&&inScope(rel,scope)) { if(!passed) { if(rel===after) passed=true; } else out.push(rel); } } } if(start&&!fs.lstatSync(path.join(dir,start)).isDirectory()) return {files:inScope(start,scope)?[start]:[],truncated:false}; walk(start,0); if(!passed) throw new Error('cursor not found: list again from the start'); return {files:out,truncated}; }
170
+ export function guardedFiles(dir,start='',max=2000,scope=null,after='') { const out=[];let truncated=false,passed=!after; function walk(base,depth) { if(out.length>=max) { truncated=true; return; } if(depth>16) { truncated=true; return; } const entries=fs.readdirSync(path.join(dir,base),{withFileTypes:true}).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0); for(const ent of entries) { if(out.length>=max) { truncated=true; return; } if(ent.name.toLowerCase()==='.git') continue; const rel=base?`${base}/${ent.name}`:ent.name; if(ent.isSymbolicLink()) continue; if(ent.isDirectory()) { if(leadsToScope(rel,scope)) walk(rel,depth+1); } else if(ent.isFile()&&inScope(rel,scope)) { if(!passed) { if(rel===after) passed=true; } else out.push(rel); } } } if(start&&!fs.lstatSync(path.join(dir,start)).isDirectory()) return {files:inScope(start,scope)?[start]:[],truncated:false}; walk(start,0); if(!passed) throw new Error('cursor not found: list again from the start'); return {files:out,truncated}; }
161
171
  function patchPaths(patch) {
162
172
  const found=[];let current=null,inHeader=false,oldHeader=false,newHeader=false;
163
173
  for(const line of patch.split('\n')) {
@@ -492,6 +502,79 @@ export function excludedPathsAccountedAtBase(mirror,assignment) {
492
502
  try { excluded=new Set(assignment.scope_excluded.map(entry=>relative(entry.path))); } catch { return false; }
493
503
  return listed.stdout.split('\0').filter(file=>file&&!excluded.has(file)).every(file=>!withheldRepoPath(file,policy.paths));
494
504
  }
505
+ // Internal producer only: the caller must supply a persisted, validated assignment
506
+ // and its trusted mirror. Do not accept a request-supplied path/ref or reuse checkout files.
507
+ export const SCOPED_SOURCE_MAX_BYTES=512*1024;
508
+ export function pinnedScopedSource(mirror,assignment) {
509
+ if(assignment.paged_read_scope===true) throw new Error('paged read scope does not support artifacts');
510
+ const pin=assignmentInput(assignment).base_sha;
511
+ if(typeof pin!=='string'||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(pin)||
512
+ !Array.isArray(assignment.scope_paths)||!assignment.scope_paths.length)
513
+ throw new Error('validated pinned source scope required');
514
+ const scope=scopeOf({...assignment,output_paths:[]});
515
+ const policy=sensitivePolicyPaths();
516
+ if(policy.error) throw new Error('sensitive_policy_unavailable');
517
+ const env={...gitEnv(),GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1',GIT_OPTIONAL_LOCKS:'0'};
518
+ const readGit=(args,maxBuffer,input)=>spawnSync('git',['-C',mirror,...args],{env,timeout:3000,maxBuffer,input});
519
+ const anchor=readGit(['cat-file','-t',pin],1024);
520
+ if(anchor.status!==0||anchor.stdout.toString().trim()!=='commit')
521
+ throw new Error('pinned source commit unavailable');
522
+ const tree=readGit(['ls-tree','-rlz','--full-tree',pin],16*1024*1024);
523
+ if(tree.error||tree.status!==0) throw new Error('pinned source tree unavailable');
524
+ const decoder=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
525
+ const entries=[],spellings=new Map();
526
+ let total=0,offset=0;
527
+ while(offset<tree.stdout.length) {
528
+ const end=tree.stdout.indexOf(0,offset);
529
+ if(end<0) throw new Error('invalid pinned source tree');
530
+ const entry=tree.stdout.subarray(offset,end);
531
+ offset=end+1;
532
+ const tab=entry.indexOf(9);
533
+ if(tab<0) throw new Error('invalid pinned source tree');
534
+ const meta=/^100(?:644|755) blob ([a-f0-9]+) +(\d+)$/.exec(entry.subarray(0,tab).toString('ascii'));
535
+ if(!meta||meta[1].length!==pin.length) continue;
536
+ let file;
537
+ try { file=relative(decoder.decode(entry.subarray(tab+1))); } catch { continue; }
538
+ if(file.split('/').some(part=>/[:]|[. ]$/.test(part))||canonicalPath(file).split('/').some(part=>part==='.git'||part==='.gitmodules')||!inScope(file,scope)||
539
+ withheldRepoPath(file,policy.paths)||secretContent.test(file)) continue;
540
+ const parts=file.split('/');
541
+ for(let i=1;i<=parts.length;i++) {
542
+ const spelling=parts.slice(0,i).join('/'),key=canonicalPath(spelling);
543
+ if(spellings.has(key)&&spellings.get(key)!==spelling) throw new Error('pinned source paths collide');
544
+ spellings.set(key,spelling);
545
+ }
546
+ const length=Number(meta[2]);
547
+ total+=length;
548
+ if(entries.length>=256||total>SCOPED_SOURCE_MAX_BYTES) throw new Error('pinned source snapshot exceeds limits');
549
+ entries.push({file,oid:meta[1],length});
550
+ }
551
+ const files=[],blobs=new Map();
552
+ const manifest={schema_version:1,pin,scope_complete:false,files};
553
+ if(!entries.length) return {manifest,blobs};
554
+ const batch=readGit(['cat-file','--batch'],total+entries.length*96,entries.map(entry=>entry.oid).join('\n')+'\n');
555
+ if(batch.error||batch.status!==0) throw new Error('pinned source blob unavailable');
556
+ let cursor=0;
557
+ for(const {file,oid,length} of entries) {
558
+ const header=Buffer.from(`${oid} blob ${length}\n`);
559
+ if(!batch.stdout.subarray(cursor,cursor+header.length).equals(header)) throw new Error('invalid pinned source batch');
560
+ cursor+=header.length;
561
+ const bytes=batch.stdout.subarray(cursor,cursor+length);
562
+ cursor+=length;
563
+ if(batch.stdout[cursor++]!==10) throw new Error('invalid pinned source batch');
564
+ if(bytes.includes(0)) continue;
565
+ let content;
566
+ try { content=decoder.decode(bytes); } catch { continue; }
567
+ if(secretContent.test(content)||redactSecrets(content).redacted) continue;
568
+ files.push({path:file,length,sha256:sha(bytes)});
569
+ blobs.set(file,bytes);
570
+ }
571
+ if(cursor!==batch.stdout.length) throw new Error('invalid pinned source batch');
572
+ // Claim completeness only for an exact file list. Directory scopes always
573
+ // describe the approved subset without disclosing whether paths were withheld.
574
+ manifest.scope_complete=Boolean(scope?.paths?.length&&!scope.excluded.size&&scope.paths.every(file=>blobs.has(file)));
575
+ return {manifest,blobs};
576
+ }
577
+
495
578
  // A list shown in the receipt: the first `shown` names, the true total, and a flag when the preview is shorter than the total.
496
579
  const preview=(list,shown)=>list===null?null:({preview:list.slice(0,shown),total:list.length,truncated:list.length>shown});
497
580
  // The lists go to one bounded artifact; null when every list is empty. The cap counts the serialized JSON, envelope and separators
@@ -614,7 +697,9 @@ export class Workspace {
614
697
  const {dir,a}=this.ensure(requestId,claimId,subject,false,worker),scope=scopeOf(a.assignment);
615
698
  relative(p,true);
616
699
  if(p&&!leadsToScope(p,scope)) throw new Error(`path outside scope_paths: ${p}`);
617
- const missing=p&&!fs.lstatSync(safePath(dir,p),{throwIfNoEntry:false});
700
+ const start=p?safePath(dir,p):null;
701
+ if(start&&!leadsToScope(realRelative(dir,start,p),scope)) throw new Error(`path outside scope_paths: ${p}`);
702
+ const missing=start&&!fs.lstatSync(start,{throwIfNoEntry:false});
618
703
  const outputs=outputsOf(a.assignment);
619
704
  const creatable=(!cursor||missing)&&outputs.size?[...outputs].filter(output=>{
620
705
  if(!inScope(output,scope)||(p&&!output.startsWith(p+'/'))) return false;
@@ -1335,6 +1420,7 @@ export class Workspace {
1335
1420
  if(!this.store.mayAct(worker,requestId)) throw new Error('assignment not found');
1336
1421
  const a=this.store.get(requestId);this.store.assertClaim(requestId,claimId,subject,worker);
1337
1422
  if(a.status!=='claimed'||a.cancelled_at) throw closedWorkspace(a,requestId,claimId);
1423
+ if(a.assignment.paged_read_scope===true) throw new Error('paged read scope only supports listing and reading files');
1338
1424
  const artifacts=this.store.db.prepare("SELECT COALESCE(client_artifact_id,id) id,size,sha256 FROM artifacts WHERE request_id=? AND claim_id=? AND kind='upload' AND sealed=1").all(requestId,claimId);
1339
1425
  if(!a.assignment.inputs?.some(input=>input.github_repo)) return {checks:[],artifacts:artifacts};
1340
1426
  const {dir,input}=this.ensure(requestId,claimId,subject,true,worker);
@@ -1378,6 +1464,7 @@ export class Workspace {
1378
1464
  if(!this.store.mayAct(worker,requestId)) throw new Error('assignment not found');
1379
1465
  const a=this.store.get(requestId);this.store.assertClaim(requestId,claimId,subject,worker);
1380
1466
  if(a.status!=='claimed'||a.cancelled_at) throw closedWorkspace(a,requestId,claimId);
1467
+ if(a.assignment.paged_read_scope===true) throw new Error('paged read scope does not support artifacts');
1381
1468
  if(typeof id!=='string'||!/^art_[a-zA-Z0-9_-]{8,128}$/.test(id)) throw new Error('invalid artifact_id: must match art_ followed by 8 to 128 letters, digits, _ or -');
1382
1469
  if(!Number.isInteger(offset)||offset<0) throw new Error('invalid offset: must be a whole number, 0 or more, equal to the bytes stored so far');
1383
1470
  if(typeof base64!=='string') throw new Error('invalid data_base64: must be a string (an empty string is allowed)');