@sema-agent/core 7.61.0 → 7.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/CHANGELOG.md +312 -0
  2. package/dist/agents/cascade.d.ts +11 -3
  3. package/dist/agents/cascade.js +1 -1
  4. package/dist/agents/peer-held-queue.d.ts +27 -4
  5. package/dist/agents/peer-held-queue.js +81 -36
  6. package/dist/agents/peer-session-drain.js +13 -3
  7. package/dist/agents/subagent.d.ts +6 -1
  8. package/dist/agents/subagent.js +66 -12
  9. package/dist/agents/suspend-guard.d.ts +38 -16
  10. package/dist/agents/suspend-guard.js +9 -4
  11. package/dist/agents/verify.js +4 -3
  12. package/dist/core/checkpoint-features.d.ts +722 -0
  13. package/dist/core/checkpoint-features.js +98 -0
  14. package/dist/core/checkpoint-requirements.d.ts +9 -2
  15. package/dist/core/checkpoint-requirements.js +9 -4
  16. package/dist/core/checkpoint-row-verdict.d.ts +99 -0
  17. package/dist/core/checkpoint-row-verdict.js +225 -0
  18. package/dist/core/checkpoint-store.d.ts +55 -745
  19. package/dist/core/checkpoint-store.js +39 -141
  20. package/dist/core/engine-notice.d.ts +19 -3
  21. package/dist/core/engine-notice.js +9 -2
  22. package/dist/core/gate-fold.js +2 -2
  23. package/dist/core/governance-codes.d.ts +3 -1
  24. package/dist/core/governance-codes.js +3 -0
  25. package/dist/core/hooks.d.ts +13 -0
  26. package/dist/core/human-input-projection.d.ts +1 -0
  27. package/dist/core/human-input-projection.js +3 -0
  28. package/dist/core/image-admission.d.ts +1 -1
  29. package/dist/core/locked-config.d.ts +2 -2
  30. package/dist/core/mcp-host-seat.js +6 -1
  31. package/dist/core/memory-engine/consolidation-driver.d.ts +1 -1
  32. package/dist/core/memory-vector.d.ts +1 -1
  33. package/dist/core/memory.d.ts +10 -10
  34. package/dist/core/mode-policy.js +1 -1
  35. package/dist/core/mods/classic-events.d.ts +9 -1
  36. package/dist/core/mods/dollar.d.ts +32 -1
  37. package/dist/core/mods/dollar.js +13 -1
  38. package/dist/core/mods/kernel/events.d.ts +11 -3
  39. package/dist/core/mods/kernel/events.js +13 -10
  40. package/dist/core/mods/lifecycle-stations.d.ts +36 -4
  41. package/dist/core/mods/lifecycle-stations.js +44 -9
  42. package/dist/core/mods/session-append.d.ts +4 -1
  43. package/dist/core/mods/session-append.js +7 -0
  44. package/dist/core/mods/session-receive.js +12 -15
  45. package/dist/core/mods/stations.d.ts +51 -6
  46. package/dist/core/mods/stations.js +124 -0
  47. package/dist/core/own-property-receipt.d.ts +7 -0
  48. package/dist/core/own-property-receipt.js +3 -0
  49. package/dist/core/read-root-candidate.js +1 -1
  50. package/dist/core/resume-startup-cause.d.ts +5 -4
  51. package/dist/core/runner/compact-session.js +5 -2
  52. package/dist/core/runner/contracts.d.ts +18 -8
  53. package/dist/core/runner/delegation-owner.d.ts +43 -0
  54. package/dist/core/runner/delegation-owner.js +59 -0
  55. package/dist/core/runner/lineage-reroot-view.d.ts +56 -0
  56. package/dist/core/runner/lineage-reroot-view.js +108 -0
  57. package/dist/core/runner/permission-rule-lanes.d.ts +2 -1
  58. package/dist/core/runner/permission-rule-lanes.js +2 -2
  59. package/dist/core/runner/person-path-rows.d.ts +15 -0
  60. package/dist/core/runner/person-path-rows.js +26 -3
  61. package/dist/core/runner/prepare-acquire-reconcile.d.ts +4 -1
  62. package/dist/core/runner/prepare-acquire-reconcile.js +7 -2
  63. package/dist/core/runner/prepare-caps-and-workflow.d.ts +1 -0
  64. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  65. package/dist/core/runner/prepare-config-doors.d.ts +6 -6
  66. package/dist/core/runner/prepare-config-doors.js +3 -4
  67. package/dist/core/runner/prepare-hands-readface.d.ts +1 -1
  68. package/dist/core/runner/prepare-hands-readface.js +28 -7
  69. package/dist/core/runner/prepare-inherited-gate.d.ts +2 -0
  70. package/dist/core/runner/prepare-inherited-gate.js +7 -3
  71. package/dist/core/runner/prepare-task.js +10 -7
  72. package/dist/core/runner/resume-admission.d.ts +3 -3
  73. package/dist/core/runner/resume-admission.js +6 -3
  74. package/dist/core/runner/resume-apply.d.ts +4 -0
  75. package/dist/core/runner/resume-apply.js +11 -4
  76. package/dist/core/runner/resume-checkpoint-screen.d.ts +9 -0
  77. package/dist/core/runner/resume-checkpoint-screen.js +4 -84
  78. package/dist/core/runner/run-git-lane.d.ts +2 -0
  79. package/dist/core/runner/run-git-lane.js +4 -1
  80. package/dist/core/runner/run-harness-handlers.d.ts +2 -0
  81. package/dist/core/runner/run-harness-handlers.js +3 -2
  82. package/dist/core/runner/run-leg.js +24 -7
  83. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  84. package/dist/core/runner/run-stop-and-final-verify.js +2 -1
  85. package/dist/core/runner/run-turn-boundary.js +7 -4
  86. package/dist/core/runner/runtask.js +6 -6
  87. package/dist/core/runner/steering-preview.d.ts +9 -0
  88. package/dist/core/runner/steering-preview.js +5 -0
  89. package/dist/core/runner/stream-steer-verb.js +8 -0
  90. package/dist/core/runner/tool-face-overlay.js +2 -0
  91. package/dist/core/runner/turn-attachments.d.ts +5 -0
  92. package/dist/core/runner/turn-attachments.js +1 -1
  93. package/dist/core/runner-deps.d.ts +2 -2
  94. package/dist/core/secret-env.d.ts +8 -5
  95. package/dist/core/secret-env.js +37 -18
  96. package/dist/core/session-store.d.ts +1 -1
  97. package/dist/core/session-store.js +5 -1
  98. package/dist/core/session.d.ts +14 -4
  99. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +6 -0
  100. package/dist/core/store-contracts/checkpoint-store-contract.js +68 -0
  101. package/dist/core/store-contracts/session-store-contract.js +22 -8
  102. package/dist/core/task-event.d.ts +7 -1
  103. package/dist/core/task-notification.js +2 -1
  104. package/dist/core/task-registry-agent.d.ts +27 -7
  105. package/dist/core/task-registry-agent.js +12 -5
  106. package/dist/core/task-registry-shared.d.ts +7 -0
  107. package/dist/core/task-registry-workflow.js +4 -3
  108. package/dist/core/task-registry.d.ts +13 -2
  109. package/dist/core/task-registry.js +11 -4
  110. package/dist/core/task-result.d.ts +5 -5
  111. package/dist/core/task-spec.d.ts +1 -1
  112. package/dist/core/terminal-cause.d.ts +6 -6
  113. package/dist/core/tool-face.d.ts +6 -2
  114. package/dist/core/tool-face.js +1 -1
  115. package/dist/core/tool-policy.d.ts +2 -1
  116. package/dist/core/tool-roster.d.ts +4 -4
  117. package/dist/core/tool-spec.d.ts +4 -0
  118. package/dist/core/types.d.ts +1 -1
  119. package/dist/core/types.js +1 -1
  120. package/dist/engine/execution-env/node-execution-env.d.ts +3 -0
  121. package/dist/engine/execution-env/node-execution-env.js +12 -5
  122. package/dist/engine/harness/types.d.ts +11 -0
  123. package/dist/engine/session/parent-chain-guard.d.ts +3 -3
  124. package/dist/engine/session/parent-chain-guard.js +1 -1
  125. package/dist/engine/session/path-to-root.d.ts +18 -3
  126. package/dist/engine/session/path-to-root.js +15 -1
  127. package/dist/engine/session/repo-utils.d.ts +12 -1
  128. package/dist/engine/session/repo-utils.js +41 -0
  129. package/dist/engine/session/session.js +1 -1
  130. package/dist/engine/session/storage-base.d.ts +20 -0
  131. package/dist/engine/session/storage-base.js +28 -9
  132. package/dist/index.d.ts +9 -8
  133. package/dist/index.js +4 -4
  134. package/dist/internal/harness.d.ts +4 -3
  135. package/dist/internal/harness.js +3 -2
  136. package/dist/orchestration/run-workflow-tool.d.ts +3 -0
  137. package/dist/orchestration/run-workflow-tool.js +27 -11
  138. package/dist/orchestration/workflow-governance.d.ts +1 -1
  139. package/dist/orchestration/workflow.d.ts +3 -0
  140. package/dist/orchestration/workflow.js +2 -7
  141. package/dist/stores/file/checkpoint-store.d.ts +2 -0
  142. package/dist/stores/file/checkpoint-store.js +7 -6
  143. package/dist/stores/file/fs-atomic.d.ts +0 -22
  144. package/dist/stores/file/fs-atomic.js +0 -17
  145. package/dist/stores/file/index.d.ts +2 -9
  146. package/dist/stores/file/index.js +2 -4
  147. package/dist/stores/file/session-store.d.ts +13 -7
  148. package/dist/stores/file/session-store.js +40 -17
  149. package/dist/tools/fs/bash-program-position.d.ts +3 -2
  150. package/dist/tools/fs/bash-program-position.js +7 -7
  151. package/dist/tools/fs/removal-targets.js +2 -2
  152. package/dist/tools/fs/shell-read-argv.d.ts +4 -2
  153. package/dist/tools/fs/shell-read-argv.js +14 -3
  154. package/dist/tools/fs/shell-read-bindings.d.ts +18 -2
  155. package/dist/tools/fs/shell-read-bindings.js +148 -68
  156. package/dist/tools/fs/shell-read-check.js +20 -4
  157. package/dist/tools/fs/shell-read-establish.js +22 -8
  158. package/dist/tools/fs/shell-read-functions.js +2 -2
  159. package/dist/tools/fs/shell-read-object-path.d.ts +59 -0
  160. package/dist/tools/fs/shell-read-object-path.js +119 -0
  161. package/dist/tools/fs/shell-read-plan.d.ts +8 -0
  162. package/dist/tools/fs/shell-read-plan.js +47 -30
  163. package/dist/tools/fs/shell-read-start.d.ts +66 -13
  164. package/dist/tools/fs/shell-read-start.js +89 -17
  165. package/dist/tools/fs/shell-read-workdir.d.ts +29 -8
  166. package/dist/tools/fs/shell-read-workdir.js +31 -8
  167. package/package.json +2 -2
  168. package/test/export-surface.snapshot.json +21 -33
  169. package/wire-changes/core-stores-sql@7.62.0.json +30 -0
  170. package/wire-changes/core@7.62.0.json +2181 -0
  171. package/wire-changes/mods-kernel@7.62.0.json +42 -0
  172. package/wire-changes/primitives@7.62.0.json +30 -0
  173. package/dist/core/consolidate-scope.d.ts +0 -93
  174. package/dist/core/consolidate-scope.js +0 -98
  175. package/dist/core/runner/memory-consolidation.d.ts +0 -109
  176. package/dist/core/runner/memory-consolidation.js +0 -251
