@sema-agent/core 7.61.0 → 7.62.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.
Files changed (176) hide show
  1. package/CHANGELOG.md +312 -0
  2. package/dist/agents/cascade.d.ts +11 -3
  3. package/dist/agents/cascade.js +1 -1
  4. package/dist/agents/peer-held-queue.d.ts +27 -4
  5. package/dist/agents/peer-held-queue.js +81 -36
  6. package/dist/agents/peer-session-drain.js +13 -3
  7. package/dist/agents/subagent.d.ts +6 -1
  8. package/dist/agents/subagent.js +66 -12
  9. package/dist/agents/suspend-guard.d.ts +38 -16
  10. package/dist/agents/suspend-guard.js +9 -4
  11. package/dist/agents/verify.js +4 -3
  12. package/dist/core/checkpoint-features.d.ts +722 -0
  13. package/dist/core/checkpoint-features.js +98 -0
  14. package/dist/core/checkpoint-requirements.d.ts +9 -2
  15. package/dist/core/checkpoint-requirements.js +9 -4
  16. package/dist/core/checkpoint-row-verdict.d.ts +99 -0
  17. package/dist/core/checkpoint-row-verdict.js +225 -0
  18. package/dist/core/checkpoint-store.d.ts +55 -745
  19. package/dist/core/checkpoint-store.js +39 -141
  20. package/dist/core/engine-notice.d.ts +19 -3
  21. package/dist/core/engine-notice.js +9 -2
  22. package/dist/core/gate-fold.js +2 -2
  23. package/dist/core/governance-codes.d.ts +3 -1
  24. package/dist/core/governance-codes.js +3 -0
  25. package/dist/core/hooks.d.ts +13 -0
  26. package/dist/core/human-input-projection.d.ts +1 -0
  27. package/dist/core/human-input-projection.js +3 -0
  28. package/dist/core/image-admission.d.ts +1 -1
  29. package/dist/core/locked-config.d.ts +2 -2
  30. package/dist/core/mcp-host-seat.js +6 -1
  31. package/dist/core/memory-engine/consolidation-driver.d.ts +1 -1
  32. package/dist/core/memory-vector.d.ts +1 -1
  33. package/dist/core/memory.d.ts +10 -10
  34. package/dist/core/mode-policy.js +1 -1
  35. package/dist/core/mods/classic-events.d.ts +9 -1
  36. package/dist/core/mods/dollar.d.ts +32 -1
  37. package/dist/core/mods/dollar.js +13 -1
  38. package/dist/core/mods/kernel/events.d.ts +11 -3
  39. package/dist/core/mods/kernel/events.js +13 -10
  40. package/dist/core/mods/lifecycle-stations.d.ts +36 -4
  41. package/dist/core/mods/lifecycle-stations.js +44 -9
  42. package/dist/core/mods/session-append.d.ts +4 -1
  43. package/dist/core/mods/session-append.js +7 -0
  44. package/dist/core/mods/session-receive.js +12 -15
  45. package/dist/core/mods/stations.d.ts +51 -6
  46. package/dist/core/mods/stations.js +124 -0
  47. package/dist/core/own-property-receipt.d.ts +7 -0
  48. package/dist/core/own-property-receipt.js +3 -0
  49. package/dist/core/read-root-candidate.js +1 -1
  50. package/dist/core/resume-startup-cause.d.ts +5 -4
  51. package/dist/core/runner/compact-session.js +5 -2
  52. package/dist/core/runner/contracts.d.ts +18 -8
  53. package/dist/core/runner/delegation-owner.d.ts +43 -0
  54. package/dist/core/runner/delegation-owner.js +59 -0
  55. package/dist/core/runner/lineage-reroot-view.d.ts +56 -0
  56. package/dist/core/runner/lineage-reroot-view.js +108 -0
  57. package/dist/core/runner/permission-rule-lanes.d.ts +2 -1
  58. package/dist/core/runner/permission-rule-lanes.js +2 -2
  59. package/dist/core/runner/person-path-rows.d.ts +15 -0
  60. package/dist/core/runner/person-path-rows.js +26 -3
  61. package/dist/core/runner/prepare-acquire-reconcile.d.ts +4 -1
  62. package/dist/core/runner/prepare-acquire-reconcile.js +7 -2
  63. package/dist/core/runner/prepare-caps-and-workflow.d.ts +1 -0
  64. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  65. package/dist/core/runner/prepare-config-doors.d.ts +6 -6
  66. package/dist/core/runner/prepare-config-doors.js +3 -4
  67. package/dist/core/runner/prepare-hands-readface.d.ts +1 -1
  68. package/dist/core/runner/prepare-hands-readface.js +28 -7
  69. package/dist/core/runner/prepare-inherited-gate.d.ts +2 -0
  70. package/dist/core/runner/prepare-inherited-gate.js +7 -3
  71. package/dist/core/runner/prepare-task.js +10 -7
  72. package/dist/core/runner/resume-admission.d.ts +3 -3
  73. package/dist/core/runner/resume-admission.js +6 -3
  74. package/dist/core/runner/resume-apply.d.ts +4 -0
  75. package/dist/core/runner/resume-apply.js +11 -4
  76. package/dist/core/runner/resume-checkpoint-screen.d.ts +9 -0
  77. package/dist/core/runner/resume-checkpoint-screen.js +4 -84
  78. package/dist/core/runner/run-git-lane.d.ts +2 -0
  79. package/dist/core/runner/run-git-lane.js +4 -1
  80. package/dist/core/runner/run-harness-handlers.d.ts +2 -0
  81. package/dist/core/runner/run-harness-handlers.js +3 -2
  82. package/dist/core/runner/run-leg.js +24 -7
  83. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  84. package/dist/core/runner/run-stop-and-final-verify.js +2 -1
  85. package/dist/core/runner/run-turn-boundary.js +7 -4
  86. package/dist/core/runner/runtask.js +6 -6
  87. package/dist/core/runner/steering-preview.d.ts +9 -0
  88. package/dist/core/runner/steering-preview.js +5 -0
  89. package/dist/core/runner/stream-steer-verb.js +8 -0
  90. package/dist/core/runner/tool-face-overlay.js +2 -0
  91. package/dist/core/runner/turn-attachments.d.ts +5 -0
  92. package/dist/core/runner/turn-attachments.js +1 -1
  93. package/dist/core/runner-deps.d.ts +2 -2
  94. package/dist/core/secret-env.d.ts +8 -5
  95. package/dist/core/secret-env.js +37 -18
  96. package/dist/core/session-store.d.ts +1 -1
  97. package/dist/core/session-store.js +5 -1
  98. package/dist/core/session.d.ts +14 -4
  99. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +6 -0
  100. package/dist/core/store-contracts/checkpoint-store-contract.js +68 -0
  101. package/dist/core/store-contracts/session-store-contract.js +22 -8
  102. package/dist/core/task-event.d.ts +7 -1
  103. package/dist/core/task-notification.js +2 -1
  104. package/dist/core/task-registry-agent.d.ts +27 -7
  105. package/dist/core/task-registry-agent.js +12 -5
  106. package/dist/core/task-registry-shared.d.ts +7 -0
  107. package/dist/core/task-registry-workflow.js +4 -3
  108. package/dist/core/task-registry.d.ts +13 -2
  109. package/dist/core/task-registry.js +11 -4
  110. package/dist/core/task-result.d.ts +5 -5
  111. package/dist/core/task-spec.d.ts +1 -1
  112. package/dist/core/terminal-cause.d.ts +6 -6
  113. package/dist/core/tool-face.d.ts +6 -2
  114. package/dist/core/tool-face.js +1 -1
  115. package/dist/core/tool-policy.d.ts +2 -1
  116. package/dist/core/tool-roster.d.ts +4 -4
  117. package/dist/core/tool-spec.d.ts +4 -0
  118. package/dist/core/types.d.ts +1 -1
  119. package/dist/core/types.js +1 -1
  120. package/dist/engine/execution-env/node-execution-env.d.ts +3 -0
  121. package/dist/engine/execution-env/node-execution-env.js +12 -5
  122. package/dist/engine/harness/types.d.ts +11 -0
  123. package/dist/engine/session/parent-chain-guard.d.ts +3 -3
  124. package/dist/engine/session/parent-chain-guard.js +1 -1
  125. package/dist/engine/session/path-to-root.d.ts +18 -3
  126. package/dist/engine/session/path-to-root.js +15 -1
  127. package/dist/engine/session/repo-utils.d.ts +12 -1
  128. package/dist/engine/session/repo-utils.js +41 -0
  129. package/dist/engine/session/session.js +1 -1
  130. package/dist/engine/session/storage-base.d.ts +20 -0
  131. package/dist/engine/session/storage-base.js +28 -9
  132. package/dist/index.d.ts +9 -8
  133. package/dist/index.js +4 -4
  134. package/dist/internal/harness.d.ts +4 -3
  135. package/dist/internal/harness.js +3 -2
  136. package/dist/orchestration/run-workflow-tool.d.ts +3 -0
  137. package/dist/orchestration/run-workflow-tool.js +27 -11
  138. package/dist/orchestration/workflow-governance.d.ts +1 -1
  139. package/dist/orchestration/workflow.d.ts +3 -0
  140. package/dist/orchestration/workflow.js +2 -7
  141. package/dist/stores/file/checkpoint-store.d.ts +2 -0
  142. package/dist/stores/file/checkpoint-store.js +7 -6
  143. package/dist/stores/file/fs-atomic.d.ts +0 -22
  144. package/dist/stores/file/fs-atomic.js +0 -17
  145. package/dist/stores/file/index.d.ts +2 -9
  146. package/dist/stores/file/index.js +2 -4
  147. package/dist/stores/file/session-store.d.ts +13 -7
  148. package/dist/stores/file/session-store.js +40 -17
  149. package/dist/tools/fs/bash-program-position.d.ts +3 -2
  150. package/dist/tools/fs/bash-program-position.js +7 -7
  151. package/dist/tools/fs/removal-targets.js +2 -2
  152. package/dist/tools/fs/shell-read-argv.d.ts +4 -2
  153. package/dist/tools/fs/shell-read-argv.js +14 -3
  154. package/dist/tools/fs/shell-read-bindings.d.ts +18 -2
  155. package/dist/tools/fs/shell-read-bindings.js +148 -68
  156. package/dist/tools/fs/shell-read-check.js +20 -4
  157. package/dist/tools/fs/shell-read-establish.js +22 -8
  158. package/dist/tools/fs/shell-read-functions.js +2 -2
  159. package/dist/tools/fs/shell-read-object-path.d.ts +59 -0
  160. package/dist/tools/fs/shell-read-object-path.js +119 -0
  161. package/dist/tools/fs/shell-read-plan.d.ts +8 -0
  162. package/dist/tools/fs/shell-read-plan.js +47 -30
  163. package/dist/tools/fs/shell-read-start.d.ts +66 -13
  164. package/dist/tools/fs/shell-read-start.js +89 -17
  165. package/dist/tools/fs/shell-read-workdir.d.ts +29 -8
  166. package/dist/tools/fs/shell-read-workdir.js +31 -8
  167. package/package.json +2 -2
  168. package/test/export-surface.snapshot.json +21 -33
  169. package/wire-changes/core-stores-sql@7.62.0.json +30 -0
  170. package/wire-changes/core@7.62.0.json +2181 -0
  171. package/wire-changes/mods-kernel@7.62.0.json +42 -0
  172. package/wire-changes/primitives@7.62.0.json +30 -0
  173. package/dist/core/consolidate-scope.d.ts +0 -93
  174. package/dist/core/consolidate-scope.js +0 -98
  175. package/dist/core/runner/memory-consolidation.d.ts +0 -109
  176. package/dist/core/runner/memory-consolidation.js +0 -251
