@zq-silk/yui 0.15.7 → 0.15.8

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 (281) hide show
  1. package/ARCHITECTURE.md +192 -399
  2. package/README.md +127 -1149
  3. package/dist/agent/adapterCatalog.js +15 -2
  4. package/dist/agent/agent.js +23 -3
  5. package/dist/agent/argumentPolicy.js +7 -1
  6. package/dist/agent/connectionPlan.js +62 -0
  7. package/dist/agent/executionComponents.js +158 -0
  8. package/dist/agent/launchEnvironment.js +31 -3
  9. package/dist/agent/managedRuntimeEnvironment.js +3 -5
  10. package/dist/{turn/turn.js → agentRun/agentRun.js} +166 -109
  11. package/dist/{turn/turnIdentity.js → agentRun/runIdentity.js} +4 -4
  12. package/dist/brief/taskBrief.js +12 -0
  13. package/dist/cli/agentConfigurationPicker.js +13 -0
  14. package/dist/cli/commandCatalog.js +157 -70
  15. package/dist/cli/interactionCandidates.js +5 -5
  16. package/dist/cli/interactionPolicy.js +38 -8
  17. package/dist/cli/invocationRouter.js +1 -1
  18. package/dist/cli/managedDiagnostics.js +28 -0
  19. package/dist/cli/operatorWizard.js +1 -7
  20. package/dist/cli/roleOptionOrder.js +27 -0
  21. package/dist/cli/roleWizard.js +50 -14
  22. package/dist/cli/updateOrchestrator.js +1 -1
  23. package/dist/cli/updatePorts.js +3 -4
  24. package/dist/cli.js +178 -95
  25. package/dist/commands/agentCommands.js +72 -14
  26. package/dist/commands/capabilityCommands.js +9 -6
  27. package/dist/commands/configCommands.js +20 -20
  28. package/dist/commands/deliveryGuardPreflight.js +2 -2
  29. package/dist/commands/executionAuditCommands.js +24 -24
  30. package/dist/commands/globalRoleCommands.js +1 -1
  31. package/dist/commands/grantCommands.js +4 -4
  32. package/dist/commands/operatorCommands.js +1 -7
  33. package/dist/commands/projectCommands.js +4 -4
  34. package/dist/commands/resourcesCommands.js +2 -2
  35. package/dist/commands/roleConfiguration.js +25 -5
  36. package/dist/commands/roleRuntimeGuard.js +4 -5
  37. package/dist/commands/sessionCommands.js +3 -7
  38. package/dist/commands/taskActivationCommands.js +259 -0
  39. package/dist/commands/taskActor.js +28 -49
  40. package/dist/commands/taskCommands.js +1188 -710
  41. package/dist/commands/taskContextCommand.js +39 -583
  42. package/dist/commands/taskExecutionCommands.js +32 -32
  43. package/dist/commands/taskInputCommands.js +40 -104
  44. package/dist/commands/taskIntegrationCommands.js +3 -2
  45. package/dist/commands/taskIntegrationQueueCommands.js +1 -1
  46. package/dist/commands/taskNextActionCommand.js +8 -8
  47. package/dist/commands/taskOverviewCommand.js +33 -45
  48. package/dist/commands/taskRemoteDeliveryCommand.js +2 -2
  49. package/dist/commands/taskRoleRuntimeStatus.js +133 -102
  50. package/dist/commands/telemetryCommands.js +36 -38
  51. package/dist/config/configCatalog.js +4 -4
  52. package/dist/config/yuiConfig.js +8 -8
  53. package/dist/context/contextSnapshot.js +10 -10
  54. package/dist/context/dispatchContext.js +11 -11
  55. package/dist/context/roleSessionContext.js +6 -3
  56. package/dist/context/{turnContextPack.js → runContextPack.js} +146 -81
  57. package/dist/context/{turnInputContract.js → runInputContract.js} +73 -60
  58. package/dist/context/sessionBootstrapManifest.js +21 -2
  59. package/dist/context/sourceRunContext.js +30 -0
  60. package/dist/context/taskContext.js +458 -0
  61. package/dist/context/wakeNotification.js +27 -27
  62. package/dist/controller/agentRuntimeObserver.js +21 -24
  63. package/dist/controller/capabilityBridge.js +17 -6
  64. package/dist/controller/clientRuntime.js +65 -92
  65. package/dist/controller/controller.js +114 -188
  66. package/dist/controller/fileSchedulerStoreAdapter.js +787 -887
  67. package/dist/controller/jobControl.js +54 -85
  68. package/dist/controller/resourceInventory.js +8 -27
  69. package/dist/controller/resourceInventoryLinux.js +12 -13
  70. package/dist/controller/runtime.js +529 -479
  71. package/dist/controller/runtimeEventInbox.js +55 -25
  72. package/dist/controller/runtimeEventProcessor.js +22 -31
  73. package/dist/controller/{runtimeHookTurnFence.js → runtimeHookRunFence.js} +91 -115
  74. package/dist/controller/runtimeLaunchCoordinator.js +80 -426
  75. package/dist/controller/runtimeObservationHook.js +14 -18
  76. package/dist/controller/sessionNotify.js +16 -24
  77. package/dist/controller/sessionOwnerReconciliation.js +168 -50
  78. package/dist/controller/structuredProviderObservation.js +138 -99
  79. package/dist/coordination/workMailbox.js +3 -3
  80. package/dist/coordination/workMailboxQueue.js +36 -33
  81. package/dist/core/boundedRpc.js +8 -1
  82. package/dist/core/controllerClient.js +20 -1
  83. package/dist/core/controllerServer.js +4 -4
  84. package/dist/doctor/doctor.js +13 -2
  85. package/dist/domain/agentResultTransport.js +9 -9
  86. package/dist/execution/codexThreadNaming.js +2 -8
  87. package/dist/execution/executionHealth.js +51 -63
  88. package/dist/execution/reviewMainRun.js +137 -0
  89. package/dist/execution/workItemExecution.js +28 -29
  90. package/dist/execution/workItemExecutionProjection.js +99 -107
  91. package/dist/execution/workItemMainRun.js +141 -0
  92. package/dist/executor/agentAdapter.js +227 -20
  93. package/dist/executor/agentConfigurationCatalog.js +126 -4
  94. package/dist/executor/agentConfigurationProbe.js +162 -4
  95. package/dist/executor/agentExecutor.js +79 -78
  96. package/dist/executor/effectiveLaunch.js +105 -18
  97. package/dist/executor/executorRegistry.js +29 -44
  98. package/dist/executor/fileRoleLaunchPlanner.js +229 -154
  99. package/dist/executor/workspacePreflightClassification.js +16 -16
  100. package/dist/grant/capabilityGrant.js +6 -3
  101. package/dist/input/inputRequest.js +12 -10
  102. package/dist/integration/gitIntegrationService.js +4 -11
  103. package/dist/integration/integrationQueueService.js +4 -4
  104. package/dist/interaction/operatorPresentation.js +1 -1
  105. package/dist/kernel/builtinCapabilities.js +247 -12
  106. package/dist/kernel/capabilityRegistry.js +64 -18
  107. package/dist/kernel/instanceHost.js +12 -1
  108. package/dist/kernel/kernelPorts.js +2 -2
  109. package/dist/lifecycle/canonicalLifecycleEvent.js +44 -49
  110. package/dist/lifecycle/exactRunTerminalization.js +449 -0
  111. package/dist/message/message.js +62 -6
  112. package/dist/message/messageContinuation.js +204 -0
  113. package/dist/observability/executionAudit.js +70 -72
  114. package/dist/observability/faultClassification.js +2 -2
  115. package/dist/observability/orchestrationMetrics.js +8 -8
  116. package/dist/operator/operatorSessionHistory.js +1 -7
  117. package/dist/output/agentConfigurationPresentation.js +8 -3
  118. package/dist/output/agentRunConfigurationPresentation.js +128 -0
  119. package/dist/output/rolePresentation.js +54 -3
  120. package/dist/plugins/pluginChild.js +104 -0
  121. package/dist/plugins/pluginIntent.js +26 -0
  122. package/dist/plugins/pluginInterpreter.js +43 -0
  123. package/dist/plugins/pluginPackage.js +101 -0
  124. package/dist/plugins/pluginProcess.js +112 -0
  125. package/dist/plugins/pluginService.js +380 -0
  126. package/dist/profile/agentProfile.js +1 -1
  127. package/dist/repository/gitWorkspace.js +26 -4
  128. package/dist/repository/project.js +19 -4
  129. package/dist/repository/taskBaseFreshness.js +13 -13
  130. package/dist/repository/taskWorkspaceCoordinator.js +20 -27
  131. package/dist/repository/taskWorkspacePreparer.js +344 -83
  132. package/dist/resources/autoResourceGc.js +3 -3
  133. package/dist/resources/liveReferences.js +3 -3
  134. package/dist/resources/projectResource.js +123 -0
  135. package/dist/resources/projectResourceService.js +421 -0
  136. package/dist/resources/resourceDiscovery.js +6 -6
  137. package/dist/resources/resourceGc.js +1 -1
  138. package/dist/resources/resourceRegistrar.js +1 -1
  139. package/dist/resources/resourceTypes.js +1 -1
  140. package/dist/review/deltaRecheck.js +3 -3
  141. package/dist/review/reviewAcceptance.js +16 -16
  142. package/dist/review/reviewDecision.js +7 -7
  143. package/dist/review/reviewRound.js +21 -20
  144. package/dist/review/reviewerAvailability.js +2 -2
  145. package/dist/role/role.js +51 -7
  146. package/dist/role/taskRoleUpdate.js +30 -0
  147. package/dist/runtime/acpProtocol.js +425 -0
  148. package/dist/runtime/acpSession.js +731 -0
  149. package/dist/runtime/acpSessionConfiguration.js +260 -0
  150. package/dist/runtime/agentDriver.js +30 -11
  151. package/dist/runtime/agentEndpoint.js +278 -0
  152. package/dist/runtime/agentEndpointIdentity.js +86 -0
  153. package/dist/runtime/agentEndpointOwnership.js +239 -0
  154. package/dist/runtime/agentError.js +2 -10
  155. package/dist/runtime/agentHost.js +565 -314
  156. package/dist/runtime/agentRunConfiguration.js +258 -0
  157. package/dist/runtime/builtinAgentDrivers.js +134 -18
  158. package/dist/runtime/builtinAgentErrorMappers.js +55 -3
  159. package/dist/runtime/builtinTranscriptUsage.js +1 -1
  160. package/dist/runtime/claude-process-owner +0 -0
  161. package/dist/runtime/codexAppServerRuntime.js +38 -30
  162. package/dist/runtime/codexInteractiveHost.js +41 -6
  163. package/dist/runtime/continuationManager.js +2 -6
  164. package/dist/runtime/executionEnvironment.js +30 -0
  165. package/dist/runtime/firstProgressAdvisory.js +11 -11
  166. package/dist/runtime/index.js +4 -3
  167. package/dist/runtime/jsonLineChannel.js +109 -0
  168. package/dist/runtime/launchBroker.js +91 -16
  169. package/dist/runtime/launchDiagnostics.js +2 -2
  170. package/dist/runtime/lifecycleReservation.js +10 -18
  171. package/dist/runtime/managedCaller.js +61 -17
  172. package/dist/runtime/nativeSessionControl.js +102 -0
  173. package/dist/runtime/ports.js +6 -21
  174. package/dist/runtime/processExitObservation.js +8 -7
  175. package/dist/runtime/promptEnvelope.js +17 -6
  176. package/dist/runtime/providerContinuation.js +3 -9
  177. package/dist/runtime/providerContinuationReconciliationService.js +4 -13
  178. package/dist/runtime/providerControl.js +2 -7
  179. package/dist/runtime/providerRuntimeIdentity.js +110 -222
  180. package/dist/runtime/providerRuntimeReconciler.js +5 -9
  181. package/dist/runtime/runtimeBinding.js +0 -1
  182. package/dist/runtime/runtimeContinuationProjection.js +4 -7
  183. package/dist/runtime/runtimeDeadlines.js +9 -0
  184. package/dist/runtime/runtimeHealthPolicy.js +1 -1
  185. package/dist/runtime/runtimeObservation.js +29 -65
  186. package/dist/runtime/runtimeProjection.js +43 -51
  187. package/dist/runtime/runtimeSessionCandidate.js +1 -3
  188. package/dist/runtime/sessionLaunchRequest.js +3 -7
  189. package/dist/runtime/sessionOwnerIdentity.js +7 -54
  190. package/dist/runtime/sessionOwnerRegistry.js +22 -17
  191. package/dist/runtime/sessionReconciliation.js +4 -8
  192. package/dist/runtime/sessionTerminationGuard.js +70 -259
  193. package/dist/runtime/sessionTokenMetrics.js +5 -16
  194. package/dist/runtime/structuredProviderHost.js +237 -117
  195. package/dist/runtime/taskRuntimeIsolation.js +39 -122
  196. package/dist/runtime/tmuxAdapters.js +39 -86
  197. package/dist/scheduler/activeRoleRunDelivery.js +354 -0
  198. package/dist/scheduler/leaderWakeupProcessor.js +75 -266
  199. package/dist/scheduler/operatorInputNotificationProcessor.js +1 -1
  200. package/dist/scheduler/ports.js +80 -9
  201. package/dist/scheduler/{roleTurnLiveness.js → roleRunLiveness.js} +26 -30
  202. package/dist/scheduler/{roleTurnStall.js → roleRunStall.js} +128 -139
  203. package/dist/scheduler/taskExecutionProjection.js +120 -124
  204. package/dist/scheduler/taskObservabilityProjection.js +29 -29
  205. package/dist/scheduler/taskWake.js +11 -4
  206. package/dist/scheduler/wakeReason.js +9 -1
  207. package/dist/setup/setupCommand.js +1 -0
  208. package/dist/storage/migrations/agentRunContract.js +159 -0
  209. package/dist/storage/migrations/removeRuntimeGeneration.js +207 -0
  210. package/dist/storage/sqliteSchema.js +431 -5
  211. package/dist/storage/sqliteStore.js +375 -220
  212. package/dist/storage/storageVersions.js +1 -1
  213. package/dist/storage/storeRpc.js +10 -5
  214. package/dist/storage/taskStore.js +13 -11
  215. package/dist/storage/upgrade/upgradeOrchestrator.js +5 -7
  216. package/dist/surface/surfaceContributions.js +102 -0
  217. package/dist/task/completionReadiness.js +32 -6
  218. package/dist/task/deliveryGuard.js +16 -16
  219. package/dist/task/draftPlan.js +72 -12
  220. package/dist/task/nextAction.js +144 -128
  221. package/dist/task/remoteDelivery.js +6 -6
  222. package/dist/task/task.js +184 -18
  223. package/dist/task/taskActivation.js +301 -0
  224. package/dist/task/taskActivationService.js +392 -0
  225. package/dist/task/taskRecordReference.js +5 -4
  226. package/dist/task/taskRecordRetirement.js +1 -1
  227. package/dist/telemetry/sqliteTelemetryStore.js +55 -68
  228. package/dist/telemetry/telemetryConfig.js +14 -14
  229. package/dist/telemetry/telemetryWiring.js +2 -2
  230. package/dist/web/assets/assetManifest.js +2 -0
  231. package/dist/web/assets/client/app.js +120 -20
  232. package/dist/web/assets/client/components.js +87 -54
  233. package/dist/web/assets/client/i18n.js +83 -41
  234. package/dist/web/assets/client/markdown.js +1 -1
  235. package/dist/web/assets/client/taskSurface.js +353 -0
  236. package/dist/web/assets/client/view.js +49 -44
  237. package/dist/web/assets/shell.js +1 -1
  238. package/dist/web/assets/styles/cards.js +22 -4
  239. package/dist/web/controllerWeb.js +60 -0
  240. package/dist/web/webMutation.js +28 -0
  241. package/dist/web/webServer.js +118 -8
  242. package/dist/web/webSnapshot.js +81 -74
  243. package/dist/web/webTaskSurface.js +64 -0
  244. package/dist/workItem/dependencyGate.js +1 -1
  245. package/dist/workItem/workItem.js +80 -48
  246. package/dist/workspace/workItemChangeSetManager.js +16 -9
  247. package/docs/agent-result-consumption.md +94 -0
  248. package/docs/agent-runtime-drivers.md +91 -0
  249. package/docs/architecture/README.md +38 -0
  250. package/docs/architecture/capabilities-and-resources.md +79 -0
  251. package/docs/managed-turn-and-session-runtime.md +222 -0
  252. package/docs/observability/README.md +81 -0
  253. package/docs/plugin-sdk.md +290 -0
  254. package/docs/provider-runtime.md +163 -0
  255. package/docs/release-workflow.md +303 -0
  256. package/docs/roles-and-configuration.md +113 -0
  257. package/docs/sqlite-control-plane-design.md +76 -0
  258. package/docs/task-dag-semantics.md +57 -0
  259. package/docs/task-delivery.md +103 -0
  260. package/docs/task-local-identity.md +6 -6
  261. package/docs/testing/verification-levels.md +86 -0
  262. package/i18n/README.zh-CN.md +98 -739
  263. package/package.json +2 -2
  264. package/skills/yui-leader/SKILL.md +130 -103
  265. package/skills/yui-leader/references/integration.md +39 -0
  266. package/skills/yui-leader/references/replicated-execution.md +42 -0
  267. package/skills/yui-leader/references/task-plugins.md +33 -0
  268. package/skills/yui-operator/SKILL.md +30 -59
  269. package/skills/yui-reviewer/SKILL.md +35 -36
  270. package/skills/yui-runtime/SKILL.md +88 -24
  271. package/skills/yui-runtime/references/publication.md +22 -0
  272. package/skills/yui-runtime/references/recovery.md +64 -0
  273. package/skills/yui-worker/SKILL.md +37 -39
  274. package/dist/cli/roleOptionCatalog.js +0 -68
  275. package/dist/context/sourceTurnContext.js +0 -30
  276. package/dist/execution/reviewMainTurn.js +0 -161
  277. package/dist/execution/workItemMainTurn.js +0 -164
  278. package/dist/lifecycle/exactTurnTerminalization.js +0 -407
  279. package/dist/runtime/preallocatedNativeSession.js +0 -13
  280. package/dist/runtime/runtimeStopReceipt.js +0 -42
  281. package/dist/scheduler/activeRoleTurnDelivery.js +0 -315
