@sema-agent/core 7.17.6 → 7.18.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 (164) hide show
  1. package/CHANGELOG.md +165 -13
  2. package/dist/agents/send-message-tool.js +1 -0
  3. package/dist/agents/subagent.d.ts +1 -0
  4. package/dist/agents/subagent.js +5 -0
  5. package/dist/agents/teacher.js +1 -0
  6. package/dist/agents/verify.js +3 -0
  7. package/dist/brain/route-adjudicator.d.ts +18 -0
  8. package/dist/brain/route-adjudicator.js +16 -0
  9. package/dist/core/agent-definition.d.ts +10 -0
  10. package/dist/core/artifact-host.d.ts +41 -4
  11. package/dist/core/artifact-host.js +18 -2
  12. package/dist/core/auto-mode.d.ts +141 -45
  13. package/dist/core/auto-mode.js +109 -3
  14. package/dist/core/checkpoint-store.d.ts +16 -2
  15. package/dist/core/engine-notice.d.ts +47 -1
  16. package/dist/core/engine-notice.js +7 -0
  17. package/dist/core/gate-lanes.js +2 -1
  18. package/dist/core/gate-outcome.d.ts +17 -2
  19. package/dist/core/gate-outcome.js +16 -0
  20. package/dist/core/governance-codes.d.ts +1 -1
  21. package/dist/core/governance-codes.js +8 -0
  22. package/dist/core/hook-seats.d.ts +66 -0
  23. package/dist/core/hook-seats.js +37 -0
  24. package/dist/core/runner/advertised-writable-dirs.d.ts +8 -3
  25. package/dist/core/runner/assemble-result.d.ts +2 -1
  26. package/dist/core/runner/assemble-result.js +1 -1
  27. package/dist/core/runner/classifier-ladder.d.ts +89 -0
  28. package/dist/core/runner/classifier-ladder.js +65 -0
  29. package/dist/core/runner/contracts.d.ts +69 -13
  30. package/dist/core/runner/decide-continuation.d.ts +1 -3
  31. package/dist/core/runner/decide-continuation.js +1 -7
  32. package/dist/core/runner/deferral-census.d.ts +52 -0
  33. package/dist/core/runner/deferral-census.js +44 -0
  34. package/dist/core/runner/derived-route-fallback.d.ts +8 -4
  35. package/dist/core/runner/derived-route-fallback.js +8 -3
  36. package/dist/core/runner/gate-exit.d.ts +12 -0
  37. package/dist/core/runner/gate-exit.js +6 -3
  38. package/dist/core/runner/prepare-artifact.d.ts +10 -2
  39. package/dist/core/runner/prepare-artifact.js +5 -4
  40. package/dist/core/runner/prepare-caps-and-workflow.d.ts +4 -2
  41. package/dist/core/runner/prepare-caps-and-workflow.js +30 -31
  42. package/dist/core/runner/prepare-config-doors.d.ts +1 -1
  43. package/dist/core/runner/prepare-config-doors.js +5 -3
  44. package/dist/core/runner/prepare-defer-classify.d.ts +13 -19
  45. package/dist/core/runner/prepare-defer-classify.js +8 -3
  46. package/dist/core/runner/prepare-gate-stations.d.ts +26 -0
  47. package/dist/core/runner/prepare-gate-stations.js +1 -1
  48. package/dist/core/runner/prepare-hands-readface.d.ts +24 -7
  49. package/dist/core/runner/prepare-hands-readface.js +60 -24
  50. package/dist/core/runner/prepare-inherited-gate.d.ts +17 -4
  51. package/dist/core/runner/prepare-inherited-gate.js +10 -2
  52. package/dist/core/runner/prepare-lsp.d.ts +2 -2
  53. package/dist/core/runner/prepare-lsp.js +1 -1
  54. package/dist/core/runner/prepare-policy-chain.js +2 -0
  55. package/dist/core/runner/prepare-project-context.js +4 -2
  56. package/dist/core/runner/prepare-prompt-inputs.d.ts +4 -2
  57. package/dist/core/runner/prepare-prompt-inputs.js +4 -1
  58. package/dist/core/runner/prepare-run-refs.d.ts +9 -1
  59. package/dist/core/runner/prepare-run-refs.js +3 -2
  60. package/dist/core/runner/prepare-suspend-saga.d.ts +5 -0
  61. package/dist/core/runner/prepare-suspend-saga.js +5 -2
  62. package/dist/core/runner/prepare-task.js +18 -13
  63. package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +5 -0
  64. package/dist/core/runner/prepare-tool-disclosure-mount.js +10 -2
  65. package/dist/core/runner/prepare-turn-wiring.d.ts +8 -4
  66. package/dist/core/runner/prepare-turn-wiring.js +3 -2
  67. package/dist/core/runner/prepare-wiring-manifest.d.ts +5 -5
  68. package/dist/core/runner/prepare-wiring-manifest.js +5 -2
  69. package/dist/core/runner/resume-checkpoint-screen.js +7 -0
  70. package/dist/core/runner/run-harness-handlers.js +4 -1
  71. package/dist/core/runner/run-identity-wiring.js +6 -2
  72. package/dist/core/runner/run-leg.d.ts +2 -0
  73. package/dist/core/runner/run-leg.js +35 -41
  74. package/dist/core/runner/run-notification-lane.js +55 -27
  75. package/dist/core/runner/run-settle-and-teardown.js +1 -0
  76. package/dist/core/runner/run-terminal-adoption.js +16 -13
  77. package/dist/core/runner/run-turn-boundary.js +3 -1
  78. package/dist/core/runner/runtask.d.ts +6 -5
  79. package/dist/core/runner/runtask.js +26 -14
  80. package/dist/core/runner/skill-base-dir.d.ts +54 -0
  81. package/dist/core/runner/skill-base-dir.js +42 -0
  82. package/dist/core/runner/synthetic-tools.d.ts +16 -19
  83. package/dist/core/runner/synthetic-tools.js +18 -10
  84. package/dist/core/runner/tool-defer-gate.d.ts +22 -9
  85. package/dist/core/runner/tool-defer-gate.js +15 -5
  86. package/dist/core/runner/tool-disclosure.d.ts +5 -0
  87. package/dist/core/runner/tool-disclosure.js +2 -0
  88. package/dist/core/runner/tool-progress-lane.d.ts +42 -0
  89. package/dist/core/runner/tool-progress-lane.js +61 -0
  90. package/dist/core/runner-deps.d.ts +48 -7
  91. package/dist/core/swappable-deps.d.ts +9 -7
  92. package/dist/core/swappable-deps.js +7 -3
  93. package/dist/core/task-event.d.ts +96 -29
  94. package/dist/core/task-notification.d.ts +142 -16
  95. package/dist/core/task-notification.js +106 -0
  96. package/dist/core/task-result.d.ts +9 -1
  97. package/dist/core/task-spec.d.ts +20 -3
  98. package/dist/core/tighten-task-spec.js +7 -5
  99. package/dist/core/tool-model-gate.d.ts +1 -1
  100. package/dist/core/tool-search-setting.d.ts +78 -0
  101. package/dist/core/tool-search-setting.js +90 -0
  102. package/dist/core/tool-spec.d.ts +8 -0
  103. package/dist/core/types.d.ts +1 -1
  104. package/dist/core/types.js +1 -1
  105. package/dist/core/wiring-manifest.d.ts +46 -0
  106. package/dist/core/wiring-manifest.js +9 -1
  107. package/dist/engine/execution-env/node-execution-env.js +10 -4
  108. package/dist/engine/harness/agent-harness.d.ts +42 -0
  109. package/dist/engine/harness/agent-harness.js +61 -29
  110. package/dist/engine/loop/agent-loop.d.ts +68 -3
  111. package/dist/engine/loop/agent-loop.js +109 -16
  112. package/dist/index.d.ts +10 -5
  113. package/dist/index.js +9 -5
  114. package/dist/internal/harness.d.ts +1 -1
  115. package/dist/orchestration/run-workflow-tool.d.ts +3 -0
  116. package/dist/orchestration/run-workflow-tool.js +6 -1
  117. package/dist/orchestration/workflow-governance.d.ts +7 -1
  118. package/dist/orchestration/workflow-governance.js +9 -5
  119. package/dist/orchestration/workflow-primitives.d.ts +3 -0
  120. package/dist/orchestration/workflow-primitives.js +6 -1
  121. package/dist/orchestration/workflow-types.d.ts +48 -13
  122. package/dist/orchestration/workflow-types.js +1 -1
  123. package/dist/orchestration/workflow.js +45 -17
  124. package/dist/prompt-assembly/epoch.js +2 -0
  125. package/dist/prompt-assembly/packs/sema-default.js +2 -2
  126. package/dist/prompt-assembly/section-usage.d.ts +26 -0
  127. package/dist/prompt-assembly/section-usage.js +10 -0
  128. package/dist/prompt-assembly/types.d.ts +8 -6
  129. package/dist/prompts/default.d.ts +13 -0
  130. package/dist/prompts/default.js +16 -8
  131. package/dist/tools/artifact/artifact-text.d.ts +10 -1
  132. package/dist/tools/artifact/artifact-text.js +6 -3
  133. package/dist/tools/artifact/artifact-tool.d.ts +12 -2
  134. package/dist/tools/artifact/artifact-tool.js +203 -70
  135. package/dist/tools/artifact/conformance.d.ts +56 -0
  136. package/dist/tools/artifact/conformance.js +349 -0
  137. package/dist/tools/artifact/local-stub.js +1 -1
  138. package/dist/tools/artifact/reject-breaker.d.ts +28 -0
  139. package/dist/tools/artifact/reject-breaker.js +42 -0
  140. package/dist/tools/fs/bash-lexer.d.ts +132 -0
  141. package/dist/tools/fs/bash-lexer.js +563 -0
  142. package/dist/tools/fs/bash-program-position.d.ts +142 -0
  143. package/dist/tools/fs/bash-program-position.js +125 -0
  144. package/dist/tools/fs/bash-readonly-classifier.d.ts +54 -16
  145. package/dist/tools/fs/bash-readonly-classifier.js +375 -530
  146. package/dist/tools/fs/containment-face.d.ts +89 -0
  147. package/dist/tools/fs/containment-face.js +81 -0
  148. package/dist/tools/fs/fs-bash.d.ts +46 -1
  149. package/dist/tools/fs/fs-bash.js +158 -22
  150. package/dist/tools/fs/fs-read.d.ts +1 -1
  151. package/dist/tools/fs/fs-search-tools.d.ts +3 -3
  152. package/dist/tools/fs/fs-write.d.ts +4 -3
  153. package/dist/tools/fs/fs-write.js +9 -9
  154. package/dist/tools/fs/index.d.ts +24 -5
  155. package/dist/tools/fs/index.js +18 -6
  156. package/dist/tools/fs/repo-map.d.ts +2 -2
  157. package/dist/tools/fs/safety.d.ts +3 -3
  158. package/dist/tools/fs/safety.js +4 -4
  159. package/package.json +1 -1
  160. package/test/export-surface.snapshot.json +85 -9
  161. package/wire-changes/core@7.17.6.json +81 -0
  162. package/wire-changes/core@7.17.7.json +49 -0
  163. package/dist/tools/fs/read-face.d.ts +0 -68
  164. package/dist/tools/fs/read-face.js +0 -47
