@tnunamak/dalan 0.8.1 → 0.8.2

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 (124) hide show
  1. package/CHANGELOG.md +59 -2
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +8 -12
  4. package/bin/dalan.mjs +25 -4
  5. package/bin/dot-acp-agent.mjs +572 -76
  6. package/bin/dot-alert.mjs +9 -3
  7. package/bin/dot-deadman.mjs +3 -1
  8. package/bin/dot-heartbeat.mjs +14 -7
  9. package/bin/dot-pr-reviewer.mjs +3 -31
  10. package/bin/dot-worker.mjs +121 -34
  11. package/contracts/adapter-qualification.schema.json +94 -7
  12. package/docs/chatgpt-worker-onboarding.md +1 -1
  13. package/docs/codex-to-muse.md +2 -2
  14. package/docs/connect-chatgpt.md +1 -1
  15. package/docs/connection-longevity.md +2 -2
  16. package/docs/dalan-upgrade.md +8 -5
  17. package/docs/deadman.md +4 -0
  18. package/docs/design/authority-matrix.md +18 -0
  19. package/docs/design/failure-table.md +87 -0
  20. package/docs/design/identities.md +22 -0
  21. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  22. package/docs/design/reuse-ledger.md +75 -0
  23. package/docs/design/target-architecture-v2.md +434 -0
  24. package/docs/local-agent-mcp.md +14 -0
  25. package/docs/local-agent-requester.md +2 -1
  26. package/docs/manual-setup.md +1 -1
  27. package/docs/operations.md +77 -14
  28. package/docs/pull-workers.md +11 -1
  29. package/docs/service-setup.md +10 -10
  30. package/docs/t3-integration.md +4 -2
  31. package/docs/t3-reverse-control.md +5 -5
  32. package/docs/test-suite-isolation.md +7 -6
  33. package/docs/trials/chatgpt-agent.md +47 -0
  34. package/docs/trials/claude-code-requester.md +68 -0
  35. package/docs/trials/muse.md +46 -0
  36. package/docs/usage.md +21 -7
  37. package/docs/worker-clients.md +1 -1
  38. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  39. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  40. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  41. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  42. package/package.json +4 -3
  43. package/packages/job-core/protocol/canonical.mjs +45 -7
  44. package/packages/job-core/transitions.mjs +4 -2
  45. package/scripts/upgrade-drain.mjs +96 -8
  46. package/scripts/worker-bridge-setup.mjs +215 -120
  47. package/src/ack-ledger.mjs +7 -1
  48. package/src/acp-bridge.mjs +256 -28
  49. package/src/admin-socket.mjs +32 -3
  50. package/src/alerts.mjs +17 -8
  51. package/src/answer-journal-retention.mjs +82 -0
  52. package/src/answer-journal.mjs +6 -4
  53. package/src/as-store.mjs +51 -6
  54. package/src/as.mjs +27 -5
  55. package/src/catalog-switch-inventory.mjs +70 -0
  56. package/src/check-response.mjs +4 -1
  57. package/src/cli-help.mjs +14 -3
  58. package/src/cli-name.mjs +13 -1
  59. package/src/connect-cli.mjs +159 -4
  60. package/src/deadman.mjs +8 -5
  61. package/src/delivery.mjs +2 -19
  62. package/src/destinations/index.mjs +75 -14
  63. package/src/drain-runner.mjs +5 -1
  64. package/src/follow-current.mjs +3 -1
  65. package/src/get-summary.mjs +11 -2
  66. package/src/git-env.mjs +1 -1
  67. package/src/gozar-routes.mjs +313 -94
  68. package/src/host-budget-storage.py +56 -6
  69. package/src/host-budget.mjs +98 -15
  70. package/src/host-execution-policy.mjs +17 -6
  71. package/src/legacy-names.mjs +0 -2
  72. package/src/lifecycle.mjs +44 -9
  73. package/src/loopback-probe.mjs +46 -0
  74. package/src/mcp-outcome.mjs +3 -1
  75. package/src/mcp-sse.mjs +2 -1
  76. package/src/mcp-stdio.mjs +192 -30
  77. package/src/patch-apply.mjs +212 -7
  78. package/src/phase-trace.mjs +73 -0
  79. package/src/prepared-go-modules.mjs +127 -0
  80. package/src/prepared-node-modules.mjs +225 -38
  81. package/src/prepared-pnpm.mjs +276 -0
  82. package/src/prepared-store-prune.mjs +52 -0
  83. package/src/projects.mjs +59 -7
  84. package/src/protocol-artifact-commands.mjs +28 -0
  85. package/src/protocol-finish.mjs +3 -2
  86. package/src/publication-authority.mjs +22 -0
  87. package/src/publish-plan.mjs +2 -2
  88. package/src/pull-queue.mjs +55 -20
  89. package/src/read-api.mjs +127 -0
  90. package/src/redaction.mjs +173 -0
  91. package/src/rejections.mjs +19 -3
  92. package/src/route-custody.mjs +90 -0
  93. package/src/route-publication.mjs +50 -0
  94. package/src/route-setup.mjs +184 -0
  95. package/src/schema-subset.mjs +5 -3
  96. package/src/server.mjs +503 -98
  97. package/src/service-launchd.mjs +5 -1
  98. package/src/service-update-lock.mjs +7 -4
  99. package/src/service-update-runtime.mjs +64 -19
  100. package/src/service-update.mjs +193 -48
  101. package/src/service.mjs +276 -77
  102. package/src/setup.mjs +48 -25
  103. package/src/signal.mjs +1 -1
  104. package/src/status-evidence.mjs +18 -5
  105. package/src/store.mjs +876 -120
  106. package/src/submission-policy.mjs +257 -56
  107. package/src/t3-control.mjs +1 -1
  108. package/src/t3.mjs +14 -8
  109. package/src/terminal-safe.mjs +9 -7
  110. package/src/tool-registry.mjs +134 -41
  111. package/src/try-exposure.mjs +53 -86
  112. package/src/try-hosted.mjs +257 -70
  113. package/src/try.mjs +48 -22
  114. package/src/work-order.mjs +11 -6
  115. package/src/worker-instructions.mjs +26 -4
  116. package/src/worker-runs.mjs +35 -0
  117. package/src/workers.mjs +34 -7
  118. package/src/workspace.mjs +354 -54
  119. package/systemd/dot-deadman.service +3 -1
  120. package/docs/dot-pr-reviewer.config.example.json +0 -9
  121. package/docs/pr-head-reviewer.md +0 -70
  122. package/src/pr-head-reviewer.mjs +0 -596
  123. package/systemd/dot-pr-reviewer.service +0 -11
  124. package/systemd/dot-pr-reviewer.timer +0 -10
@@ -1,4 +1,5 @@
1
1
  import { defaultPath } from './paths.mjs';
2
+ import { serviceHomeFor } from './default-home.mjs';
2
3
  import { secretContent, hasSecretContent, hasCredentialHints, registerSecret, registeredSecrets } from './redaction.mjs';
3
4
  import {gitEnv} from './git-env.mjs';
4
5
  import fs from 'node:fs';
@@ -6,7 +7,7 @@ import os from 'node:os';
6
7
  import path from 'node:path';
7
8
  import { spawnSync } from 'node:child_process';
8
9
  import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
9
- import { assignmentInput, prepareGithubRepo } from './projects.mjs';
10
+ import { assignmentInput, namedCheckPath, prepareGithubRepo } from './projects.mjs';
10
11
  import { firstSegment, laterSegment, readablePath, hasRouterSyntax } from './path-syntax.mjs';
11
12
 
12
13
  const infrastructureError=message=>Object.assign(new Error(message),{code:'DOT_BRIDGE_INFRASTRUCTURE'});
