@sema-agent/core 7.61.0 → 7.63.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 (298) hide show
  1. package/CHANGELOG.md +840 -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-transcript-placement.d.ts +23 -0
  8. package/dist/agents/subagent-transcript-placement.js +14 -0
  9. package/dist/agents/subagent.d.ts +6 -1
  10. package/dist/agents/subagent.js +143 -58
  11. package/dist/agents/suspend-guard.d.ts +38 -16
  12. package/dist/agents/suspend-guard.js +9 -4
  13. package/dist/agents/verify.js +4 -3
  14. package/dist/brain/route-adjudicator.js +9 -4
  15. package/dist/core/approval-object.js +1 -1
  16. package/dist/core/arg-summary.js +1 -1
  17. package/dist/core/ask-question.d.ts +2 -2
  18. package/dist/core/canonical-json.d.ts +23 -13
  19. package/dist/core/canonical-json.js +4 -4
  20. package/dist/core/checkpoint-features.d.ts +722 -0
  21. package/dist/core/checkpoint-features.js +98 -0
  22. package/dist/core/checkpoint-queries.d.ts +47 -4
  23. package/dist/core/checkpoint-queries.js +36 -16
  24. package/dist/core/checkpoint-requirements.d.ts +12 -5
  25. package/dist/core/checkpoint-requirements.js +11 -5
  26. package/dist/core/checkpoint-row-verdict.d.ts +110 -0
  27. package/dist/core/checkpoint-row-verdict.js +245 -0
  28. package/dist/core/checkpoint-store.d.ts +76 -753
  29. package/dist/core/checkpoint-store.js +83 -144
  30. package/dist/core/compliance.d.ts +6 -2
  31. package/dist/core/compliance.js +3 -3
  32. package/dist/core/engine-attestation.d.ts +1 -1
  33. package/dist/core/engine-notice.d.ts +38 -7
  34. package/dist/core/engine-notice.js +9 -2
  35. package/dist/core/gate-fold.js +2 -2
  36. package/dist/core/git-worktree-env.d.ts +62 -3
  37. package/dist/core/git-worktree-env.js +91 -30
  38. package/dist/core/governance-codes.d.ts +9 -3
  39. package/dist/core/governance-codes.js +16 -3
  40. package/dist/core/hooks.d.ts +13 -0
  41. package/dist/core/human-input-projection.d.ts +1 -0
  42. package/dist/core/human-input-projection.js +3 -0
  43. package/dist/core/image-admission.d.ts +1 -1
  44. package/dist/core/locked-config.d.ts +2 -2
  45. package/dist/core/mcp-host-seat.js +6 -1
  46. package/dist/core/memory-engine/consolidation-driver.d.ts +33 -18
  47. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  48. package/dist/core/memory-engine/consolidation.d.ts +73 -10
  49. package/dist/core/memory-engine/consolidation.js +167 -11
  50. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  51. package/dist/core/memory-engine/data-plane.js +11 -6
  52. package/dist/core/memory-engine/delegation-settlement.d.ts +37 -35
  53. package/dist/core/memory-engine/delegation-settlement.js +53 -59
  54. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  55. package/dist/core/memory-engine/dual-root.js +9 -5
  56. package/dist/core/memory-engine/engine.d.ts +98 -35
  57. package/dist/core/memory-engine/engine.js +477 -380
  58. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  59. package/dist/core/memory-engine/entry-scan.js +3 -0
  60. package/dist/core/memory-engine/file-backend.d.ts +29 -3
  61. package/dist/core/memory-engine/file-backend.js +66 -35
  62. package/dist/core/memory-engine/index.d.ts +7 -7
  63. package/dist/core/memory-engine/index.js +6 -6
  64. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  65. package/dist/core/memory-engine/landing-admission.js +3 -3
  66. package/dist/core/memory-engine/layout.d.ts +121 -45
  67. package/dist/core/memory-engine/layout.js +252 -102
  68. package/dist/core/memory-engine/memory-backend-contract.d.ts +19 -1
  69. package/dist/core/memory-engine/memory-backend-contract.js +320 -0
  70. package/dist/core/memory-engine/memory-deployment.d.ts +31 -8
  71. package/dist/core/memory-engine/memory-deployment.js +26 -12
  72. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  73. package/dist/core/memory-engine/scope-contract.js +68 -19
  74. package/dist/core/memory-engine/session-write-home.d.ts +3 -1
  75. package/dist/core/memory-engine/session-write-home.js +1 -1
  76. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  77. package/dist/core/memory-engine/sync-client.js +7 -0
  78. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  79. package/dist/core/memory-engine/sync-report.js +6 -2
  80. package/dist/core/memory-engine/tools.d.ts +2 -2
  81. package/dist/core/memory-engine/tools.js +10 -10
  82. package/dist/core/memory-engine/types.d.ts +118 -19
  83. package/dist/core/memory-engine/types.js +1 -0
  84. package/dist/core/memory-vector.d.ts +1 -1
  85. package/dist/core/memory.d.ts +10 -10
  86. package/dist/core/memory.js +15 -6
  87. package/dist/core/mode-policy.js +1 -1
  88. package/dist/core/mods/classic-events.d.ts +9 -1
  89. package/dist/core/mods/dollar.d.ts +32 -1
  90. package/dist/core/mods/dollar.js +13 -1
  91. package/dist/core/mods/kernel/events.d.ts +11 -3
  92. package/dist/core/mods/kernel/events.js +13 -10
  93. package/dist/core/mods/lifecycle-stations.d.ts +36 -4
  94. package/dist/core/mods/lifecycle-stations.js +44 -9
  95. package/dist/core/mods/session-append.d.ts +4 -1
  96. package/dist/core/mods/session-append.js +7 -0
  97. package/dist/core/mods/session-receive.js +12 -15
  98. package/dist/core/mods/stations.d.ts +70 -6
  99. package/dist/core/mods/stations.js +144 -1
  100. package/dist/core/own-property-receipt.d.ts +7 -0
  101. package/dist/core/own-property-receipt.js +3 -0
  102. package/dist/core/park-selfcheck.js +2 -2
  103. package/dist/core/pause-registry.d.ts +2 -0
  104. package/dist/core/pause-registry.js +3 -0
  105. package/dist/core/permission-rule-consent.d.ts +10 -3
  106. package/dist/core/permission-rule-consent.js +37 -24
  107. package/dist/core/permission-rule-store.d.ts +35 -1
  108. package/dist/core/permission-rule-store.js +27 -8
  109. package/dist/core/read-only-shell.js +3 -2
  110. package/dist/core/read-root-candidate.js +1 -1
  111. package/dist/core/redaction-marks.d.ts +8 -0
  112. package/dist/core/redaction-marks.js +6 -0
  113. package/dist/core/remote-env.d.ts +12 -1
  114. package/dist/core/remote-env.js +3 -0
  115. package/dist/core/resume-startup-cause.d.ts +5 -4
  116. package/dist/core/runner/child-tree.d.ts +29 -3
  117. package/dist/core/runner/child-tree.js +39 -16
  118. package/dist/core/runner/compact-session.js +5 -2
  119. package/dist/core/runner/contracts.d.ts +36 -17
  120. package/dist/core/runner/delegation-owner.d.ts +43 -0
  121. package/dist/core/runner/delegation-owner.js +59 -0
  122. package/dist/core/runner/gate-exit.js +2 -2
  123. package/dist/core/runner/inherited-ask-grants.js +1 -1
  124. package/dist/core/runner/lineage-reroot-view.d.ts +56 -0
  125. package/dist/core/runner/lineage-reroot-view.js +108 -0
  126. package/dist/core/runner/memory-consolidation-driver.d.ts +6 -3
  127. package/dist/core/runner/memory-consolidation-driver.js +4 -4
  128. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  129. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  130. package/dist/core/runner/permission-rule-lanes.d.ts +2 -1
  131. package/dist/core/runner/permission-rule-lanes.js +2 -2
  132. package/dist/core/runner/person-path-rows.d.ts +23 -3
  133. package/dist/core/runner/person-path-rows.js +31 -4
  134. package/dist/core/runner/placement-fence.d.ts +12 -0
  135. package/dist/core/runner/placement-fence.js +20 -6
  136. package/dist/core/runner/prepare-acquire-reconcile.d.ts +4 -1
  137. package/dist/core/runner/prepare-acquire-reconcile.js +7 -2
  138. package/dist/core/runner/prepare-ask-lane.js +2 -2
  139. package/dist/core/runner/prepare-caps-and-workflow.d.ts +5 -1
  140. package/dist/core/runner/prepare-caps-and-workflow.js +6 -3
  141. package/dist/core/runner/prepare-config-doors.d.ts +6 -6
  142. package/dist/core/runner/prepare-config-doors.js +3 -4
  143. package/dist/core/runner/prepare-execution-env.js +17 -6
  144. package/dist/core/runner/prepare-hands-readface.d.ts +3 -2
  145. package/dist/core/runner/prepare-hands-readface.js +32 -10
  146. package/dist/core/runner/prepare-inherited-gate.d.ts +12 -8
  147. package/dist/core/runner/prepare-inherited-gate.js +14 -6
  148. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  149. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  150. package/dist/core/runner/prepare-memory.d.ts +3 -2
  151. package/dist/core/runner/prepare-memory.js +28 -20
  152. package/dist/core/runner/prepare-park-ask.js +4 -3
  153. package/dist/core/runner/prepare-task.js +22 -16
  154. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  155. package/dist/core/runner/resume-admission.d.ts +3 -3
  156. package/dist/core/runner/resume-admission.js +6 -3
  157. package/dist/core/runner/resume-apply.d.ts +4 -0
  158. package/dist/core/runner/resume-apply.js +11 -4
  159. package/dist/core/runner/resume-checkpoint-screen.d.ts +9 -0
  160. package/dist/core/runner/resume-checkpoint-screen.js +4 -84
  161. package/dist/core/runner/run-git-lane.d.ts +2 -0
  162. package/dist/core/runner/run-git-lane.js +4 -1
  163. package/dist/core/runner/run-harness-handlers.d.ts +2 -0
  164. package/dist/core/runner/run-harness-handlers.js +3 -2
  165. package/dist/core/runner/run-leg.js +25 -8
  166. package/dist/core/runner/run-settle-and-teardown.js +6 -4
  167. package/dist/core/runner/run-stop-and-final-verify.js +2 -1
  168. package/dist/core/runner/run-turn-boundary.js +7 -4
  169. package/dist/core/runner/runtask.js +6 -6
  170. package/dist/core/runner/steering-preview.d.ts +9 -0
  171. package/dist/core/runner/steering-preview.js +5 -0
  172. package/dist/core/runner/stream-steer-verb.js +8 -0
  173. package/dist/core/runner/terminal-account.js +1 -1
  174. package/dist/core/runner/tool-face-overlay.js +2 -0
  175. package/dist/core/runner/turn-attachments.d.ts +5 -0
  176. package/dist/core/runner/turn-attachments.js +1 -1
  177. package/dist/core/runner-deps.d.ts +8 -4
  178. package/dist/core/secret-env.d.ts +9 -6
  179. package/dist/core/secret-env.js +41 -22
  180. package/dist/core/session-checkout.d.ts +108 -0
  181. package/dist/core/session-checkout.js +485 -0
  182. package/dist/core/session-store.d.ts +13 -5
  183. package/dist/core/session-store.js +28 -4
  184. package/dist/core/session.d.ts +29 -5
  185. package/dist/core/session.js +3 -0
  186. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +6 -12
  187. package/dist/core/store-contracts/checkpoint-store-contract.js +73 -6
  188. package/dist/core/store-contracts/session-store-contract.js +61 -8
  189. package/dist/core/task-event.d.ts +28 -1
  190. package/dist/core/task-notification.d.ts +9 -1
  191. package/dist/core/task-notification.js +8 -1
  192. package/dist/core/task-registry-agent.d.ts +40 -8
  193. package/dist/core/task-registry-agent.js +57 -24
  194. package/dist/core/task-registry-shared.d.ts +33 -11
  195. package/dist/core/task-registry-workflow.js +4 -3
  196. package/dist/core/task-registry.d.ts +27 -10
  197. package/dist/core/task-registry.js +19 -13
  198. package/dist/core/task-result.d.ts +5 -5
  199. package/dist/core/task-spec-members.js +1 -1
  200. package/dist/core/task-spec.d.ts +21 -1
  201. package/dist/core/terminal-cause.d.ts +6 -6
  202. package/dist/core/tool-face.d.ts +6 -2
  203. package/dist/core/tool-face.js +1 -1
  204. package/dist/core/tool-policy.d.ts +16 -13
  205. package/dist/core/tool-policy.js +11 -10
  206. package/dist/core/tool-roster.d.ts +4 -4
  207. package/dist/core/tool-spec.d.ts +42 -19
  208. package/dist/core/types.d.ts +2 -2
  209. package/dist/core/types.js +1 -1
  210. package/dist/core/untrusted-egress.d.ts +15 -4
  211. package/dist/core/untrusted-egress.js +23 -22
  212. package/dist/core/workspace-snapshot.d.ts +3 -1
  213. package/dist/core/workspace-snapshot.js +1 -0
  214. package/dist/engine/execution-env/node-execution-env.d.ts +3 -0
  215. package/dist/engine/execution-env/node-execution-env.js +12 -5
  216. package/dist/engine/harness/types.d.ts +77 -1
  217. package/dist/engine/harness/types.js +108 -0
  218. package/dist/engine/session/import-validate.js +6 -1
  219. package/dist/engine/session/parent-chain-guard.d.ts +3 -3
  220. package/dist/engine/session/parent-chain-guard.js +1 -1
  221. package/dist/engine/session/path-to-root.d.ts +18 -3
  222. package/dist/engine/session/path-to-root.js +15 -1
  223. package/dist/engine/session/repo-utils.d.ts +12 -1
  224. package/dist/engine/session/repo-utils.js +41 -0
  225. package/dist/engine/session/session.d.ts +24 -1
  226. package/dist/engine/session/session.js +46 -2
  227. package/dist/engine/session/storage-base.d.ts +20 -0
  228. package/dist/engine/session/storage-base.js +28 -9
  229. package/dist/index.d.ts +16 -12
  230. package/dist/index.js +11 -8
  231. package/dist/internal/harness-types.d.ts +1 -1
  232. package/dist/internal/harness.d.ts +4 -3
  233. package/dist/internal/harness.js +3 -2
  234. package/dist/orchestration/run-workflow-tool.d.ts +7 -1
  235. package/dist/orchestration/run-workflow-tool.js +28 -11
  236. package/dist/orchestration/workflow-governance.d.ts +1 -1
  237. package/dist/orchestration/workflow.d.ts +6 -0
  238. package/dist/orchestration/workflow.js +5 -8
  239. package/dist/stores/file/checkpoint-store.d.ts +2 -0
  240. package/dist/stores/file/checkpoint-store.js +7 -6
  241. package/dist/stores/file/fs-atomic.d.ts +0 -22
  242. package/dist/stores/file/fs-atomic.js +0 -17
  243. package/dist/stores/file/index.d.ts +2 -9
  244. package/dist/stores/file/index.js +2 -4
  245. package/dist/stores/file/session-store.d.ts +13 -7
  246. package/dist/stores/file/session-store.js +42 -18
  247. package/dist/tools/fs/bash-program-position.d.ts +3 -2
  248. package/dist/tools/fs/bash-program-position.js +10 -10
  249. package/dist/tools/fs/program-read-model.d.ts +34 -10
  250. package/dist/tools/fs/program-read-model.js +37 -7
  251. package/dist/tools/fs/program-read-model.rows.js +13 -2
  252. package/dist/tools/fs/read-deny.d.ts +13 -1
  253. package/dist/tools/fs/read-deny.js +10 -2
  254. package/dist/tools/fs/removal-targets.js +5 -5
  255. package/dist/tools/fs/safety.d.ts +2 -0
  256. package/dist/tools/fs/safety.js +1 -1
  257. package/dist/tools/fs/shell-read-argv.d.ts +11 -2
  258. package/dist/tools/fs/shell-read-argv.js +45 -29
  259. package/dist/tools/fs/shell-read-bindings.d.ts +20 -2
  260. package/dist/tools/fs/shell-read-bindings.js +153 -69
  261. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  262. package/dist/tools/fs/shell-read-brace.js +79 -0
  263. package/dist/tools/fs/shell-read-check.js +29 -11
  264. package/dist/tools/fs/shell-read-establish.js +43 -22
  265. package/dist/tools/fs/shell-read-functions.js +2 -2
  266. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  267. package/dist/tools/fs/shell-read-judge.js +3 -3
  268. package/dist/tools/fs/shell-read-object-path.d.ts +59 -0
  269. package/dist/tools/fs/shell-read-object-path.js +119 -0
  270. package/dist/tools/fs/shell-read-plan.d.ts +18 -0
  271. package/dist/tools/fs/shell-read-plan.js +217 -104
  272. package/dist/tools/fs/shell-read-start.d.ts +76 -13
  273. package/dist/tools/fs/shell-read-start.js +97 -17
  274. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  275. package/dist/tools/fs/shell-read-word.js +9 -5
  276. package/dist/tools/fs/shell-read-workdir.d.ts +54 -14
  277. package/dist/tools/fs/shell-read-workdir.js +103 -19
  278. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  279. package/dist/tools/worktree.d.ts +3 -2
  280. package/dist/tools/worktree.js +7 -35
  281. package/package.json +3 -2
  282. package/test/export-surface.snapshot.json +93 -43
  283. package/wire-changes/core-stores-sql@7.62.0.json +30 -0
  284. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  285. package/wire-changes/core@7.62.0.json +2181 -0
  286. package/wire-changes/core@7.63.0.json +3523 -0
  287. package/wire-changes/mods-kernel@7.62.0.json +42 -0
  288. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  289. package/wire-changes/primitives@7.62.0.json +30 -0
  290. package/wire-changes/primitives@7.63.0.json +445 -0
  291. package/dist/core/consolidate-scope.d.ts +0 -93
  292. package/dist/core/consolidate-scope.js +0 -98
  293. package/dist/core/credential-vocabulary.d.ts +0 -176
  294. package/dist/core/credential-vocabulary.js +0 -190
  295. package/dist/core/redaction-passes.d.ts +0 -82
  296. package/dist/core/redaction-passes.js +0 -377
  297. package/dist/core/runner/memory-consolidation.d.ts +0 -109
  298. package/dist/core/runner/memory-consolidation.js +0 -251