package/dist/index.js CHANGED
@@ -4,14 +4,16 @@ export { terminalProjection } from "./core/runner/terminal-projection.js";
4
4
  export { SESSION_LOG_DIGEST_SCHEME, sessionEntryDigest, sessionLogDigest, sessionLogDigestsComparable, } from "./engine/session/log-digest.js";
5
5
  export { defineTool } from "./core/tools.js";
6
6
  export { SKILL_TOOL_NAME } from "./core/runner/synthetic-tools.js";
7
+ export { TOOL_SEARCH_POLICIES, TOOL_SEARCH_DEFAULT_THRESHOLD_PERCENT, TOOL_SEARCH_INVALID_CODE, } from "./core/tool-search-setting.js";
7
8
  export { createSkillsFromDirectory, } from "./core/skills-directory.js";
8
9
  export { REPORT_FINDINGS_TOOL_NAME } from "./core/runner/synthetic-tools.js";
9
10
  export { formatToolError, formatZodValidationError, formatValidationPath, truncateError, errorClassOf } from "./core/tool-errors.js";
10
11
  export { createWebFetchTool, webFetchToolSpec, htmlToText, createWebSearchTool, createSearxngSearchBackend, probeSearchBackend, createWebFetchSummarizer, WEBFETCH_SUMMARY_MAX_CONTENT, WEBFETCH_SUMMARY_GUIDELINES, } from "./tools/web.js";
11
12
  export { createTodoWriteTool } from "./tools/todo.js";
12
- export { ARTIFACT_ACTIONS, ARTIFACT_PLANES, ARTIFACT_PUBLISH_CONTEXTS, ARTIFACT_LIST_SCOPES, ARTIFACT_PLANE_CONTENT_ORIGIN, ARTIFACT_ACTION_HOST_METHOD, ARTIFACT_HOST_FAILURE_CODES, ARTIFACT_FAILURE_RESULT_CODE, ARTIFACT_HOST_ERROR_CODE, ARTIFACT_CARD, readArtifactHostCapabilities, } from "./core/artifact-host.js";
13
+ export { ARTIFACT_ACTIONS, ARTIFACT_PLANES, ARTIFACT_COMMIT_CERTAINTIES, ARTIFACT_COMMIT_THROW_OUTCOME, ARTIFACT_PUBLISH_CONTEXTS, ARTIFACT_LIST_SCOPES, ARTIFACT_PLANE_CONTENT_ORIGIN, ARTIFACT_ACTION_HOST_METHOD, ARTIFACT_ACTION_CONCURRENCY_SAFE, ARTIFACT_HOST_FAILURE_CODES, ARTIFACT_FAILURE_RESULT_CODE, ARTIFACT_HOST_ERROR_CODE, ARTIFACT_CARD, readArtifactHostCapabilities, } from "./core/artifact-host.js";
13
14
  export { createArtifactTool, artifactAttemptId, normalizePublishedPath, mediaTypeOf } from "./tools/artifact/artifact-tool.js";
14
15
  export { localArtifactStub, LocalArtifactStub, EVAL_STUB_URL_PREFIX, LOCAL_STUB_MAX_FILE_BYTES, LOCAL_STUB_MAX_TOTAL_BYTES } from "./tools/artifact/local-stub.js";
16
+ export { ARTIFACT_CONFORMANCE_VECTORS, artifactConformanceVectors, runArtifactConformance, } from "./tools/artifact/conformance.js";
15
17
  export { createTaskListTools, createMemoryTaskListStore, assertJsonMetadata } from "./tools/task-list.js";
16
18
  export { assembleCodeTools, CODE_ROLE } from "./scenarios/full-body.js";
17
19
  export { TOOL_MODEL_GATE_CLASSES, isModelGatedForClass } from "./core/tool-model-gate.js";