@@ -3,13 +3,13 @@ import { mintSystemReminder } from "../reminder-mint.js";
3
3
  import { eventDefaultOn } from "../../prompt-assembly/event-registry.js";
4
4
  import { compactionFailureReason, compactionPassReport, DEFAULT_COMPACTION_INSTRUCTIONS, isCompactionManualCancel, manualCompactOutcomeOf, maybeCompact, mintCompactedEvent, nextTrimForceBackoff, recordCompactionAndCheckRapidRefill } from "../auto-compaction.js";
5
5
  import { emitTrace } from "../trace.js";
6
- import { redactThenCut } from "../../agents/subagent-steps.js";
6
+ import { steeringPreview } from "./steering-preview.js";
7
7
  import { ATTACHMENT_BYTE_CAP, CHANGED_FILES_MAX, TOTAL_TOKENS_REMINDER_DEFAULT_MODE, attachmentEnvelopeTags, clipToBytes, collectDateChange, collectDueAttachments, collectInstructionsChange, commitAgentListing, commitInstructionsChange, commitSkillsListing, isIntactSource, rebaseCadenceWindows, renderAgentListingFrame, renderMcpInstructionsDelta, selectMcpDroppedBatch, renderSkillsListingFrame } from "./turn-attachments.js";
8
8
  import { announceListingTruncation } from "../skill-listing-budget.js";
9
9
  import { buildWorkingFileAttachments, centerAdoptionOption, contextInstructionFilesOption, emitInputTruncated, forkContextOption, legCompactionSettings, legContextOverlayOption } from "./compaction-call-options.js";
10
10
  import { classicEventBase, dispatchClassic, seatHears, stringMembersAnswer, stringMembersOf } from "../mods/stations.js";
11
11
  import { offeredAgentListing } from "../mods/agent-stations.js";
12
- import { raiseCompletedTurn } from "../mods/lifecycle-stations.js";
12
+ import { measureSession, raiseCompletedTurn } from "../mods/lifecycle-stations.js";
13
13
  import { sanitizeUntrustedText, SHELLED_BODY_ENVELOPE_TAGS } from "../untrusted-text.js";
14
14
  import { droppedToolDigest, withAnnounceDigests } from "./announce-once-ledger.js";
15
15
  import { formatDiagnosticsBlock, withholdListedDiagnostics } from "../lsp-diagnostics.js";