@@ -44,6 +45,11 @@ function paths(value,label) {
44
45
  if(!Array.isArray(value)||!value.length||value.some(p=>typeof p!=='string'||!p||p.includes('\0')||p.includes('\\')||p.startsWith('/')||p.split('/').some(x=>x==='..')||/[\x00-\x1f\x7f*?]/.test(p)||(hasRouterSyntax(p)&&!readablePath(p.replace(/^\.\//,'').replace(/\/$/,''))))) throw new Error(`invalid ${label}; explicit repository-relative paths required`);
45
46
  return value.map(p=>p.replace(/^\.\//,'').replace(/\/$/,''));
46
47
  }
48
+ // For scope derived from a Git file list: never coerce an unrepresentable file into a different spelling.
49
+ export function isLiteralScopePath(value) {
50
+ try { return value !== '.' && paths([value], 'scope_paths')[0] === value; }
51
+ catch { return false; }
52
+ }
47
53
  // output_paths: NEW files the job may create (see docs/usage.md "Creating new files"). Shape only; existence and sensitivity are
48
54
  // checked against the pinned tree in validateSubmission. Entries must already be in canonical form, so the assignment hash the
49
55
  // submitter sent is the one that is stored.
@@ -98,10 +104,56 @@ export function renderAssignment(assignment) {
98
104
  return {...assignment,brief:`Objective:\n${assignment.objective}\n\nExact inputs:\n${revisions}\n\nRead allow-list:\n${scope.length?scope.join('\n'):'No repository scope'}${outs}\n\nExpected output:\n${assignment.expected_output}\n\nStop rule:\n${assignment.stop_rule}`};
99
105
  }
100
106
  function loadPolicy() {
101
- const file=defaultPath(os.homedir(),'.config/dot-bridge/submission-policy.json');
102
- if(!fs.existsSync(file)) return {version:1,sensitive_paths:[],exceptions:[],sandbox_source_exemptions:[]};
103
- if((fs.statSync(file).mode&0o777)!==0o600) throw new Error('submission policy must be mode 0600');
104
- const p=JSON.parse(fs.readFileSync(file,'utf8'));
107
+ const policyName='.config/dot-bridge/submission-policy.json';
108
+ const serviceHome=serviceHomeFor(process.env);
109
+ const file=defaultPath(serviceHome,policyName);
110
+ const ownerHome=os.homedir();
111
+ let legacy;
112
+ let differentHomes=path.resolve(serviceHome)!==path.resolve(ownerHome);
113
+ if(differentHomes) {
114
+ try { differentHomes=fs.realpathSync(serviceHome)!==fs.realpathSync(ownerHome); }
115
+ catch { /* If a home cannot be resolved, keep the conservative lexical comparison. */ }
116
+ }
117
+ const legacyLocation=()=>new Error('policy_legacy_location: the submission policy is at the legacy location; move it into the service home');
118
+ const unreadable=()=>new Error('policy_unreadable: could not read the service submission policy');
119
+ let entry, legacyEntry, resolved, resolvedLegacy, canonicalHome;
120
+ try {
121
+ entry=fs.lstatSync(file,{throwIfNoEntry:false});
122
+ if(differentHomes) {
123
+ try { legacy=defaultPath(ownerHome,policyName);legacyEntry=fs.lstatSync(legacy,{throwIfNoEntry:false}); }
124
+ // A legacy location that cannot be listed (a loop or a non-directory above it) holds no policy, so it cannot
125
+ // refuse a valid service policy. With no service policy, stay fail-closed.
126
+ catch(error) { if(!entry) throw error; }
127
+ }
128
+ if(entry) {
129
+ resolved=fs.realpathSync(file);
130
+ canonicalHome=fs.realpathSync(serviceHome);
131
+ if(legacyEntry) {
132
+ try { resolvedLegacy=fs.realpathSync(legacy); }
133
+ catch(error) { if(!['ENOENT','ELOOP','ENOTDIR'].includes(error.code)) throw error; }
134
+ }
135
+ }
136
+ } catch { throw unreadable(); }
137
+ if(!entry) {
138
+ if(legacyEntry) throw legacyLocation();
139
+ return {version:1,sensitive_paths:[],exceptions:[],sandbox_source_exemptions:[]};
140
+ }
141
+ if(resolvedLegacy&&resolved===resolvedLegacy) throw legacyLocation();
142
+ const relative=path.relative(canonicalHome,resolved);
143
+ if(!relative||relative==='..'||relative.startsWith('..'+path.sep)||path.isAbsolute(relative)) throw unreadable();
144
+ // The service owner controls the policy directory. Validate and read one file snapshot during rotation.
145
+ const modeError=new Error('submission policy must be mode 0600');
146
+ let fd, raw;
147
+ try {
148
+ fd=fs.openSync(resolved,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);
149
+ const stat=fs.fstatSync(fd);
150
+ if(!stat.isFile()) throw unreadable();
151
+ if((stat.mode&0o777)!==0o600) throw modeError;
152
+ raw=fs.readFileSync(fd,'utf8');
153
+ } catch(error) { throw error===modeError?error:unreadable(); }
154
+ finally { if(fd!==undefined) fs.closeSync(fd); }
155
+ let p;
156
+ try { p=JSON.parse(raw); } catch { throw new Error('invalid submission policy'); }
105
157
  if(p.version!==1||!Array.isArray(p.sensitive_paths??[])||!Array.isArray(p.exceptions??[])||!Array.isArray(p.sandbox_source_exemptions??[])) throw new Error('invalid submission policy');
106
158
  paths(p.sensitive_paths?.length?p.sensitive_paths:['placeholder'],'sensitive_paths');
107
159
  for(const e of p.exceptions||[]) {
@@ -120,7 +172,7 @@ function loadPolicy() {
120
172
  const alwaysHardNames=String.raw`\.env[^/]*|\.ssh|\.gnupg|\.aws|\.npmrc|\.netrc|\.git-credentials|\.pgpass|\.pypirc|\.htpasswd|kubeconfig(?:\.[^/]*)?|id_(?:rsa|dsa|ed25519|ecdsa)(?:[-_.][^/]*)?|sign[-_][^/]*release[^/]*`;
121
173
  const sensitivePathTail=String.raw`(?:\/|$)|(?:^|\/)(?:\.docker|\.kube)\/config(?:\.json)?$|\.(?:pem|p12|pfx|key|keystore|jks|ppk|tfstate(?:\.backup)?)$`;
122
174
  const alwaysHard=new RegExp(`(?:^|/)(?:${alwaysHardNames})${sensitivePathTail}`,'i');
123
- const hardPath=new RegExp(String.raw`(?:^|/)(?:${alwaysHardNames}|service[-_]account(?:\.[^/]*)?|secrets?(?:\.[^/]*)?|[^/]*(?:credentials?|private[-_.]?key|gpg[-_.]?secret)[^/]*|(?:[^/]*[-_.])?signing(?:[-_.][^/]*)?)${sensitivePathTail}`,'i');
175
+ const hardPath=new RegExp(String.raw`(?:^|/)(?:${alwaysHardNames}|service[-_]account(?:\.[^/]*)?|secrets?(?:\.[^/]*)?|[^/]*(?:credentials?|private[-_.]?key|recovery[-_.]?(?:key|codes?)|gpg[-_.]?secret)[^/]*|(?:[^/]*[-_.])?signing(?:[-_.][^/]*)?)${sensitivePathTail}`,'i');
124
176
  // "token" alone is not a credential: tokens.css and design-tokens.json are design tokens. A token file is sensitive when a
125
177
  // credential word qualifies it (auth-token, access_token, gh-tokens.txt, npm.token), or it is a bare `token` file or a
126
178
  // `tokens.txt|env|key|secret`. Plain `tokens/` and `tokens.json` are the usual design-token names and pass.
@@ -138,7 +190,7 @@ export function isSourceExemptionPath(file) {
138
190
  }
139
191
  // In a code file's own name, the precise secret words still mark secret material (credentials.ts, secrets.py, private-key.ts,
140
192
  // service-account.ts, owner-credential.ts); a word inside a longer name (logout-cancels-credential-setup.test.ts) does not.
141
- const codeSecretName=/(?:^|\/)(?:credentials?|secrets?|private[-_.]?key|service[-_.]?account|[^/]*[-_.](?:credentials?|secrets?))\.[^/.]+$/i;
193
+ const codeSecretName=/(?:^|\/)(?:credentials?|secrets?|private[-_.]?key|recovery[-_.]?(?:key|codes?)|service[-_.]?account|[^/]*[-_.](?:credentials?|secrets?))\.[^/.]+$/i;
142
194
  // Password stores are secret material by name in any form.
143
195
  const passwordName=/(?:^|\/)(?:\.?htpasswd|shadow|[^/]*passw(?:or)?ds?(?:\.[^/]*)?)$/i;
144
196
  const secretDirectory=/(?:^|\/)(?:secrets?|credentials?)\//i;
@@ -157,7 +209,7 @@ export { secretContent } from './redaction.mjs';
157
209
  const authority=/\b(?:we|you|dot)\s+(?:have|has|can use)\s+(?:\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:(?:free|available|live|idle|worker)\s+)*(?:slots?|lanes?|workers?)\b|\b(?:\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:free|available|live|idle)\s+(?:slots?|lanes?|workers?)\b|\b(?:\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:(?:free|available|live|idle|worker|dot)\s+)*(?:slots?|lanes?|workers?)\s+(?:are\s+)?(?:free|available|idle|remaining|open)\b|\b(?:keep|fill|maintain)\s+(?:all\s+)?(?:\d+\s+)?(?:slots?|lanes?)\s+(?:full|busy)/i;
158
210
  // Role words only. A regex cannot tell a named person from a role or a product, so named-person claims are a documented residual.
159
211
  const grantedAuthority=/\b(?:the\s+)?(?:owner|user|operator|admin(?:istrator)?|maintainer|requester)\s+(?:has\s+)?(?:grants?|granted|approves?|approved|authorizes?|authorized)\s+(?:new|additional|expanded)\s+(?:authority|access|permissions?)\b/i;
160
- function within(p,scope) { return !/^(?:\/|~\/|\$HOME\/)/.test(p)&&!p.split('/').includes('..')&&scope.some(s=>s==='.'||p===s||p.startsWith(`${s}/`)); }
212
+ export function within(p,scope) { return !/^(?:\/|~\/|\$HOME\/)/.test(p)&&!p.split('/').includes('..')&&scope.some(s=>s==='.'||p===s||p.startsWith(`${s}/`)); }
161
213
  const sourceExtension=/\.(?:mjs|cjs|jsx|ts|tsx|py|rs|go|md|txt|html|css|scss|sh|json|yaml|yml|toml|ini|conf|sql|vue|svelte|xml|pem|key|asc|jks|keystore|ppk|tfstate(?:\.backup)?)$/i;
162
214
  const pathToken=new RegExp(`(?<![A-Za-z0-9_.@-])((?:(?:~|\\$HOME)?\\/|\\.?\\.?\\/)?${firstSegment}(?:\\/${laterSegment})*\\/?)(?![A-Za-z0-9_@-])`,'gm');
163
215
  const plainToken=/(?<![A-Za-z0-9_.@-])((?:(?:~|\$HOME)?\/|\.?\.?\/)?[A-Za-z0-9_.@-]+(?:\/[A-Za-z0-9_.@-]+)*\/?)(?![A-Za-z0-9_@-])/g;
@@ -166,13 +218,37 @@ const plainToken=/(?<![A-Za-z0-9_.@-])((?:(?:~|\$HOME)?\/|\.?\.?\/)?[A-Za-z0-9_.
166
218
  function pathTokens(text) {
167
219
  return [...text.matchAll(pathToken)].flatMap(m=>hasRouterSyntax(m[1])&&!m[1].includes('/')?[...m[1].matchAll(plainToken)].map(sub=>Object.assign([sub[0],sub[1]],{index:m.index+sub.index})):[m]);
168
220
  }
221
+ // Prose outside the repository is context, never a scope grant. Capture the whole
222
+ // spelling so a token inside $CONFIG_DIR/client.toml cannot become a repo path.
223
+ function externalPathMentions(text) {
224
+ const pattern=/(?<![A-Za-z0-9_./:@)\]}<-])((?:\$(?:[A-Za-z_]\w*|\{[A-Za-z_]\w*\})[\/\\]|[A-Za-z]:[\/\\]|\\\\)[^\s`"'<>;,!?]*)/g;
225
+ // Capture variable, drive and UNC spellings before splitting ordinary path tokens.
226
+ return [...text.matchAll(pattern)];
227
+ }
169
228
  function mentionedPaths(text,knownPaths=[]) {
170
- const known=new Set(knownPaths.flatMap(file=>{const parts=file.split('/');return [file,...parts.slice(0,-1).map((_,i)=>parts.slice(0,i+1).join('/'))];}));
171
- const authoritative=file=>known.has(file)||knownPaths.some(scope=>file.startsWith(`${scope}/`));
229
+ const roots=new Set(knownPaths),known=new Set(roots);
230
+ for(const file of roots) for(let i=file.indexOf('/');i>=0;i=file.indexOf('/',i+1)) known.add(file.slice(0,i));
231
+ const authoritative=file=>{
232
+ if(known.has(file)) return true;
233
+ for(let i=file.indexOf('/');i>=0;i=file.indexOf('/',i+1)) if(roots.has(file.slice(0,i))) return true;
234
+ return false;
235
+ };
172
236
  const unwrap=file=>{const name=file.replace(/^_+|_+$/g,'');return file.startsWith('_')&&file.endsWith('_')&&(known.has(name)||hardPath.test(name)||(name.startsWith('@')&&(known.has(name.slice(1))||hardPath.test(name.slice(1)))))?name:file;};
173
237
  // Names written with a slash (./old.mjs, Makefile/) stay explicit paths after normalization.
174
- const explicit=new Set();
175
- const candidates=pathTokens(text).map(m=>{const file=normalize(m);if(file!==null&&m[1].includes('/')) explicit.add(file);return file;});
238
+ const explicit=new Set(),external=new Set();
239
+ const hostMentions=externalPathMentions(text);
240
+ const tokens=[...hostMentions,...pathTokens(text).filter(m=>!hostMentions.some(h=>m.index>=h.index&&m.index<h.index+h[0].length))];
241
+ const candidates=tokens.map(m=>{
242
+ const outside=hostMentions.includes(m);
243
+ let file=outside?m[1].replace(/[.)]+$/,''):normalize(m);
244
+ if(file===null) return null;
245
+ // HOME is a known host location. Keep it out of the warning-only variable path set.
246
+ const homePrefix=outside&&/^\$(?:HOME|\{HOME\})[/\\]/.exec(file);
247
+ if(homePrefix) file='$HOME/'+file.slice(homePrefix[0].length).replaceAll('\\','/');
248
+ else if(outside) external.add(file);
249
+ if(homePrefix||m[1].includes('/')) explicit.add(file);
250
+ return file;
251
+ });
176
252
  function normalize(m) {
177
253
  const raw=m[1];
178
254
  // A JSX/HTML tag name right after `<` or `</` (</Button>, <Card.Header>, <Icon />) is markup, not a path. A hard
@@ -194,6 +270,7 @@ function mentionedPaths(text,knownPaths=[]) {
194
270
  // Exact tree/scope names and explicit lists carry authority. Ordinary words,
195
271
  // framework brands and hostnames do not establish repository paths.
196
272
  if(file===null) return false;
273
+ if(external.has(file)) return true;
197
274
  if(authoritative(file)) return true;
198
275
  if(/^(?:e\.g\.|i\.e\.)\/(?:e\.g|i\.e)\.?$/i.test(file)) return false;
199
276
  if(/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+\//.test(file)) return false;
@@ -202,7 +279,7 @@ function mentionedPaths(text,knownPaths=[]) {
202
279
  if(file.includes('/')) return sourceExtension.test(file)||file.split('/').some(part=>part.includes('.'));
203
280
  return sourceExtension.test(file)||(file.includes('.')&&hardPath.test(file));
204
281
  });
205
- return Object.assign(found,{explicit});
282
+ return Object.assign(found,{explicit,external});
206
283
  }
207
284
  export function scanGit(mirror,args,spawn=spawnSync) {
208
285
  const maxBuffer=32*1024*1024;
@@ -275,21 +352,33 @@ function codeInDiffFences(brief,inspect) {
275
352
  closeHunk(!(oldLeft>0||newLeft>0));
276
353
  return out.join('\n');
277
354
  }
278
- const allowListMarker='Read allow-list (scope_paths';
279
- export const allowListHeading=`${allowListMarker}; every path below, and everything under a listed directory, may be read):`;
355
+ export const allowListHeading='Read allow-list (scope_paths; every path below, and everything under a listed directory, may be read):';
356
+ const allowListBlock=(list,more=0)=>{
357
+ const lines=[allowListHeading,...list];
358
+ if(more) lines.push(`...and ${more} more paths in scope_paths, all readable`);
359
+ return lines.join('\n');
360
+ };
280
361
  const vagueExclusion=/\[excluded (?:file|path)\]|\b(?:omitted|excluded) by policy\b/i;
281
362
  function withAllowList(result,warn) {
282
363
  if(vagueExclusion.test(result.brief)) warn('the brief mentions an excluded file without naming it; the worker\'s reviewer then refuses in-scope reads that look like it. Name the path, or drop the sentence: the bridge scope note names dropped sensitive files');
283
364
  const scope=result.scope_paths||[];
284
365
  // The whole repository ('.', the ACP scope) needs no list.
285
- if(!scope.length||scope.includes('.')||result.brief.includes(allowListMarker)||result.brief.includes('\nRead allow-list:\n')) return result;
366
+ if(!scope.length||scope.includes('.')) return result;
367
+ const blocks=result.brief.split('\n\n');
368
+ if(blocks.includes(allowListBlock(scope))||blocks.includes(`Read allow-list:\n${scope.join('\n')}`)) return result;
369
+ // A previous admission may have emitted the exact prefix that fit its brief.
370
+ for(const block of blocks) {
371
+ if(!block.startsWith(`${allowListHeading}\n`)) continue;
372
+ const count=block.split('\n').length-2;
373
+ if(count>0&&count<scope.length&&block===allowListBlock(scope.slice(0,count),scope.length-count)) return result;
374
+ }
286
375
  const head=`\n\n${allowListHeading}\n`;
287
376
  const room=Math.min(submissionLimits.brief-bytes(result.brief),submissionLimits.instructions-(bytes(result.brief)+bytes(result.expected_output)+bytes(result.execution_scope||'')+bytes(typeof result.scope_text==='string'?result.scope_text:'')+bytes(scope.join('\n'))))-bytes(head)-80;
288
377
  const listed=[];let used=0;
289
378
  for(const p of scope) { if(used+bytes(p)+1>room) break; listed.push(p);used+=bytes(p)+1; }
290
379
  if(!listed.length) { warn('the brief has no room for the scope_paths allow-list; the worker\'s reviewer may refuse in-scope reads'); return result; }
291
380
  const more=scope.length-listed.length;
292
- const expanded={...result,brief:`${result.brief}${head}${listed.join('\n')}${more?`\n...and ${more} more paths in scope_paths, all readable`:''}`};
381
+ const expanded={...result,brief:`${result.brief}\n\n${allowListBlock(listed,more)}`};
293
382
  const n=bytes(expanded.brief);
294
383
  if(n>submissionLimits.brief) throw Object.assign(new Error(`brief: ${n} UTF-8 bytes exceeds ${submissionLimits.brief}; cut at least ${n-submissionLimits.brief} bytes`),{expandedPayload:expanded});
295
384
  return expanded;
@@ -297,8 +386,10 @@ function withAllowList(result,warn) {
297
386
  // The brief names the files the job may create; the worker's reviewer judges a write by the brief's prose. Idempotent.
298
387
  function withOutputPaths(result) {
299
388
  const list=result.output_paths||[];
300
- if(!list.length||result.brief.includes(outputPathsHeading)) return result;
301
- const brief=`${result.brief}\n\n${outputBlock(list)}`;
389
+ if(!list.length) return result;
390
+ const block=outputBlock(list);
391
+ if(result.brief.split('\n\n').includes(block)) return result;
392
+ const brief=`${result.brief}\n\n${block}`;
302
393
  const expanded={...result,brief},n=bytes(brief);
303
394
  if(n>submissionLimits.brief) throw Object.assign(new Error(`brief: ${n} UTF-8 bytes exceeds ${submissionLimits.brief}; cut at least ${n-submissionLimits.brief} bytes`),{expandedPayload:expanded});
304
395
  return expanded;
@@ -306,13 +397,47 @@ function withOutputPaths(result) {
306
397
  // The scope deny rule as a yes/no on one repository path: hard names (keys, env files, credential stores), the soft credential/auth/
307
398
  // signing name lint, a router-group spelling of a hard name, and the owner's `sensitive_paths`. Submit uses these rules to refuse or drop
308
399
  // scope paths; the check sandbox uses them to mask the same files (src/workspace.mjs). Exceptions are per-submission and do not unmask.
400
+ // A refusal caused by one sensitive path carries that path as `sensitive_path`, apart from its display text.
401
+ const sensitivePathError=(message,file)=>Object.assign(new Error(message),{sensitive_path:file});
402
+ const hardSensitiveRepoPath=file=>hardName(file)||(hasRouterSyntax(file)&&hardName(file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,'')));
403
+ const ownerSensitiveRepoPath=(file,policyPaths)=>policyPaths.some(x=>file===x||file.startsWith(`${x}/`));
309
404
  export function isSensitiveRepoPath(file,policyPaths=[]) {
310
- return hardName(file)||(hasRouterSyntax(file)&&hardName(file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,'')))||softName(file)||policyPaths.some(x=>file===x||file.startsWith(`${x}/`));
405
+ return hardSensitiveRepoPath(file)||softName(file)||ownerSensitiveRepoPath(file,policyPaths);
406
+ }
407
+ // Soft ancestors describe a code topic, not a credential store. Keep the
408
+ // established source exception, but never for a hard or owner-denied ancestor.
409
+ export function withheldRepoPath(file,policyPaths=[],{directory=false}={}) {
410
+ if(directory) return hardSensitiveRepoPath(file)||ownerSensitiveRepoPath(file,policyPaths);
411
+ if(isSensitiveRepoPath(file,policyPaths)) return true;
412
+ const parts=file.split('/');
413
+ return parts.slice(1).some((_,i)=>{
414
+ const ancestor=parts.slice(0,i+1).join('/');
415
+ return hardSensitiveRepoPath(ancestor)||(!codeFile.test(file)&&softName(ancestor));
416
+ });
311
417
  }
312
418
  // The owner's sensitive_paths, or an error message when the policy file cannot be read (execution callers must fail closed).
313
419
  export function sensitivePolicyPaths() {
314
420
  try { const policy=loadPolicy();return {paths:policy.sensitive_paths,sourceExemptions:policy.sandbox_source_exemptions,error:null}; } catch(error) { return {paths:[],sourceExemptions:[],error:error.message}; }
315
421
  }
422
+ const namedCheckError=(message,index)=>Object.assign(new Error(`invalid_named_check: ${message}`),{code:'invalid_named_check',...(index===undefined?{}:{check_index:index})});
423
+ export function submissionNamedCheckPaths(assignment, { review=false, policyPaths=[] }={}) {
424
+ if (assignment.checks===undefined) return [];
425
+ if (review || assignment.execution_scope!=='implementation') throw namedCheckError('checks require an implementation assignment');
426
+ if (!Array.isArray(assignment.checks) || assignment.checks.length>8) throw namedCheckError('use an array of at most eight node <path> commands');
427
+ return Array.from(assignment.checks,(command,index)=>{
428
+ const file=namedCheckPath(command), entry=index+1;
429
+ if (!file) throw namedCheckError(`entry ${entry}: use exactly node <repo-relative .js, .mjs or .cjs path>`,entry);
430
+ if (isSensitiveRepoPath(file,policyPaths)) throw namedCheckError(`entry ${entry}: choose a non-sensitive test path`,entry);
431
+ return file;
432
+ });
433
+ }
434
+ export function validateNamedCheckTargets(namedPaths, scan, outputSet) {
435
+ const regularFiles=new Set(scan.regularFiles??scan.files.filter(file=>!scan.symlinks?.includes(file)));
436
+ for (const [index,file] of namedPaths.entries()) {
437
+ if (!regularFiles.has(file) && !outputSet.has(file))
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
+ }
440
+ }
316
441
  export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanInput,warnings=null,excludeSensitive=false,review=false,worker}={}) {
317
442
  const warn=message=>{if(warnings&&!warnings.includes(message)) warnings.push(message);};
318
443
  let p;
@@ -331,6 +456,14 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
331
456
  if(hasSecretContent(rendered)) throw new Error('hard sensitive content exclusion');
332
457
  // Labelled values are medium precision: every output sink masks them, so intake warns instead of refusing.
333
458
  if(hasCredentialHints(rendered)) warn('the assignment contains a credential-labelled value; output to the worker masks it, so pass credentials through the bridge, not the brief');
459
+ for(const candidate of rendered.inputs??[]) {
460
+ if(!candidate?.github_repo) continue;
461
+ for(const field of ['base_sha','head_sha','source_sha']) {
462
+ const value=candidate[field];
463
+ if(typeof value==='string'&&/^[a-f0-9]{7,12}$/i.test(value))
464
+ throw new Error(`invalid ${field}: use the full 40-character SHA`);
465
+ }
466
+ }
334
467
  const input=rendered.execution_scope==='implementation'||rendered.inputs?.some(i=>i.github_repo!==undefined)?assignmentInput(rendered):null;
335
468
  const mismatch=(reads,scope)=>[...reads.filter(p=>!scope.includes(p)),...scope.filter(p=>!reads.includes(p))].join(', ')||'lists differ in length';
336
469
  const scope=rendered.scope_paths===undefined||rendered.scope_paths?.length===0?[]:[...paths(rendered.scope_paths,'scope_paths')];
@@ -345,12 +478,19 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
345
478
  }
346
479
  const exception=sensitiveScopeOverride===null?null:p.exceptions.find(e=>e.id===sensitiveScopeOverride&&e.github_repo===input?.github_repo);
347
480
  if(sensitiveScopeOverride!==null&&!exception) throw new Error('unknown sensitive scope override');
348
- // Why a path is sensitive, for the record kept when a directory scope drops it.
349
- const sensitiveReason=file=>hardName(file)||(hasRouterSyntax(file)&&hardName(file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,'')))?'hard sensitive path (credential, key or signing material)':p.sensitive_paths.some(x=>file===x||file.startsWith(`${x}/`))?'listed in the submission policy sensitive_paths':'name matches the credential, auth or signing lint';
481
+ // Shared facts keep the directory exclusion policy and the explicit path refusal aligned.
482
+ const hardSensitive=file=>hardName(file)||(hasRouterSyntax(file)&&hardName(file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,'')));
483
+ const policyEntry=file=>p.sensitive_paths.find(x=>file===x||file.startsWith(`${x}/`));
484
+ const sensitiveReason=file=>hardSensitive(file)?'hard sensitive path (credential, key or signing material)':policyEntry(file)?'listed in the submission policy sensitive_paths':'name matches the credential, auth or signing lint';
485
+ const sensitiveRefusal=file=>{
486
+ const entry=policyEntry(file), base=file.split('/').at(-1);
487
+ 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
+ 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
+ };
350
490
  function inspectPath(file) {
351
491
  // A router group cannot hide a sensitive name: `(x).env` is also checked as `.env`.
352
- if(hardName(file)||(hasRouterSyntax(file)&&hardName(file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,'')))) throw new Error(`hard sensitive path exclusion: ${file}`);
353
- if((softName(file)||p.sensitive_paths.some(s=>file===s||file.startsWith(`${s}/`)))&&(!exception||file!==exception.path)) throw new Error(`sensitive scope path: ${file}`);
492
+ if(hardSensitive(file)) throw sensitivePathError(`hard sensitive path exclusion: ${file}`,file);
493
+ if((softName(file)||policyEntry(file))&&(!exception||file!==exception.path)) throw sensitiveRefusal(file);
354
494
  }
355
495
  for(const file of scope) inspectPath(file);
356
496
  // output_paths: shape here, the pinned tree below. Review mode is read-only, so it takes no output file.
@@ -365,10 +505,16 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
365
505
  }
366
506
  }
367
507
  const outputSet=new Set(outputs);
508
+ const namedPaths=submissionNamedCheckPaths(rendered,{review,policyPaths:p.sensitive_paths});
368
509
  // Unified-diff /dev/null markers are sentinels, not filesystem requests. An exact exclusion diagnostic grants no
369
510
  // read permission. Keep scanning its content for secrets above and checking scope/diff paths below; remove only
370
511
  // a well-formed, actually sensitive name from instruction references.
371
- const instructionBrief=rendered.brief.replace(/^(?:---|\+\+\+) \/dev\/null$/gm,'').replace(/^omitted: (.+) \(sensitive\)$/gm,(line,file)=>{
512
+ // Only a standalone quoted path is a display note. It cannot grant access.
513
+ const scopedBrief=rendered.brief.replace(/^[ \t]*note:[ \t]+(["'`])((?:~\/|\$(?:HOME|\{HOME\})[/\\]|\/|\.\.\/)[^"'`\r\n]+)\1[ \t]*$/gm,(_line,_quote,file)=>{
514
+ inspectPath(file.replaceAll('\\','/'));
515
+ return 'note: [external path, not an input]';
516
+ });
517
+ const instructionBrief=scopedBrief.replace(/^(?:---|\+\+\+) \/dev\/null$/gm,'').replace(/^omitted: (.+) \(sensitive\)$/gm,(line,file)=>{
372
518
  try { paths([file],'omitted path'); } catch { return line; }
373
519
  try { inspectPath(file); return line; }
374
520
  catch(error) { if(/^(?:hard sensitive path exclusion|sensitive scope path): /.test(error.message)) return '';throw error; }
@@ -377,8 +523,8 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
377
523
  // A name in code is a reference, not a read. The worker reads only scope files, and every scope and diff file gets inspectPath.
378
524
  // A code token refuses only when it points at host secret material (for example, ~/.ssh/id_rsa) or a policy-listed path.
379
525
  const inspectCode=(file,raw=file)=>{
380
- if(hostPath.test(raw)&&hardPath.test(file)) throw new Error(`hard sensitive path exclusion: ${raw}`);
381
- if(p.sensitive_paths.some(x=>file===x||file.startsWith(`${x}/`))&&(!exception||file!==exception.path)) throw new Error(`sensitive scope path: ${file}`);
526
+ if(hostPath.test(raw)&&hardPath.test(file)) throw sensitivePathError(`hard sensitive path exclusion: ${raw}`,raw);
527
+ if(policyEntry(file)&&(!exception||file!==exception.path)) throw sensitiveRefusal(file);
382
528
  };
383
529
  const text=[codeInDiffFences(instructionBrief,inspectCode),rendered.expected_output,scopeText,rendered.objective||'',rendered.stop_rule||'',JSON.stringify((rendered.inputs||[]).map(({input_patch,...rest})=>rest))].join('\n\n');
384
530
  warnOutputDirectoryMentions(outputs,text,warn);
@@ -392,6 +538,9 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
392
538
  }
393
539
  }
394
540
  const repositoryImplementation=rendered.execution_scope==='implementation'&&scope.includes('.');
541
+ // Every implementation directory keeps its write grant while withholding sensitive files.
542
+ // This must not depend on an opt-in: the worker receives no access to hard or soft secret paths.
543
+ const withholdImplementation=rendered.execution_scope==='implementation';
395
544
  const dropped=[];let narrowedScope=null;
396
545
  const firstPass=mentionedPaths(text,scope);
397
546
  for(const file of firstPass) {
@@ -410,7 +559,8 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
410
559
  const files=tree.map(entry=>entry.path),symlinks=tree.filter(entry=>entry.mode==='120000').map(entry=>entry.path);
411
560
  const diff=input.head_sha?git(mirror,['diff','--no-ext-diff','--no-textconv','--binary',input.base_sha,input.head_sha]):'';
412
561
  const diffFiles=input.head_sha?git(mirror,['diff','--no-ext-diff','--name-only','-z',input.base_sha,input.head_sha]).split('\0').filter(Boolean):[];
413
- return {files,diff,diffFiles,symlinks};
562
+ const regularFiles=tree.filter(entry=>entry.mode==='100644'||entry.mode==='100755').map(entry=>entry.path);
563
+ return {files,diff,diffFiles,symlinks,regularFiles};
414
564
  })();
415
565
  if(!scan||!Array.isArray(scan.files)||!Array.isArray(scan.diffFiles)||typeof scan.diff!=='string') throw infrastructureError('submission scope scanner failed');
416
566
  // A free-form read-only or review assignment may grow its scope by the files its own brief names and its PR changes: the
@@ -421,10 +571,33 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
421
571
  // Review mode cannot write (apply_patch refuses review submissions), so growing a review assignment's scope adds read access only.
422
572
  const maxGrowth=200;
423
573
  const want=(file,mention=file)=>{ if(within(file,scope)) return; if(mention!==file) mentionedAs.set(file,mention); if(growable) { if(added.length>=maxGrowth) throw new Error(`scope growth limit: the brief names more than ${maxGrowth} files outside scope_paths; list them in scope_paths`); scope.push(file);added.push(file); } else fixable.push(file); };
424
- const treeFiles=new Set(scan.files),isTreeDir=file=>scan.files.some(f=>f.startsWith(`${file}/`));
574
+ const treeFiles=new Set(scan.files),treeDirs=new Set();
575
+ validateNamedCheckTargets(namedPaths,scan,outputSet);
425
576
  const treePass=mentionedPaths(text,[...scope,...scan.files]);
577
+ // Index only the suffixes the brief mentions. Keep tree order for ambiguity
578
+ // diagnostics and recheck matches against the scope as that scope grows.
579
+ const mentions=new Set(treePass),suffixMatches=new Map();
580
+ const indexMatch=(suffix,file)=>{
581
+ if(!mentions.has(suffix))return;
582
+ if(!suffixMatches.has(suffix))suffixMatches.set(suffix,[]);
583
+ suffixMatches.get(suffix).push(file);
584
+ };
585
+ for(const file of scan.files) {
586
+ indexMatch(file,file);
587
+ for(let i=file.indexOf('/');i>=0;i=file.indexOf('/',i+1)) {
588
+ treeDirs.add(file.slice(0,i));
589
+ indexMatch(file.slice(i+1),file);
590
+ }
591
+ }
592
+ const isTreeDir=file=>treeDirs.has(file);
426
593
  for(const file of treePass) {
427
594
  if(file===input.github_repo||outputSet.has(file)) continue;
595
+ if(treePass.external.has(file)) {
596
+ inspectPath(file.replaceAll('\\','/'));
597
+ warn(`the brief mentions external path ${file}; this does not grant repository or host-file access`);
598
+ continue;
599
+ }
600
+ if(file.startsWith('$HOME/')) inspectPath(file);
428
601
  const bare=bareToken(file)&&!treePass.explicit.has(file);
429
602
  if(bare&&bareWord(file)&&!hardPath.test(file)) { if(!within(file,scope)) warn(`bare word "${file}" matches a repository path outside scope_paths; it is not treated as a path reference`); continue; }
430
603
  // In scope, or a directory that holds scope entries (`gateway` for gateway/x.py): context, not a new read.
@@ -432,7 +605,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
432
605
  if(scope.some(s=>s.startsWith(`${file}/`))) continue;
433
606
  // A bare filename (README.md) names a file only when it resolves to exactly one tree path.
434
607
  if(bare) {
435
- const matches=scan.files.filter(f=>f===file||f.endsWith(`/${file}`));
608
+ const matches=suffixMatches.get(file)??[];
436
609
  if(matches.some(f=>within(f,scope))) continue;
437
610
  if(matches.length===1) { inspectPath(matches[0]);want(matches[0],file);continue; }
438
611
  // A file name the tree lacks (gh-tokens.txt, secrets.yaml) may point the worker at a host file: full inspect. An identifier
@@ -442,25 +615,27 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
442
615
  ambiguous.push(matches.length?`ambiguous bare filename "${file}": it matches ${matches.length} repository paths outside scope_paths (${matches.slice(0,5).join(', ')}${matches.length>5?', ...':''}). Write the full path of the one you mean, for example ${matches[0]===file?'./':''}${matches[0]} instead of ${file}`:`unknown bare filename "${file}": it is not in the repository tree. Write the full repository path of the file (a new file needs its full path too; ./${file} names a file at the repository root), or remove the mention`);
443
616
  continue;
444
617
  }
445
- if(treeFiles.has(file)) { inspectPath(file);want(file);continue; }
446
- if(isTreeDir(file)) { inspectPath(file);warn(`the brief mentions directory ${file}, outside scope_paths; the worker cannot read it`);continue; }
618
+ if(!hostPath.test(file)) {
619
+ if(treeFiles.has(file)) { inspectPath(file);want(file);continue; }
620
+ if(isTreeDir(file)) { inspectPath(file);warn(`the brief mentions directory ${file}, outside scope_paths; the worker cannot read it`);continue; }
621
+ }
447
622
  // Not in the tree: an identifier, route or URL path (input.privateKey, secrets.API_TOKEN, /v1) names no file the worker could
448
623
  // read. A file-shaped secret name (/home/u/credentials, .env, secrets.yaml) still refuses, and so do host paths, parent
449
624
  // traversal and an absolute spelling of a repository path (/README.md never inherits scope).
450
625
  // A router group cannot hide a sensitive name: web/(x).env is checked as web/.env.
451
- if(fileShaped(file)&&(hardName(file)||(hasRouterSyntax(file)&&hardName(file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,''))))) throw new Error(`hard sensitive path exclusion: ${file}`);
626
+ if(fileShaped(file)&&(hardName(file)||(hasRouterSyntax(file)&&hardName(file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,''))))) throw sensitivePathError(`hard sensitive path exclusion: ${file}`,file);
452
627
  const rest=file.replace(/^\/+/,''),unrouted=file.replace(/\[[^\]/]*\]\]?|\([^)/]*\)/g,'');
453
628
  // A relative path the tree lacks is usually abbreviated (bin/x.ts for packages/p/bin/x.ts) or not a path (a branch name):
454
629
  // it resolves like a bare filename, by suffix, and otherwise warns. Invalid syntax, traversal and router segments the tree
455
630
  // lacks (x/$(id)/y.ts) refuse. Leading-slash routes (/v1, /me) pass; a file extension makes it a host file (/y.ts).
456
631
  // A bare host directory in prose ("use ~/.tmp, not /tmp") names no file: it warns.
457
- if(/^~\/\.(?:docker|kube)\/?$/.test(file)) throw new Error(`hard sensitive path exclusion: ${file}`);
632
+ if(/^~\/\.(?:docker|kube)\/?$/.test(file)) throw sensitivePathError(`hard sensitive path exclusion: ${file}`,file);
458
633
  if(/^(?:\/(?:tmp|home|var|etc|usr|opt)|~|~\/\.?\w[\w-]*|\$HOME)\/?$/.test(file)) { warn(`the brief mentions host directory ${file}; the worker cannot read host paths`);continue; }
459
634
  if(hostPath.test(file)||hostPath.test(unrouted)) { undeclared.push(file);continue; }
460
635
  if(!file.startsWith('/')) {
461
636
  const invalid=hasRouterSyntax(file)||file.split('/').includes('..')||(()=>{try{paths([file],'mention');return false;}catch{return true;}})();
462
637
  if(invalid) { undeclared.push(file);continue; }
463
- const matches=scan.files.filter(f=>f.endsWith(`/${file}`));
638
+ const matches=suffixMatches.get(file)??[];
464
639
  if(matches.some(f=>within(f,scope))) continue;
465
640
  if(matches.length===1) { inspectPath(matches[0]);want(matches[0],file);continue; }
466
641
  if(matches.length) { ambiguous.push(`ambiguous abbreviated path "${file}": it matches ${matches.length} repository paths outside scope_paths (${matches.slice(0,5).join(', ')}${matches.length>5?', ...':''}). Write the full path of the one you mean, for example ${matches[0]===file?'./':''}${matches[0]} instead of ${file}`);continue; }
@@ -487,8 +662,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
487
662
  // Case-insensitive and Unicode-normalizing filesystems (macOS) hold one file under several spellings. An output path that matches
488
663
  // an existing tree path, directory or PR-diff path after lowercasing or NFC normalization (or both) would overwrite it there.
489
664
  const lookalikeKeys=outputPathKeys.slice(1);
490
- const existingPaths=new Set([...scan.files,...scan.diffFiles]);
491
- for(const f of scan.files) for(let i=f.indexOf('/');i>0;i=f.indexOf('/',i+1)) existingPaths.add(f.slice(0,i));
665
+ const existingPaths=new Set([...treeFiles,...scan.diffFiles,...treeDirs]);
492
666
  const lookalikes=lookalikeKeys.map(key=>{const byKey=new Map();for(const e of existingPaths) { const k=key(e); if(!byKey.has(k)) byKey.set(k,e); } return byKey;});
493
667
  // The output itself or any ancestor directory: an exact existing path is handled by the branches below, not here.
494
668
  const lookalikeOf=file=>{
@@ -509,7 +683,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
509
683
  else if(parent) taken.push(`${file} cannot be created: ${parent} is a file at ${input.head_sha||input.base_sha}; choose a path whose parent directories are not files`);
510
684
  }
511
685
  if(taken.length) throw new Error(`output_paths: ${taken.join('\n')}`);
512
- const unknown=scope.filter(s=>s!=='.'&&!scan.files.some(f=>f===s||f.startsWith(`${s}/`))&&!scan.diffFiles.includes(s));
686
+ const unknown=scope.filter(s=>s!=='.'&&!treeFiles.has(s)&&!treeDirs.has(s)&&!scan.diffFiles.includes(s));
513
687
  if(unknown.length) {
514
688
  const error=new Error(`unknown scope path: ${unknown.join(', ')}`), rest=scope.filter(s=>!unknown.includes(s));
515
689
  // Where a path looks like a typo, the requester gets the tree paths it may have meant.
@@ -517,30 +691,45 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
517
691
  if(rest.length) error.suggested_scope_paths=rest;
518
692
  throw error;
519
693
  }
520
- // Repository-wide implementation scopes withhold unnamed sensitive files physically.
521
- // Other scopes retain the explicit read-only exclusion option. Named paths and patch
522
- // paths still refuse above and below; exclusions grant no access to those files.
694
+ // Implementation scopes keep their directory grants and physically withhold unnamed
695
+ // sensitive files. Read-only directory scopes are narrowed to exclude them.
696
+ // Named paths and patch paths still refuse above and below.
523
697
  for(const file of scan.files.filter(f=>within(f,scope)&&!scope.includes(f))) {
524
- if(repositoryImplementation&&isSensitiveRepoPath(file,p.sensitive_paths)) {
525
- dropped.push({path:file,reason:sensitiveReason(file)});continue;
698
+ if(withholdImplementation&&withheldRepoPath(file,p.sensitive_paths)) {
699
+ dropped.push({path:file,reason:isSensitiveRepoPath(file,p.sensitive_paths)?sensitiveReason(file):'sensitive ancestor directory (withheld)'});continue;
700
+ }
701
+ if(rendered.execution_scope!=='implementation'&&softName(file)&&!hardSensitive(file)&&!policyEntry(file)&&file!==exception?.path) {
702
+ dropped.push({path:file,reason:'soft sensitive name (dropped, not refused)'});continue;
526
703
  }
527
704
  try { inspectPath(file); }
528
705
  catch(error) {
529
706
  if(!/^(?:hard sensitive path exclusion|sensitive scope path): /.test(error.message)) throw error;
530
707
  if(!excludeSensitive) throw error;
531
- // Narrowing turns a directory into a file list; for implementation work that would forbid new files, so it is refused.
532
- if(rendered.execution_scope==='implementation') throw new Error(`${error.message} (--exclude-sensitive applies to read-only work, not implementation scope)`);
533
708
  dropped.push({path:file,reason:sensitiveReason(file)});
534
709
  }
535
710
  }
536
711
  for(const file of scan.files.filter(f=>scope.includes(f))) inspectPath(file);
537
- // A symlink inside a directory scope: the workspace never follows one (list skips it, read refuses), so read-only work
538
- // with excludeSensitive records it as dropped instead of refusing the scope. A named symlink still refuses.
539
- for(const file of scan.symlinks||[]) if(within(file,scope)&&!scope.includes(file)&&excludeSensitive&&rendered.execution_scope!=='implementation') dropped.push({path:file,reason:'symlink (the workspace never follows symlinks)'});
712
+ // Implementation directories withhold unnamed links while keeping write access to safe files.
713
+ // Read-only exclusion still narrows scope. An explicitly named link refuses.
714
+ const explicit=new Set(scope.map(outputPathKeys[3]));
715
+ for(const file of scan.symlinks||[]) {
716
+ if(!within(file,scope)) continue;
717
+ if(explicit.has(outputPathKeys[3](file))) throw new Error(`symlink in repository scope: ${file}`);
718
+ if(withholdImplementation||(excludeSensitive&&rendered.execution_scope!=='implementation')) {
719
+ if(!dropped.some(d=>d.path===file)) dropped.push({path:file,reason:'symlink (the workspace never follows symlinks)'});
720
+ }
721
+ }
540
722
  // A scope whose narrowing needs more than maxNarrowedEntries entries is refused (fail closed): keeping the broad scope
541
723
  // would rest on an exact-path exclusion that a case or Unicode alias on a case-insensitive filesystem can miss.
542
- if(dropped.length) narrowedScope=repositoryImplementation?scope:narrowScope(scope,[...new Set([...scan.files,...scan.diffFiles])],dropped.map(d=>d.path));
724
+ if(dropped.length) narrowedScope=withholdImplementation?scope:narrowScope(scope,[...new Set([...scan.files,...scan.diffFiles])],dropped.map(d=>d.path));
543
725
  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
+ const inspectPatchPath=file=>{
727
+ inspectPath(file);
728
+ const key=file.normalize('NFC').toLowerCase();
729
+ if(dropped.some(({path})=>{const excluded=path.normalize('NFC').toLowerCase();return key===excluded||key.startsWith(`${excluded}/`);})) throw new Error(`patch touches excluded scope path: ${file}`);
730
+ if(!within(file,scope)) throw new Error(`patch outside scope_paths: ${file}`);
731
+ };
732
+ for(const file of scan.diffFiles) inspectPatchPath(file);
544
733
  if(input.input_patch) {
545
734
  if(/^new (?:file )?mode 120000$/m.test(input.input_patch)) throw new Error('symlink in input patch scope');
546
735
  const parsed=spawnSync('git',['apply','--numstat','-z','-'],{input:input.input_patch,encoding:'utf8',timeout:10000,maxBuffer:1048576,env:gitEnv()});
@@ -549,7 +738,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
549
738
  for(const entry of parsed.stdout.split('\0').filter(Boolean)) {
550
739
  const file=entry.includes('\t')?entry.split('\t').slice(2).join('\t'):entry;
551
740
  if(!file) continue;
552
- inspectPath(file);if(!within(file,scope)) throw new Error(`patch outside scope_paths: ${file}`);
741
+ inspectPatchPath(file);
553
742
  }
554
743
  }
555
744
  const patch=[scan.diff,input.input_patch||''].join('\n');
@@ -557,13 +746,16 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
557
746
  // The PR diff and input_patch are code under review: path-shaped tokens get the hard and policy checks, like an inlined diff.
558
747
  codeInDiffFences(patch,inspectCode);
559
748
  for(const m of patch.matchAll(/^(?:diff --git a\/(.+) b\/(.+)|(?:---|\+\+\+) [ab]\/(.+)|(?:rename (?:from|to)|copy (?:from|to)) (.+))$/gm)) for(const file of m.slice(1).filter(Boolean)) {
560
- inspectPath(file);if(!within(file,scope)) throw new Error(`patch outside scope_paths: ${file}`);
749
+ inspectPatchPath(file);
561
750
  }
562
751
  if(input.input_patch&&!/^diff --git /m.test(input.input_patch)) throw new Error('incomplete input patch');
563
752
  } else if(scope.length) throw new Error('scope_paths require pinned repository input');
564
- if(!dropped.length) {const done=withOutputPaths(withAllowList(rendered,warn));checkInstructionSize(done);return done;}
753
+ // Persist exactly the normalized scope used above, including the no-growth path.
754
+ const stored=rendered.scope_paths,same=Array.isArray(stored)&&stored.length===scope.length&&stored.every((path,i)=>path===scope[i]);
755
+ const normalized=!same&&(stored!==undefined||scope.length>0)?{...rendered,scope_paths:[...scope]}:rendered;
756
+ if(!dropped.length) {const done=withOutputPaths(withAllowList(normalized,warn));checkInstructionSize(done);return done;}
565
757
  const final=renderAssignment({...assignment,scope_paths:narrowedScope});
566
- const note=`\n\nBridge scope note: ${dropped.length} sensitive file(s) are outside scope_paths; do not read them: ${dropped.slice(0,20).map(d=>d.path).join(', ')}${dropped.length>20?`, and ${dropped.length-20} more`:''}.`;
758
+ const note=`\n\nBridge scope note: ${dropped.length} sensitive file(s) are ${withholdImplementation?'withheld from the workspace':'outside scope_paths'}; do not read them: ${dropped.slice(0,20).map(d=>d.path).join(', ')}${dropped.length>20?`, and ${dropped.length-20} more`:''}.`;
567
759
  const brief=final.brief+note;
568
760
  const expanded={...final,brief,scope_paths:narrowedScope,scope_excluded:dropped,...(final.read_paths!==undefined?{read_paths:narrowedScope}:{}),...(final.read_list!==undefined?{read_list:narrowedScope}:{})};
569
761
  const finalBriefBytes=bytes(brief);
@@ -596,7 +788,7 @@ export function narrowScope(scope,files,bad) {
596
788
  };
597
789
  for(const entry of scope) visit(entry==='.'?'':entry);
598
790
  const narrowed=[...new Set(out)];
599
- if(!narrowed.length) throw new Error(`sensitive scope path: ${bad[0]} (every file in the scope is sensitive)`);
791
+ if(!narrowed.length) throw sensitivePathError(`sensitive scope path: ${bad[0]} (every file in the scope is sensitive)`,bad[0]);
600
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)`);
601
793
  const unnameable=narrowed.find(entry=>{try{paths([entry],'scope_paths');return false;}catch{return true;}});
602
794
  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)`);
@@ -610,14 +802,23 @@ export async function validateSubmissionAsync(assignment,options={}) {
610
802
  let worker;
611
803
  try { worker=new Worker(new URL(import.meta.url),{workerData:{operation:'submission',assignment,options:{...options,warnings:undefined},secrets:registeredSecrets()}}); }
612
804
  catch(error) { throw infrastructureError(error.message); }
805
+ return awaitSubmissionScanner(worker, assignment, options);
806
+ }
807
+
808
+ export function awaitSubmissionScanner(worker, assignment, options = {}) {
613
809
  return new Promise((resolve,reject)=>{
810
+ let replied = false;
614
811
  const timer=setTimeout(()=>{reject(infrastructureError('submission scope scanner timeout'));worker.terminate();},180000);
615
812
  // The worker holds a snapshot of the registry taken when it started. A secret registered later is checked here,
616
813
  // in the main thread, before any verdict is returned.
617
814
  const lateSecret=()=>{try{return hasSecretContent(renderAssignment(assignment));}catch{return false;}};
618
- worker.once('message',message=>{clearTimeout(timer);if(lateSecret())reject(new Error('hard sensitive content exclusion'));else if(message.error)reject(message.code==='DOT_BRIDGE_INFRASTRUCTURE'?infrastructureError(message.error):Object.assign(new Error(message.error),message.suggested_scope_paths?{suggested_scope_paths:message.suggested_scope_paths}:{},message.candidates?{candidates:message.candidates}:{},message.expandedPayload?{expandedPayload:message.expandedPayload}:{}));else {for(const w of message.warnings||[]) if(options.warnings&&!options.warnings.includes(w)) options.warnings.push(w);resolve(message.assignment);}});
815
+ worker.once('message',message=>{replied=true;clearTimeout(timer);if(lateSecret())reject(new Error('hard sensitive content exclusion'));else if(message.error)reject(message.code==='DOT_BRIDGE_INFRASTRUCTURE'?infrastructureError(message.error):Object.assign(new Error(message.error),message.suggested_scope_paths?{suggested_scope_paths:message.suggested_scope_paths}:{},message.candidates?{candidates:message.candidates}:{},message.expandedPayload?{expandedPayload:message.expandedPayload}:{}));else {for(const w of message.warnings||[]) if(options.warnings&&!options.warnings.includes(w)) options.warnings.push(w);resolve(message.assignment);}});
619
816
  worker.once('error',error=>{clearTimeout(timer);reject(infrastructureError(error.message));});
620
- worker.once('exit',code=>{clearTimeout(timer);if(code!==0)reject(infrastructureError('submission scope scanner failed'));});
817
+ worker.once('exit',code=>{
818
+ clearTimeout(timer);
819
+ if (replied) return;
820
+ reject(infrastructureError(code === 0 ? 'scanner_no_reply: submission scope scanner exited without a reply' : 'submission scope scanner failed'));
821
+ });
621
822
  });
622
823
  }
623
824
  if(!isMainThread&&workerData?.operation==='submission') {
@@ -54,7 +54,7 @@ export function compactThreadList(data,{limit=THREAD_LIST_LIMIT,budget=THREAD_LI
54
54
  const shown=[];
55
55
  for(let i=0,used=0;i<threads.length&&shown.length<limit;i++) {
56
56
  const entry=compactThread(threads[i]), bytes=Buffer.byteLength(JSON.stringify(entry))+1;
57
- if(shown.length&&used+bytes>budget) break;
57
+ if(used+bytes>budget) break;
58
58
  shown.push(entry); used+=bytes;
59
59
  }
60
60
  const titles=new Map((Array.isArray(data?.projects)?data.projects:[]).map(p=>[p.id,p.title]));