@@ -80,7 +82,7 @@ export { bashReversibilityProbe, bashReadBoundaryProbe, BASH_READONLY_DEFAULT_AL
80
82
  export { classifyCompoundReadonlyDetailed, formatOutOfRootReadApprovalOption, } from "./tools/fs/index.js";
81
83
  export { resolveBashTimeoutCaps } from "./tools/fs/index.js";
82
84
  export { READ_FACE_DEFAULT_DENY_ENTRIES, READ_FACE_BUILTIN_DENY_TABLE, READ_DENY_BUILTIN_TIERS, READ_DENY_DEFAULT_TIERS, resolveReadDenyBuiltins, compileReadDeny, } from "./tools/fs/index.js";
83
- export { deploymentReadFaceClampNotice, resolveReadFace } from "./tools/fs/index.js";
85
+ export { deploymentFaceClampNotice, resolveContainmentFace, } from "./tools/fs/index.js";
84
86
  export { WRITE_PROTECTED_DEFAULT_TABLE, resolveWriteProtectedTable, compileWriteProtection, } from "./core/write-protect.js";
85
87
  export { InMemoryToolResultStore, OFFLOAD_TOOL_NAME, DEFAULT_TOOL_RESULT_THRESHOLD_CHARS, assertSafeToolResultRef, buildToolResultRef, toolResultContentSegment, MAX_MINTED_TOOL_RESULT_REF_CHARS, assertToolResultProvenanceMatch, normalizeToolResultProvenance, toolResultProvenanceOf, ToolResultRefConflictError, TOOL_RESULT_REF_CONFLICT_CODE, } from "./core/tool-result-store.js";
86
88
  export { InMemoryCheckpointStore, CheckpointError, mintCheckpointId, mintCheckpointToken, checkpointVersionOf, CURRENT_CHECKPOINT_VERSION, MAX_SUPPORTED_CHECKPOINT_VERSION, ORG_ADMISSION_CHECKPOINT_VERSION, F012_CHECKPOINT_VERSION, REAL_APPROVAL_CHECKPOINT_VERSION, RESOURCE_CHECKPOINT_VERSION, TOKEN_CHECKPOINT_VERSION, debitLedger, remainingBudgetMicroUsd, remainingTokens, winnerFromOutcome, validatePendingSteer, readPendingSteerQueue, appendPendingSteer, MAX_PENDING_STEER_CHARS, MAX_PENDING_STEER_ENTRIES, PENDING_STEER_QUEUE_BYTE_BUDGET_BYTES, PENDING_STEER_FROZEN_FIELDS, ACTOR_ASSERTION_FROZEN_FIELDS, MAX_ACTOR_FIELD_CHARS, MAX_STEER_INPUT_ID_CHARS, riskSeverity, buildRiskDescriptor, summarizeCheckpoint, realApprovalOrgFact, resolveCheckpointStore, checkpointStoreExecutionUndeclared, } from "./core/checkpoint-store.js";
@@ -119,7 +121,7 @@ export { parkedToolIdentity } from "./core/tool-roster.js";
119
121
  export {} from "./core/fs-write-gate-policy.js";
120
122
  export { catalogRuleFaceView } from "./core/permission-rules.js";
121
123
  export { DURABLE_HISTORY_NAMES } from "./engine/compaction/utils.js";
122
- export { describeStaticWiring, deriveWiringManifest, deriveAskEffective, resolveDeclaredDurability, resolveSubagentTranscriptTier, resolveAskSeamForm, resolveQuestionSeam, countElicitOptIns, AUTO_MODE_ARM_REASONS, } from "./core/wiring-manifest.js";
124
+ export { describeStaticWiring, deriveWiringManifest, deriveAskEffective, resolveDeclaredDurability, resolveSubagentTranscriptTier, resolveAskSeamForm, resolveQuestionSeam, countElicitOptIns, AUTO_MODE_ARM_REASONS, LSP_LANES, } from "./core/wiring-manifest.js";
123
125
  export { probeParkRoundTrip, durableParkGapOf, durableParkGapFor, PARK_SELFCHECK_SCOPE_PREFIX, } from "./core/park-selfcheck.js";
124
126
  export {} from "./core/checkpoint-store.js";
125
127
  export {} from "./core/checkpoint-store.js";
@@ -148,7 +150,7 @@ export { AUTO_MODE_DENY_SOURCES, isAutoModeDenySource } from "./core/runtime-cap
148
150
  export { SETTLEMENT_KINDS, isSettlementKind, SETTLEMENT_IS_REFUSAL, DENIED_BY_VALUES, isDeniedBy, DENIED_BY_MAY_VETO, CLASSIFIER_DENY_CAUSES, isClassifierDenyCause, DENIED_BY_MAY_CARRY_CAUSE, screenGateOutcome } from "./core/gate-outcome.js";
149
151
  export {} from "./core/hooks.js";
150
152
  export { SWAPPABLE_DEP_SEATS, SWAP_SEAT_NOTICE, isSwappableDepSeat, screenSwappableDeps } from "./core/swappable-deps.js";
151
- export { parseAutoModeResponse, createAutoModeDecider, AUTO_MODE_UNAVAILABLE_CAUSES, isAutoModeUnavailableCause, classifierUnavailableDenyMessage, CLASSIFIER_PARSE_FAILURE_DENY_MESSAGE, createAutoModeDenialTracker, denialLimitFallbackMessage, denialLimitSentence, unarmedWindow, } from "./core/auto-mode.js";
153
+ export { parseAutoModeResponse, createAutoModeDecider, AUTO_MODE_UNAVAILABLE_CAUSES, isAutoModeUnavailableCause, classifierUnavailableDenyMessage, CLASSIFIER_PARSE_FAILURE_DENY_MESSAGE, AUTO_MODE_CLASSIFIER_FALLBACKS, isAutoModeClassifierFallback, AUTO_MODE_FALLBACK_CAUSES, isAutoModeFallbackCause, createAutoModeDenialTracker, denialLimitFallbackMessage, denialLimitSentence, unarmedWindow, } from "./core/auto-mode.js";
152
154
  export { AUTO_MODE_DENIAL_LIMIT_DEFAULTS, AUTO_MODE_DENIAL_AUTO_DENY_DEFAULT_MS, AUTO_MODE_CLASSIFIER_MAX_TOKENS } from "./core/auto-mode-defaults.js";
153
155
  export { buildAutoModePrompt, renderAutoModeWindow, renderAutoModeAction, AUTO_MODE_DEFAULTS_SENTINEL, } from "./core/auto-mode-prompt.js";
154
156
  export { AUTO_MODE_BASE_PROMPT, AUTO_MODE_PERMISSIONS_EXTERNAL } from "./core/auto-mode-prompt-assets.js";
@@ -171,6 +173,7 @@ export { adoptFilePermissionRuleStore } from "./stores/file/permission-rule-adop
171
173
  export { AdoptionError, assertAdoptionBootGate, readRootAdoptionFile, writeRootAdoptionFile, ROOT_ADOPTION_FILE, } from "./stores/file/adoption/marker.js";
172
174
  export { adoptLocalDataRoot, ackAdoptionConfig, witnessAdoptionConfig, listAdoptionQuarantine, readAdoptionStatus, } from "./stores/file/adoption/adopt.js";
173
175
  export { formatHookFeedback, runToolGate, createHookEnvCapabilities, createPreToolUseConstraintPolicy, normalizePersistedRuleHit, } from "./core/hooks.js";
176
+ export { HOOK_FAMILIES, HOOKS_INVALID_CODE } from "./core/hook-seats.js";
174
177
  export { InMemoryMemoryStore, composeMemoryBlock, composeLayeredMemoryBlock, normalizeMemorySpec, supportsConsolidation, supportsPeriodicConsolidation, firstSentence, expandLexicalTerms, lexicalSearchMatch, classifyPromotable, enforcePromotableWriteGate, guardedMemoryStore, MemoryGateError, detectSecret, enforceSecretWriteGate, enforceStructuredNoteSecretGate, } from "./core/memory.js";
175
178
  export { MemoryEngine, FileMemoryEngineBackend, memoryBackendContract, assertMemoryBackendSearchEquivalence, buildMemoryInstruction, writableRootOf, truncateIndex, scanEntryFiles, deriveRepoKey, deriveRepoMemoryDir, deriveControlPlaneDir, deriveRepoControlPlaneDir, resolveMemoryEngineRoot, scopeDirName, ControlPlaneCorruptError, parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, MEMORY_ORIGIN_CAUSES, committedOriginOf, originEquals, consolidationExposedFrontmatter, ambiguousOriginRepresentation, committedDistilledOf, distilledEquals, CONSOLIDATION_DEFAULTS, ConsolidationRefusedError, MEMORY_SEARCH_SUPERSEDED_TAG, consolidationTypeEligible, deriveSupersededSet, memorySupersededNote, readIntentCredentials, supersessionFuseCeiling, memoryConsolidationRecommendedNotice, memoryConsolidationCommittedNotice, memoryConsolidationConflictNotice, memoryConsolidationIncompleteNotice, memoryConsolidationRefusedNotice, memoryConsolidationWithheldNotice, DISTILLER_DEFAULT_MAX_INPUTS_PER_PRODUCT, LLM_DISTILLER_CONTRACT, LLM_DISTILLER_CONTRACT_DL2, LLM_DISTILLER_CONTRACT_DL3, LLM_DISTILLER_CONTRACTS, MEMORY_DISTILLER_CONTRACT_V1, contractGroupingDiff, driveConsolidationToFixpoint, isAliasModelId, llmPlanDistiller, mintExposurePartitionedPlan, mintLlmConsolidationPlan, MEMORY_DISTILLER_PURITY_CONTRACT_V1, detectCleanArmVerbatimLeak, openAiCompatChatSeat, parseJsonAnswer, planParseRepairs, sanitizeLlmGroups, scheduleUnderFuse, CONSOLIDATION_DRIVER_PLANS_DIR, CONSOLIDATION_DRIVER_RUNS_FILE, CONSOLIDATION_RUN_STOP_REASONS, archiveDistillerPlan, readConsolidationDriverRun, runMemoryConsolidationDriver, isInstructionEntry, MEMORY_INSTRUCTION_TEMPLATE, MEMORY_RECALL_DISCIPLINE, MEMORY_PREFERENCE_DISCIPLINE, MEMORY_READONLY_NOTICE, MEMORY_CAPTURE_OPTOUT_NOTICE, memoryCaptureOptedOutNotice, memoryCaptureOptOutUnpersistedNotice, SESSION_CAPTURE_OPTOUT_DIR, markSessionCaptureOptOut, readSessionCaptureOptOut, listSessionCaptureOptOut, fileSessionCaptureRecordStore, readV2HeaderHints, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, CHALLENGE_LEDGER_MAX_EVENTS, rebuildStrictControlPlaneLedger, MEMORY_INDEX_FILENAME, MEMORY_INDEX_MAX_LINES, MEMORY_INDEX_MAX_BYTES, MEMORY_SEARCH_TOOL_NAME, MEMORY_GET_TOOL_NAME, MEMORY_INDEX_TOOL_NAME, MEMORY_ENGINE_TOOL_NAMES, MEMORY_EXPOSURE_BANNER, MEMORY_EXPOSURE_HANDLE_TAG, memoryExposureIndexRow, STUB_ARCHIVED_LINE, DEFAULT_MAX_MEMORY_FILES, DEFAULT_MAX_ENTRY_DEPTH, DEFAULT_HARVEST_DEADLINE_MS, DEFAULT_HARVEST_FILE_BUDGET, MASS_DELETION_FUSE_RATIO, scanMemoryWrite, scanMemoryFileName, scanRemediation, MEMORY_FILENAME_SEGMENT_RE, renderAnnouncements, enqueueMemoryAnnouncement, drainMemoryAnnouncements, peekMemoryAnnouncements, bumpScanFuse, scanFuseCount, clearScanFuse, ANNOUNCEMENTS_FILE, MEMORY_ANNOUNCEMENTS_MAX, SCAN_FUSE_FILE, SCAN_FUSE_THRESHOLD, erasureSelectHash, computeMemoryBundleHash, SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, migrateScope, materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, syncMemoryScope, } from "./core/memory-engine/index.js";
176
179
  export { SHARED_MEMORY_READ_CAP_BYTES, SHARED_MEMORY_LIST_PAGE_SIZE, SharedMemoryStoreError, } from "./core/shared-memory/types.js";
@@ -181,7 +184,7 @@ export { runMemoryConsolidation, CONSOLIDATION_SYSTEM_PROMPT, DEFAULT_CONSOLIDAT
181
184
  export { consolidateScope, advanceCursorAfterInline, } from "./core/consolidate-scope.js";
182
185
  export { resolveMemoryConsolidationDriver, } from "./core/runner/memory-consolidation-driver.js";
183
186
  export { DEFAULT_COMPACTION_INSTRUCTIONS } from "./core/auto-compaction.js";
184
- export { DEFAULT_SYSTEM_PROMPT, CODE_AGENT_PROMPT, SUBAGENT_PROMPT, CODE_SYSTEM_PROMPT, MEMORY_GUIDANCE, MEMORY_SAFETY, MEMORY_HYGIENE, NO_PERSISTENT_MEMORY_NOTICE, OUTPUT_EFFICIENCY, CYBER_RISK, HARNESS_SECTION_ANCHOR, URL_SAFETY, SUMMARIZE_TOOL_RESULTS, EXECUTION_ENVIRONMENT, EXECUTION_ENVIRONMENT_OPEN_READS, harnessContext, buildEnvironmentContext, buildGitSnapshot, buildScratchpadSection, GIT_STATUS_MAX_CHARS, formatLocalDate, defaultPromptProvider, composeSystemPrompt, composeConstitution, constitutionBlocks, analyzePromptCacheFriendliness, assertPromptCacheFriendly, } from "./prompts/default.js";
187
+ export { DEFAULT_SYSTEM_PROMPT, CODE_AGENT_PROMPT, SUBAGENT_PROMPT, CODE_SYSTEM_PROMPT, MEMORY_GUIDANCE, MEMORY_SAFETY, MEMORY_HYGIENE, NO_PERSISTENT_MEMORY_NOTICE, OUTPUT_EFFICIENCY, CYBER_RISK, HARNESS_SECTION_ANCHOR, URL_SAFETY, SUMMARIZE_TOOL_RESULTS, EXECUTION_ENVIRONMENT, EXECUTION_ENVIRONMENT_OPEN_READS, executionEnvironmentBlockFor, harnessContext, buildEnvironmentContext, buildGitSnapshot, buildScratchpadSection, GIT_STATUS_MAX_CHARS, formatLocalDate, defaultPromptProvider, composeSystemPrompt, composeConstitution, constitutionBlocks, analyzePromptCacheFriendliness, assertPromptCacheFriendly, } from "./prompts/default.js";
185
188
  export { SUPERVISOR_PROMPT, ORCHESTRATION_GUIDANCE, ORCHESTRATION_AWARENESS, GOAL_COMPLETION_GUIDANCE } from "./prompts/supervisor.js";
186
189
  export { compose, validatePack } from "./prompt-assembly/composer.js";
187
190
  export { SEMA_DEFAULT_PACK } from "./prompt-assembly/packs/sema-default.js";
@@ -192,6 +195,7 @@ export { buildTurnPromptSnapshot, loweringRecordFor, LOWERING_VERSION, PREFIX_IN
192
195
  export { CenterPromptSource, FilePromptArtifactStore, FilePromptSourceStateStore, MemoryPromptArtifactStore, MemoryPromptSourceStateStore, } from "./prompt-assembly/artifact-store.js";
193
196
  export { stripEngineMetadata } from "./internal/llm.js";
194
197
  export { EVENT_PROMPT_REGISTRY, eventDefaultOn } from "./prompt-assembly/event-registry.js";
198
+ export { contextUsageSections } from "./prompt-assembly/section-usage.js";
195
199
  export { DEFAULT_EFFORT_LEVELS, REASONING_BUDGET_SHARE, isThinkingLevel, rankOf, resolveEffort, reasoningEffortLevelsOf, resolveBinary, reasoningBudgetShare, resolveReasoning, thinkingOffExpressible, declaredOffSpelling, resolveReasoningProfile, } from "./brain/reasoning.js";
196
200
  export { DESIGN_REVIEW_PROMPTS, CODE_REVIEW_PROMPT, SCENARIO_REGISTRY, runScenario, } from "./scenarios/scenario-registry.js";
197
201
  export { teacherMode, TEACHER_PROFILE, } from "./scenarios/teacher-quickstart.js";
@@ -11,7 +11,7 @@
11
11
  */
12
12
  export * from "./harness-types.js";
13
13
  export { AgentHarness } from "../engine/harness/agent-harness.js";
14
- export type { HaltConsumption, SeatCutSource, StopRequestSource } from "../engine/harness/agent-harness.js";
14
+ export type { HaltConsumption, PromptDeliveredCallback, SeatCutSource, StopRequestSource, TrailingToolBatchOptions } from "../engine/harness/agent-harness.js";
15
15
  export { CompactionError, ExecutionError, FileError, ok, err } from "../engine/harness/types.js";
16
16
  export { DEFAULT_CHARS_PER_TOKEN, DEFAULT_CLAMP_TOLERANCE, DEFAULT_COMPACTION_SETTINGS, compact, computeFileLists, dryRunSummarizationClamp, estimateContextTokens, estimateTokens, prepareCompaction, shouldCompact, summaryOutputBudgetTokens, } from "../engine/compaction/compaction.js";
17
17
  export { SKILL_RETENTION_PER_SKILL_MAX_CHARS, SKILL_RETENTION_TOTAL_MAX_CHARS, SKILL_RETENTION_TRUNCATION_MARKER, formatFileOperations, formatPersistedOutputRefs, readCompactionActiveTools, readRetainedInvokedSkills, renderInvokedSkillsRetention, } from "../engine/compaction/utils.js";
@@ -276,6 +276,9 @@ export interface RunWorkflowToolDeps {
276
276
  * read-face containment; folds stricter-wins into every spawned workflow child (see
277
277
  * `buildWorkflowPrimitives`'s injection block for the full rationale). */
278
278
  parentReadFace?: () => import("../core/types.js").TaskSpec["readFace"];
279
+ /** The WRITE seat's twin of the above: the HOST task's RESOLVED write-face containment, folded
280
+ * stricter-wins into every spawned workflow child on its own seat. */
281
+ parentWriteFace?: () => import("../core/types.js").TaskSpec["writeFace"];
279
282
  /** Twin of the above for the deny-set additions (union, not replace). */
280
283
  parentReadDenyPatterns?: () => import("../core/types.js").TaskSpec["readDenyPatterns"];
281
284
  /** #345 ③ — the HOST task's write-hands clamp, the read-face clamp's sibling on this lane (the
@@ -21,6 +21,11 @@ import { builtinWorkflowListings, canonicalWorkflowName, resolveBuiltinWorkflow,
21
21
  import { workflowSizeGuidelineSection } from "./workflow-size-guideline.js";
22
22
  import { toolFace } from "../core/tool-catalog-entries.js";
23
23
  export const RUN_WORKFLOW_TOOL_NAME = "Workflow";
24
+ function parentFaceSeat(ctxSeat, dep) {
25
+ if (ctxSeat !== "roots")
26
+ return dep;
27
+ return () => "roots";
28
+ }
24
29
  function stripCodeFences(s) {
25
30
  const t = s.trim();
26
31
  const m = /^```[A-Za-z]*\r?\n([\s\S]*?)\r?\n?```$/.exec(t);
@@ -503,7 +508,7 @@ export async function createRunWorkflowTool(d) {
503
508
  const childParkSeat = ctx.checkpointStoreForChildren ?? d.parentCheckpointStore;
504
509
  const parkStore = checkpointStoreOfSeat(childParkSeat);
505
510
  const scriptFn = (wfCtx) => {
506
- const primitives = buildWorkflowPrimitives(wfCtx, runGovernance, d.onAgentSpawn, childParkSeat, d.parentReadFace, d.parentReadDenyPatterns, ctx.handsReadOnly === true || d.parentHandsReadOnly === true, ctx.interactiveTools === false || d.parentInteractiveTools === false);
511
+ const primitives = buildWorkflowPrimitives(wfCtx, runGovernance, d.onAgentSpawn, childParkSeat, parentFaceSeat(ctx.readFace, d.parentReadFace), parentFaceSeat(ctx.writeFace, d.parentWriteFace), d.parentReadDenyPatterns, ctx.handsReadOnly === true || d.parentHandsReadOnly === true, ctx.interactiveTools === false || d.parentInteractiveTools === false);
507
512
  return d.scriptRunner.run({ scriptSource: script, primitives, scriptArgs: effectiveArgs, signal: wfCtx.signal }).then((r) => r.result);
508
513
  };
509
514
  if (ctx.signal?.aborted) {
@@ -65,6 +65,12 @@ export interface WorkflowAgentSpec {
65
65
  * {@link pickWhitelist} enforces it on the untrusted value.
66
66
  */
67
67
  readFace?: "roots";
68
+ /**
69
+ * TIGHTEN-ONLY, the write seat's twin of {@link readFace}: `"roots"` — the write-face containment
70
+ * judgment — is the ONLY value a script may set. `"open"` is the WIDENING direction, so it is
71
+ * stripped and announced rather than applied.
72
+ */
73
+ writeFace?: "roots";
68
74
  /**
69
75
  * design/199 件B, TIGHTEN-ONLY: additional read-deny entries. Add-only at every layer a governed
70
76
  * SCRIPT can reach: the baseline's entries and the deployment-ACTIVE built-in set are always in
@@ -91,7 +97,7 @@ export interface WorkflowAgentSpec {
91
97
  * NON-GOAL of this window: it would break every existing script carrying a harmless extra field, and is held
92
98
  * for a BREAKING window.
93
99
  */
94
- export declare const WHITELIST_KEYS: readonly ["objective", "modelName", "thinking", "systemPrompt", "images", "limits", "readFace", "readDenyPatterns"];
100
+ export declare const WHITELIST_KEYS: readonly ["objective", "modelName", "thinking", "systemPrompt", "images", "limits", "readFace", "writeFace", "readDenyPatterns"];
95
101
  /**
96
102
  * #505 ② — ACCEPTED ALIAS SPELLINGS on the spec: `alias → the {@link WHITELIST_KEYS} member it means`.
97
103
  *
@@ -22,6 +22,7 @@ export const WHITELIST_KEYS = [
22
22
  "images",
23
23
  "limits",
24
24
  "readFace",
25
+ "writeFace",
25
26
  "readDenyPatterns",
26
27
  ];
27
28
  const WHITELIST_KEY_SET = new Set(WHITELIST_KEYS);
@@ -46,7 +47,7 @@ function emitStrippedKeysNotice(survey, onNotice) {
46
47
  const omitted = survey.total - shown.length;
47
48
  const list = shown.map((s) => JSON.stringify(s.key)).join(", ") + (omitted > 0 ? `, +${omitted} more` : "");
48
49
  const message = `workflow governance: ${survey.total} field(s) of an agent spec were NOT applied to the child (${list}). ` +
49
- `A governed workflow script may set only: ${WHITELIST_KEYS.join(", ")} — and \`readFace\` only as "roots" ` +
50
+ `A governed workflow script may set only: ${WHITELIST_KEYS.join(", ")} — and \`readFace\`/\`writeFace\` only as "roots" ` +
50
51
  `(the containment-tightening direction; "open" widens and is never taken from a script). Every other field ` +
51
52
  `of the child comes from the deployment baseline.`;
52
53
  try {
@@ -277,13 +278,16 @@ function pickWhitelist(scriptSpec) {
277
278
  readAxis("maxCostUsd", "spend ceiling");
278
279
  safe.limits = limits;
279
280
  }
280
- if (s.readFace !== undefined) {
281
- if (s.readFace === "roots") {
282
- safe.readFace = "roots";
281
+ for (const faceKey of ["readFace", "writeFace"]) {
282
+ const declared = s[faceKey];
283
+ if (declared === undefined)
284
+ continue;
285
+ if (declared === "roots") {
286
+ safe[faceKey] = "roots";
283
287
  }
284
288
  else {
285
289
  stripped.total++;
286
- stripped.sample.unshift({ key: "readFace", reason: "not_a_tightening_value" });
290
+ stripped.sample.unshift({ key: faceKey, reason: "not_a_tightening_value" });
287
291
  if (stripped.sample.length > MAX_STRIPPED_KEYS_ANNOUNCED)
288
292
  stripped.sample.pop();
289
293
  }
@@ -48,6 +48,9 @@ parentCheckpointStore?: CheckpointStore | "disabled",
48
48
  * a workflow child is that subtree; the Task/SendMessage delegation lane already carries this,
49
49
  * the workflow lane was the one gap. Lazy (read at spawn time, after prepare has resolved it). */
50
50
  parentReadFace?: () => TaskSpec["readFace"],
51
+ /** The WRITE seat's twin of the above — the host run's RESOLVED write-face containment, folded
52
+ * stricter-wins into every spawned child on its own seat (the two seats never read each other). */
53
+ parentWriteFace?: () => TaskSpec["writeFace"],
51
54
  /** Twin of the above for the deny-set additions (built-ins always apply; these are the extra
52
55
  * entries the host's own deployment/task layers stacked on). */
53
56
  parentReadDenyPatterns?: () => TaskSpec["readDenyPatterns"],
@@ -65,7 +65,7 @@ function formatResourceClampNote(notes) {
65
65
  const parts = notes.map((n) => `${n.field}: requested ${n.requested === undefined ? "unset" : n.requested} → applied ${n.applied}`);
66
66
  return `workflow governance tightened this agent's resource limits (${parts.join("; ")})`;
67
67
  }
68
- export function buildWorkflowPrimitives(ctx, governance, onAgentSpawn, parentCheckpointStore, parentReadFace, parentReadDenyPatterns, parentHandsReadOnly, parentInteractiveToolsOff) {
68
+ export function buildWorkflowPrimitives(ctx, governance, onAgentSpawn, parentCheckpointStore, parentReadFace, parentWriteFace, parentReadDenyPatterns, parentHandsReadOnly, parentInteractiveToolsOff) {
69
69
  const agent = (spec, opts) => {
70
70
  if (typeof spec === "string")
71
71
  spec = { objective: spec };
@@ -82,6 +82,11 @@ export function buildWorkflowPrimitives(ctx, governance, onAgentSpawn, parentChe
82
82
  if (pf === "roots" && childSpec.readFace !== "roots")
83
83
  childSpec.readFace = "roots";
84
84
  }
85
+ if (parentWriteFace) {
86
+ const pw = parentWriteFace();
87
+ if (pw === "roots" && childSpec.writeFace !== "roots")
88
+ childSpec.writeFace = "roots";
89
+ }
85
90
  if (parentReadDenyPatterns) {
86
91
  const pd = parentReadDenyPatterns();
87
92
  if (pd !== undefined && pd.length > 0) {
@@ -5,11 +5,14 @@ export type WorkflowRunStatus = "running" | "completed" | "failed";
5
5
  * {@link WorkflowAgentRun.parkedCheckpointToken}); a phase or group never parks (a parked agent ends the run). */
6
6
  export type WorkflowItemStatus = "running" | "completed" | "failed" | "parked";
7
7
  /** The arm a `workflow.park_truth_unreadable` resume refusal fired on (`detail.reason`): the prior run's record could not
8
- * be read (`store_threw`), is absent under this scope (`record_missing`), is not terminal (`record_not_terminal`) or
9
- * carries no `parks` array (`parks_unreadable`); a candidate's checkpoint could not be read (`checkpoint_store_threw`);
10
- * or the record/journal name parks while this workflow holds no checkpoint seat to prove them (`capability_not_armed`).
8
+ * be read (`store_threw`), is absent under this scope (`record_missing`), is not terminal (`record_not_terminal`),
9
+ * carries no `parks` array and nothing to derive one from — an empty journal, or an empty derived union
10
+ * (`parks_unreadable`) — or says its OWN resume admission never completed
11
+ * ({@link WorkflowRun.resumeAdmissionIncomplete} — nothing on it describes a settled park set, so it is not a
12
+ * resume base: `admission_incomplete`); a candidate's checkpoint could not be read (`checkpoint_store_threw`); or
13
+ * the record/journal name parks while this workflow holds no checkpoint seat to prove them (`capability_not_armed`).
11
14
  * Registered in docs/CLOSED-SETS.md with a mint obligation: every throw site spells its word. */
12
- export declare const PARK_TRUTH_UNREADABLE_REASONS: readonly ["store_threw", "record_missing", "record_not_terminal", "parks_unreadable", "checkpoint_store_threw", "capability_not_armed"];
15
+ export declare const PARK_TRUTH_UNREADABLE_REASONS: readonly ["store_threw", "record_missing", "record_not_terminal", "parks_unreadable", "admission_incomplete", "checkpoint_store_threw", "capability_not_armed"];
13
16
  export type ParkTruthUnreadableReason = (typeof PARK_TRUTH_UNREADABLE_REASONS)[number];
14
17
  /** What the checkpoint store said about a parked ordinal's token when a resume carried no acknowledgement for it
15
18
  * (`workflow.park_not_pending`, `detail.status`): the row's own word, or `absent` when the store holds no row. */
@@ -141,6 +144,13 @@ export interface WorkflowAgentRun {
141
144
  * truth read binds on the same two facts — `WorkflowRun.parks`); the checkpoint row itself carries no
142
145
  * workflow key. It is the resume CAPABILITY (never log it or put it in a URL); a durable row is its home
143
146
  * exactly as on the background lane. Absent on every other status.
147
+ *
148
+ * CONTRACT (a resume's second key cache). This token lands in the SAME store write as the run record's
149
+ * {@link WorkflowRun.parks} entry for the same call, so a record carrying one carries both — and one written before
150
+ * `parks` existed carries only this. A resume of a record WITHOUT that list reads a `parked` row as a park CANDIDATE
151
+ * of equal standing with the journal's entry, proven the only way any cache is: one `checkpointStore.get(token)`,
152
+ * whose word is the truth. Deriving adds NO trust; the row is POSITIVE evidence only (an empty `agents` array never
153
+ * reads as "no park"), and one carrying neither this token nor its {@link sessionId} claims its ordinal with NO key.
144
154
  */
145
155
  parkedCheckpointToken?: string;
146
156
  /**
@@ -388,22 +398,47 @@ export interface WorkflowRun {
388
398
  };
389
399
  /**
390
400
  * Every park this run is RESPONSIBLE for: its own (written at the park) and the ones it inherited from the run
391
- * it resumed and did not settle (written at resume admission). KEYS ONLY — the truth of a park is the checkpoint
392
- * store (`get(token).status`), never this list: a listed token may be resolved, expired or reaped, and the next
393
- * resume reads the store for every entry. Present on every record this engine writes (`[]` when there is none)
394
- * EXCEPT a record whose resume admission refused before its inherited set was established (deliberately absent:
395
- * not a resume base). It is an ADMISSION INPUT of the next resume, so a store must project it verbatim and keep
396
- * it through any size degrade; a reader treats absence as a state (an older engine's record, a stripped
397
- * projection), never as `[]`. `token` is the same capability as {@link WorkflowAgentRun.parkedCheckpointToken}
398
- * (never log it, never put it in a URL); `originRunId` is the run whose journal holds the `parked` entry for
399
- * `callKey` (the re-park material).
401
+ * it resumed and did not settle (written when resume admission COMPLETES). KEYS ONLY — the truth of a park is the
402
+ * checkpoint store (`get(token).status`), never this list: a listed token may be resolved, expired or reaped, and
403
+ * the next resume reads the store for every entry. Present on every record this engine writes (`[]` when there is
404
+ * none) EXCEPT a record whose resume admission never completed — that record carries
405
+ * {@link resumeAdmissionIncomplete} instead, which is what says "not a resume base". Absence ALONE is the older
406
+ * engine's record or a stripped projection, and the next resume derives its candidates from the other two key
407
+ * caches ({@link WorkflowAgentRun.parkedCheckpointToken} on this record's `parked` agent rows, and the journal's
408
+ * `parked` entries) — and that union must come back NON-EMPTY: a record with no list beside an empty journal, or
409
+ * beside an empty union, is refused (`parks_unreadable`), zero positive evidence not being evidence of zero (both
410
+ * derived caches only ever hold a park the run MADE, so one it inherited and never reached lives in the list alone).
411
+ * When the list IS present it is the record's word ALONE (the agent rows are not a second opinion, so a size degrade
412
+ * emptying `agents` costs nothing), and it is an ADMISSION INPUT of the next resume: a store must project it
413
+ * verbatim and keep it through any size degrade. `token` is the same capability as
414
+ * {@link WorkflowAgentRun.parkedCheckpointToken} (never log it, never put it in a URL); `originRunId` is the run
415
+ * whose journal holds the `parked` entry for `callKey` (the re-park material).
416
+ *
417
+ * `originUnconfirmed: true` says the entry IS on the record but no journal has confirmed whose it is: the key
418
+ * must be durable before the append is awaited, so it lands first and the confirmation follows. `originRunId`
419
+ * then names the run the park was made in — where the material BELONGS, not where it has been seen — and A
420
+ * CONSUMER MUST NOT READ IT AS CONFIRMED. The member is REMOVED (never written `false`) the moment a journal is
421
+ * read or written carrying this token's `parked` entry, so
422
+ * absence is the confirmed state and an entry written before this member reads as confirmed, exactly as it did; the
423
+ * engine's own material read identity-checks what it finds, so an unconfirmed origin degrades rather than mis-binds.
400
424
  */
401
425
  parks?: Array<{
402
426
  callKey: string;
403
427
  sessionId: string;
404
428
  token: string;
405
429
  originRunId: string;
430
+ originUnconfirmed?: true;
406
431
  }>;
432
+ /**
433
+ * Set (`true`) on a resume run's record from its creation and REMOVED the moment its admission completes — so a record
434
+ * still carrying it is one whose admission never finished (it refused, or the process died inside it). Nothing on such
435
+ * a record describes a settled park set: `parks` is absent, its own journal holds no prefix, and the run it resumed is
436
+ * still the valid base. PRESENCE MEANS NOT A RESUME BASE — the engine refuses (`workflow.park_truth_unreadable` /
437
+ * `admission_incomplete`) and derives no candidate from it — while absence is the ordinary state of every non-resume
438
+ * run and of every completed admission, so a reader treats presence as the signal. Same projection obligation as
439
+ * {@link parks}: dropping it turns a refused record back into an admissible one.
440
+ */
441
+ resumeAdmissionIncomplete?: true;
407
442
  /** RB-243: how many agent results were NOT journaled because they exceeded the per-entry size
408
443
  * cap ({@link MAX_JOURNAL_RESULT_BYTES}) — each skip also logs and journals a tombstone. Additive
409
444
  * observation; absent when 0. */
@@ -1,4 +1,4 @@
1
- export const PARK_TRUTH_UNREADABLE_REASONS = ["store_threw", "record_missing", "record_not_terminal", "parks_unreadable", "checkpoint_store_threw", "capability_not_armed"];
1
+ export const PARK_TRUTH_UNREADABLE_REASONS = ["store_threw", "record_missing", "record_not_terminal", "parks_unreadable", "admission_incomplete", "checkpoint_store_threw", "capability_not_armed"];
2
2
  export const PARK_NOT_PENDING_STATUSES = ["resolved", "expired", "absent"];
3
3
  export class WorkflowBudgetExceededError extends Error {
4
4
  spent;
@@ -564,7 +564,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
564
564
  startedAt: 0,
565
565
  })),
566
566
  agents: [],
567
- ...(opts.resumeFromRunId === undefined ? { parks: [] } : {}),
567
+ ...(opts.resumeFromRunId === undefined ? { parks: [] } : { resumeAdmissionIncomplete: true }),
568
568
  groups: [],
569
569
  stats: { tokens: 0, turns: 0, costMicroUsd: 0, nested: { tokens: 0, turns: 0, tasks: 0, costMicroUsd: 0 } },
570
570
  startedAt: t0,
@@ -999,10 +999,11 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
999
999
  };
1000
1000
  const journalAppendParked = async (callKey, paused) => {
1001
1001
  if (!journalStore)
1002
- return;
1002
+ return false;
1003
1003
  const p = journalStore.append(runId, scope, { callKey, parked: paused });
1004
1004
  journalTail = journalTail.then(() => p).catch(() => undefined);
1005
1005
  await p;
1006
+ return true;
1006
1007
  };
1007
1008
  const parkAgentLeg = async (rec, paused, activityTail, chargeLive) => {
1008
1009
  const s = paused.stats;
@@ -1027,15 +1028,20 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
1027
1028
  const ordinal = callKeyOrdinal(rec.callKey);
1028
1029
  const parks = run.parks ?? (run.parks = []);
1029
1030
  const at = parks.findIndex((e) => e.callKey === rec.callKey);
1030
- const key = { callKey: rec.callKey, sessionId: paused.sessionId, token: paused.terminal.token, originRunId: at === -1 ? runId : parks[at].originRunId };
1031
+ const held = at === -1 ? undefined : parks[at];
1032
+ const key = held !== undefined && held.token === paused.terminal.token && held.originUnconfirmed !== true
1033
+ ? { callKey: rec.callKey, sessionId: paused.sessionId, token: paused.terminal.token, originRunId: held.originRunId }
1034
+ : { callKey: rec.callKey, sessionId: paused.sessionId, token: paused.terminal.token, originRunId: runId, originUnconfirmed: true };
1031
1035
  if (at === -1)
1032
1036
  parks.push(key);
1033
1037
  else
1034
1038
  parks[at] = key;
1035
1039
  void persist("update");
1036
1040
  try {
1037
- await journalAppendParked(rec.callKey, paused);
1038
- key.originRunId = runId;
1041
+ if (await journalAppendParked(rec.callKey, paused)) {
1042
+ key.originRunId = runId;
1043
+ delete key.originUnconfirmed;
1044
+ }
1039
1045
  }
1040
1046
  catch (err) {
1041
1047
  emitRunLog(`resume-journal: the PARKED leg at ordinal ${ordinal} ("${rec.label.slice(0, 80)}") could not be recorded in this run's journal (${withoutToken(errText(err), key.token)}) — ` +
@@ -2214,34 +2220,52 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
2214
2220
  throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run's record is not in the run store under this scope, so its parks cannot be proven.`, { reason: "record_missing" });
2215
2221
  if (parkSeat !== undefined && prior !== null && prior.status === "running")
2216
2222
  throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run is still recorded as running; a run that could park must have finished before it is resumed (a crashed park-capable run is decided through the deployment's approval channel, not resumed).`, { reason: "record_not_terminal" });
2217
- if (prior !== null && !Array.isArray(prior.parks))
2218
- throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run's record carries no parks list (written by an older engine, or stripped by the store's projection), so its parks cannot be proven.`, { reason: "parks_unreadable" });
2223
+ if (prior?.resumeAdmissionIncomplete === true)
2224
+ throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — that record's own resume admission never completed, so it settled no park set and its journal holds no replayable prefix; the run IT resumed is still the base. Resume that one instead.`, { reason: "admission_incomplete" });
2225
+ const recordParks = Array.isArray(prior?.parks) ? prior.parks : undefined;
2226
+ const noParksList = prior !== null && recordParks === undefined;
2227
+ const parksUnreadable = (why) => new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run's record carries no parks list (written by an older engine, or stripped by the store's projection) and ${why}, so its parks cannot be proven.`, { reason: "parks_unreadable" });
2228
+ if (noParksList && entries.length === 0)
2229
+ throw parksUnreadable("its journal yielded no entry to derive one from");
2219
2230
  const candidates = new Map();
2220
- const recordParks = prior !== null && Array.isArray(prior.parks) ? prior.parks : [];
2221
- for (const raw of recordParks) {
2231
+ const keyed = (k) => k.token !== "" && k.sessionId !== "";
2232
+ const offerCandidate = (ord, key) => {
2233
+ const recorded = candidates.get(ord);
2234
+ if (recorded !== undefined && (recorded.callKey !== key.callKey || (keyed(recorded) && keyed(key) && (recorded.token !== key.token || recorded.sessionId !== key.sessionId))))
2235
+ throw parkBindingBroken(ord, "the prior run's key caches name different tokens, sessions or calls for it");
2236
+ if (recorded === undefined || (!keyed(recorded) && keyed(key)))
2237
+ candidates.set(ord, key);
2238
+ };
2239
+ for (const raw of recordParks ?? []) {
2222
2240
  const e = raw;
2223
2241
  if (e === null || typeof e !== "object" || typeof e.callKey !== "string" || typeof e.sessionId !== "string" || typeof e.token !== "string" || typeof e.originRunId !== "string" || !/^\d+:/.test(e.callKey)) {
2224
2242
  throw parkBindingBroken(-1, "a recorded park entry is malformed or its call key has no ordinal");
2225
2243
  }
2226
- candidates.set(callKeyOrdinal(e.callKey), { callKey: e.callKey, sessionId: e.sessionId, token: e.token, originRunId: e.originRunId });
2244
+ offerCandidate(callKeyOrdinal(e.callKey), { callKey: e.callKey, sessionId: e.sessionId, token: e.token, originRunId: e.originRunId, ...(e.originUnconfirmed === true ? { originUnconfirmed: true } : {}) });
2227
2245
  }
2228
2246
  for (const [ord, e] of replayByOrdinal.entries()) {
2229
2247
  if (e?.parked === undefined)
2230
2248
  continue;
2231
- const fromJournal = { callKey: e.callKey, sessionId: e.parked.sessionId, token: e.parked.terminal.token, originRunId: opts.resumeFromRunId };
2232
- const recorded = candidates.get(ord);
2233
- if (recorded === undefined)
2234
- candidates.set(ord, fromJournal);
2235
- else if (recorded.token !== fromJournal.token || recorded.sessionId !== fromJournal.sessionId || recorded.callKey !== fromJournal.callKey)
2236
- throw parkBindingBroken(ord, "the run record and the journal name different tokens, sessions or calls for it");
2249
+ offerCandidate(ord, { callKey: e.callKey, sessionId: e.parked.sessionId, token: e.parked.terminal.token, originRunId: opts.resumeFromRunId });
2250
+ const settled = candidates.get(ord);
2251
+ settled.originRunId = opts.resumeFromRunId;
2252
+ delete settled.originUnconfirmed;
2237
2253
  }
2254
+ for (const rec of recordParks === undefined && Array.isArray(prior?.agents) ? prior.agents : []) {
2255
+ if (rec === null || typeof rec !== "object" || rec.status !== "parked")
2256
+ continue;
2257
+ if (typeof rec.callKey !== "string" || !/^\d+:/.test(rec.callKey))
2258
+ throw parkBindingBroken(-1, "a parked agent row is malformed or its call key has no ordinal");
2259
+ offerCandidate(callKeyOrdinal(rec.callKey), { callKey: rec.callKey, sessionId: rec.sessionId ?? "", token: rec.parkedCheckpointToken ?? "", originRunId: opts.resumeFromRunId, originUnconfirmed: true });
2260
+ }
2261
+ if (noParksList && candidates.size === 0)
2262
+ throw parksUnreadable("neither its journal nor its own parked agent rows names a park to derive (a park it inherited and never reached is recorded in that list alone)");
2238
2263
  const inherited = [];
2239
2264
  for (const [ord, key] of [...candidates.entries()].sort((a, b) => a[0] - b[0])) {
2240
2265
  if (replayByOrdinal[ord]?.result !== undefined)
2241
2266
  continue;
2242
2267
  inherited.push(key);
2243
2268
  }
2244
- run.parks = inherited;
2245
2269
  if (parkSeat === undefined) {
2246
2270
  if (inherited.length > 0) {
2247
2271
  throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — it is responsible for ${inherited.length} recorded park(s) and this workflow holds no checkpoint store to prove them against (RunWorkflowOptions.checkpointStore); without the seat a parked call would run live beside its pinned child.`, { reason: "capability_not_armed" });
@@ -2261,6 +2285,10 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
2261
2285
  parkedByOrdinal[ord] = truth;
2262
2286
  }
2263
2287
  }
2288
+ if (!finalized) {
2289
+ run.parks = inherited;
2290
+ delete run.resumeAdmissionIncomplete;
2291
+ }
2264
2292
  run.resume = {
2265
2293
  fromRunId: clampRunIdText(opts.resumeFromRunId),
2266
2294
  journalEntries: entries.length,
@@ -23,6 +23,7 @@ const PROBE_FACTS_OFF = {
23
23
  promptProfile: "simple",
24
24
  fableMitigations: false,
25
25
  readFaceOpen: false,
26
+ writeFaceOpen: false,
26
27
  reminderMark: undefined,
27
28
  };
28
29
  const PROBE_FACTS_ON = {
@@ -41,6 +42,7 @@ const PROBE_FACTS_ON = {
41
42
  promptProfile: "classic",
42
43
  fableMitigations: true,
43
44
  readFaceOpen: true,
45
+ writeFaceOpen: true,
44
46
  reminderMark: "PROBE-FIXED-MARK-AXIS0",
45
47
  };
46
48
  const PROBE_VECTORS = [
@@ -1,4 +1,4 @@
1
- import { CYBER_RISK, EXECUTION_ENVIRONMENT, EXECUTION_ENVIRONMENT_OPEN_READS, URL_SAFETY, SUMMARIZE_TOOL_RESULTS, WORKTREE_NOTICE, SUBAGENT_CONSENT_NOTICE, SUBAGENT_DELIVERY_NOTES, harnessHeadLines, } from "../../prompts/default.js";
1
+ import { CYBER_RISK, executionEnvironmentBlockFor, URL_SAFETY, SUMMARIZE_TOOL_RESULTS, WORKTREE_NOTICE, SUBAGENT_CONSENT_NOTICE, SUBAGENT_DELIVERY_NOTES, harnessHeadLines, } from "../../prompts/default.js";
2
2
  import { GOAL_COMPLETION_GUIDANCE, ORCHESTRATION_AWARENESS, ORCHESTRATION_GUIDANCE, ORCHESTRATION_GUIDANCE_DEFERRED, SUPERVISOR_PROMPT, } from "../../prompts/supervisor.js";
3
3
  import { TEAMMATE_COMMUNICATION_ADDENDUM } from "../../prompts/coordinator.js";
4
4
  import { SIMPLE_ACTION_CAUTION, SIMPLE_ACT_DONT_REDERIVE, SIMPLE_AUTONOMY_FABLE, SIMPLE_COMMUNICATING_FABLE, SIMPLE_CORRECTIONS_FABLE, SIMPLE_DELIVERING_WORK_FABLE, SIMPLE_COMMUNICATING_LEAN, SIMPLE_CONTEXT_MANAGEMENT, SIMPLE_PRONOUNS, SIMPLE_TOOL_PARAM_JSON, SEMA_VERIFY_FRESH, SEMA_EVIDENCE_AUDIT, } from "../../prompts/simple-sections.js";
@@ -41,7 +41,7 @@ export const SEMA_DEFAULT_PACK = {
41
41
  rank: 240,
42
42
  ...CORE,
43
43
  admit: (i) => i.facts.policyEnabled || i.facts.isolationEnabled,
44
- content: (i) => (i.facts.readFaceOpen === true ? EXECUTION_ENVIRONMENT_OPEN_READS : EXECUTION_ENVIRONMENT),
44
+ content: (i) => executionEnvironmentBlockFor({ readOpen: i.facts.readFaceOpen === true, writeOpen: i.facts.writeFaceOpen === true }),
45
45
  blockId: "harness.context",
46
46
  },
47
47
  { id: "core/simple.communicating", slot: "harness", rank: 250, ...CORE, admit: (i) => i.facts.promptProfile !== "classic", content: (i) => (i.facts.fableMitigations === true ? SIMPLE_COMMUNICATING_FABLE : SIMPLE_COMMUNICATING_LEAN), blockId: "harness.context" },
@@ -0,0 +1,26 @@
1
+ /** One section's share of the leg's system prompt, as the `context_usage` frame reports it. */
2
+ export interface ContextUsageSection {
3
+ /** The pack section id — the same wordlist `prompt.assembled`'s `sections[].id` uses. */
4
+ id: string;
5
+ /** The section's ESTIMATED token weight (see {@link contextUsageSections} for what that promises). */
6
+ tokens: number;
7
+ /** The section's semantic slot (`identity`, `security`, …), so a view can group without knowing every
8
+ * id. Absent only if the manifest entry carried no slot. */
9
+ kind?: string;
10
+ }
11
+ /**
12
+ * Project the manifest's compiled sections onto the frame's occupancy view.
13
+ * @contract context_usage.sections — `sections[]` is the leg's PREPARE-TIME system-prompt composition,
14
+ * one entry per rendered pack section, `tokens` ESTIMATED from rendered characters at the engine's
15
+ * chars→tokens coefficient. A different measurement from `usedTokens`, the engine's trigger input over the
16
+ * whole conversation. The two coordinates MUST NOT be mixed: do not subtract `Σ sections[].tokens` from
17
+ * `usedTokens`, do not compare a section to `compactAtTokens`, and do not read a change across frames as
18
+ * growth — the value is frozen at prepare and re-reported verbatim at every boundary of the leg. It
19
+ * answers "what is my system prompt made of, and which part is big". Absent when the leg assembled no
20
+ * section IR (a provider that replaced the prompt wholesale ships one opaque block).
21
+ */
22
+ export declare function contextUsageSections(sections: ReadonlyArray<{
23
+ id: string;
24
+ slot?: string;
25
+ chars: number;
26
+ }> | undefined): ContextUsageSection[] | undefined;
@@ -0,0 +1,10 @@
1
+ import { DEFAULT_CHARS_PER_TOKEN } from "../internal/harness.js";
2
+ export function contextUsageSections(sections) {
3
+ if (sections === undefined || sections.length === 0)
4
+ return undefined;
5
+ return sections.map((s) => ({
6
+ id: s.id,
7
+ tokens: Math.ceil(s.chars / DEFAULT_CHARS_PER_TOKEN),
8
+ ...(s.slot !== undefined ? { kind: s.slot } : {}),
9
+ }));
10
+ }
@@ -45,6 +45,10 @@ export interface PromptRuntimeFacts {
45
45
  * open-reads first bullet). OPTIONAL: absence reads as false (roots wording, byte-identical),
46
46
  * so existing fact constructors keep compiling. */
47
47
  readFaceOpen?: boolean;
48
+ /** The resolved WRITE face is OPEN (renders the execution-environment block's open-writes first
49
+ * bullet column). OPTIONAL on the same law as {@link readFaceOpen}: absence reads as false (roots
50
+ * wording, byte-identical), so existing fact constructors keep compiling. */
51
+ writeFaceOpen?: boolean;
48
52
  /** design/319 (A ticket) — the session's reminder provenance mark: threads into the
49
53
  * `core/harness.head` section (single-sourced from `harnessHeadLines`), which extends the
50
54
  * reminder sentence into the strict mark declaration when present. OPTIONAL (public export —
@@ -190,12 +194,10 @@ export interface ComposedPrompt {
190
194
  * routes sections into groups WITHOUT reordering them (emission stays rank order — slot never
191
195
  * drives physical order).
192
196
  *
193
- * Accuracy note (hardening 2026-07-31): the layout is a LOWERING argument, not a pack field —
194
- * `PromptPack` declares none, and every production `layoutSystemBlocks` call site passes no second
195
- * argument, i.e. always `SINGLE_BLOCK_LAYOUT` (one group, one cache_control breakpoint at the end).
196
- * Multi-block layouts (CC209's billing/persona/body) are therefore a lowering CAPABILITY exercised
197
- * only by fixtures today; no bundled pack can select one. The earlier wording ("the pack's layout")
198
- * described an association that does not exist in the type system.
197
+ * The layout is a LOWERING argument, not a pack field — `PromptPack` declares none, and every production
198
+ * `layoutSystemBlocks` call site passes no second argument, i.e. always `SINGLE_BLOCK_LAYOUT` (one group,
199
+ * one cache_control breakpoint at the end). Multi-block layouts are a lowering CAPABILITY exercised only
200
+ * by fixtures today; no bundled pack can select one.
199
201
  */
200
202
  export interface CompiledSystemBlock {
201
203
  groupId: string;
@@ -167,6 +167,10 @@ export declare const URL_SAFETY = "IMPORTANT: You must NEVER generate or guess U
167
167
  * per-message aggregate tool-result budget, which sheds the largest results at any size.
168
168
  */
169
169
  export declare const SUMMARIZE_TOOL_RESULTS = "When working with tool results, write down any important information you might need later in your own response, as the original tool result may be cleared or summarized from the context later.";
170
+ export declare function executionEnvironmentBlockFor(faces?: {
171
+ readOpen?: boolean;
172
+ writeOpen?: boolean;
173
+ }): string;
170
174
  export declare const EXECUTION_ENVIRONMENT: string;
171
175
  /** design/199 F8① — the open-read-face variant (first bullet tells the truth about reads). */
172
176
  export declare const EXECUTION_ENVIRONMENT_OPEN_READS: string;
@@ -319,6 +323,9 @@ export interface EnvironmentFacts {
319
323
  * structured key). Rendered only when "open" (the roots posture is the historical default and
320
324
  * renders nothing new — byte-compat). */
321
325
  readFace?: "open" | "roots";
326
+ /** The RESOLVED write-face containment state ("open" | "roots"; additive structured key). Rendered
327
+ * only when "open" (the roots posture is the historical default and renders nothing new). */
328
+ writeFace?: "open" | "roots";
322
329
  /** OS name (uname -s) — remote = the container's, not the host's. */
323
330
  platform?: string;
324
331
  /** OS version (uname -r). */
@@ -496,6 +503,12 @@ export interface StablePromptContext {
496
503
  * byte-identical.
497
504
  */
498
505
  readFaceOpen?: boolean;
506
+ /**
507
+ * The resolved WRITE face is OPEN: the `# Execution environment` block's first bullet renders its
508
+ * open-writes column so the prompt never claims a write fence that is not there. Absent/false ⇒
509
+ * the historical (roots) wording, byte-identical.
510
+ */
511
+ writeFaceOpen?: boolean;
499
512
  /**
500
513
  * design/319 (A ticket) — the session's reminder provenance mark
501
514
  * ({@link import("../core/reminder-mint.js").mintReminderMark}): when present, the `# Harness`