@@ -1,15 +1,17 @@
1
1
  import { expansionsInHeredocBody, lexShell, PARSE_FAILURE_SENTENCE, substitutionsInHeredocBody, literalTextOf, literalTildeSpelling, parameterRereadsValue, UNRESOLVED_SENTENCE, } from "../../shell/lex.js";
2
2
  import { programTextOf, readOfText, readsOf, rewritten, segmentReadingsOf, settledFieldsOf, spelledWithHome, unreadableSentenceOf } from "./shell-read-word.js";
3
+ import { braceWordListsOf } from "./shell-read-brace.js";
3
4
  import { assignmentArithmetic, bare, listedVerbCandidates, pathSubcommandOf, programTextSentence, pushAssignment, roleReads, subscriptOnly, unlistedWords } from "./shell-read-argv.js";
4
- import { ARITHMETIC_TEST_OPERATORS, BindingThread, arithmeticSubstitutions, inheritedFunctionsOf, inheritedExportedFunctions, isArithmeticCommand, bindingEffectOf, joinRebound, loopListHeadAt, namesBoundIn, parameterBodySubstitutions, projectSegment, valueOf, } from "./shell-read-bindings.js";
5
+ import { ARITHMETIC_TEST_OPERATORS, BindingThread, arithmeticSubstitutions, assignsAsStatement, inheritedFunctionsOf, inheritedExportedFunctions, isArithmeticCommand, bindingEffectOf, joinRebound, loopListHeadAt, namesBoundIn, parameterBodySubstitutions, projectSegments, valueOf, } from "./shell-read-bindings.js";
5
6
  import { commandEnvironmentNames, isShellSyntaxWord, programBasename, programPositionRunsShell, readProgramPosition, shellScanDeclineOf, } from "./bash-program-position.js";