@@ -192,7 +192,7 @@ export function createTurnBoundary(input) {
192
192
  if (tightest !== undefined && tightest.ratio >= thresholds[index]) {
193
193
  const percent = Math.min(100, Math.round(tightest.ratio * 100));
194
194
  const body = limitApproachFrames(index === 0 ? 0 : 1, tightest.axis, percent, prepared.reminderMark);
195
- const preview = body.slice(0, 220);
195
+ const preview = steeringPreview(body);
196
196
  prepared.frameReceipts.pending.push({
197
197
  source: "limit_approach",
198
198
  text: body,
@@ -458,7 +458,7 @@ export function createTurnBoundary(input) {
458
458
  bundleReceipts.push({
459
459
  source: a.source,
460
460
  commit: () => {
461
- queue.push({ type: "steering_injected", source: a.source, preview: redactThenCut(a.body, 220), ...ident() });
461
+ queue.push({ type: "steering_injected", source: a.source, preview: steeringPreview(a.body, a.echoBound), ...ident() });
462
462
  rs.attach.attachmentsInjected += 1;
463
463
  record?.();
464
464
  },
@@ -623,6 +623,9 @@ export function createTurnBoundary(input) {
623
623
  if (comp.contextUsage) {
624
624
  const sections = contextUsageSections(prepared.promptManifest.sections);
625
625
  queue.push({ type: "context_usage", ...comp.contextUsage, ...(sections !== undefined ? { sections } : {}), ...ident() });
626
+ const measured = measureSession(prepared.modBus, prepared.sessionMeasure, comp.contextUsage, prepared.hookIdentity, prepared.abortController.signal);
627
+ if (measured !== undefined)
628
+ await measured;
626
629
  }
627
630
  if (comp.unevaluableWindow) {
628
631
  discloseUnevaluableWindow(comp.unevaluableWindow, prepared, rs.telemetry.tracer, rs.telemetry.taskId, runnerHooks.onError);
@@ -440,7 +440,7 @@ export class Runner {
440
440
  const postToolBatchArmed = prepared.modBus.hasHandlers("classic.PostToolBatch");
441
441
  const batchArgs = postToolBatchArmed ? new Map() : undefined;
442
442
  rs.turn.toolBatch = [];
443
- const { onMessageUpdate, onMessageEnd, onToolStart, onToolEnd, onTurnEnd, announceWorkspaceMove } = createHarnessHandlers({
443
+ const { onMessageUpdate, onMessageEnd, onToolStart, onToolEnd, onTurnEnd, onTurnStart, announceWorkspaceMove } = createHarnessHandlers({
444
444
  prepared, stats, rs,
445
445
  deps: {
446
446
  spec, queue, internals, ident, mediaBudgetBase64Chars: this.deps.mediaBudgetBase64Chars,
@@ -469,7 +469,7 @@ export class Runner {
469
469
  runner: this.depsSeat,
470
470
  },
471
471
  });
472
- const { flushGitMirror, unsubGitRetry, unsubBoundary, unsub } = runGitLane({ prepared, queue, rs, ident, onMessageUpdate, onMessageEnd, onToolStart, onToolEnd, onTurnEnd, onTurnBoundary, runner: this.depsSeat });
472
+ const { flushGitMirror, unsubGitRetry, unsubBoundary, unsub } = runGitLane({ prepared, queue, rs, ident, onMessageUpdate, onMessageEnd, onToolStart, onToolEnd, onTurnEnd, onTurnStart, onTurnBoundary, runner: this.depsSeat });
473
473
  return withLegRequestSinks(() => runLeg({
474
474
  spec, queue, prepared, resume, rs, entryActor, objectiveAuthor: internals?.objectiveAuthor, effectiveTimeoutMs, timeout, pushContent, ident, emitCommitted, writeFamilyOf, startedToolCallIds,
475
475
  announceWorkspaceMove, withBrainSinks, flushGitMirror, loopLatch, notificationLane, unsubscribeTaskNotifications, unsubGitRetry, unsubBoundary, unsub,
@@ -532,20 +532,20 @@ export class Runner {
532
532
  cp, config, internals, outcomeGate, wakeMessage, resumeSignal, recheckGovernanceWindow,
533
533
  plainPolicyOutcome: capturedPolicyOutcome, plainReviewOutcome, plainParkOutcome,
534
534
  runner: this.depsSeat, effectiveDelegationFacts,
535
- next: ({ wakeHookContext, legMods, plainPolicyOutcome, outcomeForStore }) => resumePreflight({
535
+ next: ({ wakeHookContext, wakeMessage: wakeDelivered, wakeRewrittenBy, legMods, plainPolicyOutcome, outcomeForStore }) => resumePreflight({
536
536
  token, cp, resumeSignal, recheckGovernanceWindow, store, runner: this.depsSeat,
537
537
  locallyClaimedTokens: this.locallyClaimedTokens, parentConstraintRegistry: this.parentConstraintRegistry, suspendedEnvReaps: this.suspendedEnvReaps,
538
538
  next: () => resumeClaim({
539
539
  token, cp, store, outcomeForStore, holder: internals?.holder,
540
540
  locallyClaimedTokens: this.locallyClaimedTokens, parentConstraintRegistry: this.parentConstraintRegistry, suspendedEnvReaps: this.suspendedEnvReaps,
541
541
  onDestroyError: (err, sessionId) => this.depsSeat.deps.onError?.(err, { phase: "config", sessionId }),
542
- next: () => this.resumeHandoff({ token, cp, store, config, internals, resumeInternals, plainPolicyOutcome, redeemedAnswer, outcomeForStore, wakeMessage, wakeHookContext, legMods, resumeSignal }),
542
+ next: () => this.resumeHandoff({ token, cp, store, config, internals, resumeInternals, plainPolicyOutcome, redeemedAnswer, outcomeForStore, wakeMessage: wakeDelivered, wakeRewrittenBy, wakeHookContext, legMods, resumeSignal }),
543
543
  }),
544
544
  }),
545
545
  });
546
546
  }
547
547
  async resumeHandoff(claimed) {
548
- const { token, cp, store, config, internals, resumeInternals, plainPolicyOutcome, redeemedAnswer, outcomeForStore, wakeMessage, wakeHookContext, legMods, resumeSignal } = claimed;
548
+ const { token, cp, store, config, internals, resumeInternals, plainPolicyOutcome, redeemedAnswer, outcomeForStore, wakeMessage, wakeRewrittenBy, wakeHookContext, legMods, resumeSignal } = claimed;
549
549
  let consumeFlipDone = false;
550
550
  if (internals?.afterCheckpointResolve !== undefined) {
551
551
  await internals.afterCheckpointResolve();
@@ -575,7 +575,7 @@ export class Runner {
575
575
  throw new CheckpointError("checkpoint.resume_aborted", said);
576
576
  throw new CheckpointError("checkpoint.reopen_failed", said);
577
577
  }
578
- return this.runTaskStream(spec, { cp, outcome: outcomeForStore, reopenUnstarted, recordExecutionOutcome, ...(wakeMessage !== undefined ? { wakeMessage } : {}), ...(wakeHookContext !== undefined ? { wakeMessageHookContext: wakeHookContext } : {}), ...(legMods !== undefined ? { legMods } : {}) }, resumeInternals);
578
+ return this.runTaskStream(spec, { cp, outcome: outcomeForStore, reopenUnstarted, recordExecutionOutcome, ...(wakeMessage !== undefined ? { wakeMessage } : {}), ...(wakeRewrittenBy !== undefined ? { wakeMessageRewrittenBy: wakeRewrittenBy } : {}), ...(wakeHookContext !== undefined ? { wakeMessageHookContext: wakeHookContext } : {}), ...(legMods !== undefined ? { legMods } : {}) }, resumeInternals);
579
579
  }
580
580
  }
581
581
  export function runTask(spec, deps) {
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The display bound, in characters, of a prose frame's echo. The wire contract names no number ("the injected text
3
+ * clipped to a display bound"); this is the one the stream has always used. A frame whose body is a list of rows the
4
+ * renderer already bounds declares its own wider bound on the frame (`TurnAttachment.echoBound`) rather than being
5
+ * cut mid-row by this one.
6
+ */
7
+ export declare const STEERING_PREVIEW_BUDGET = 220;
8
+ /** The echo text of an injected frame body, bounded at `bound` (the shared budget when the frame declares none). */
9
+ export declare function steeringPreview(body: string, bound?: number): string;
@@ -0,0 +1,5 @@
1
+ import { redactThenCut } from "../../agents/subagent-steps.js";
2
+ export const STEERING_PREVIEW_BUDGET = 220;
3
+ export function steeringPreview(body, bound = STEERING_PREVIEW_BUDGET) {
4
+ return redactThenCut(body, bound);
5
+ }
@@ -48,6 +48,7 @@ export function streamSteerVerb(input) {
48
48
  };
49
49
  let payload;
50
50
  let mintsAFrame;
51
+ let rewrittenBy;
51
52
  const publishQueued = (h) => {
52
53
  const identity = internals?.parentToolCallId !== undefined ? { parentToolCallId: internals.parentToolCallId, sourceTaskId: h.hookIdentity.taskId } : {};
53
54
  queue.push({
@@ -60,6 +61,7 @@ export function streamSteerVerb(input) {
60
61
  ...(actor !== undefined ? { actor } : {}),
61
62
  ...(actor?.issuer !== undefined ? { issuer: actor.issuer } : {}),
62
63
  ...(spec.principal !== undefined ? { principal: spec.principal } : {}),
64
+ ...(rewrittenBy !== undefined ? { rewrittenBy } : {}),
63
65
  }),
64
66
  eventId: uuidv7(),
65
67
  ...identity,
@@ -111,6 +113,12 @@ export function streamSteerVerb(input) {
111
113
  if (screen?.block !== undefined && screen.block !== "") {
112
114
  throw steeringError(`the deployment's userPromptSubmit hook blocked this steering input: ${inlineUntrusted(screen.block)}`, "steering.blocked_by_hook");
113
115
  }
116
+ if (screen?.kind === "answered" && screen.rewrittenBy !== undefined) {
117
+ const rewritten = projectHumanInput({ text: screen.text, actor, source: "steer" });
118
+ payload = trusted ? formatHookFeedback(rewritten, h.reminderMark) : frameMidTurnUserInput(rewritten);
119
+ mintsAFrame = payload.trim().length !== 0;
120
+ rewrittenBy = screen.rewrittenBy;
121
+ }
114
122
  if (screen?.additionalContext !== undefined && screen.additionalContext !== "") {
115
123
  payload = `${formatHookFeedback(screen.additionalContext, h.reminderMark)}\n\n${payload}`;
116
124
  }
@@ -16,6 +16,8 @@ export const APPROVAL_CARD_REQUIRED_KEYS = Object.freeze({
16
16
  plan: [],
17
17
  question: [],
18
18
  generic: [],
19
+ "computer-access": ["apps"],
20
+ "computer-control": [],
19
21
  });
20
22
  export function toolFaceProblem(face, schema, tool) {
21
23
  return faceProblem(face, schema, tool);
@@ -194,6 +194,11 @@ export interface TurnAttachment {
194
194
  * run: the caller runs it on the receipt of the message carrying the frame (`FrameReceipt`). A frame the lane cap
195
195
  * drops is not returned, so its step never runs and the frame is due again; a clipped frame keeps it. */
196
196
  commit?: () => void;
197
+ /** The bound, in characters, of this frame's `steering_injected` echo when the shared display budget would cut it
198
+ * mid-row: a frame whose body is a list of rows its renderer already bounds states the bound of that list (here, the
199
+ * lane cap it rides under) so the echo is the list the model received, not the first row or two of it. Absent = the
200
+ * shared budget ({@link import("./steering-preview.js").STEERING_PREVIEW_BUDGET}). */
201
+ echoBound?: number;
197
202
  }
198
203
  /** H4 — the thin projection of a todo list kept run-local (NEVER the wire-capped `tool_end.structured` card).
199
204
  * Pure CONTENT memory: the write-window anchor lives on {@link AttachmentState.todoLastWriteTurn}
@@ -210,7 +210,7 @@ export function collectDueAttachments(state, inp) {
210
210
  }
211
211
  if (inp.config.backgroundTasks && state.postCompactPending) {
212
212
  if (inp.backgroundTasks !== undefined && inp.backgroundTasks.length > 0) {
213
- (out ??= []).push({ source: "background_tasks", body: renderBackgroundTasks(inp.backgroundTasks), commit: () => void (state.postCompactPending = false) });
213
+ (out ??= []).push({ source: "background_tasks", body: renderBackgroundTasks(inp.backgroundTasks), echoBound: ATTACHMENT_BYTE_CAP, commit: () => void (state.postCompactPending = false) });
214
214
  }
215
215
  else {
216
216
  state.postCompactPending = false;
@@ -1372,8 +1372,8 @@ export interface RunnerDeps {
1372
1372
  * errors and do not affect the run, which the engine otherwise prints via `console.warn` (e.g. a
1373
1373
  * configured timeout/env value discarded in favor of another). When wired, a notice goes HERE
1374
1374
  * INSTEAD of `console.warn` (structured replaces the console line — a host forwarding notices to
1375
- * its own surface must not show every fact twice); when absent, the historic `console.warn` line
1376
- * is printed verbatim, so an unwired build keeps its exact loudness. Swallow-guarded at every
1375
+ * its own surface must not show every fact twice); when absent, the default seat the host installed
1376
+ * (`setDefaultEngineNoticeSeat`) takes it, else the historic `console.warn` line is printed verbatim. Swallow-guarded at every
1377
1377
  * emission point (`onError`/`tracer` posture): neither a throwing sink nor an async sink's
1378
1378
  * rejected promise ever affects the run. A PRESENT NON-function value (an untyped host wiring
1379
1379
  * null/junk) is a bad deployment value, not a wired sink: every notice then falls back to the
@@ -97,7 +97,8 @@ export declare function namesASecret(value: string): boolean;
97
97
  * word, one character repeated, fewer than {@link CREDENTIAL_MIN_CHARS} characters — withholding it would take a setting
98
98
  * such as `CI=true` from every child) or that is, in this process's environment now, the value of such a variable —
99
99
  * throws and leaves the declaration as it was. A value listed twice is the one value (the declaration is a set). No
100
- * refusal sentence repeats a value.
100
+ * refusal sentence repeats a value. A value refused as no credential is the one value the refusal names: the host was
101
+ * told of it there, so the engine's intake ({@link holdOwnCredentialValues}) does not say it again.
101
102
  *
102
103
  * Two Windows readings, measured on a real machine: a withheld name that the child's own shell or runtime re-creates
103
104
  * with a DEFAULT of its own (`ComSpec`, `PATHEXT`, `HOME`, `CommonProgramFiles`, …) shows up in the child's table with
@@ -121,9 +122,11 @@ export declare function declareWithheldEnv(table: WithheldEnvDeclaration): void;
121
122
  * gateway is told to be handed) is not taken in: its holder uses it as given (it is no bad value), and the variables
122
123
  * that hold the same string stay with every child. Said once per process per value, never the value, as the notice
123
124
  * `config.credential_not_withheld` through the engine's one notice throat ({@link deliverEngineNotice}): to `onNotice`
124
- * when the intake has the structured seat in hand (the `RunnerDeps` receipt at `new Runner`), else as that notice's
125
- * line on `console.warn` (the throat's own arm for an absent seat — a brain's construction, a request's route reading,
126
- * a peer's dial, a directly built distiller seat). A value that is, in this process's
125
+ * when the intake has the structured seat in hand (the `RunnerDeps` receipt at `new Runner`), else to the process's
126
+ * default seat ({@link import("./engine-notice.js").setDefaultEngineNoticeSeat}) when a host installed one, else as that
127
+ * notice's line on `console.warn` (the throat's own arm for an absent seat — a brain's construction, a request's route
128
+ * reading, a peer's dial, a directly built distiller seat). A value the host's declaration refused as no credential
129
+ * ({@link declareWithheldEnv}) was told in that refusal and is on the same account: not said again. A value that is, in this process's
127
130
  * environment now, the value of a variable every child is handed whatever the spawn passes cannot be withheld: the intake
128
131
  * throws (`config.invalid_argument`, the variable named, never the value) and takes nothing in — the brain is not built,
129
132
  * the peer is not dialed.
@@ -209,7 +212,7 @@ export declare function withheldEnvNames(findings: readonly SecretEnvFinding[]):
209
212
  /**
210
213
  * The ONE disclosure point for a scrub's withheld keys. Routed through {@link deliverEngineNotice} — the
211
214
  * engine's one notice throat — so a wired `onNotice` seat REPLACES the console line exactly as every
212
- * other `EngineNotice` does, and an absent seat prints the same words `console.warn` always printed here.
215
+ * other `EngineNotice` does, and an absent seat (no default seat installed) prints the same words `console.warn` always printed here.
213
216
  * `detail` is {@link withheldEnvNames}: `names` every withheld key, `ownCredentials` (present only when one was
214
217
  * withheld) the subset that is the engine's own credentials. Once per PROCESS, never per call or per site; an
215
218
  * EMPTY findings array is a no-op.
@@ -217,20 +217,23 @@ function notACredentialReason(value) {
217
217
  export function namesASecret(value) {
218
218
  return notACredentialReason(value) === undefined;
219
219
  }
220
- function credentialValueProblem(v) {
220
+ function notVariableValueReason(v) {
221
221
  if (typeof v !== "string")
222
222
  return kindOf(v);
223
223
  if (v === "")
224
224
  return "an empty string, which every variable set to nothing equals";
225
225
  if (v.includes("\0") || UNPAIRED_SURROGATE_RE.test(v))
226
226
  return `a value holding ${v.includes("\0") ? "a NUL" : "an unpaired surrogate"}, which no variable can hold`;
227
- return notACredentialReason(v);
227
+ return undefined;
228
228
  }
229
- function credentialValueListProblem(value) {
230
- for (const [i, v] of value.entries()) {
229
+ function credentialValueProblem(v) {
230
+ return notVariableValueReason(v) ?? notACredentialReason(v);
231
+ }
232
+ function firstRefusedValue(value) {
233
+ for (const [index, v] of value.entries()) {
231
234
  const why = credentialValueProblem(v);
232
235
  if (why !== undefined)
233
- return `values[${i}] is not a credential value (got ${why})`;
236
+ return { index, why };
234
237
  }
235
238
  return undefined;
236
239
  }
@@ -255,9 +258,13 @@ export function declareWithheldEnv(table) {
255
258
  if (!Array.isArray(givenValues))
256
259
  throw new Error(`declareWithheldEnv: values must be an array of credential values (got ${kindOf(givenValues)})`);
257
260
  const values = listCopy("values", givenValues);
258
- const valueProblem = credentialValueListProblem(values);
259
- if (valueProblem !== undefined)
260
- throw new Error(`declareWithheldEnv: ${valueProblem}`);
261
+ const refused = firstRefusedValue(values);
262
+ if (refused !== undefined) {
263
+ const told = values[refused.index];
264
+ if (typeof told === "string" && notVariableValueReason(told) === undefined && !isBlankCredential(told))
265
+ noteIntakeSaid(told);
266
+ throw new Error(`declareWithheldEnv: values[${refused.index}] is not a credential value (got ${refused.why})`);
267
+ }
261
268
  for (const [i, v] of values.entries()) {
262
269
  const holder = runtimeSuppliedHolderOf(v);
263
270
  if (holder !== undefined)
@@ -270,20 +277,27 @@ export function declareWithheldEnv(table) {
270
277
  }
271
278
  export function holdOwnCredentialValues(values, onNotice) {
272
279
  const given = [...values].filter((v) => typeof v === "string" && !isBlankCredential(v));
280
+ const notTaken = new Map();
273
281
  const taken = given.filter((v) => {
274
282
  const why = notACredentialReason(v);
275
283
  if (why !== undefined)
276
- sayNotTaken(v, why, onNotice);
284
+ notTaken.set(v, why);
277
285
  return why === undefined;
278
286
  });
279
- for (const v of taken) {
280
- const holder = runtimeSuppliedHolderOf(v);
281
- if (holder !== undefined)
282
- throw Object.assign(new Error(`a credential the engine was handed is the value of ${holder}, ${CANNOT_BE_WITHHELD}; the credential is refused`), { code: "config.invalid_argument" });
287
+ try {
288
+ for (const v of taken) {
289
+ const holder = runtimeSuppliedHolderOf(v);
290
+ if (holder !== undefined)
291
+ throw Object.assign(new Error(`a credential the engine was handed is the value of ${holder}, ${CANNOT_BE_WITHHELD}; the credential is refused`), { code: "config.invalid_argument" });
292
+ }
293
+ const { held } = withheldEnvOf();
294
+ for (const v of taken)
295
+ indexAdd(held, v);
296
+ }
297
+ finally {
298
+ for (const [v, why] of notTaken)
299
+ sayNotTaken(v, why, onNotice);
283
300
  }
284
- const { held } = withheldEnvOf();
285
- for (const v of taken)
286
- indexAdd(held, v);
287
301
  }
288
302
  const AUTH_SCHEME_VALUE_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+ +(\S[\s\S]*)$/;
289
303
  export function authSchemeCredentials(value) {
@@ -313,11 +327,16 @@ export function credentialHeaderValues(headers) {
313
327
  return out;
314
328
  }
315
329
  const intakeSaid = new Set();
316
- function sayNotTaken(value, why, onNotice) {
330
+ function noteIntakeSaid(value) {
317
331
  const key = valueDigest(value.trim());
318
332
  if (intakeSaid.has(key))
319
- return;
333
+ return false;
320
334
  intakeSaid.add(key);
335
+ return true;
336
+ }
337
+ function sayNotTaken(value, why, onNotice) {
338
+ if (!noteIntakeSaid(value))
339
+ return;
321
340
  try {
322
341
  deliverEngineNotice(onNotice, {
323
342
  code: "config.credential_not_withheld",
@@ -340,6 +340,6 @@ export declare class TtlSessionStore implements SessionStore {
340
340
  * Exported at the package root: the bundled store's `fork` and any other store's `fork` are the same question and must give the same
341
341
  * answer — a backend reads the source session (`SessionRepo.open`), asks this, and hands the answer to `SessionRepo.fork` with the id
342
342
  * and owner it mints. Forking the whole log instead copies the in-flight turn. The walk is one of the parent-chain walks, so it takes the
343
- * shared guard: a leaf on a loop of tool-result messages is refused `invalid_session` (the sentence of `getPathToRoot`) instead of followed.
343
+ * shared guard: a leaf on a loop of tool-result messages is refused `corrupt_session` (the sentence of `getPathToRoot`) instead of followed.
344
344
  */
345
345
  export declare function settledForkOptions(source: Session): Promise<ForkPoint>;
@@ -25,6 +25,10 @@ export function admitSessionPlacement(sessionId, persisted, request, capability)
25
25
  }
26
26
  }
27
27
  }
28
+ function placedRowCells(placement) {
29
+ const { owner, ...tuple } = placement;
30
+ return { placement: tuple, owner };
31
+ }
28
32
  const TTL_SESSION_STORE_OPTION_KEYS = optionKeys()({ defaultTtlDays: 0, sweepIntervalMs: 0, repo: 0, evict: 0, durability: 0, placements: 0, retention: 0, hooks: 0 });
29
33
  export const STORE_HOOK_KEYS = optionKeys()({ beforeSessionDelete: 0 });
30
34
  export class TtlSessionStore {
@@ -197,7 +201,7 @@ export class TtlSessionStore {
197
201
  async createAndStore(id, placement) {
198
202
  let session;
199
203
  try {
200
- session = await this.repo.create({ ...(id !== undefined ? { id } : {}), ...(placement !== undefined ? { placement } : {}) });
204
+ session = await this.repo.create({ ...(id !== undefined ? { id } : {}), ...(placement !== undefined ? placedRowCells(placement) : {}) });
201
205
  }
202
206
  catch (err) {
203
207
  if (id === undefined || !isSessionConflict(err))
@@ -33,6 +33,10 @@ export interface SessionPlacement {
33
33
  rootSessionId?: string;
34
34
  /** The durable agent row key (`a…`) — the store-side join key for orphan GC. */
35
35
  handle?: string;
36
+ /** The delegation tree's owner: the owner of the tree root's row as the root run read it, carried unchanged to every descendant
37
+ * (`null` = the root is anonymous). The placing write records exactly it in the row's owner cell — never in the tuple
38
+ * ({@link SessionPlacementRecord} has no owner); a re-open ignores it (first-write immutable). */
39
+ owner: string | null;
36
40
  }
37
41
  /**
38
42
  * One row of {@link SessionStore.listPlaced}. The row-store join key is the FULL `(scope, handle)`
@@ -207,7 +211,10 @@ export interface SessionStore<S extends SessionStoreSummary = SessionStoreSummar
207
211
  * placement argument) returns the same session and never rewrites the tuple;
208
212
  * 6. a placed id cannot be CLAIMED: a later claim-form acquire (no `requireExisting`, no
209
213
  * creation placement) of an existing placed id refuses loudly
210
- * (`SessionError("placement_refused")`) instead of attaching.
214
+ * (`SessionError("placement_refused")`) instead of attaching;
215
+ * 7. the placing write records exactly `placement.owner` in the row's owner cell (no owner of its own derived), and the store
216
+ * answers {@link headOf} for every session it holds — with the row's `incarnation`, the same token the acquired session's
217
+ * metadata carries for a row this store created (a revived child reads its tree's owner off its own row through it).
211
218
  */
212
219
  readonly placements?: {
213
220
  subagent?: {
@@ -323,9 +330,12 @@ export interface SessionStore<S extends SessionStoreSummary = SessionStoreSummar
323
330
  * from `acquire`, only a session of the occupant it names — a cached view of an occupant the row no longer holds (the row deleted,
324
331
  * or deleted and created again, through another writer — on the File lane a writer in another process too) is not served — so its `incarnation` and the acquired session's metadata agree (the kit pins both); a run's own memory seat reads the session it ACQUIRED instead, never this lookup. The owner is a cell of the row: `null` = anonymous (admitted to every principal) — a row created
325
332
  * with no owner (`acquire` names none), or a row written before the cell existed; a principal name = owned (a cell holding a blank string
326
- * names nobody and is a read fault, never an owner). A placed row carries the owner its placing write recorded: the bundled stores'
327
- * placing write names none (`acquire`'s options and {@link SessionPlacement} carry no principal), so their placed rows read `null`; a
328
- * store's own placing write may record a principal (e.g. a delegation tree's owner), and a reader takes the row's owner as it reads. **Optional**: absent ⇒ no by-id read,
333
+ * names nobody and is a read fault, never an owner). A placed row carries the owner of its delegation tree: the placing write records
334
+ * exactly `placement.owner` ({@link SessionPlacement.owner} — minted by the engine from the tree root's row, as the root run read it, and
335
+ * carried unchanged down the tree), and no store derives an owner of its own; the child's owner VALUE is its root's (`null` when the
336
+ * root is anonymous) — a deployment's gate may still admit an ownerless placed row more narrowly than an ownerless root row, because a
337
+ * row placed before 7.62.0 keeps what its placing write recorded (`null` on the bundled stores, whatever its root's owner), and a
338
+ * descendant spawned from such a row after a revival records that `null` too. **Optional**: absent ⇒ no by-id read,
329
339
  * and a deployment's authorizer, which needs this and {@link register} together, takes its fail-closed arm.
330
340
  */
331
341
  headOf?(sessionId: string): Promise<SessionHead | undefined>;
@@ -57,6 +57,9 @@ export declare function checkpointListByScopeSummaries(store: CheckpointStore):
57
57
  /** The canonical expected summary projection (what `summarizeCheckpoint` must yield for the fixture above). */
58
58
  export declare const EXPECTED_LISTBYSCOPE_SUMMARIES: ({
59
59
  token: string;
60
+ rowVerdict: {
61
+ kind: string;
62
+ };
60
63
  sessionId: string;
61
64
  scope: string;
62
65
  gateKind: string;
@@ -75,6 +78,9 @@ export declare const EXPECTED_LISTBYSCOPE_SUMMARIES: ({
75
78
  spentMicroUsd?: undefined;
76
79
  } | {
77
80
  token: string;
81
+ rowVerdict: {
82
+ kind: string;
83
+ };
78
84
  sessionId: string;
79
85
  scope: string;
80
86
  gateKind: string;
@@ -1,6 +1,8 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { executionVerdict } from "../checkpoint-execution-record.js";
3
3
  import { MAX_PENDING_STEER_ENTRIES, checkpointIndexFacts, mintCheckpointToken, readPendingSteerQueue, } from "../checkpoint-store.js";
4
+ import { judgeCheckpointRow } from "../checkpoint-row-verdict.js";
5
+ import { memberPresent } from "../own-property-receipt.js";
4
6
  import { checkpointFrom } from "../pause-registry.js";
5
7
  import { beginContract } from "./contract-harness.js";
6
8
  export function createCheckpointFixture(over = {}) {
@@ -31,6 +33,11 @@ export function createCheckpointFixture(over = {}) {
31
33
  ...over,
32
34
  });
33
35
  }
36
+ function damagedWriteFaceFixture(over) {
37
+ const cp = createCheckpointFixture(over);
38
+ Reflect.set(cp.state, "writeFace", { face: "neither" });
39
+ return cp;
40
+ }
34
41
  export const ALLOW = {
35
42
  gate: "policy_ask",
36
43
  decision: "allow",
@@ -275,6 +282,48 @@ export async function checkpointStoreContract(make, runAssertion, options = {})
275
282
  assert.equal(list[0].token, pending.token);
276
283
  assert.equal((await store.get(pending.token)).status, "pending");
277
284
  });
285
+ run("rowVerdict: every listed summary's verdict equals judgeCheckpointRow of the row get hands back (an ok row, a damaged row), and editing a listed summary's preview leaves the stored row as it was", async () => {
286
+ const store = make();
287
+ const okRow = createCheckpointFixture({
288
+ sessionId: "verdict-ok",
289
+ pendingAction: { kind: "tool_approval", origin: "policy", toolCallId: "call-3", toolName: "Write", args: { path: "/x", content: "y" }, preview: { lines: ["a"] }, boundInputHash: "h0", boundGrantAbsence: "not_bindable", batchToolCallIds: ["call-3"], completedCallIds: [] },
290
+ });
291
+ const damagedRow = damagedWriteFaceFixture({ sessionId: "verdict-damaged" });
292
+ for (const cp of [okRow, damagedRow])
293
+ await store.put(cp.token, cp);
294
+ const listed = await store.listByScope("tenant-a");
295
+ assert.equal(listed.length, 2);
296
+ assert.equal(judgeCheckpointRow(okRow).kind, "ok");
297
+ assert.equal(judgeCheckpointRow(damagedRow).kind, "damaged");
298
+ for (const s of listed)
299
+ assert.deepEqual(s.rowVerdict, judgeCheckpointRow((await store.get(s.token))), `the listing and the get judge one row (${s.sessionId})`);
300
+ const byId = new Map(listed.map((s) => [s.sessionId, s]));
301
+ byId.get("verdict-ok").preview.lines.push("edited on the summary");
302
+ const stored = (await store.get(okRow.token)).pendingAction;
303
+ assert.deepEqual(stored.preview, { lines: ["a"] }, "a summary's preview is a copy: editing it does not edit the stored row");
304
+ const relisted = new Map((await store.listByScope("tenant-a")).map((s) => [s.sessionId, s]));
305
+ assert.deepEqual(relisted.get("verdict-ok").preview, { lines: ["a"] });
306
+ });
307
+ run("rowVerdict: a listed verdict is the verdict judged now — on a second listing, and (deleteSessionCheckpoints offered) after a token's row is replaced by a damaged one", async () => {
308
+ const store = make();
309
+ const row = createCheckpointFixture({ sessionId: "memo-row" });
310
+ await store.put(row.token, row);
311
+ const first = (await store.listByScope("tenant-a")).find((s) => s.token === row.token);
312
+ const second = (await store.listByScope("tenant-a")).find((s) => s.token === row.token);
313
+ assert.deepEqual(first.rowVerdict, judgeCheckpointRow((await store.get(row.token))));
314
+ assert.deepEqual(second.rowVerdict, first.rowVerdict);
315
+ const heads = options.sessionHeads;
316
+ if (store.deleteSessionCheckpoints === undefined || heads === undefined)
317
+ return;
318
+ heads.set("memo-row", { owner: null });
319
+ if ((await store.deleteSessionCheckpoints("memo-row", { owner: null })) !== 1)
320
+ return;
321
+ const replaced = damagedWriteFaceFixture({ token: row.token, sessionId: "memo-row" });
322
+ await store.put(replaced.token, replaced);
323
+ const after = (await store.listByScope("tenant-a")).find((s) => s.token === row.token);
324
+ assert.equal(after.rowVerdict.kind, "damaged", "a replaced row is judged again, never answered from the verdict its predecessor had");
325
+ assert.deepEqual(after.rowVerdict, judgeCheckpointRow((await store.get(row.token))));
326
+ });
278
327
  run("#438 hasBidiControls three-form matrix: a row's `true` survives + projects; absent stays absent (clean args); an out-of-contract `false` reads as absent; a bit-less marked row backfills at projection", async () => {
279
328
  const store = make();
280
329
  const RLO = String.fromCodePoint(0x202e);
@@ -460,6 +509,23 @@ export async function checkpointStoreContract(make, runAssertion, options = {})
460
509
  assert.equal((await store.get(bogus.token)).state.runOrigin, "weekly", "a word outside the set must be kept on the row verbatim");
461
510
  assert.equal("runOrigin" in byId.get("ro-bogus"), false, "a word outside the closed set must read as absent in the listing, never project verbatim");
462
511
  });
512
+ run("member presence: a row whose top level and `state` carry members holding undefined reads them absent — the value undefined (`memberPresent` false), the listing without them — and judges as its twin without the keys", async () => {
513
+ const store = make();
514
+ const holding = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "mp-holding" });
515
+ Object.assign(holding, { deadline: undefined, humanReview: undefined });
516
+ Object.assign(holding.state, { compositionLeg: undefined, rowTaskId: undefined });
517
+ const omitted = createCheckpointFixture({ token: mintCheckpointToken(), sessionId: "mp-omitted" });
518
+ for (const cp of [holding, omitted])
519
+ await store.put(cp.token, cp);
520
+ const got = (await store.get(holding.token));
521
+ for (const name of ["deadline", "humanReview"])
522
+ assert.equal(memberPresent(got, name), false, `a top-level ${name} holding undefined must read absent`);
523
+ for (const name of ["compositionLeg", "rowTaskId"])
524
+ assert.equal(memberPresent(got.state, name), false, `a state.${name} holding undefined must read absent`);
525
+ const listed = (await store.listByScope("tenant-a")).find((s) => s.sessionId === "mp-holding");
526
+ assert.equal("deadline" in listed, false, "the listing must leave out a deadline that holds undefined");
527
+ assert.deepEqual(judgeCheckpointRow(got), judgeCheckpointRow((await store.get(omitted.token))), "a member holding undefined must judge as the member left out");
528
+ });
463
529
  run("decider pair: a policy-decided allow resolves like a person's — its `policy_allowed` record (party `policy`, the attribution) round-trips verbatim on the resolved winner and as the execution record; the same record is already_recorded, a person's record for that row conflicts", async () => {
464
530
  const store = make();
465
531
  const cp = createCheckpointFixture();
@@ -688,6 +754,7 @@ export async function checkpointListByScopeSummaries(store) {
688
754
  export const EXPECTED_LISTBYSCOPE_SUMMARIES = [
689
755
  {
690
756
  token: "tok-escalation",
757
+ rowVerdict: { kind: "ok" },
691
758
  sessionId: "needs-approval",
692
759
  scope: "tenant-a",
693
760
  gateKind: "human",
@@ -706,6 +773,7 @@ export const EXPECTED_LISTBYSCOPE_SUMMARIES = [
706
773
  },
707
774
  {
708
775
  token: "tok-resource",
776
+ rowVerdict: { kind: "ok" },
709
777
  sessionId: "out-of-budget",
710
778
  scope: "tenant-a",
711
779
  gateKind: "resource_limit",
@@ -22,8 +22,8 @@ function compactionEntry(id, parentId, firstKeptEntryId) {
22
22
  return { id, parentId, type: "compaction", timestamp: AT, summary: "summary of the turns above the floor", firstKeptEntryId, tokensBefore: 1000 };
23
23
  }
24
24
  const freshId = () => uuidv7();
25
- function placementFor(scope, handle = `a${uuidv7().slice(-12)}`) {
26
- return { kind: "subagent", scope: scope ?? `kit-${uuidv7().slice(-12)}`, ...(handle !== null ? { handle } : {}) };
25
+ function placementFor(scope, handle = `a${uuidv7().slice(-12)}`, owner = null) {
26
+ return { kind: "subagent", scope: scope ?? `kit-${uuidv7().slice(-12)}`, ...(handle !== null ? { handle } : {}), owner };
27
27
  }
28
28
  const tick = () => new Promise((resolve) => setTimeout(resolve, 20));
29
29
  async function append(session, entry, opts) {
@@ -73,7 +73,7 @@ async function refusedAsLoop(storage, leafId, loopMembers, what) {
73
73
  const outcome = await Promise.race([settled, expiry]).finally(() => clearTimeout(timer));
74
74
  if ("path" in outcome)
75
75
  assert.fail(`${what}: a parent chain that loops back on itself answered a path of ${outcome.path.length} entries instead of refusing`);
76
- assert.equal(readMember(outcome.err, "code"), "invalid_session", `${what}: the refusal must carry code invalid_session`);
76
+ assert.equal(readMember(outcome.err, "code"), "corrupt_session", `${what}: the refusal must carry code corrupt_session`);
77
77
  const sentence = String(readMember(outcome.err, "message"));
78
78
  assert.ok(loopMembers.some((id) => sentence.includes(id)), `${what}: the refusal must name an entry of the loop (${loopMembers.join(" / ")}), got "${sentence}"`);
79
79
  }
@@ -290,7 +290,7 @@ async function runSessionStoreContract(make, hooks) {
290
290
  assert.equal(await storage.getLeafId(), "e1", "a refused setLeafId leaves the leaf where it was");
291
291
  await rejectsWithCode(() => storage.getPathToRoot("kit-never-written"), "not_found", "getPathToRoot from an id the session never held");
292
292
  });
293
- run("[tree] a path stops at a root or at the storage's declared floor; a parent missing above the floor reads invalid_session, never a truncated path", async (store) => {
293
+ run("[tree] a path stops at a root or at the storage's declared floor; a parent missing above the floor reads corrupt_session, never a truncated path", async (store) => {
294
294
  const { session } = await store.acquire(freshId());
295
295
  await append(session, userEntry("e1", null));
296
296
  let accepted = true;
@@ -301,12 +301,12 @@ async function runSessionStoreContract(make, hooks) {
301
301
  accepted = false;
302
302
  }
303
303
  if (accepted) {
304
- await rejectsWithCode(() => session.getStorage().getPathToRoot("orphan"), "invalid_session", "the path through an entry whose parent was never written");
304
+ await rejectsWithCode(() => session.getStorage().getPathToRoot("orphan"), "corrupt_session", "the path through an entry whose parent was never written");
305
305
  }
306
306
  const head = (await session.getStorage().getPathToRoot("e1"))[0];
307
307
  assert.ok(head.parentId === null || head.id === session.getStorage().getFloorId?.(), "a path's head is a root or the declared floor");
308
308
  });
309
- run("[tree] a parent chain that loops back on itself — an entry that is its own parent, two entries that parent each other, a leaf that walks into such a pair — reads invalid_session naming an entry of the loop, and the walk ends (also for a ring of three)", async (store) => {
309
+ run("[tree] a parent chain that loops back on itself — an entry that is its own parent, two entries that parent each other, a leaf that walks into such a pair — reads corrupt_session naming an entry of the loop, and the walk ends (also for a ring of three)", async (store) => {
310
310
  const { session } = await store.acquire(freshId());
311
311
  await append(session, userEntry("e1", null));
312
312
  const accepted = async (...entries) => {
@@ -743,6 +743,20 @@ async function runSessionStoreContract(make, hooks) {
743
743
  await append(acquired.session, userEntry("e1", null));
744
744
  assert.deepEqual(await entryIds((await readBack(store, id))), ["e1"]);
745
745
  });
746
+ faceRun("[placements] the placing write records exactly placement.owner as the row's owner, and headOf answers the placed row with the occupant the acquired session carries — before and after a restart", ["placements"], async (store, open) => {
747
+ assert.ok(hasHead(store), "a store that declares placements answers headOf (obligation 7): a revived child reads its tree's owner off its own row through it");
748
+ const named = freshId();
749
+ const anonymous = freshId();
750
+ const owner = `kit-tree-${freshId()}`;
751
+ const acquired = await store.acquire(named, { placement: placementFor(undefined, undefined, owner) });
752
+ await store.acquire(anonymous, { placement: placementFor() });
753
+ const token = await tokenOf(store, named, "a placed row this store created");
754
+ assert.equal((await acquired.session.getMetadata()).incarnation, token, "the placed session handed out is the occupant the head names");
755
+ assert.equal(await ownerOf(store, named, "a placed row"), owner, "the placing write recorded the placement's owner");
756
+ assert.equal(await ownerOf(store, anonymous, "a placed row of an anonymous tree"), null, "a null placement owner is an anonymous row");
757
+ const second = await open(hooks.reopen(store));
758
+ assert.deepEqual(await headOf(second, named), await headOf(store, named), "the owner lives in the row, not in an instance");
759
+ });
746
760
  faceRun("[placements] listPlaced returns each placed session with its full (scope, handle) tuple or the honest tupleIncomplete, filters by scope and age, and never lists an ordinary session", ["listPlaced"], async (store) => {
747
761
  const scope = `kit-${uuidv7().slice(-12)}`;
748
762
  const full = placementFor(scope);
@@ -843,13 +857,13 @@ async function runSessionStoreContract(make, hooks) {
843
857
  if (declaresPlacements(store)) {
844
858
  for (const owner of [`kit-claimant-${freshId()}`, null]) {
845
859
  const placed = freshId();
846
- await store.acquire(placed, { placement: placementFor() });
860
+ await store.acquire(placed, { placement: placementFor(undefined, undefined, `kit-tree-${freshId()}`) });
847
861
  const recorded = await ownerOf(store, placed, "a placed row");
848
862
  await store.register(placed, owner);
849
863
  assert.equal(await ownerOf(store, placed, "a placed row after a register"), recorded, `a register carrying ${owner === null ? "null" : "an owner"} left the placed row's owner as its placing write recorded it`);
850
864
  }
851
865
  const sequenced = freshId();
852
- await store.acquire(sequenced, { placement: placementFor() });
866
+ await store.acquire(sequenced, { placement: placementFor(undefined, undefined, `kit-tree-${freshId()}`) });
853
867
  const recordedSeq = await ownerOf(store, sequenced, "a placed row (sequence)");
854
868
  await store.register(sequenced, null);
855
869
  await store.register(sequenced, `kit-claimant-${freshId()}`);