@@ -89,11 +89,14 @@ export function inheritedExportedFunctions(names) {
89
89
  }
90
90
  const ATTRIBUTE_KINDS = { integer: "integer", transformed: "transformed", frozen: "frozen" };
91
91
  const EVERY_ATTRIBUTE = Object.values(ATTRIBUTE_KINDS).map((kind) => ({ kind }));
92
- export function projectSegment(segment) {
93
- const tokens = [...segment.tokens];
94
- let grouped = tokens.some((t) => t.kind === "group");
95
- const defines = dropDefinitionHeads(tokens).flat();
96
- dropCasePattern(tokens);
92
+ export function projectSegments(segments) {
93
+ const { dropped, arms } = segmentStructure(segments);
94
+ return segments.map((segment, si) => projectSegment(segment, dropped[si], arms[si]));
95
+ }
96
+ function projectSegment(segment, dropped, arm) {
97
+ let grouped = segment.tokens.some((t) => t.kind === "group");
98
+ const defines = dropped.heads.flat();
99
+ const tokens = dropped.tokens.slice(arm.own.size === 0 ? 0 : Math.max(...arm.own) + 1);
97
100
  const words = tokens.filter((t) => {
98
101
  if (t.kind !== "word")
99
102
  return false;
@@ -127,31 +130,96 @@ export function dropDefinitionHeads(tokens) {
127
130
  }
128
131
  return heads;
129
132
  }
130
- function dropCasePattern(tokens) {
131
- const end = casePatternEnd(tokens);
132
- if (end >= 0)
133
- tokens.splice(0, end + 1);
133
+ function withoutDefinitionHeads(segment) {
134
+ const tokens = [...segment.tokens];
135
+ return { tokens, heads: dropDefinitionHeads(tokens) };
134
136
  }
135
- function casePatternEnd(tokens) {
136
- const open = [];
137
- let end = -1;
138
- for (let k = 0; k < tokens.length; k++) {
139
- const t = tokens[k];
140
- if (t.kind === "word" && t.raw === "[[")
141
- return -1;
142
- if (t.kind !== "group")
143
- continue;
144
- if (t.op === "(") {
145
- open.push(k);
146
- continue;
147
- }
148
- const from = open.pop();
149
- if (from !== undefined && extglobParen(tokens, from))
150
- continue;
151
- if (tokens[k + 1]?.kind === "word")
152
- end = k;
153
- }
154
- return end;
137
+ function segmentStructure(segments) {
138
+ const dropped = segments.map((segment) => withoutDefinitionHeads(segment));
139
+ const tokens = dropped.map((d) => d.tokens);
140
+ const operands = operandsOf(tokens, segments.map((segment) => isArithmeticCommand(segment)));
141
+ return { dropped, operands, arms: caseWordsOf(tokens, segments.map((s) => s.connector), operands) };
142
+ }
143
+ function operandsOf(segments, arithmetic) {
144
+ let conditional = false;
145
+ let parens = 0;
146
+ return segments.map((tokens, si) => {
147
+ const out = new Set();
148
+ tokens.forEach((t, k) => {
149
+ if (parens === 0 && !conditional) {
150
+ if (t.kind === "word" && t.atCommandPosition && t.raw === "[[")
151
+ conditional = true;
152
+ else if (t.kind === "group" && t.op === "(" && ((k === 0 && arithmetic[si] === true) || extglobParen(tokens, k))) {
153
+ parens = 1;
154
+ out.add(k);
155
+ }
156
+ return;
157
+ }
158
+ if (parens === 0 && t.kind === "word" && t.raw === "]]") {
159
+ conditional = false;
160
+ return;
161
+ }
162
+ out.add(k);
163
+ if (parens > 0 && t.kind === "group")
164
+ parens += t.op === "(" ? 1 : -1;
165
+ });
166
+ return out;
167
+ });
168
+ }
169
+ function caseWordsOf(segments, connectors, operands) {
170
+ const frames = [];
171
+ const toPattern = (f) => { f.state = "pattern"; f.started = false; };
172
+ return segments.map((tokens, si) => {
173
+ const top = frames[frames.length - 1];
174
+ const next = connectors[si + 1];
175
+ if (top?.state === "arm" && tokens.length === 0 && connectors[si] === ";" && (next === ";" || next === "&"))
176
+ toPattern(top);
177
+ const own = new Set();
178
+ let end = -1;
179
+ tokens.forEach((t, k) => {
180
+ if (operands[si].has(k))
181
+ return;
182
+ const f = frames[frames.length - 1];
183
+ if (f === undefined || f.state === "arm") {
184
+ const keyword = t.kind === "word" && t.atCommandPosition && t.raw === t.folded ? t.folded : undefined;
185
+ if (keyword === "case")
186
+ frames.push({ state: "subject", started: false });
187
+ else if (keyword === "esac" && f !== undefined)
188
+ frames.pop();
189
+ return;
190
+ }
191
+ if (f.state === "subject") {
192
+ if (t.kind === "word") {
193
+ own.add(k);
194
+ f.state = "in";
195
+ }
196
+ else
197
+ frames.pop();
198
+ return;
199
+ }
200
+ if (f.state === "in") {
201
+ if (t.kind === "word" && t.raw === "in") {
202
+ own.add(k);
203
+ toPattern(f);
204
+ }
205
+ else
206
+ frames.pop();
207
+ return;
208
+ }
209
+ if (!f.started && t.kind === "word" && t.raw === "esac") {
210
+ frames.pop();
211
+ return;
212
+ }
213
+ own.add(k);
214
+ if (t.kind === "group" && t.op === ")") {
215
+ end = k;
216
+ f.state = "arm";
217
+ return;
218
+ }
219
+ f.started = true;
220
+ });
221
+ return { own, end };
222
+ });
155
223
  }
156
224
  function extglobParen(tokens, at) {
157
225
  const before = tokens[at - 1];
@@ -174,9 +242,11 @@ function blockStructure(segments) {
174
242
  while (frames.length > 0 && frames[frames.length - 1].opened && depth <= frames[frames.length - 1].body.base)
175
243
  frames.pop();
176
244
  };
177
- return segments.map((segment) => {
178
- const tokens = [...segment.tokens];
179
- const heads = dropDefinitionHeads(tokens);
245
+ const { dropped, operands, arms } = segmentStructure(segments);
246
+ return segments.map((segment, si) => {
247
+ const { tokens, heads } = dropped[si];
248
+ const arm = arms[si];
249
+ const operand = operands[si];
180
250
  const defs = [];
181
251
  const startBodies = (k) => {
182
252
  for (const name of heads[k]) {
@@ -186,40 +256,32 @@ function blockStructure(segments) {
186
256
  }
187
257
  };
188
258
  const arithmetic = isArithmeticCommand(segment);
189
- const patternEnd = casePatternEnd(tokens);
190
- const skipped = new Set();
191
- const open = [];
192
259
  let lowest = depth;
193
260
  let words;
194
261
  let subshells;
195
262
  let body;
263
+ let within = [];
196
264
  const switches = [];
197
265
  const innermost = () => [...frames].reverse().find((f) => f.opened)?.body;
266
+ const openBodies = () => frames.filter((f) => f.opened).map((f) => f.body.id);
267
+ const place = () => { words ??= depth; subshells ??= [...subshellStack]; body = innermost(); within = openBodies(); };
198
268
  const visit = (t, k) => {
269
+ if (arm.own.has(k)) {
270
+ if (k === arm.end)
271
+ switches.push(depth);
272
+ return;
273
+ }
274
+ if (operand.has(k)) {
275
+ if (t.kind === "word")
276
+ place();
277
+ return;
278
+ }
199
279
  if (t.kind === "group") {
200
- if (arithmetic || skipped.has(k))
201
- return;
202
280
  if (t.op === "(") {
203
- if (extglobParen(tokens, k)) {
204
- skipped.add(k);
205
- open.push(-1);
206
- return;
207
- }
208
- open.push(k);
209
- if (k <= patternEnd)
210
- return;
211
281
  deeper();
212
282
  subshellStack.push(subshellIds++);
213
283
  return;
214
284
  }
215
- const from = open.pop();
216
- if (from === -1)
217
- return;
218
- if (k <= patternEnd) {
219
- if (k === patternEnd)
220
- switches.push(depth);
221
- return;
222
- }
223
285
  shallower();
224
286
  subshellStack.pop();
225
287
  lowest = Math.min(lowest, depth);
@@ -236,11 +298,8 @@ function blockStructure(segments) {
236
298
  }
237
299
  else if (keyword !== undefined && SWITCHING_WORDS.has(keyword))
238
300
  switches.push(depth);
239
- else if (k > patternEnd) {
240
- words ??= depth;
241
- subshells ??= [...subshellStack];
242
- body = innermost();
243
- }
301
+ else
302
+ place();
244
303
  };
245
304
  tokens.forEach((t, k) => {
246
305
  startBodies(k);
@@ -257,8 +316,10 @@ function blockStructure(segments) {
257
316
  else
258
317
  f.flat = true;
259
318
  }
260
- if (settled && t.kind === "word")
319
+ if (settled && t.kind === "word") {
261
320
  body = innermost();
321
+ within = openBodies();
322
+ }
262
323
  const top = frames[frames.length - 1];
263
324
  if (top?.parens !== undefined && t.kind === "group") {
264
325
  top.parens += t.op === "(" ? 1 : -1;
@@ -272,7 +333,7 @@ function blockStructure(segments) {
272
333
  while (frames.length > 0 && frames[frames.length - 1].flat === true)
273
334
  frames.pop();
274
335
  startBodies(tokens.length);
275
- return { words: words ?? depth, after: depth, lowest, switches, subshells: subshells ?? [...subshellStack], defs, ...(body !== undefined ? { body } : {}) };
336
+ return { words: words ?? depth, after: depth, lowest, switches, subshells: subshells ?? [...subshellStack], defs, placed: words !== undefined, within, ...(body !== undefined ? { body } : {}) };
276
337
  });
277
338
  }
278
339
  const READABLE_VALUE = /^[^\\~()]*$/;
@@ -547,13 +608,13 @@ export function bindingEffectOf(segment, argv, shape, readValue, shadow, availab
547
608
  const pos = readProgramPosition(argv);
548
609
  const program = pos.program;
549
610
  const row = program === undefined ? undefined : programRow(program.basename);
550
- const statement = program === undefined && pos.launchers.length === 0 && pos.refusal === undefined;
611
+ const statement = assignsAsStatement(pos);
551
612
  for (const k of pos.assignments) {
552
613
  const a = argv[k].assignment;
553
614
  if (a === undefined)
554
615
  continue;
555
616
  if (statement)
556
- bind({ name: a.name, state: assignedState(a, readValue, overlay), ...(a.form === "compound" ? { floor: compoundFloor(a.value.raw, readValue, overlay) } : {}) });
617
+ bind({ name: a.name, state: assignedState(a, readValue, overlay), ...(bindsArrayElement(a) ? { floor: arrayElementFloor(a, readValue, overlay) } : {}) });
557
618
  else if (program !== undefined && SPECIAL_BUILTINS.has(program.basename))
558
619
  bind({ name: a.name, state: assignedState(a, readValue, overlay), prefix: true });
559
620
  }
@@ -607,8 +668,8 @@ export function bindingEffectOf(segment, argv, shape, readValue, shadow, availab
607
668
  if (name === undefined)
608
669
  continue;
609
670
  const refused = attributes.some((x) => x.name === undefined || x.name === name);
610
- if (a?.form === "compound")
611
- bind({ name, state: "unknown", floor: compoundFloor(a.value.raw, readValue, expanded) });
671
+ if (a !== undefined && bindsArrayElement(a))
672
+ bind({ name, state: "unknown", floor: arrayElementFloor(a, readValue, expanded) });
612
673
  else if (a === undefined || !storesText || refused)
613
674
  kill(name);
614
675
  else
@@ -686,8 +747,15 @@ function compoundElementWords(raw) {
686
747
  return [prefix === undefined ? element : value, ...(folded !== undefined ? [{ pieces: element.pieces, folded: element.folded.slice(folded.length), tail: true }] : [])].filter((w) => w !== undefined);
687
748
  });
688
749
  }
689
- function compoundFloor(raw, readValue, overlay) {
690
- return compoundElementWords(raw).flatMap((w) => {
750
+ export function bindsArrayElement(a) {
751
+ return a.form === "compound" || a.subscript !== undefined;
752
+ }
753
+ export function assignsAsStatement(pos) {
754
+ return pos.program === undefined && pos.launchers.length === 0 && pos.refusal === undefined;
755
+ }
756
+ function arrayElementFloor(a, readValue, overlay) {
757
+ const words = a.form === "compound" ? compoundElementWords(a.value.raw) : [{ pieces: a.value.pieces, folded: a.value.folded }];
758
+ return words.flatMap((w) => {
691
759
  const v = w.tail === true ? "unknown" : readValue(w, true, overlay);
692
760
  if (v !== "unknown")
693
761
  return v.map(floorOf);
@@ -725,8 +793,9 @@ export function namesBoundIn(text, depth = 0) {
725
793
  return "all";
726
794
  const names = new Set();
727
795
  const nothing = () => "unknown";
728
- for (const segment of lexed.segments) {
729
- const p = projectSegment(segment);
796
+ const projected = projectSegments(lexed.segments);
797
+ for (const [si, segment] of lexed.segments.entries()) {
798
+ const p = projected[si];
730
799
  const effect = bindingEffectOf(segment, p.argv, p, nothing);
731
800
  if (effect.all === "unknown")
732
801
  return "all";
@@ -909,6 +978,17 @@ export class BindingThread {
909
978
  const own = this.standingOf(at, b.name).body;
910
979
  return own !== undefined && b.scope !== "local" ? own : undefined;
911
980
  }
981
+ reaches(at, j) {
982
+ if (j !== undefined && !this.blocks[j].placed)
983
+ return true;
984
+ const s = this.standingOf(at);
985
+ const reader = j === undefined ? undefined : this.blocks[j];
986
+ if (s.body !== undefined && !(reader?.within ?? []).includes(s.body.id))
987
+ return false;
988
+ if (j !== at && this.ownSubshellAt(at, s))
989
+ return false;
990
+ return s.subshells.every((id) => (reader?.subshells ?? []).includes(id));
991
+ }
912
992
  inFunctionBody(at) {
913
993
  return this.blocks[at].body !== undefined;
914
994
  }
@@ -303,13 +303,28 @@ function refusalOf(tool, fold, boundary, paths) {
303
303
  const target = w.read.target ?? w.deny.matchedView;
304
304
  const write = w.deny.face === "write";
305
305
  const core = readDenySentence({ target, pattern: w.deny.pattern, matchedView: w.deny.matchedView, ...(write ? { face: "write" } : {}) });
306
- const sentence = `Error (${tool}): ${core} ${write ? WRITE_DENY_REFUSAL_NOTE : DENY_REFUSAL_NOTE}`;
306
+ const through = deniedThrough(w.read, boundary);
307
+ const sentence = `Error (${tool}): ${core} ${write ? WRITE_DENY_REFUSAL_NOTE : DENY_REFUSAL_NOTE}${through !== undefined ? ` ${DENIED_THROUGH_NOTE[through]}` : ""}`;
307
308
  return { sentence, ...(write ? {} : { details: violationDetails({ code: "read_path_denied", message: sentence, target, pattern: w.deny.pattern }) }) };
308
309
  }
309
310
  const account = findingAccount(fold, boundary);
310
311
  const sentence = `Error (${tool}): ${account}. ${BASH_READONLY_CONFINEMENT_NOTE}`;
311
312
  return { sentence, details: findingDetails(fold.finding, paths) };
312
313
  }
314
+ const DENIED_THROUGH_NOTE = {
315
+ home: "The word was judged as spelled with the environment's declared home: the command may rebind HOME before it, or hands " +
316
+ "the program a literal ~ it may expand itself — the shell may open another file, and a deny row is refused wherever the command may read it.",
317
+ floor: "The working directory at this word is not settled — a move before it may fail or is one this boundary does not follow — " +
318
+ "so the word was also judged where the command stood before that move (a bare cd stands it in the declared home).",
319
+ };
320
+ function deniedThrough(read, boundary) {
321
+ if (read.established === "unestablishable" && read.candidate.bases === "unmodelled")
322
+ return "floor";
323
+ const home = boundary.homeDir;
324
+ if (read.candidate.denyOnly === true && home !== undefined && withinAnyRoot([home], read.candidate.spelled) && /~|HOME/.test(read.candidate.raw))
325
+ return "home";
326
+ return undefined;
327
+ }
313
328
  const WRITE_DENY_REFUSAL_NOTE = "The boundary judges this command's write targets — its output redirections and the operands of mkdir, touch, rm, " +
314
329
  "rmdir, mv, cp, tee and an in-place sed — against the write deny list; a denied write is refused here rather than escalated.";
315
330
  const DENY_REFUSAL_NOTE = "The read boundary judges the paths this command names — as written and, where a filesystem can be consulted, where " +
@@ -343,8 +358,9 @@ function verdictOf(tool, seat, fold, judged, boundary) {
343
358
  ...(grant !== undefined ? { readRootCandidate: { dir: grant.dir, ...(grant.covers !== undefined ? { covers: grant.covers } : {}), clearsThisAsk: true } } : {}),
344
359
  };
345
360
  }
346
- function declarationsOf(boundary, readers, cdPath) {
347
- return { readers, cwd: boundary.cwd ?? boundary.roots[0] ?? "", roots: boundary.roots, cdPath, ...(boundary.homeDir !== undefined ? { homeDir: boundary.homeDir } : {}), ...(boundary.face !== undefined ? { face: boundary.face } : {}) };
361
+ function declarationsOf(boundary, readers, cdPath, receivedEnvNames) {
362
+ const names = Array.isArray(receivedEnvNames) && receivedEnvNames.every((n) => typeof n === "string") ? { receivedEnvNames: receivedEnvNames } : {};
363
+ return { readers, cwd: boundary.cwd ?? boundary.roots[0] ?? "", roots: boundary.roots, cdPath, ...names, ...(boundary.homeDir !== undefined ? { homeDir: boundary.homeDir } : {}), ...(boundary.face !== undefined ? { face: boundary.face } : {}) };
348
364
  }
349
365
  function judgePlan(plan, established, boundary) {
350
366
  return judgeEstablishedPlan(plan, established.reads, boundary, (n) => {
@@ -381,7 +397,7 @@ async function applyAlsoInside(judged, boundary) {
381
397
  return rewrite(judged);
382
398
  }
383
399
  async function runShellReadStation(tool, command, declared, seat, readers, establisher, env, signal) {
384
- const plan = planShellReads(command, declarationsOf(declared, readers, env.cdPath));
400
+ const plan = planShellReads(command, declarationsOf(declared, readers, env.cdPath, env.receivedEnvNames));
385
401
  const door = observeEnvironment(env);
386
402
  const established = await establisher.establish(plan, declared, signal, door);
387
403
  const boundary = { ...declared, roots: established.roots };
@@ -7,6 +7,7 @@ import { movedReads, withHomeViews } from "./shell-read-identity.js";
7
7
  import { passesUnasked } from "./shell-read-device.js";
8
8
  import { compileFsGlob, fsGlobClass } from "./fs-glob.js";
9
9
  import { chainHopsOrNone, leafChainMayHold, symlinkChainHops } from "../../core/path-identity.js";
10
+ import { everyAncestor, repositoryTopOf } from "./shell-read-object-path.js";
10
11
  const GLOB_METACHAR_RE = /[*?[]/;
11
12
  export const MAX_GLOB_DIRS = 256;
12
13
  export const MAX_GLOB_MATCHES = 8192;
@@ -92,17 +93,17 @@ function pathSegmentsFrom(p, from, posix = false) {
92
93
  function basesFor(candidate, boundary) {
93
94
  if (candidate.bases === "unmodelled")
94
95
  return "unmodelled";
95
- if (candidate.bases.length > 0)
96
- return candidate.bases;
97
- return [boundary.cwd ?? boundary.roots[0] ?? ""];
96
+ const bases = candidate.bases.length > 0 ? candidate.bases : [boundary.cwd ?? boundary.roots[0] ?? ""];
97
+ return candidate.repositoryTop !== undefined ? everyAncestor(bases) : bases;
98
98
  }
99
- function lexicalReadsOf(candidate, boundary) {
99
+ function lexicalReadsOf(candidate, boundary, placed) {
100
100
  if (candidate.expands === "unresolvable") {
101
101
  return [{ candidate, established: "unestablishable", spellings: [candidate.spelled], cause: `"${candidate.raw}" is rewritten by the shell before the program sees it` }];
102
102
  }
103
- const bases = basesFor(candidate, boundary);
103
+ const bases = placed ?? basesFor(candidate, boundary);
104
104
  if (bases === "unmodelled") {
105
- const floors = candidate.floorBases ?? [boundary.cwd ?? boundary.roots[0] ?? ""];
105
+ const floorsAt = candidate.floorBases ?? [boundary.cwd ?? boundary.roots[0] ?? ""];
106
+ const floors = candidate.repositoryTop !== undefined ? everyAncestor(floorsAt) : floorsAt;
106
107
  const spellings = [candidate.spelled];
107
108
  for (const floorBase of floors) {
108
109
  const viaFloor = floorBase === "" ? undefined : resolveOperandSpellings(floorBase, candidate.spelled, boundary.homeDir);
@@ -226,6 +227,18 @@ function establishLegOver(seen, readRoots) {
226
227
  const SEP = family === "posix" ? /\// : /[\\/]/;
227
228
  const TRAILING_SEP = family === "posix" ? /\/+$/ : /[\\/]+$/;
228
229
  const joinUnder = (dir, name) => `${dir.replace(TRAILING_SEP, "")}/${name}`;
230
+ const tops = new Map();
231
+ const atRepositoryTops = async (starts, signal) => {
232
+ const out = new Set();
233
+ for (const start of starts) {
234
+ if (!tops.has(start))
235
+ tops.set(start, repositoryTopOf(env, start, family, signal));
236
+ const top = await tops.get(start);
237
+ for (const b of top !== undefined ? [top] : everyAncestor([start]))
238
+ out.add(b);
239
+ }
240
+ return [...out];
241
+ };
229
242
  const resolveWithoutParentSteps = async (p, signal, writeTarget = false, linkHops = WRITE_LINK_HOPS) => {
230
243
  const parts = p.split(SEP);
231
244
  const tail = [];
@@ -521,7 +534,8 @@ function establishLegOver(seen, readRoots) {
521
534
  const node = await rootKindOf(read.target, signal);
522
535
  out.push({ ...read, ...(node !== undefined ? { node } : {}) });
523
536
  };
524
- for (const [i, lexical] of lexicalReadsOf(candidate, boundary).entries()) {
537
+ const placed = candidate.repositoryTop === "discovered" && candidate.bases !== "unmodelled" && candidate.bases.length > 0 ? await atRepositoryTops(candidate.bases, signal) : undefined;
538
+ for (const [i, lexical] of lexicalReadsOf(candidate, boundary, placed).entries()) {
525
539
  if (lexical.established !== "lexical" || passesUnasked(candidate)) {
526
540
  out.push(writtenAt(lexical, writtenSeats, writtenSeats.written.includes("landing") ? "landing" : "entry"));
527
541
  continue;
@@ -531,7 +545,7 @@ function establishLegOver(seen, readRoots) {
531
545
  const walked = spellings.find((s) => s !== folded) ?? folded;
532
546
  if (candidate.expands === "glob") {
533
547
  let matched = false;
534
- for (const p of candidate.pattern === undefined ? spellings : lexicalReadsOf({ ...candidate, spelled: candidate.pattern }, boundary)[i]?.spellings ?? spellings) {
548
+ for (const p of candidate.pattern === undefined ? spellings : lexicalReadsOf({ ...candidate, spelled: candidate.pattern }, boundary, placed)[i]?.spellings ?? spellings) {
535
549
  const expanded = await expandGlobCandidate(p, roots, signal);
536
550
  if (expanded !== undefined && "unverifiable" in expanded) {
537
551
  out.push({ candidate, established: "unestablishable", spellings, origin: folded, cause: expanded.unverifiable });
@@ -1,6 +1,6 @@
1
1
  import { lexShell, literalTextOf } from "../../shell/lex.js";
2
2
  import { readProgramPosition } from "./bash-program-position.js";
3
- import { SPECIAL_BUILTINS, projectSegment } from "./shell-read-bindings.js";
3
+ import { SPECIAL_BUILTINS, projectSegments } from "./shell-read-bindings.js";
4
4
  import { reentryText } from "./shell-reentry-text.js";
5
5
  export function functionCallOf(argv, functions, stateOf = () => "maybe") {
6
6
  const pos = readProgramPosition(argv);
@@ -23,7 +23,7 @@ export function evalDefinedFunctions(argvs, depth = 0) {
23
23
  const lexed = words.length > 0 && words.every((t) => t !== undefined) ? lexShell(reentryText("eval", words) ?? "") : undefined;
24
24
  if (lexed === undefined || "parseFailure" in lexed)
25
25
  return [];
26
- const inner = lexed.segments.map((segment) => projectSegment(segment));
26
+ const inner = projectSegments(lexed.segments);
27
27
  return [...inner.flatMap((p) => p.defines), ...evalDefinedFunctions(inner.map((p) => p.argv), depth + 1)];
28
28
  });
29
29
  }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * AN OBJECT PATH — `<rev>:<path>` (`git show HEAD:x`, `git cat-file -p :0:x`) — and the file of the working tree it names,
3
+ * which is what the deny rows are met at. The place is where git resolves the path (gitrevisions(7)):
4
+ * · spelled `./…` / `../…`, it is relative to the directory git starts in;
5
+ * · any other spelling is relative to the repository's TOP: the directory `--work-tree` names, else the one git's discovery
6
+ * finds walking up from where it starts — a filesystem fact ({@link repositoryTopOf}), read by the establishment where it
7
+ * has a filesystem, never by the plan;
8
+ * · git starts in the command's directory moved by each `-C` (git chdir()s to the spelling: the kernel's walk of it).
9
+ * Where git may be pointed at a repository by other means (`--git-dir`, `--bare`, a `GIT_*` variable the command's
10
+ * environment may carry — bound in the text, or received from the environment that runs it, `ExecutionEnv.receivedEnvNames`),
11
+ * where the text does not settle where git starts, or where the filesystem does not say, the top is any directory at or above
12
+ * where git starts: every ancestor meets the deny rows.
13
+ */
14
+ import type { ExecutionEnv } from "../../internal/harness-types.js";
15
+ import { type ProgramRow } from "./program-read-model.js";
16
+ import { type PathFamily } from "./safety.js";
17
+ import type { Read } from "./shell-read-word.js";
18
+ /** What git's own options in front of the subcommand say about the repository an object path resolves in. */
19
+ export interface ObjectPathRepository {
20
+ /** Each `-C` value, in order (`undefined`: one the text does not settle). */
21
+ readonly moves: readonly (string | undefined)[];
22
+ /** The last `--work-tree` value (`null`: one the text does not settle). */
23
+ readonly workTree?: string | null;
24
+ /** `--git-dir` / `--bare`: the repository is named, and only its configuration knows its top. */
25
+ readonly named?: true;
26
+ }
27
+ /** How an object path's top is found: `discovered` — by git's discovery from where it starts; `unknown` — not from the text. */
28
+ export type RepositoryTop = "discovered" | "unknown";
29
+ /** {@link ObjectPathRepository} of the program's words in front of its subcommand, read by the program's own row. */
30
+ export declare function objectPathRepositoryOf(row: ProgramRow | undefined, globals: readonly Read[]): ObjectPathRepository;
31
+ /** Whether a command's environment may carry a variable git reads for its repository (any `GIT_*` name one of its parts holds;
32
+ * `all`: a part whose names are not known). */
33
+ export declare function mayCarryGitVariables(...names: readonly (Iterable<string> | "all")[]): boolean;
34
+ /** Where a process stands after it `chdir()`s to `spelling` from each of `bases` (git's `-C`, a launcher's working-directory
35
+ * option): the kernel's walk of the spelling, a `..` kept (`<base>/link/..` is the link target's parent, not `<base>`).
36
+ * `undefined` where the spelling resolves to no place from some base (`~user`, a namespace spelling the base's family refuses). */
37
+ export declare function chdirFrom(bases: readonly string[], spelling: string, homeDir: string | undefined): string[] | undefined;
38
+ /** The place of a RELATIVE object path: the directories it is relative to (`at`: where the command stands; `floor`: the deny
39
+ * floor of an unsettled `at`), and how its top is found where it is relative to the top. */
40
+ export declare function objectPathPlacement(spelled: string, repository: ObjectPathRepository | undefined, at: readonly string[] | "unmodelled", floor: readonly string[] | undefined, homeDir: string | undefined, variables: boolean): {
41
+ readonly bases: readonly string[] | "unmodelled";
42
+ readonly floorBases?: readonly string[];
43
+ readonly repositoryTop?: RepositoryTop;
44
+ };
45
+ /** Each directory, and every directory above it (its `..`-folded spelling's, a spelling that climbs kept beside them). */
46
+ export declare function everyAncestor(dirs: readonly string[]): string[];
47
+ /** What {@link repositoryTopOf} asks of the environment (the station's door, where it has one). */
48
+ export type RepositoryProbe = Pick<ExecutionEnv, "canonicalPath" | "fileInfo" | "readTextFile" | "readLink">;
49
+ /**
50
+ * The repository top git's discovery finds starting in `dir` (setup.c `setup_git_directory_gently_1`): walking up from the
51
+ * directory's canonical form, the first directory holding a `.git` DIRECTORY that is a repository (`HEAD` naming a ref or an
52
+ * object id, `objects/` and `refs/` directories) whose own `config` names no work tree. `undefined` wherever git's answer may be
53
+ * another directory, or the history it reads another directory's: a `.git` that is not such a directory — a `gitdir:` file or a
54
+ * link, which name a repository kept elsewhere (a linked work tree's, a submodule's, the home's own), or one git skips (an
55
+ * empty or broken one) and walks on from —, a directory that is itself a repository (a bare one, the inside of a `.git`), a
56
+ * configuration that may name the work tree, no repository at all, or a lookup the environment did not answer. Any reader of
57
+ * "which repository does git run in from here" reads it.
58
+ */
59
+ export declare function repositoryTopOf(fs: RepositoryProbe, dir: string, family: PathFamily, signal?: AbortSignal): Promise<string | undefined>;
@@ -0,0 +1,119 @@
1
+ import { literalTildeSpelling } from "../../shell/lex.js";
2
+ import { resolveOperandLexically, resolveOperandSpellings } from "./bash-readonly-classifier.js";
3
+ import { readArgRoles } from "./program-read-model.js";
4
+ import { anchorSpelling, normalizeAbsPathLexically } from "./safety.js";
5
+ import { isAbsence } from "./shell-read-environment.js";
6
+ const STARTS_IN = "-C";
7
+ const NAMES_TOP = "--work-tree";
8
+ const NAMES_REPOSITORY = new Set(["--git-dir", "--bare"]);
9
+ export function objectPathRepositoryOf(row, globals) {
10
+ const words = globals.map((r) => r.folded);
11
+ const settled = (r, value) => (r.expands === false && (r.values?.length ?? 1) <= 1 ? value : undefined);
12
+ const moves = [];
13
+ let workTree;
14
+ let named = false;
15
+ for (const e of row === undefined ? [] : readArgRoles(row, words)) {
16
+ if (e.kind !== "value" && e.kind !== "option")
17
+ continue;
18
+ const option = e.kind === "value" ? words[e.of] : words[e.at].split("=")[0];
19
+ const value = e.kind === "value" ? settled(globals[e.at], words[e.at]) : typeof e.reading === "object" ? settled(globals[e.at], literalTildeSpelling(e.reading.attached)) : undefined;
20
+ if (option === STARTS_IN)
21
+ moves.push(value);
22
+ else if (option === NAMES_TOP)
23
+ workTree = value ?? null;
24
+ else if (NAMES_REPOSITORY.has(option))
25
+ named = true;
26
+ }
27
+ return { moves, ...(workTree !== undefined ? { workTree } : {}), ...(named ? { named: true } : {}) };
28
+ }
29
+ export function mayCarryGitVariables(...names) {
30
+ return names.some((part) => part === "all" || [...part].some((n) => n.startsWith("GIT_")));
31
+ }
32
+ export function chdirFrom(bases, spelling, homeDir) {
33
+ const out = bases.map((b) => resolveOperandSpellings(b, spelling, homeDir)).map((s) => s?.spelled ?? s?.folded);
34
+ return out.every((p) => p !== undefined) ? [...new Set(out)] : undefined;
35
+ }
36
+ export function objectPathPlacement(spelled, repository, at, floor, homeDir, variables) {
37
+ const dotted = /^\.\.?(?:\/|$)/.test(spelled);
38
+ const place = (bases, word) => chdirFrom(bases, word, homeDir);
39
+ const unplaced = (top) => {
40
+ const floors = at === "unmodelled" ? floor : at;
41
+ return { bases: "unmodelled", ...(floors !== undefined && floors.length > 0 ? { floorBases: floors } : {}), ...(top !== undefined ? { repositoryTop: top } : {}) };
42
+ };
43
+ let starts = at === "unmodelled" ? undefined : at;
44
+ for (const move of repository?.moves ?? [])
45
+ if (starts !== undefined && move !== "")
46
+ starts = move === undefined ? undefined : place(starts, move);
47
+ if (starts === undefined)
48
+ return unplaced(dotted ? undefined : "unknown");
49
+ if (dotted)
50
+ return { bases: starts };
51
+ const workTree = repository?.workTree;
52
+ if (workTree !== undefined) {
53
+ const tops = workTree === null ? undefined : place(starts, workTree);
54
+ return tops === undefined ? unplaced("unknown") : { bases: tops };
55
+ }
56
+ return { bases: starts, repositoryTop: repository?.named === true || variables ? "unknown" : "discovered" };
57
+ }
58
+ export function everyAncestor(dirs) {
59
+ const out = new Set(dirs);
60
+ for (const dir of dirs) {
61
+ for (let d = resolveOperandLexically(dir, ".", undefined) ?? dir;;) {
62
+ out.add(d);
63
+ const up = resolveOperandLexically(d, "..", undefined) ?? d;
64
+ if (up === d)
65
+ break;
66
+ d = up;
67
+ }
68
+ }
69
+ return [...out];
70
+ }
71
+ const READ_LIMIT = 65_536;
72
+ export async function repositoryTopOf(fs, dir, family, signal) {
73
+ const start = await fs.canonicalPath(dir, signal);
74
+ if (!start.ok)
75
+ return undefined;
76
+ const entry = async (path) => {
77
+ const info = await fs.fileInfo(path, signal);
78
+ if (!info.ok)
79
+ return isAbsence(info.error.code) ? "absent" : "unanswered";
80
+ return info.value.kind === "symlink" ? "link" : info.value.kind;
81
+ };
82
+ const text = async (path) => {
83
+ const info = await fs.fileInfo(path, signal);
84
+ if (!info.ok || info.value.kind !== "file" || info.value.size > READ_LIMIT)
85
+ return undefined;
86
+ const read = await fs.readTextFile(path, signal);
87
+ return read.ok ? read.value : undefined;
88
+ };
89
+ const isRepository = async (git) => {
90
+ for (const name of ["objects", "refs"]) {
91
+ const info = await fs.fileInfo(anchorSpelling(family, git, name), signal);
92
+ if (!info.ok || info.value.kind !== "directory" || (info.value.mode !== undefined && (info.value.mode & 0o100) === 0))
93
+ return false;
94
+ }
95
+ const head = anchorSpelling(family, git, "HEAD");
96
+ const headRef = (await entry(head)) === "link" ? await fs.readLink?.(head, signal).then((r) => (r.ok && r.value.startsWith("refs/") ? "ref: refs/" : undefined)) : await text(head);
97
+ if (headRef === undefined || !/^(?:ref:[ \t\n\r]*refs\/|[0-9a-fA-F]{40})/.test(headRef.slice(0, 255)))
98
+ return false;
99
+ const config = anchorSpelling(family, git, "config");
100
+ return (await entry(config)) === "absent" || ((await text(config)) ?? "worktree").search(/worktree/i) < 0;
101
+ };
102
+ for (let d = start.value;;) {
103
+ const git = anchorSpelling(family, d, ".git");
104
+ const found = await entry(git);
105
+ if (found === "directory")
106
+ return (await isRepository(git)) ? d : undefined;
107
+ if (found !== "absent")
108
+ return undefined;
109
+ const head = await entry(anchorSpelling(family, d, "HEAD"));
110
+ if (head === "unanswered")
111
+ return undefined;
112
+ if (head !== "absent" && ((await entry(anchorSpelling(family, d, "refs"))) !== "absent" || (await entry(anchorSpelling(family, d, "commondir"))) !== "absent"))
113
+ return undefined;
114
+ const up = normalizeAbsPathLexically(anchorSpelling(family, d, ".."));
115
+ if (up === d)
116
+ return undefined;
117
+ d = up;
118
+ }
119
+ }