6
7
  import { WorkdirThread, baseShiftOf, textCalls, textMayMove, textMovesOf, textSetsPhysical, withCommandEnvironment } from "./shell-read-workdir.js";
7
- import { POLL_LOOP_MAX_BEATS, attachedOptionPayloads, resolveOperandLexically, isPathShapedToken, programTextSlotFiles, } from "./bash-readonly-classifier.js";
8
+ import { POLL_LOOP_MAX_BEATS, attachedOptionPayloads, isPathShapedToken, programTextSlotFiles, } from "./bash-readonly-classifier.js";
9
+ import { mayCarryGitVariables, objectPathPlacement } from "./shell-read-object-path.js";
8
10
  import { BLOCK_WORD_NAMES, commandLineOf, commandLineOptionSpellings, declaredAttributes, isDeclarationBuiltin, isInertBuiltin, launcherOptionPathRole, launcherOptionStep, readOptionRole, programLanguageOf, programTextOpensOf, selectedOptions, movesBaseByStack, opensNoOperand, programDelivery, programRow, readArgRoles, runsShellText, } from "./program-read-model.js";
9
11
  import { shellWordsOf } from "../../shell/shell-words.js";
10
12
  import { isAbsoluteForFamily } from "./safety.js";
11
13
  import { codeBodies, launchedInput, pipedTextOf, printedByProcess, reentersShell, reentryText, scriptFileAt, stdinTextsOf } from "./shell-reentry-text.js";
12
- import { heldAt, plannedOnce, rebasePlan, startedAt, stdinFeeds } from "./shell-read-start.js";
14
+ import { heldAt, launchedAt, launchedInOf, nestedStartOf, plannedOnce, rebasePlan, startedAt, stdinFeeds } from "./shell-read-start.js";
13
15
  import { markStandardDevices } from "./shell-read-device.js";