@@ -1,586 +1,42 @@
1
- import { taskNotFound, usageError } from "../errors/cliError.js";
2
- import { taskMessageAuthorLabel } from "../message/message.js";
3
- import { formatTimestamp } from "../output/timePresentation.js";
4
- import { isRoleTurnStalled, latestStallProgressAt } from "../scheduler/roleTurnStall.js";
5
- import { buildTaskExecutionProjection } from "../scheduler/taskExecutionProjection.js";
6
- import { projectNextAction } from "../task/nextAction.js";
7
- import { projectWorkItemExecution } from "../execution/workItemExecutionProjection.js";
8
- import { operationalTaskRecords } from "../task/taskRecordRetirement.js";
9
- import { projectReviewDecision } from "../review/reviewDecision.js";
10
- import { projectTaskRemoteDeliveryFromStore, renderTaskRemoteDelivery } from "./taskRemoteDeliveryCommand.js";
11
- const RECENT_RECORD_LIMIT = 5;
12
- const RELATED_RECORD_LIMIT = 5;
13
- const SUMMARY_TEXT_LIMIT = 400;
14
- const TERMINAL_WORK_ITEM_STATUSES = new Set([
15
- "completed",
16
- "failed",
17
- "retired"
18
- ]);
19
- export function runTaskContextCommand(args, store, currentTaskReviewCandidate = null) {
20
- if (args.length !== 1 || args[0]?.trim().length === 0) {
21
- throw usageError("Task context usage: yui task context <task>.");
22
- }
23
- const taskId = args[0].trim();
24
- const now = new Date();
25
- const data = store.transaction((reader) => {
26
- const task = reader.getTask(taskId);
27
- if (task === null)
28
- throw taskNotFound(taskId);
29
- const workItems = reader.listWorkItems(task.id);
30
- const inputRequests = reader.listInputRequests(task.id);
31
- const roles = reader.listRoles(task.id);
32
- const execution = buildTaskExecutionProjection(reader, task.id, task, now);
33
- if (execution === null) {
34
- throw new Error(`Task execution projection disappeared: ${task.id}.`);
35
- }
36
- const roleSessionSets = reader.listRoleSessionSets(task.id);
37
- const coordinationMailboxes = [
38
- reader.getWorkMailbox({ kind: "task", taskId: task.id }),
39
- ...roles.map((role) => reader.getWorkMailbox({
40
- kind: "role",
41
- taskId: task.id,
42
- roleName: role.name
43
- }))
44
- ].filter((mailbox) => mailbox !== null);
45
- const events = reader.listEvents(task.id);
46
- const turns = chronological(operationalTaskRecords(reader.listTurns(task.id), events, "turn"));
47
- const reviewRounds = chronological(reader.listReviewRounds(task.id));
48
- const reviewConfig = reader.getReviewConfig();
49
- const changeSets = chronological(reader.listChangeSets(task.id));
50
- const integrations = chronological(reader.listIntegrationAttempts(task.id));
51
- const publications = chronological(reader.listPublicationReferences(task.id));
52
- const remoteDelivery = projectTaskRemoteDeliveryFromStore(reader, task, currentTaskReviewCandidate);
53
- const nextActionFacts = reader.readNextActionFacts(task.id);
54
- if (nextActionFacts === null) {
55
- throw new Error(`Task next-action facts disappeared: ${task.id}.`);
1
+ import { usageError } from "../errors/cliError.js";
2
+ import { inspectTaskContext, readTaskContext, readTaskContextDelta } from "../context/taskContext.js";
3
+ /** CLI parsing only; typed callers and capability ingress share the read model. */
4
+ export function runTaskContextCommand(args, store, environment = {}) {
5
+ const explicit = ["read", "delta", "inspect"].includes(args[0] ?? "");
6
+ const action = explicit ? args[0] : "read";
7
+ const taskId = args[explicit ? 1 : 0];
8
+ if (!taskId || taskId.startsWith("--"))
9
+ throw usageError("Task context usage: yui task context [read|delta|inspect] <task> [--after <cursor>] [--continuation <cursor>] [--limit <1..100>] [--store <store> --ref <id> --digest <digest>].");
10
+ const options = new Map();
11
+ const rest = args.slice(explicit ? 2 : 1);
12
+ const allowed = action === "read" ? [] : action === "delta"
13
+ ? ["--after", "--continuation", "--limit"] : ["--store", "--ref", "--digest"];
14
+ for (let i = 0; i < rest.length; i += 2) {
15
+ const flag = rest[i];
16
+ const value = rest[i + 1];
17
+ if (!allowed.includes(flag) || options.has(flag) || value === undefined || value.startsWith("--")) {
18
+ throw usageError(`Invalid Context option: ${flag}.`);
56
19
  }
57
- return {
58
- task,
59
- execution,
60
- reviewConfig,
61
- reviewDecision: projectReviewDecision({
62
- store: reader,
63
- task,
64
- roles,
65
- turns,
66
- rounds: reviewRounds,
67
- reviewConfig,
68
- currentCandidate: currentTaskReviewCandidate
69
- }),
70
- brief: reader.getTaskBrief(task.id),
71
- activeDecisions: reader.listDecisions(task.id)
72
- .filter((decision) => decision.status === "active"),
73
- milestones: reader.listMilestones(task.id),
74
- roles,
75
- managedWorkspaces: reader.listManagedWorkspaces(task.id),
76
- roleSessionSets,
77
- coordinationMailboxes,
78
- workItems,
79
- turns,
80
- reviewRounds,
81
- changeSets,
82
- integrations,
83
- publications,
84
- remoteDelivery,
85
- messages: operationalTaskRecords(reader.listMessages(task.id), events, "message"),
86
- openInputRequests: inputRequests.filter((request) => request.status === "open"),
87
- resolvedInputRequests: inputRequests.filter((request) => request.status !== "open"),
88
- events,
89
- nextAction: projectNextAction({
90
- ...nextActionFacts,
91
- currentTaskReviewCandidate,
92
- executionGroups: execution.executionGroups
93
- })
94
- };
95
- });
96
- const { task, execution, reviewConfig, reviewDecision, brief, activeDecisions, milestones, roles, managedWorkspaces, roleSessionSets, coordinationMailboxes, workItems, turns, reviewRounds, changeSets, integrations, publications, remoteDelivery, messages, openInputRequests, resolvedInputRequests, events, nextAction } = data;
97
- const timeZone = store.getConfig().timeZone;
98
- const displayedActiveDecisions = activeDecisions.slice(-RECENT_RECORD_LIMIT);
99
- const displayedWorkItems = currentAndRecentWorkItems(workItems);
100
- const currentWorkItems = workItems.filter(({ status }) => status !== "retired");
101
- const displayedOpenInputRequests = openInputRequests.slice(-RECENT_RECORD_LIMIT);
102
- const displayedResolvedInputRequests = resolvedInputRequests.slice(-RECENT_RECORD_LIMIT);
103
- const displayedActiveTurns = execution.activeTurns;
104
- const executionGroupsById = new Map(execution.executionGroups.map((group) => [
105
- group.groupId,
106
- group
107
- ]));
108
- const observability = execution.observability;
109
- const lines = [
110
- `Task context: ${task.id}`,
111
- `Title: ${compactText(task.title)}`,
112
- `Status: ${task.status}`,
113
- "Next action:",
114
- ` ${nextAction.kind}: ${nextAction.reason}`,
115
- ...(nextAction.refs.length === 0
116
- ? []
117
- : [` Refs: ${nextAction.refs.map(({ kind, id }) => `${kind} ${id}`).join(", ")}`]),
118
- ...(nextAction.recommendedCommand === undefined
119
- ? []
120
- : [` Recommended: ${nextAction.recommendedCommand}`]),
121
- ...(nextAction.judgmentRequired === undefined
122
- ? []
123
- : [` Judgment: ${nextAction.judgmentRequired}`]),
124
- ...(nextAction.alternatives === undefined || nextAction.alternatives.length === 0
125
- ? []
126
- : [
127
- " Alternatives:",
128
- ...nextAction.alternatives.map((alternative) => ` ${alternative.kind}: ${alternative.reason}`)
129
- ]),
130
- ...(task.description === undefined ? [] : [`Description: ${compactText(task.description)}`]),
131
- ...(task.priority === undefined ? [] : [`Priority: ${task.priority}`]),
132
- ...(task.tags === undefined ? [] : [`Tags: ${task.tags.join(", ")}`]),
133
- ...(task.dueAt === undefined ? [] : [`Due: ${formatTimestamp(task.dueAt, timeZone)}`]),
134
- ...(task.completionSummary === undefined ? [] : [`Completion summary: ${task.completionSummary}`]),
135
- ...(task.retirementSummary === undefined ? [] : [`Retirement summary: ${task.retirementSummary}`]),
136
- ...(task.replacementTaskId === undefined ? [] : [`Replacement Task: ${task.replacementTaskId}`]),
137
- ...(task.archiveSummary === undefined ? [] : [`Archive summary: ${task.archiveSummary}`]),
138
- renderTaskRemoteDelivery(remoteDelivery).trimEnd(),
139
- "Execution:",
140
- ` Status: ${execution.status}`,
141
- ` Owner/action: ${execution.owner}/${execution.action}`,
142
- ` Monitoring: ${execution.monitoring}`,
143
- ` Fail-closed: ${execution.failClosed ? "yes" : "no"}`,
144
- ` Reason: ${execution.reason}`,
145
- ` Attention: ${execution.attention.length === 0
146
- ? "none"
147
- : execution.attention.map(({ kind, owner }) => `${kind}/${owner}`).join(", ")}`,
148
- ` Active Turns (${displayedActiveTurns.length}):`,
149
- ...(displayedActiveTurns.length === 0
150
- ? [" None."]
151
- : displayedActiveTurns.map((run) => (` ${run.roleName}: ${run.id} [${run.status}/${run.purpose}; ${`provider-${run.providerSession}`}${run.workItemId === undefined ? "" : `; work-item=${run.workItemId}`}${run.reviewRoundId === undefined ? "" : `; review-round=${run.reviewRoundId}`}${run.executionGroupId === undefined ? "" : `; group=${run.executionGroupId}`}${run.executionLaneId === undefined ? "" : `; lane=${run.executionLaneId}`}]`))),
152
- "Observability:",
153
- ` DAG: ${observability.dag.nodes.length} node(s), ${observability.dag.edges.length} edge(s); ready=${observability.dag.readyIds.join(", ") || "none"}; blocked=${observability.dag.blockedIds.join(", ") || "none"}`,
154
- ` Cost: tokens=${resourceUsageLabel(observability.cost.tokens, undefined, observability.cost.tokensObservable)}; tools=${resourceUsageLabel(observability.cost.toolCalls, undefined, observability.cost.toolCallsObservable)}; wall=${observability.cost.wallClockSeconds}s; lanes=${observability.cost.laneCount}; groups=${observability.cost.groupCount}; retries=${observability.cost.retryCount}; marginal-value=unavailable`,
155
- ` Context: snapshots=${observability.context.snapshotCount}; bytes=${observability.context.totalBytes === null ? "partial" : observability.context.totalBytes}; compression=unavailable`,
156
- " Session tokens:",
157
- ...(observability.sessionTokens.length === 0
158
- ? [" unobserved"]
159
- : observability.sessionTokens.map(({ roleName, agentId, metrics }) => {
160
- const total = metrics.cumulativeTotal.status === "observed"
161
- ? metrics.cumulativeTotal.totalTokens
162
- : "unobserved";
163
- const maximum = metrics.maximumRequestInput.status === "observed"
164
- ? metrics.maximumRequestInput.inputTokens
165
- : "unobserved";
166
- return ` ${roleName}/${agentId}: total=${total}; max-request-input=${maximum}`;
167
- })),
168
- ...(task.projectBindings.length === 0
169
- ? []
170
- : [
171
- "Projects:",
172
- ...task.projectBindings.map((binding) => (`- ${binding.directory}: ${binding.projectId} @ ${binding.baseRef}`))
173
- ]),
174
- ...(task.cwd === undefined ? [] : [`Workspace: ${task.cwd}`]),
175
- `Managed Workspaces (${managedWorkspaces.length}):`,
176
- ...(managedWorkspaces.length === 0
177
- ? [" None."]
178
- : managedWorkspaces.map((workspace) => (` ${managedWorkspaceLabel(workspace)}: ${workspace.root} (${workspace.entries.filter(({ access }) => access === "write").length} writable / ${workspace.entries.length} Projects)`))),
179
- `Type: ${task.type ?? "unspecified"}`,
180
- `Execution topology: ${currentWorkItems.length === 0
181
- ? "Leader-owned Task main"
182
- : `${currentWorkItems.length} independently owned WorkItem(s), integrated on Task main`}`,
183
- `Completion evidence: ${task.projectBindings.length === 0
184
- ? "no Project evidence required"
185
- : currentWorkItems.length === 0
186
- ? "clean committed Task main required"
187
- : "each delivered WorkItem requires a ChangeSet and committed Integration"}`,
188
- `Global review: ${reviewConfig === null
189
- ? "disabled"
190
- : `${reviewConfig.roleName} (${reviewConfig.trigger})`}`,
191
- "Review decision support:",
192
- ` Current durable heads: ${reviewDecision.currentCandidate?.projects
193
- .map(({ projectId, commit }) => `${projectId}@${commit.slice(0, 12)}`).join(", ")
194
- ?? "unavailable"}`,
195
- " Active Reviews:",
196
- ...(reviewDecision.activeReviews.length === 0
197
- ? [" - none"]
198
- : reviewDecision.activeReviews.map((review) => (` - ${review.reviewRoundId}/${review.reviewerRoleName}/${review.mode}`
199
- + ` [${review.status}; current=${review.candidateRelation}]`
200
- + ` heads=${review.frozenCandidate?.projects.map(({ projectId, commit }) => (`${projectId}@${commit.slice(0, 12)}`)).join(", ") ?? "unavailable"}`
201
- + `${review.workspaceRoot === undefined
202
- ? ""
203
- : ` workspace=${review.workspaceRoot}`}`))),
204
- ` Reviewer slots: ${reviewDecision.reviewers.length === 0
205
- ? "none configured"
206
- : reviewDecision.reviewers.map((reviewer) => (`${reviewer.reviewerRoleName}=${reviewer.status}`
207
- + `${reviewer.activeTurnId === undefined ? "" : `(${reviewer.activeTurnId})`}`)).join(", ")}`,
208
- ` Accepted baseline: ${reviewDecision.latestAcceptedBaseline === null
209
- ? "none"
210
- : `${reviewDecision.latestAcceptedBaseline.reviewRoundId}`
211
- + ` [${reviewDecision.latestAcceptedBaseline.relationToCurrent}]`}`,
212
- ` Delta: ${reviewDecision.delta.technicalAvailability}; ${reviewDecision.delta.reason}`,
213
- "",
214
- "Brief:",
215
- ...(brief === null
216
- ? [" No brief."]
217
- : [
218
- ` Objective: ${compactText(brief.objective)}`,
219
- " Boundaries:",
220
- ...(brief.boundaries.length === 0
221
- ? [" None."]
222
- : brief.boundaries.map((boundary) => ` - ${compactText(boundary)}`)),
223
- ` Technical approach: ${brief.technicalApproach.length === 0
224
- ? "Not defined."
225
- : compactText(brief.technicalApproach)}`,
226
- ` Current focus: ${compactText(brief.currentFocus)}`,
227
- ` Leader summary: ${compactText(brief.leaderSummary)}`,
228
- ` Updated by ${brief.updatedBy} at ${formatTimestamp(brief.updatedAt, timeZone)}`
229
- ]),
230
- "",
231
- `Active decisions (${displayedActiveDecisions.length}${activeDecisions.length > displayedActiveDecisions.length ? ` of ${activeDecisions.length}` : ""}):`,
232
- ...(displayedActiveDecisions.length === 0
233
- ? [" None."]
234
- : displayedActiveDecisions.flatMap((decision) => [
235
- ` ${decision.id}: ${compactText(decision.title)}`,
236
- ` Rationale: ${compactText(decision.rationale)}`
237
- ])),
238
- "",
239
- ...recentSection("milestones", milestones, (milestone) => [
240
- ` ${milestone.id}: ${compactText(milestone.title)} (${formatTimestamp(milestone.createdAt, timeZone)})`,
241
- ` ${compactText(milestone.summary)}`
242
- ]),
243
- "",
244
- `Task Roles (${roles.length}):`,
245
- ...(roles.length === 0
246
- ? [" None."]
247
- : roles.flatMap((role) => {
248
- const binding = role.agentBindings[role.activeAgentId];
249
- const activeTurn = turns.find((run) => (run.roleName === role.name && run.status === "active"));
250
- const sessions = roleSessionSets.find((set) => set.owner.roleName === role.name);
251
- const activeSession = sessions?.sessions[sessions.activeAgentId];
252
- const effective = activeTurn?.effective ?? activeSession?.effective;
253
- const effectiveSource = activeTurn === undefined ? "Session" : "Turn";
254
- const creation = [...events].reverse().find((event) => (event.type === "role.added" && event.payload.role === role.name));
255
- return [
256
- ` ${role.name} [${activeTurn === undefined ? "idle" : "running"}]: ${role.activeAgentId}/${binding.adapterId}`,
257
- ` Desired: r${role.launchRevision}; Profile intent: ${role.defaultAccess}; Model: ${binding.config.model ?? "default"}; effort: ${binding.config.effort ?? "default"}; permission: ${binding.config.permission.strategy}`,
258
- ` Effective: ${effective === undefined
259
- ? "not started"
260
- : `${effectiveSource} ${effective.agentId}/${effective.adapterId}; r${effective.sourceDesiredRevision}; Profile intent: ${effective.profileAccess}; permission: ${effective.permission.strategy}`}`,
261
- ` Desired drift: ${effective === undefined
262
- ? "-"
263
- : effective.sourceDesiredRevision === role.launchRevision
264
- ? "none"
265
- : "pending next launch"}`,
266
- ...(creation?.payload.runtimeSource === undefined
267
- ? []
268
- : [` Runtime source at creation: ${creation.payload.runtimeSource}`])
269
- ];
270
- })),
271
- "",
272
- `Coordination mailboxes (${coordinationMailboxes.length}):`,
273
- ...(coordinationMailboxes.length === 0
274
- ? [" None."]
275
- : coordinationMailboxes.flatMap(renderCoordinationMailbox)),
276
- "",
277
- `Current and recent work items (${displayedWorkItems.length}${workItems.length > displayedWorkItems.length ? ` of ${workItems.length}` : ""}):`,
278
- ...(displayedWorkItems.length === 0
279
- ? [" None."]
280
- : displayedWorkItems.flatMap((item) => {
281
- const itemRuns = turns.filter((run) => run.workItemId === item.id);
282
- const latestTurn = itemRuns.at(-1);
283
- return [
284
- ` ${item.id} [${item.status}]: ${compactText(item.title)}`,
285
- ` Objective: ${compactText(item.objective)}`,
286
- ` Writable Projects: ${item.writeProjectIds.length === 0
287
- ? "none"
288
- : item.writeProjectIds.join(", ")}`,
289
- ...(observability.workItems.find(({ workItemId }) => workItemId === item.id) === undefined
290
- ? []
291
- : [renderWorkItemObservability(observability.workItems.find(({ workItemId }) => workItemId === item.id))]),
292
- ...renderWorkItemExecution(projectWorkItemExecution(item, turns, roleSessionSets)),
293
- ...(item.acceptance.length === 0
294
- ? []
295
- : [` Acceptance: ${item.acceptance.map(compactText).join("; ")}`]),
296
- ...(item.candidates.length === 0
297
- ? []
298
- : item.candidates.flatMap((candidate) => [
299
- ` Candidate ${candidate.sequence}: ${candidate.id}${item.status === "awaiting_acceptance" && candidate === item.candidates.at(-1) ? " [current]" : ""} (${candidate.source.type === "turn" ? candidate.source.turnId : "direct"})`,
300
- ` Review policy: ${candidate.reviewPolicy === undefined ? "none" : `${candidate.reviewPolicy.roleName} (${candidate.reviewPolicy.trigger})`}`,
301
- ` Task-final contract: ${candidate.taskFinalReviewContract === undefined
302
- ? "none"
303
- : `Reviewer ${candidate.taskFinalReviewContract.reviewerRoleName}`}`,
304
- ` Frozen Git: ${candidate.gitSnapshot === undefined
305
- ? "unavailable"
306
- : `${candidate.gitSnapshot.reviewBaseCommit} (${candidate.gitSnapshot.projects.length} Projects)`}`,
307
- ` Summary: ${compactText(candidate.summary)}`
308
- ])),
309
- ...(latestTurn === undefined
310
- ? [" Turns: none."]
311
- : [
312
- ` Turns: ${itemRuns.length}; latest ${latestTurn.id} [${latestTurn.status}] ${latestTurn.effective.agentId}/${latestTurn.effective.adapterId} · effective r${latestTurn.effective.sourceDesiredRevision}/${latestTurn.effective.profileAccess}/${latestTurn.effective.permission.strategy}`,
313
- ` Assignment: ${latestTurn.inputs[0].input.source.channel}${latestTurn.inputs[0].input.directive === undefined ? "" : ` · ${compactText(latestTurn.inputs[0].input.directive)}`}`,
314
- ...(latestTurn.result?.output === undefined
315
- ? []
316
- : [` Result: ${compactText(latestTurn.result.output)}`]),
317
- ...(latestTurn.result?.diagnostic === undefined
318
- ? []
319
- : [` Failure: ${compactText(latestTurn.result.diagnostic)}`])
320
- ]),
321
- ...renderReviewRounds(reviewRounds.filter((round) => round.workItemId === item.id), executionGroupsById)
322
- ];
323
- })),
324
- "",
325
- "Task-final reviews:",
326
- ...renderReviewRounds(reviewRounds.filter((round) => (round.scope ?? "work-item") === "task"), executionGroupsById),
327
- "",
328
- ...recentSection("Turns", turns, (run) => [
329
- ` ${run.id} [${run.status}/${run.purpose}] ${run.roleName} via ${run.effective.agentId}/${run.effective.adapterId}`,
330
- ` Effective: r${run.effective.sourceDesiredRevision}; Profile intent: ${run.effective.profileAccess}; permission: ${run.effective.permission.strategy}; model: ${run.effective.model ?? "default"}; effort: ${run.effective.effort ?? "default"}`,
331
- ...(run.result?.output === undefined ? [] : [` Result: ${compactText(run.result.output)}`]),
332
- ...(run.result?.diagnostic === undefined
333
- ? []
334
- : [` Failure: ${compactText(run.result.diagnostic)}`])
335
- ]),
336
- "",
337
- "Runtime health:",
338
- ...(() => {
339
- const stalled = turns.filter((run) => (run.status === "active" && isRoleTurnStalled(events, run.id)));
340
- return stalled.length === 0
341
- ? [" No needs-attention Turns."]
342
- : stalled.flatMap((run) => [
343
- ` ${run.id} [needs-attention] ${run.roleName}`,
344
- ` Durable progress: ${formatTimestamp(latestStallProgressAt(events, run.id) ?? run.updatedAt, timeZone)}`,
345
- ` Cause: ${latestStallKind(events, run.id)} with no new semantic Turn evidence in the stall window`,
346
- " Next: inspect Task context/Role status; no automatic retry or Session replacement was performed."
347
- ]);
348
- })(),
349
- "",
350
- `ChangeSets (${changeSets.length}):`,
351
- ...(changeSets.length === 0
352
- ? [" None."]
353
- : changeSets.slice(-RECENT_RECORD_LIMIT).map((changeSet) => (` ${changeSet.id} [${changeSet.projectId}]: ${changeSet.baseCommit.slice(0, 12)}..${changeSet.headCommit.slice(0, 12)} (${changeSet.changedPaths.length} paths; WorkItem ${changeSet.workItemId})`))),
354
- "",
355
- `Integration Attempts (${integrations.length}):`,
356
- ...(integrations.length === 0
357
- ? [" None."]
358
- : integrations.slice(-RECENT_RECORD_LIMIT).map((integration) => (` ${integration.id} [${integration.status}/${integration.projectId}] — ${integration.targetRef}; ${integration.source.kind === "work-item"
359
- ? `WorkItem ${integration.source.workItemId}@${integration.source.resultCommit.slice(0, 12)}`
360
- : integration.source.kind === "upstream"
361
- ? `upstream ${integration.source.branch}@${integration.source.remoteCommit.slice(0, 12)}`
362
- : `historical ChangeSets ${integration.source.changeSetIds.join(", ")}`}`))),
363
- "",
364
- `Publication references (${publications.length}):`,
365
- ...(publications.length === 0
366
- ? [" None."]
367
- : publications.slice(-RECENT_RECORD_LIMIT).map((reference) => [
368
- ` ${reference.id}: ${reference.provider}/${reference.repository}/${reference.externalId}`,
369
- ...(reference.title === undefined ? [] : [` Title: ${reference.title}`]),
370
- ...(reference.sourceBranch === undefined && reference.targetBranch === undefined
371
- ? []
372
- : [` Branches: ${reference.sourceBranch ?? "unknown"} -> ${reference.targetBranch ?? "unknown"}`]),
373
- ` ${reference.state}/${reference.verification}; ${reference.localCommit ?? "unknown"} -> ${reference.remoteCommit ?? "unknown"}`,
374
- ...(reference.mergedAt === undefined
375
- ? []
376
- : [` Merged: ${formatTimestamp(reference.mergedAt, timeZone)}`]),
377
- ...(reference.supersedes === undefined
378
- ? []
379
- : [` Supersedes: ${reference.supersedes}`])
380
- ]).flat()),
381
- "",
382
- ...recentSection("messages", messages, (message) => [
383
- ` ${message.id} [${taskMessageAuthorLabel(message.author)}] ${formatTimestamp(message.createdAt, timeZone)}`,
384
- ` ${compactText(message.body)}`
385
- ]),
386
- "",
387
- `Open input requests (${displayedOpenInputRequests.length}${openInputRequests.length > displayedOpenInputRequests.length ? ` of ${openInputRequests.length}` : ""}):`,
388
- ...(displayedOpenInputRequests.length === 0
389
- ? [" None."]
390
- : displayedOpenInputRequests.flatMap((request) => renderOpenInputRequest(request, timeZone))),
391
- "",
392
- `Recent resolved input requests (${displayedResolvedInputRequests.length}${resolvedInputRequests.length > displayedResolvedInputRequests.length ? ` of ${resolvedInputRequests.length}` : ""}):`,
393
- ...(displayedResolvedInputRequests.length === 0
394
- ? [" None."]
395
- : displayedResolvedInputRequests.flatMap((request) => renderResolvedInputRequest(request, timeZone))),
396
- "",
397
- ...recentSection("events", events, (event) => [
398
- ` ${event.id} ${event.type} (${formatTimestamp(event.createdAt, timeZone)})`,
399
- ...(Object.keys(event.payload).length === 0
400
- ? []
401
- : [` ${Object.entries(event.payload)
402
- .map(([key, value]) => `${key}=${compactText(value)}`)
403
- .join(", ")}`])
404
- ])
405
- ];
406
- return {
407
- kind: "output",
408
- output: `${lines.join("\n")}\n`,
409
- data
410
- };
411
- }
412
- function renderCoordinationMailbox(mailbox) {
413
- const target = mailbox.target.kind === "role"
414
- ? `role/${mailbox.target.roleName}`
415
- : mailbox.target.kind;
416
- const pending = mailbox.pending === null ? [] : [mailbox.pending];
417
- return [
418
- ` ${target}: next=${mailbox.nextSequence}`,
419
- ` Processing: ${mailbox.processing?.batchId ?? "none"}; pending batches: ${pending.length}`,
420
- ...pending.map((batch) => (` Pending ${batch.fromSequence}-${batch.toSequence}: ${batch.reasons.join(", ")} · refs ${batch.refs.map((ref) => `${ref.type}:${ref.id}`).join(", ") || "none"}`))
421
- ];
422
- }
423
- function latestStallKind(events, turnId) {
424
- const event = [...events]
425
- .filter((candidate) => candidate.type === "turn.stalled"
426
- && candidate.payload.turnId === turnId
427
- && candidate.payload.status !== "diagnostic-only")
428
- .sort((left, right) => Date.parse(right.createdAt) - Date.parse(left.createdAt))[0];
429
- return event?.payload.kind ?? "workflow-not-progressing";
430
- }
431
- function renderReviewRounds(rounds, executionGroupsById = new Map()) {
432
- const latest = rounds.at(-1);
433
- if (latest === undefined)
434
- return [" ReviewRounds: none."];
435
- const target = (latest.scope ?? "work-item") === "task"
436
- ? "frozen Task candidate"
437
- : `Candidate ${latest.candidateId ?? "unavailable"}`;
438
- return [
439
- ` ReviewRounds: ${rounds.length}; latest ${latest.id} [${latest.status}] ${latest.scope === "task" ? "Task-final" : "WorkItem"} for ${target} via ${latest.reviewerRoleName} (${latest.requestedBy})`,
440
- ` Review base: ${latest.reviewBaseCommit}`,
441
- ...(latest.scope === "task"
442
- ? [
443
- ` Frozen Task heads: ${latest.taskCandidate?.projects
444
- .map(({ projectId, commit }) => `${projectId}@${commit}`).join(", ") ?? "unavailable"}`,
445
- ` Task-final contract: ${latest.taskFinalReviewContract === undefined
446
- ? "global policy"
447
- : `Reviewer ${latest.taskFinalReviewContract.reviewerRoleName}`}`,
448
- ...(latest.deltaRecheck === undefined
449
- ? [` Review mode: full`]
450
- : [
451
- ` Review mode: delta-recheck (rechecks ${latest.deltaRecheck.previousReviewRoundId}@${latest.deltaRecheck.previousBaseCommit.slice(0, 12)})`,
452
- ` Delta: ${latest.deltaRecheck.changedFiles.length} file(s), +${latest.deltaRecheck.addedLines}/-${latest.deltaRecheck.deletedLines}, digest ${latest.deltaRecheck.diffDigest.slice(0, 12)}`
453
- ])
454
- ]
455
- : []),
456
- ` Review workspace: ${latest.workspace === undefined
457
- ? "not prepared"
458
- : `${latest.workspace.root} (${latest.workspace.entries.length} writable Projects)`}`,
459
- ` Workspace disposition: ${latest.workspaceDisposition?.kind ?? "pending"}`,
460
- ` Main Reviewer Turn: ${latest.reviewerTurnId ?? "not dispatched"}`,
461
- ...(latest.failure === undefined
462
- ? []
463
- : [` Core failure: ${latest.failure.kind} · ${compactText(latest.failure.message)}`]),
464
- ...(latest.executionGroup === undefined
465
- ? []
466
- : [
467
- ` Execution shape: replicated`,
468
- ` Execution Group: ${latest.executionGroup.id}`,
469
- ...latest.executionGroup.lanes.map((lane) => (` Producer ${lane.id} (#${lane.ordinal}, ${lane.roleName}): `
470
- + `${lane.disposition}; turn=${lane.currentTurnId ?? "not dispatched"}`))
471
- ])
472
- ];
473
- }
474
- function renderResolvedInputRequest(request, timeZone) {
475
- if (request.status === "open")
476
- return [];
477
- return [
478
- ` ${request.id} [${request.status}]`,
479
- ` Question: ${compactText(request.question)}`,
480
- ...(request.status === "answered"
481
- ? [
482
- ` Answer: ${compactText(request.resolution.answer.text)}`,
483
- ` Answered by ${request.resolution.answeredBy} at ${formatTimestamp(request.resolution.answeredAt, timeZone)}`
484
- ]
485
- : [
486
- ` Cancelled: ${compactText(request.cancellation.reason)}`,
487
- ` Cancelled at: ${formatTimestamp(request.cancellation.cancelledAt, timeZone)}`
488
- ])
489
- ];
490
- }
491
- function renderOpenInputRequest(request, timeZone) {
492
- const choices = request.choices.slice(0, RELATED_RECORD_LIMIT);
493
- const blockedRefs = request.blockedRefs.slice(0, RELATED_RECORD_LIMIT);
494
- const recommendedChoiceKey = request.policy.kind === "recommended"
495
- ? request.policy.recommendedChoiceKey
496
- : undefined;
497
- const recommendedChoice = recommendedChoiceKey === undefined
498
- ? undefined
499
- : request.choices.find((choice) => choice.key === recommendedChoiceKey);
500
- return [
501
- ` ${request.id} [${request.policy.kind}]`,
502
- ` Question: ${compactText(request.question)}`,
503
- ...(request.choices.length === 0
504
- ? [" Choices: none (free-text answer)."]
505
- : [
506
- ` Choices (${choices.length}${request.choices.length > choices.length ? ` of ${request.choices.length}` : ""}):`,
507
- ...choices.map((choice) => ` ${choice.key}: ${compactText(choice.label)}`)
508
- ]),
509
- ...(request.policy.kind === "recommended"
510
- ? [
511
- ` Recommended choice: ${request.policy.recommendedChoiceKey}: ${compactText(recommendedChoice?.label ?? request.policy.recommendedChoiceKey)}`,
512
- ` Timeout at: ${formatTimestamp(request.policy.timeoutAt, timeZone)}`
513
- ]
514
- : []),
515
- ...(request.blockedRefs.length === 0
516
- ? [" Blocks: none."]
517
- : [
518
- ` Blocks (${blockedRefs.length}${request.blockedRefs.length > blockedRefs.length ? ` of ${request.blockedRefs.length}` : ""}):`,
519
- ...blockedRefs.map((reference) => ` ${reference.type}:${reference.id}`)
520
- ])
521
- ];
522
- }
523
- function recentSection(label, records, render) {
524
- const recent = records.slice(-RECENT_RECORD_LIMIT);
525
- const title = `Recent ${label} (${recent.length}${records.length > recent.length ? ` of ${records.length}` : ""}):`;
526
- return recent.length === 0
527
- ? [title, " None."]
528
- : [title, ...recent.flatMap(render)];
529
- }
530
- function currentAndRecentWorkItems(records) {
531
- const current = records.filter((record) => !TERMINAL_WORK_ITEM_STATUSES.has(record.status));
532
- if (current.length >= RECENT_RECORD_LIMIT)
533
- return current;
534
- const recentTerminal = records
535
- .filter((record) => TERMINAL_WORK_ITEM_STATUSES.has(record.status))
536
- .slice(-(RECENT_RECORD_LIMIT - current.length));
537
- const selected = new Set([...current, ...recentTerminal]);
538
- return records.filter((record) => selected.has(record));
539
- }
540
- function chronological(records) {
541
- return [...records].sort((left, right) => (Date.parse(left.createdAt) - Date.parse(right.createdAt)
542
- || left.id.localeCompare(right.id)));
543
- }
544
- function compactText(value) {
545
- const oneLine = value.replace(/\s+/g, " ").trim();
546
- return oneLine.length <= SUMMARY_TEXT_LIMIT
547
- ? oneLine
548
- : `${oneLine.slice(0, SUMMARY_TEXT_LIMIT - 3)}...`;
549
- }
550
- function managedWorkspaceLabel(workspace) {
551
- switch (workspace.owner.type) {
552
- case "task":
553
- return "task";
554
- case "work-item":
555
- return `work-item ${workspace.owner.workItemId}`;
556
- case "review-round":
557
- return `review-round ${workspace.owner.reviewRoundId}`;
558
- case "integration-attempt":
559
- return `integration-attempt ${workspace.owner.integrationAttemptId}`;
560
- case "execution-lane":
561
- return `execution-lane ${workspace.owner.executionGroupId}/${workspace.owner.executionLaneId}`;
20
+ options.set(flag, value);
562
21
  }
563
- }
564
- function renderWorkItemExecution(projection) {
565
- return [
566
- ` WorkItem execution [${projection.shape}]${projection.groupId === undefined ? "" : `: ${projection.groupId}`}`,
567
- ...projection.lanes.map((lane) => (` Lane ${lane.laneId} (#${lane.ordinal}, ${lane.roleName}) [${lane.status}]: `
568
- + `turn=${lane.currentTurnId ?? "unknown"}; session=${lane.session}; `
569
- + `retry=${lane.retryTurnId ?? "none"}; settle=${lane.settleTurnId ?? "none"}`)),
570
- ` Synthesis: ${projection.synthesis.status} (${projection.synthesis.successfulLaneCount}/${projection.synthesis.requiredSuccessfulLaneCount} successful)`,
571
- ` Main Turn: ${projection.mainTurn.turnId ?? "unobserved"} [${projection.mainTurn.status}]; session=${projection.mainTurn.session}`,
572
- ` Candidate source: ${projection.candidate.candidateId ?? "none"} [${projection.candidate.status}]; main=${projection.candidate.mainTurnId ?? "unobserved"}`,
573
- ...(projection.candidate.sourceExecutionGroupId === undefined
574
- ? []
575
- : [` Provenance: ${projection.candidate.mainTurnId ?? "unobserved"} -> ${projection.candidate.sourceExecutionGroupId} -> ${projection.candidate.successfulLaneTurns.map(({ laneId, successfulTurnId }) => `${laneId} -> ${successfulTurnId}`).join(", ") || "unobserved"}`]),
576
- ` Next: ${projection.nextAction.kind}; owner=${projection.nextAction.owners.join(", ") || "none"}; target=${projection.nextAction.targetIds.join(", ") || "none"}`
577
- ];
578
- }
579
- function resourceUsageLabel(used, remaining, observable) {
580
- if (!observable)
581
- return `${used} observed (partial)`;
582
- return `${used}${remaining === undefined ? "" : `, remaining=${remaining}`}`;
583
- }
584
- function renderWorkItemObservability(item) {
585
- return ` Observability (read-only): tokens=${item.cost.tokensObservable ? item.cost.tokens : "unobserved"}; tools=${item.cost.toolCallsObservable ? item.cost.toolCalls : "unobserved"}; wall=${item.cost.wallClockSeconds}s; retries=${item.cost.retryCount}; snapshots=${item.context.snapshotCount}; agent-results=${item.resultCount ?? "unobserved"}; compression=${item.context.compressionStatus}`;
22
+ let data;
23
+ if (action === "read")
24
+ data = readTaskContext(store, taskId, environment);
25
+ else if (action === "delta") {
26
+ const after = options.get("--after");
27
+ if (after === undefined)
28
+ throw usageError("Context delta requires --after from a previous read.");
29
+ data = readTaskContextDelta(store, taskId, {
30
+ after, continuation: options.get("--continuation"),
31
+ ...(options.has("--limit") ? { limit: Number(options.get("--limit")) } : {})
32
+ }, environment);
33
+ }
34
+ else {
35
+ const family = options.get("--store");
36
+ const refId = options.get("--ref");
37
+ if (family === undefined || refId === undefined)
38
+ throw usageError("Context inspect requires --store and --ref.");
39
+ data = inspectTaskContext(store, taskId, { store: family, refId, digest: options.get("--digest") }, environment);
40
+ }
41
+ return { kind: "output", output: `${JSON.stringify(data, null, 2)}\n`, data };
586
42
  }