14
16
  export const READ_CANDIDATE_PROVENANCES = Object.freeze([
15
17
  "operand",
@@ -33,13 +35,14 @@ export function planShellReads(command, decl, depth = 0, start) {
33
35
  }
34
36
  function planText(command, decl, depth, start, from) {
35
37
  const shape = { grouped: false, backgrounded: false, strayRedirection: false };
38
+ const none = new Set();
36
39
  if (depth > NESTING_MAX)
37
- return { plan: { segments: [], unreadable: `command text nested more than ${NESTING_MAX} levels deep`, shape }, end: "unmodelled", physical: false };
40
+ return { plan: { segments: [], unreadable: `command text nested more than ${NESTING_MAX} levels deep`, shape }, end: "unmodelled", physical: false, reached: none };
38
41
  const lexed = lexShell(command);
39
42
  if ("parseFailure" in lexed)
40
- return { plan: { segments: [], unreadable: PARSE_FAILURE_SENTENCE[lexed.parseFailure.reason], shape }, end: "unmodelled", physical: false };
43
+ return { plan: { segments: [], unreadable: PARSE_FAILURE_SENTENCE[lexed.parseFailure.reason], shape }, end: "unmodelled", physical: false, reached: none };
41
44
  const unreadable = unreadableSentenceOf(lexed, command);
42
- const projected = lexed.segments.map((segment) => projectSegment(segment));
45
+ const projected = projectSegments(lexed.segments);
43
46
  const exportedFunctions = inheritedFunctionsOf(projected, start?.exportedFunctions), exportedNames = new Set(exportedFunctions.keys());
44
47
  const named = projected.map((p, si) => bindingEffectOf(lexed.segments[si], p.argv, p, () => "unknown"));
45
48
  const boundHere = (name) => named.some((e) => e.all === "unknown" || e.bindings.some((b) => b.name === name));
@@ -64,7 +67,7 @@ function planText(command, decl, depth, start, from) {
64
67
  }
65
68
  const names = new BindingThread(lexed.segments, named, initial, boundAnywhere, loopEndOf, start?.homeTouched === true, start?.inherited, start?.names);
66
69
  const laterStart = { initial: (name) => declared(name, boundAnywhere(name)), boundAnywhere, homeTouched: boundAnywhere("HOME"), inherited: names.inheritedAt() };
67
- const nestedPlanner = (table, si) => (text, kind, at) => planShellReads(text, decl, depth + 1, kind === "substitution" ? { initial: (name) => table.stateOf(name), boundAnywhere, homeTouched: table.homeTouched, inherited: table.inherited, thread: heldThread(moves.functions), names: heldAt(table), ...(exportedFunctions.size > 0 ? { exportedFunctions } : {}) } : startedAt(kind === "now" ? { ...laterStart, inherited: { ...laterStart.inherited, rebound: joinRebound(table.inherited.rebound, commandEnvironmentNames(projected[si].argv)) }, ...(exportedFunctions.size > 0 ? { exportedFunctions } : {}), ...(readProgramPosition(projected[si].argv).program?.basename === "eval" ? { thread: heldThread(moves.unread), names: heldAt(table, names.functionBound()) } : exportedFunctions.size > 0 ? { thread: { physical: false, functions: exportedNames, unread: exportedNames }, names: inheritedExportedFunctions(exportedFunctions) } : {}) } : { ...laterStart, thread: heldThread(moves.functions, workdir.mayBePhysical || moves.physicalAt.some(Boolean)), names: names.heldAnywhere(), ...(exportedFunctions.size > 0 ? { exportedFunctions } : {}) }, at));
70
+ const nestedPlanner = (table, si) => (text, kind, at) => planShellReads(text, decl, depth + 1, kind === "substitution" ? { initial: (name) => table.stateOf(name), boundAnywhere, homeTouched: table.homeTouched, inherited: table.inherited, thread: heldThread(moves.functions), names: heldAt(table), ...(exportedFunctions.size > 0 ? { exportedFunctions } : {}) } : startedAt(kind === "now" ? { ...laterStart, inherited: { ...laterStart.inherited, rebound: joinRebound(table.inherited.rebound, commandEnvironmentNames(projected[si].argv)) }, ...(exportedFunctions.size > 0 ? { exportedFunctions } : {}), ...(readProgramPosition(projected[si].argv).program?.basename === "eval" ? { thread: heldThread(moves.unread), names: heldAt(table, names.functionBound()) } : exportedFunctions.size > 0 ? { thread: { physical: false, functions: exportedNames, unread: exportedNames, reached: workdir.reached }, names: inheritedExportedFunctions(exportedFunctions) } : {}) } : { ...laterStart, thread: heldThread(moves.functions, workdir.mayBePhysical || moves.physicalAt.some(Boolean)), names: names.heldAnywhere(), ...(exportedFunctions.size > 0 ? { exportedFunctions } : {}) }, at));
68
71
  const empty = lexed.segments.map((segment, si) => segmentIsEmpty(segment, projected[si]));
69
72
  const facts = projected.map(() => undefined);
70
73
  const tables = projected.map(() => undefined);
@@ -74,31 +77,45 @@ function planText(command, decl, depth, start, from) {
74
77
  tables[si] ??= table;
75
78
  return (facts[si] ??= segmentFacts(lexed.segments[si], projected[si], decl, table, nestedPlanner(table, si), fedAt(si), inheritedFns));
76
79
  };
77
- const basesOf = projected.map(() => new Set());
78
- const unmodelled = projected.map(() => false);
79
- const moves = textMovesOf(new Set(projected.flatMap((p) => p.defines)), projected.map((p) => p.argv), (si) => names.inFunctionBody(si), start?.thread);
80
+ const placesOf = () => ({ bases: projected.map(() => new Set()), unmodelled: projected.map(() => false), unsettledIn: projected.map(() => false), floors: projected.map(() => []) });
81
+ const written = placesOf(), later = placesOf();
82
+ const { bases: basesOf, unmodelled, unsettledIn } = written;
83
+ let places = written;
84
+ const stood = projected.map(() => ({ at: new Map(), lost: false }));
85
+ const keyOf = (c) => JSON.stringify([c.base, c.pwd, c.old, c.dirStack]);
86
+ const moves = textMovesOf(new Set(projected.flatMap((p) => p.defines)), lexed.segments, projected.map((p) => p.argv), (si) => names.inFunctionBody(si), start?.thread);
80
87
  names.runsBodies(moves.runsBodyAt, moves.bodiesAt.some((b) => b.length > 0), moves.mayCallAt.map((c, si) => (c ? commandEnvironmentNames(projected[si].argv) : undefined)));
81
- const workdir = new WorkdirThread(from ?? start?.bases ?? [decl.cwd], depth === 0 || start?.bases !== undefined || from !== undefined, start?.thread?.physical === true);
88
+ let workdir = new WorkdirThread(depth > 0 && from === undefined && start?.bases === undefined ? [nestedStartOf(decl.cwd)] : (from ?? start?.bases ?? [decl.cwd]), start?.thread?.physical === true);
89
+ if (start?.thread?.reached !== undefined)
90
+ workdir.reach(start.thread.reached);
82
91
  const workdirContext = {
83
92
  ...(decl.homeDir !== undefined ? { homeDir: decl.homeDir } : {}),
84
93
  textBinds: boundAnywhere,
85
- evalEnd: (text, c, table) => {
94
+ evalEnd: (text, from, table) => {
86
95
  if (moves.bodyMoves && textCalls(text, moves.functions))
87
- return { end: "unmodelled", physical: false };
96
+ return { end: "unmodelled", physical: false, reached: new Set() };
88
97
  if (!textMayMove(text, moves.functions) && !textSetsPhysical(text))
89
- return { end: [c], physical: false };
90
- const ran = planText(text, decl, depth + 1, { initial: (name) => table.stateOf(name), boundAnywhere, homeTouched: table.homeTouched, inherited: table.inherited, thread: heldThread(moves.unread), names: heldAt(table, names.functionBound()) }, [c]);
91
- return { end: ran.end, physical: ran.physical };
98
+ return { end: from, physical: false, reached: new Set() };
99
+ const ran = planText(text, decl, depth + 1, { initial: (name) => table.stateOf(name), boundAnywhere, homeTouched: table.homeTouched, inherited: table.inherited, thread: heldThread(moves.unread), names: heldAt(table, names.functionBound()) }, from);
100
+ return { end: ran.end, physical: ran.physical, reached: ran.reached, ...(ran.unsettled === true ? { unsettled: true } : {}) };
92
101
  },
93
102
  };
94
- const heldThread = (unread, physical = workdir.mayBePhysical) => ({ physical, functions: moves.functions, unread });
103
+ const heldThread = (unread, physical = workdir.mayBePhysical) => ({ physical, functions: moves.functions, unread, reached: workdir.reached });
95
104
  let andRunStart = 0;
96
105
  let crossedAllAnd = true;
97
106
  let crossedAnyOr = false;
98
107
  let previousEmitted = -1;
99
108
  const reaches = projected.map(() => undefined);
100
- const loops = [];
109
+ const scopes = [];
110
+ const closeScopes = (j) => {
111
+ const k = scopes.findIndex((s) => !names.reaches(s.at, j));
112
+ if (k < 0)
113
+ return;
114
+ workdir.restore(scopes[k].state);
115
+ scopes.length = k;
116
+ };
101
117
  const thread = (si, replay) => {
118
+ closeScopes(si);
102
119
  const connector = lexed.segments[si].connector;
103
120
  if (previousEmitted >= 0) {
104
121
  if (replay || connector !== "&&")
@@ -119,16 +136,28 @@ function planText(command, decl, depth, start, from) {
119
136
  crossedAllAnd = true;
120
137
  crossedAnyOr = false;
121
138
  previousEmitted = si;
122
- if (workdir.lost)
123
- unmodelled[si] = true;
139
+ const runsHere = places === later || !names.inFunctionBody(si);
140
+ if (workdir.lost) {
141
+ places.unmodelled[si] = true;
142
+ if (workdir.unsettled)
143
+ places.unsettledIn[si] = true;
144
+ if (runsHere)
145
+ stood[si].lost = true;
146
+ }
124
147
  else
125
- for (const c of workdir.reachable(andRunStart))
126
- basesOf[si].add(c.base);
148
+ for (const c of workdir.reachable(andRunStart)) {
149
+ places.bases[si].add(c.base);
150
+ if (runsHere)
151
+ stood[si].at.set(keyOf(c), c);
152
+ }
153
+ const losesBase = moves.losesBaseAt(si, tables[si]);
154
+ if (names.runsApart(si) && (moves.physicalAt[si] || (f.shift !== undefined && call !== "named") || losesBase))
155
+ scopes.push({ at: si, state: workdir.snapshot() });
127
156
  if (moves.physicalAt[si])
128
157
  workdir.setPhysical();
129
158
  if (f.shift !== undefined && call !== "named")
130
159
  workdir.shift(si, { shift: f.shift, provable: reaches[si].moveProvable && call === undefined, andRunStart, table: withCommandEnvironment(tables[si], projected[si].argv), cdable: moves.cdableFrom >= 0 && si > moves.cdableFrom }, workdirContext);
131
- if (moves.losesBaseAt(si, tables[si]))
160
+ if (losesBase)
132
161
  workdir.lose(si, workdir.reachable(andRunStart));
133
162
  };
134
163
  const bind = (si) => {
@@ -149,91 +178,167 @@ function planText(command, decl, depth, start, from) {
149
178
  if (moves.bodiesAt[si].length > 0)
150
179
  names.runsLater(si, moves.bodiesAt[si].reduce((held, b) => joinRebound(held, namesBoundIn(b)), names.functionBound()));
151
180
  };
152
- for (let si = 0; si < projected.length; si++) {
153
- const shapeOfLoop = loopShapes[si];
154
- if (named[si].all === "reset")
155
- names.apply(si, { bindings: [], all: "reset" }, false);
156
- thread(si, false);
157
- bind(si);
158
- if (shapeOfLoop === "head") {
159
- loops.push({ bodyStart: si + 1, beats: facts[si].loopHead?.beats });
160
- continue;
161
- }
162
- if (shapeOfLoop !== "end")
163
- continue;
164
- const frame = loops.pop();
165
- if (frame === undefined)
166
- continue;
167
- if (!facts.slice(frame.bodyStart, si).some((b, k) => b?.shift !== undefined || (tables[frame.bodyStart + k] !== undefined && moves.losesBaseAt(frame.bodyStart + k, tables[frame.bodyStart + k]))))
168
- continue;
169
- if (frame.beats === undefined) {
170
- for (let k = frame.bodyStart; k < si; k++)
171
- unmodelled[k] = true;
172
- workdir.lose(si, workdir.reachable(andRunStart));
173
- continue;
174
- }
175
- for (let beat = 1; beat < frame.beats && !workdir.lost; beat++) {
176
- for (let k = frame.bodyStart; k < si; k++)
177
- thread(k, true);
181
+ const walk = (run, first, within = 1) => {
182
+ const steps = [...new Set([...run, ...run.flatMap((si) => (loopShapes[si] === "head" && loopEndOf.has(si) ? [loopEndOf.get(si)] : []))])].sort((a, b) => a - b);
183
+ const loops = [];
184
+ for (const si of steps) {
185
+ const shapeOfLoop = loopShapes[si];
186
+ if (first && named[si].all === "reset")
187
+ names.apply(si, { bindings: [], all: "reset" }, false);
188
+ thread(si, !first);
189
+ if (first)
190
+ bind(si);
191
+ if (shapeOfLoop === "head") {
192
+ loops.push({ bodyStart: si + 1, beats: facts[si].loopHead?.beats });
193
+ continue;
194
+ }
195
+ if (shapeOfLoop !== "end")
196
+ continue;
197
+ const frame = loops.pop();
198
+ if (frame === undefined)
199
+ continue;
200
+ if (!facts.slice(frame.bodyStart, si).some((b, k) => b?.shift !== undefined || (tables[frame.bodyStart + k] !== undefined && moves.losesBaseAt(frame.bodyStart + k, tables[frame.bodyStart + k]))))
201
+ continue;
202
+ const beat = steps.filter((k) => k >= frame.bodyStart && k < si);
203
+ const around = loops.reduce((n, l) => n * (l.beats ?? 1), within);
204
+ if (frame.beats === undefined || around * frame.beats > POLL_LOOP_MAX_BEATS) {
205
+ workdir.lose(si, workdir.reachable(andRunStart), [], true);
206
+ for (const k of beat) {
207
+ places.unmodelled[k] = true;
208
+ places.unsettledIn[k] = true;
209
+ }
210
+ continue;
211
+ }
212
+ for (let n = 1; n < frame.beats && !workdir.lost; n++)
213
+ walk(beat, false, around * frame.beats);
214
+ if (workdir.lost && frame.beats > 1)
215
+ for (const k of beat) {
216
+ places.unmodelled[k] = true;
217
+ if (workdir.unsettled)
218
+ places.unsettledIn[k] = true;
219
+ }
178
220
  }
221
+ };
222
+ walk(projected.map((_, si) => si), true);
223
+ closeScopes();
224
+ const end = workdir.end();
225
+ const gather = (ats) => {
226
+ const at = new Map();
227
+ for (const p of ats)
228
+ for (const c of p.at)
229
+ at.set(keyOf(c), c);
230
+ return { at: [...at.values()], lost: ats.some((p) => p.lost) };
231
+ };
232
+ const ended = { at: end === "unmodelled" ? [] : end, lost: end === "unmodelled" };
233
+ const after = (s) => gather([ended, ...stood.slice(s + 1).map((p) => ({ at: p.at.values(), lost: p.lost }))]);
234
+ const callers = () => gather(stood.flatMap((p, j) => (moves.runsBodyAt[j] ? [{ at: p.at.values(), lost: p.lost }, ...(moves.bodiesAt[j].length > 0 ? [after(j)] : [])] : [])));
235
+ const main = workdir;
236
+ const bodies = new Map();
237
+ projected.forEach((_, si) => {
238
+ const id = names.bodyOf(si);
239
+ if (id !== undefined && facts[si] !== undefined)
240
+ bodies.set(id, [...(bodies.get(id) ?? []), si]);
241
+ });
242
+ const went = new Set();
243
+ const walkBodies = (from, floor = []) => {
244
+ for (const segs of bodies.values())
245
+ for (const start of [...(from.at.length > 0 ? [from.at] : []), ...(from.lost ? ["lost"] : [])]) {
246
+ workdir = main.fork(start, floor);
247
+ scopes.length = 0;
248
+ andRunStart = segs[0];
249
+ crossedAllAnd = true;
250
+ crossedAnyOr = false;
251
+ previousEmitted = -1;
252
+ walk(segs, false);
253
+ closeScopes();
254
+ for (const k of segs)
255
+ if (later.unmodelled[k])
256
+ later.floors[k] = [...new Set([...later.floors[k], ...(workdir.floorBases ?? [])])];
257
+ for (const p of workdir.reached)
258
+ if (!main.reached.has(p))
259
+ went.add(p);
260
+ }
261
+ };
262
+ const standing = () => stood.reduce((n, p) => n + p.at.size + (p.lost ? 1 : 0), 0);
263
+ places = later;
264
+ let grew = bodies.size > 0;
265
+ for (let pass = 0; grew && pass <= bodies.size; pass++) {
266
+ const before = standing();
267
+ walkBodies(callers());
268
+ grew = standing() > before;
179
269
  }
270
+ if (grew)
271
+ walkBodies({ at: [], lost: true }, [...new Set(stood.flatMap((p) => [...p.at.values()].map((c) => c.base)))]);
272
+ workdir = main;
273
+ places = written;
274
+ main.widen(went);
180
275
  const planned = facts.map((f) => f);
181
276
  const inert = depth === 0 && unreadable === undefined && planned.every((f) => (f.readings ?? [f]).every(segmentOpensNothing));
182
277
  const settled = inert ? planned.map((f) => ({ ...f, reads: f.reads.filter((c) => c.provenance !== "env_assignment"), ...(f.readings !== undefined ? { readings: f.readings.map((g) => ({ ...g, reads: g.reads.filter((c) => c.provenance !== "env_assignment") })) } : {}) })) : planned;
183
278
  shape.grouped = projected.some((p) => p.grouped);
184
279
  shape.backgrounded = lexed.segments.some((s) => s.connector === "&") || settled.some((f) => (f.readings ?? [f]).some((g) => g.backgrounds === true));
185
280
  shape.strayRedirection = projected.some((p) => p.argv.length === 0 && p.redirects.length > 0);
281
+ const placedRead = (c, at, atFloor, gitVariables) => {
282
+ const relative = relativeSpelling(c.spelled);
283
+ if (c.provenance === "object_path" && relative) {
284
+ const { repository, ...read } = c;
285
+ return { ...read, ...objectPathPlacement(c.spelled, repository, at, atFloor, decl.homeDir, gitVariables) };
286
+ }
287
+ return { ...c, bases: relative ? at : [], ...(relative && atFloor !== undefined ? { floorBases: atFloor } : {}) };
288
+ };
289
+ const placedAt = (at, atFloor, unsettled, gitVariables = true) => (c) => {
290
+ const read = placedRead(c, at, atFloor, gitVariables);
291
+ return unsettled && read.bases === "unmodelled" ? { ...read, unsettledStart: true } : read;
292
+ };
186
293
  const segments = [];
187
294
  for (let si = 0; si < settled.length; si++) {
188
295
  const threaded = settled[si];
189
296
  if (threaded.empty)
190
297
  continue;
191
- const bases = unmodelled[si] ? "unmodelled" : [...basesOf[si]];
192
- const floorBases = workdir.floorBases;
193
- const floor = unmodelled[si] && floorBases !== undefined && floorBases.length > 0 ? floorBases : undefined;
194
- const placedAt = (at, atFloor) => (c) => {
195
- const relative = relativeSpelling(c.spelled);
196
- const here = c.provenance === "object_path" && at !== "unmodelled" ? [...new Set(at.flatMap(ancestorsOf))] : at;
197
- return { ...c, bases: relative ? here : [], ...(relative && atFloor !== undefined ? { floorBases: atFloor } : {}) };
198
- };
199
- const withBases = placedAt(bases, floor);
298
+ const floorBases = workdir.floorBases ?? [];
299
+ const placed = new Set([...(unmodelled[si] ? [] : basesOf[si]), ...later.bases[si]]);
300
+ const lostFloor = [...new Set([...(unmodelled[si] ? floorBases : []), ...(later.unmodelled[si] ? later.floors[si] : [])])];
301
+ const standings = [
302
+ ...(!unmodelled[si] || placed.size > 0 ? [{ bases: [...placed], unsettled: false }] : []),
303
+ ...(unmodelled[si] || later.unmodelled[si] ? [{ bases: "unmodelled", ...(lostFloor.length > 0 ? { floor: lostFloor } : {}), unsettled: (unmodelled[si] === true && unsettledIn[si] === true) || (later.unmodelled[si] === true && later.unsettledIn[si] === true) }] : []),
304
+ ];
305
+ const firesAt = settled[si].readings?.some((g) => g.runLater !== undefined) === true || settled[si].runLater !== undefined ? after(si) : undefined;
306
+ const firedAt = [...new Set((firesAt?.at ?? []).map((c) => c.base))].filter((b) => !placed.has(b));
307
+ const firedLost = firesAt?.lost === true && (!(unmodelled[si] || later.unmodelled[si]) || floorBases.some((b) => !lostFloor.includes(b)) || (workdir.unsettled && !standings.some((st) => st.bases === "unmodelled" && st.unsettled)));
308
+ const fired = (n) => [...(firedAt.length > 0 ? [rebasePlan(n, firedAt, firedAt)] : []), ...(firedLost ? [rebasePlan(n, "unmodelled", floorBases.length > 0 ? floorBases : undefined, workdir.unsettled)] : [])];
200
309
  const move = threaded.baseMove;
201
- for (const f of threaded.readings ?? [threaded]) {
202
- const moved = readProgramPosition(f.argv).launcherMovesBase;
203
- const programPlaced = moved ? placedAt("unmodelled", bases !== "unmodelled" ? bases : floor) : withBases;
204
- const programRead = (c) => (c.provenance === "stdin_redirect" ? withBases(c) : programPlaced(c));
205
- const placeNested = (n) => (f.elsewhere?.has(n) === true ? n : rebasePlan(n, decl.cwd, moved && f.shellSide?.has(n) !== true ? "unmodelled" : bases, bases === "unmodelled" ? floor : bases));
206
- segments.push({
207
- text: f.text,
208
- connector: f.connector,
209
- argv: f.argv,
210
- launcherChain: f.launcherChain,
211
- ...(f.verb !== undefined ? { verb: f.verb } : {}),
212
- ...(f.reentry !== undefined ? { reentry: f.reentry } : {}),
213
- ...(f.unreadProgramText !== undefined ? { unreadProgramText: f.unreadProgramText } : {}),
214
- ...(f.stdin !== undefined ? { stdin: f.stdin } : {}),
215
- declines: f.declines,
216
- reads: dedupe(f.reads).map(programRead),
217
- redirects: f.redirects.map((r) => ({ op: r.op, direction: r.direction, ...(r.fd !== undefined ? { fd: r.fd } : {}), ...(r.target !== undefined ? { target: withBases(r.target) } : {}) })),
218
- ...(move !== undefined ? { baseMove: { target: typeof move.target === "string" ? move.target : withBases(move.target) } } : {}),
219
- bases,
220
- nested: f.nested.map(placeNested),
221
- ...(f.printed.length > 0 ? { printed: f.printed.map(placeNested) } : {}),
222
- reach: reaches[si] ?? { andJoined: false, orBroken: false, moveProvable: false },
223
- rebound: tables[si]?.rebound ?? "all",
224
- });
225
- }
310
+ for (const [k, { bases, floor, unsettled: unsettledHere }] of standings.entries())
311
+ for (const f of threaded.readings ?? [threaded]) {
312
+ const withBases = placedAt(bases, floor, unsettledHere);
313
+ const launched = launchedAt(f.launchedIn, bases, floor, decl.homeDir);
314
+ const gitVariables = mayCarryGitVariables(decl.receivedEnvNames ?? "all", tables[si]?.rebound ?? "all", commandEnvironmentNames(f.argv));
315
+ const programPlaced = launched !== undefined ? placedAt("unmodelled", launched.words, unsettledHere || launched.unsettled === true, gitVariables) : placedAt(bases, floor, unsettledHere, gitVariables);
316
+ const programRead = (c) => (c.provenance === "stdin_redirect" ? withBases(c) : programPlaced(c));
317
+ const placeNested = (n) => (f.elsewhere?.has(n) === true ? n : launched !== undefined && f.shellSide?.has(n) !== true ? rebasePlan(n, launched.to, launched.floor, unsettledHere || launched.unsettled === true) : rebasePlan(n, bases, bases === "unmodelled" ? floor : bases, unsettledHere));
318
+ segments.push({
319
+ text: f.text,
320
+ connector: f.connector,
321
+ argv: f.argv,
322
+ launcherChain: f.launcherChain,
323
+ ...(f.verb !== undefined ? { verb: f.verb } : {}),
324
+ ...(f.reentry !== undefined ? { reentry: f.reentry } : {}),
325
+ ...(f.unreadProgramText !== undefined ? { unreadProgramText: f.unreadProgramText } : {}),
326
+ ...(f.stdin !== undefined ? { stdin: f.stdin } : {}),
327
+ declines: f.declines,
328
+ reads: dedupe(f.reads).map(programRead),
329
+ redirects: f.redirects.map((r) => ({ op: r.op, direction: r.direction, ...(r.fd !== undefined ? { fd: r.fd } : {}), ...(r.target !== undefined ? { target: withBases(r.target) } : {}) })),
330
+ ...(move !== undefined ? { baseMove: { target: typeof move.target === "string" ? move.target : withBases(move.target) } } : {}),
331
+ bases,
332
+ programStart: programPlaced({ spelled: ".", raw: ".", provenance: "unlisted_word", expands: false }),
333
+ nested: [...f.nested.map(placeNested), ...(k === 0 ? [...(f.runLater ?? [])].flatMap(fired) : [])],
334
+ ...(f.printed.length > 0 ? { printed: f.printed.map(placeNested) } : {}),
335
+ reach: reaches[si] ?? { andJoined: false, orBroken: false, moveProvable: false },
336
+ rebound: tables[si]?.rebound ?? "all",
337
+ });
338
+ }
226
339
  }
227
- return { plan: { segments, shape, ...(unreadable !== undefined ? { unreadable } : {}) }, end: workdir.end(), physical: workdir.mayBePhysical };
228
- }
229
- function ancestorsOf(dir) {
230
- const out = [dir];
231
- for (let d = dir, up = parentOf(d); up !== d; d = up, up = parentOf(d))
232
- out.push(up);
233
- return out;
234
- }
235
- function parentOf(dir) {
236
- return resolveOperandLexically(dir, "..", undefined) ?? dir;
340
+ const reached = workdir.lost ? new Set([...workdir.reached, ...(workdir.floorBases ?? [])]) : workdir.reached;
341
+ return { plan: { segments, shape, ...(unreadable !== undefined ? { unreadable } : {}) }, end: workdir.end(), physical: workdir.mayBePhysical, reached, ...(workdir.unsettled ? { unsettled: true } : {}) };
237
342
  }
238
343
  function loopShapeOf(p) {
239
344
  if (p.argv[0] === undefined)
@@ -258,13 +363,14 @@ function segmentOpensNothing(f) {
258
363
  const inertProgram = program === undefined || (program.name === program.basename && isInertBuiltin(program.basename) && !(isDeclarationBuiltin(program.basename) && f.argv.slice(at + 1).some((w) => /^[-+]/.test(w.folded))));
259
364
  return inertProgram && f.argv.every((w) => !/[[\]$`]/.test(w.raw)) && f.nested.length === 0 && f.reentry === undefined && f.declines.length === 0 && f.launcherChain.length === 0 && f.redirects.every((r) => r.direction !== "in") && f.reads.every((c) => c.provenance === "env_assignment");
260
365
  }
261
- function segmentFacts(segment, p, decl, table, nestedPlan, fed, inheritedFns = new Set()) {
262
- const targets = p.redirects.flatMap((r) => (r.target === undefined ? [] : [r.target]));
263
- const readings = segmentReadingsOf(p.argv, targets, table, decl.homeDir);
366
+ function segmentFacts(segment, p0, decl, table, nestedPlan, fed, inheritedFns = new Set()) {
367
+ const argvs = isShellSyntaxWord(p0.argv[0], BLOCK_WORD_NAMES) ? [p0.argv] : braceWordListsOf(p0.argv);
368
+ const targets = p0.redirects.flatMap((r) => (r.target === undefined ? [] : [r.target]));
369
+ const readings = argvs.flatMap((argv) => segmentReadingsOf(argv, targets, table, decl.homeDir));
264
370
  if (readings.length === 1)
265
- return readingFacts(segment, { ...p, argv: readings[0].argv }, decl, readings[0], nestedPlan, fed, inheritedFns);
371
+ return readingFacts(segment, { ...p0, argv: readings[0].argv }, decl, readings[0], nestedPlan, fed, inheritedFns);
266
372
  const once = plannedOnce(nestedPlan);
267
- return readInSeveral(readings.map((reading) => readingFacts(segment, { ...p, argv: reading.argv }, decl, reading, once, fed, inheritedFns)));
373
+ return readInSeveral(readings.map((reading) => readingFacts(segment, { ...p0, argv: reading.argv }, decl, reading, once, fed, inheritedFns)));
268
374
  }
269
375
  function readInSeveral(each) {
270
376
  const first = each[0];
@@ -314,6 +420,7 @@ function segmentFactsRead(segment, p, decl, table, nestedPlan, fed, toks, inheri
314
420
  const nested = [];
315
421
  const printed = [];
316
422
  const elsewhere = new Set();
423
+ const runLater = new Set();
317
424
  const ctx = { table, reentered: [], programTextSeen: false };
318
425
  const enclosedToo = (e) => [e, ...(e.inner ?? []).flatMap(enclosedToo)];
319
426
  const expansionsOf = (sg) => sg.tokens.flatMap((t) => (t.kind === "word" ? t : t.kind === "redirect" ? t.target : undefined)?.pieces ?? []).flatMap((q) => (q.expansion !== undefined ? enclosedToo(q.expansion) : []));
@@ -375,10 +482,13 @@ function segmentFactsRead(segment, p, decl, table, nestedPlan, fed, toks, inheri
375
482
  ...(f.unreadProgramText === undefined && ctx.programText !== undefined ? { unreadProgramText: ctx.programText } : {}),
376
483
  ...(elsewhere.size > 0 ? { elsewhere } : {}),
377
484
  ...(shellSide.size > 0 ? { shellSide } : {}),
485
+ ...(runLater.size > 0 ? { runLater } : {}),
486
+ ...(launchedIn !== undefined ? { launchedIn } : {}),
378
487
  };
379
488
  };
380
489
  const head = toks[0]?.folded;
381
490
  const pos = readProgramPosition(p.argv);
491
+ const launchedIn = launchedInOf(pos, toks);
382
492
  const coproc = pos.written !== undefined && isShellSyntaxWord(p.argv[pos.written], COPROC) ? pos.written : undefined;
383
493
  if (coproc !== undefined && toks.length > coproc + 1) {
384
494
  const once = plannedOnce(nestedPlan);
@@ -418,7 +528,7 @@ function segmentFactsRead(segment, p, decl, table, nestedPlan, fed, toks, inheri
418
528
  const listed = basename !== undefined && (decl.readers.has(basename) || basename === "cd");
419
529
  const verb = program === undefined ? undefined : { name: program.name, basename: program.basename, listed };
420
530
  for (const k of pos.assignments) {
421
- pushAssignment(reads, toks[k].word, "env_assignment");
531
+ pushAssignment(reads, toks[k].word, "env_assignment", assignsAsStatement(pos) ? "statement" : "shell");
422
532
  assignmentArithmetic(toks[k].word, table.isInteger(toks[k].word.assignment?.name ?? ""), ctx);
423
533
  }
424
534
  for (const l of pos.launchers) {
@@ -479,7 +589,7 @@ function segmentFactsRead(segment, p, decl, table, nestedPlan, fed, toks, inheri
479
589
  continue;
480
590
  }
481
591
  if (r.word.assignment !== undefined) {
482
- pushAssignment(reads, r.word, "env_assignment");
592
+ pushAssignment(reads, r.word, "env_assignment", table);
483
593
  continue;
484
594
  }
485
595
  reads.push(bare(r, "unlisted_word"));
@@ -598,10 +708,10 @@ function segmentFactsRead(segment, p, decl, table, nestedPlan, fed, toks, inheri
598
708
  for (const r of argReads) {
599
709
  const a = r.word.assignment;
600
710
  if (a !== undefined && (r.expands !== "unresolvable" || a.value.expansions.length > 0))
601
- pushAssignment(reads, r.word, "env_assignment");
711
+ pushAssignment(reads, r.word, "env_assignment", table);
602
712
  else if (r.expands === "unresolvable") {
603
713
  reads.push(bare(r, "unlisted_word"));
604
- pushAssignment(reads, r.word, "unlisted_word");
714
+ pushAssignment(reads, r.word, "unlisted_word", table);
605
715
  }
606
716
  assignmentArithmetic(r.word, integer || (a !== undefined && table.isInteger(a.name)), ctx, asWritten);
607
717
  }
@@ -643,8 +753,11 @@ function segmentFactsRead(segment, p, decl, table, nestedPlan, fed, toks, inheri
643
753
  const bodies = new Set([...codeBodies(basename, texts), ...codeBodies(basename, args)]);
644
754
  if (bodies.size > 0)
645
755
  reentry = "shell";
646
- for (const body of bodies)
647
- nested.push(nestedPlan(body, "later"));
756
+ for (const body of bodies) {
757
+ const plan = nestedPlan(body, "later");
758
+ nested.push(plan);
759
+ runLater.add(plan);
760
+ }
648
761
  return done({
649
762
  empty: false,
650
763
  launcherChain,
@@ -1,14 +1,17 @@
1
1
  /**
2
2
  * Where a text the read plan (`shell-read-plan.ts`) plans starts: a nested text's start — its names, the deny floors the
3
3
  * words handing it on carry, the user its shell runs as, its standard input and its working directory — and where each
4
- * segment's standard input comes from. A nested plan parsed against the declarations' working directory is re-based onto
5
- * the segment it sits in ({@link rebasePlan}), unless it starts in a working directory of its own.
4
+ * segment's standard input comes from. A nested plan starts at a placeholder ({@link nestedStartOf}) and is re-based onto
5
+ * the segment it sits in ({@link rebasePlan}) — onto the directory a launcher settles for it ({@link launchedAt}) where one
6
+ * does —, unless it starts in a working directory of its own.
6
7
  */
7
- import type { LexedSegment } from "../../shell/lex.js";
8
+ import { type LexedSegment } from "../../shell/lex.js";
8
9
  import type { BindingTable, FloorValue, InheritedBody, InheritedFunctions, NameReader } from "./shell-read-bindings.js";
9
- import type { TargetUser } from "./program-read-model.js";
10
+ import { type ProgramPosition } from "./bash-program-position.js";
11
+ import { type TargetUser } from "./program-read-model.js";
10
12
  import type { StdinText } from "./shell-reentry-text.js";
11
13
  import type { ReadCandidate, ShellReadPlan } from "./shell-read-plan.js";
14
+ import type { Read } from "./shell-read-word.js";
12
15
  /** Where a nested text starts its names: a substitution body inherits the table of the segment it sits in (a subshell
13
16
  * holds every variable of the shell that forks it); a text the shell runs later or elsewhere (a code body, `eval`'s
14
17
  * text, a child shell's `-c`) starts from the text's own start — every name unknown, `HOME` the declared home unless
@@ -46,6 +49,9 @@ export interface HeldThread {
46
49
  readonly physical: boolean;
47
50
  readonly functions: ReadonlySet<string>;
48
51
  readonly unread: ReadonlySet<string>;
52
+ /** The places the shell's closed scopes went (a function body it may call goes there): the deny floor of a walk in the text
53
+ * that loses track ({@link WorkdirThread.reached}). */
54
+ readonly reached?: ReadonlySet<string>;
49
55
  }
50
56
  /** What a shell holds at a segment, for a text that runs in it or in a fork of it ({@link PlanStart.names}): each function and builtin key
51
57
  * as it stands there, and the names a call to one of its functions may change — the ones the text reads a call of: an `eval` text names
@@ -73,13 +79,70 @@ export declare function plannedOnce<K, P>(plan: (text: string, kind: K, at?: Nes
73
79
  */
74
80
  export declare function stdinFeeds(segments: readonly LexedSegment[], start: readonly StdinText[], piped: (si: number) => readonly StdinText[]): (si: number) => readonly StdinText[];
75
81
  /**
76
- * A nested plan (a substitution body, a here-document's substitution, a launcher's command string) was parsed
77
- * against the declarations' working directory; the segment it sits in may stand elsewhere (`cd sub && cat <<EOF
78
- * $(cat secret)`), so its relative candidates are re-based onto the ENCLOSING segment's bases — every base the
79
- * nested text derived from the start is carried over by prefix, an unsettled enclosing base leaves every
80
- * relative candidate unplaced, and absolute candidates are untouched. Recursive: a nested plan's own nested plans
81
- * derive from the same start. A candidate left unplaced is judged where the text stood when it lost track (its floor,
82
- * {@link ReadCandidate.floorBases}): the places the nested text was in move with it like its bases, and an enclosing segment that
83
- * lost its base itself hands on its own floor (`floor`).
82
+ * Where a nested text with no working directory of its own starts (a substitution body, a here-document's substitution, a
83
+ * launcher's command string): a PLACEHOLDER below the declared working directory, joined as its path family joins, whose last
84
+ * segment no text can spell: a NUL byte is in no path the shell can name. Every base the nested text derives from where it
85
+ * starts (a relative move, `-C` or `..` walk from it, the start itself) holds that segment; a place the text names itself
86
+ * (`cd /x`, `-C ~`, a `CDPATH` entry, a closed scope's place on the held thread) does not — the one mark {@link rebasePlan}
87
+ * moves by ({@link walkFromStart}), and the one a walk reads `PWD` by (a start holding it is no place the shell names).
84
88
  */
85
- export declare function rebasePlan(plan: ShellReadPlan, from: string, to: ReadCandidate["bases"], floor?: readonly string[]): ShellReadPlan;
89
+ export declare function nestedStartOf(cwd: string): string;
90
+ /**
91
+ * The walk a base made from a placeholder start ({@link nestedStartOf}): what follows the placeholder's segment (`""` for
92
+ * the start itself), or `undefined` for a place the text names itself. Read off the segment, not the spelling above it, so
93
+ * a fold of the declared working directory (`/w/.`, `/w//`) leaves the walk readable. The walk is a relative spelling: the
94
+ * separator after the segment is taken with it, and a spelling joined under the start was relative (an absolute one is
95
+ * not joined), so the anchor step re-bases it by joining.
96
+ */
97
+ export declare function walkFromStart(base: string): string | undefined;
98
+ /** Where a segment's launcher chain runs its program, where a launcher moves the base it runs in ({@link launchedInOf}): each
99
+ * launcher's working directory, in chain order — `null` for a value the text does not settle, a directory it does not
100
+ * know —, or `unmodelled`: a move the text does not say (another base moved, a value with two readings). */
101
+ /** The one spelling of the unmodelled word is `ReadCandidate["bases"]`'s — read from there, never respelled here. */
102
+ export type LaunchedIn = readonly (string | null)[] | Extract<ReadCandidate["bases"], string>;
103
+ /**
104
+ * {@link LaunchedIn} of a segment whose launcher chain moves the base (`undefined` where none does), read off the options
105
+ * the program position stepped ({@link ProgramPosition.baseMovedAt}): a value whose role is a working directory (`env -C`,
106
+ * `sudo -D`, `unshare -w`) is where that launcher runs what follows, the LAST one of a launcher's options winning (each
107
+ * implementation keeps the last before it changes directory). A value the text does not settle (a substitution, a name
108
+ * it does not bind to a literal, a pattern) is a directory the text does not know (`null`); a name the text binds to a
109
+ * literal — `HOME` included — is that literal, as a `cd` to it is. Any other move — a root, a
110
+ * program search, a directory taken from elsewhere (`nsenter -w` with no value), an optional value spelled `=V` (util-linux
111
+ * 2.41 drops the `=`, getopt and util-linux 2.38 keep it: two places), an empty value (no directory: the launcher runs
112
+ * nothing) — leaves it unsaid. Which word is whose option is the walk's reading and no other (env steps a lone `-` and reads
113
+ * on; a `--` ends the options).
114
+ */
115
+ export declare function launchedInOf(pos: ProgramPosition, toks: readonly Read[]): LaunchedIn | undefined;
116
+ /**
117
+ * Where a launcher chain that moves the base ({@link LaunchedIn}) puts its program, from where the command line stands
118
+ * (`bases`, or the deny floor `floor` of a walk that lost track): each launcher's working directory in turn, as the process
119
+ * `chdir()`s to it ({@link chdirFrom}). `to` is where the text the program hands a shell starts ({@link rebasePlan} moves it
120
+ * there) — `unmodelled` where the text does not say (an unsettled move, a lost walk, a spelling naming no place), `floor`
121
+ * its deny floor then; `words` is the deny floor of the segment's own relative words, which may be the launcher's (where
122
+ * the command line stands) or the program's (where the launcher put it). `unsettled`: a launcher's value is one the text
123
+ * does not settle — the shell computes it where the command line stands, so the floor is where the launcher stood and where
124
+ * the command line stands, and what the program does from there it does from a directory the text does not know
125
+ * ({@link ReadCandidate.unsettledStart}). `undefined`: no launcher moves the base.
126
+ */
127
+ export declare function launchedAt(launchedIn: LaunchedIn | undefined, bases: ReadCandidate["bases"], floor: readonly string[] | undefined, homeDir: string | undefined): {
128
+ readonly to: ReadCandidate["bases"];
129
+ readonly floor?: readonly string[];
130
+ readonly words?: readonly string[];
131
+ readonly unsettled?: true;
132
+ } | undefined;
133
+ /**
134
+ * A nested plan (a substitution body, a here-document's substitution, a launcher's command string) was planned from
135
+ * its placeholder start ({@link nestedStartOf}); the segment it sits in may stand elsewhere (`cd sub && cat <<EOF
136
+ * $(cat secret)`), so what it derived from the start is re-based onto the ENCLOSING segment's bases (for a text a launcher
137
+ * runs in a working directory it settles, `env -C <dir>`, onto that directory): a base spelled
138
+ * from the placeholder lands under each of them, an unsettled enclosing base leaves every relative candidate
139
+ * unplaced, and every other place (an absolute candidate, a place the nested text named itself) is untouched.
140
+ * Recursive: a nested plan's own nested plans derive from the same start. A candidate left unplaced is judged where the
141
+ * text stood when it lost track (its floor, {@link ReadCandidate.floorBases}): the places the nested text derived move with
142
+ * it like its bases, an enclosing segment that lost its base itself hands on its own floor (`floor`), and a derived place
143
+ * with nowhere to land is no place (an unplaced candidate with no floor is judged at the declared working directory).
144
+ * `unsettled`: the enclosing segment stands in a directory the text does not know — a candidate the nested text derived
145
+ * from its start is made from there ({@link ReadCandidate.unsettledStart}).
146
+ * A plan re-based onto the same place twice is one plan (a segment read in several readings hands its nested plans on alike).
147
+ */
148
+ export declare function rebasePlan(plan: ShellReadPlan, to: ReadCandidate["bases"], floor?: readonly string[], unsettled?: boolean): ShellReadPlan;