minicode-ai 0.11.1 → 0.13.1
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.
- package/CHANGELOG.md +95 -0
- package/LICENSE +21 -21
- package/README.md +4 -4
- package/cli/args.ts +46 -0
- package/cli/commands/acp.ts +163 -10
- package/cli/commands/config.ts +33 -18
- package/cli/commands/daemon.ts +515 -0
- package/cli/commands/exec.ts +145 -53
- package/cli/commands/openwork.ts +986 -0
- package/cli/commands/sessions.ts +4 -1
- package/cli/commands/stats.ts +34 -4
- package/cli/commands.ts +217 -2
- package/cli/index.ts +146 -14
- package/cli/minicode.js +6 -0
- package/cli/recovery-warning.ts +115 -0
- package/cli/router.ts +32 -1
- package/cli/setup.ts +2332 -171
- package/cli/tui.ts +113 -7
- package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
- package/docs/OUTPUT_EVENT_MODEL.md +289 -0
- package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
- package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
- package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
- package/docs/OUTPUT_UX_RULES.md +449 -0
- package/docs/PLAN_UIUX_V6.md +2 -2
- package/docs/README.md +4 -3
- package/docs/TERMINAL_CONTRACT.md +278 -71
- package/docs/architecture.md +89 -7
- package/docs/changelog.md +1 -1
- package/docs/choosing-mode.md +2 -2
- package/docs/cli.md +9 -5
- package/docs/concepts.md +1 -1
- package/docs/contributing.md +9 -2
- package/docs/environment.md +6 -2
- package/docs/exec.md +46 -5
- package/docs/memory-sessions.md +2 -0
- package/docs/policy-sandbox.md +1 -1
- package/docs/pricing-budget.md +1 -1
- package/docs/quickstart.md +2 -2
- package/docs/repl.md +6 -2
- package/docs/security-model.md +1 -1
- package/docs/security.md +1 -1
- package/docs/skills.md +2 -2
- package/docs/terminal.md +9 -5
- package/docs/tools.md +1 -1
- package/package.json +36 -6
- package/src/app/session.ts +261 -15
- package/src/app/tool-layer.ts +94 -7
- package/src/daemon/approvals.ts +361 -0
- package/src/daemon/capability.ts +145 -0
- package/src/daemon/children.ts +142 -0
- package/src/daemon/client.ts +267 -0
- package/src/daemon/control.ts +350 -0
- package/src/daemon/discovery.ts +234 -0
- package/src/daemon/feed.ts +155 -0
- package/src/daemon/framing.ts +94 -0
- package/src/daemon/host.ts +316 -0
- package/src/daemon/protocol.ts +217 -0
- package/src/daemon/resource.ts +170 -0
- package/src/daemon/sanitize.ts +57 -0
- package/src/daemon/server.ts +627 -0
- package/src/daemon/store.ts +317 -0
- package/src/daemon/subscription.ts +270 -0
- package/src/daemon/telemetry.ts +81 -0
- package/src/hooks/run.ts +12 -1
- package/src/lib/atomic-write.ts +29 -3
- package/src/lib/db-path.ts +26 -0
- package/src/lib/keystore.ts +544 -42
- package/src/lib/net.ts +43 -1
- package/src/lib/safe-open.ts +116 -1
- package/src/lib/session-id.ts +15 -0
- package/src/lsp/client.ts +123 -5
- package/src/mcp/client.ts +139 -17
- package/src/mcp/server.ts +177 -50
- package/src/mcp/transport.ts +16 -19
- package/src/memory/vector.ts +770 -55
- package/src/policy/allowlist.ts +14 -2
- package/src/policy/bash-guard.ts +105 -10
- package/src/policy/compaction.ts +82 -5
- package/src/policy/consequence-engine.ts +220 -0
- package/src/policy/context.ts +132 -0
- package/src/policy/executor.ts +187 -121
- package/src/policy/no-progress.ts +559 -0
- package/src/policy/permission.ts +4 -8
- package/src/policy/pricing.ts +17 -3
- package/src/policy/scrub.ts +69 -2
- package/src/policy/tool-contract.ts +515 -0
- package/src/policy/usage.ts +310 -24
- package/src/policy/verifier.ts +6 -3
- package/src/policy/work-mode.ts +182 -0
- package/src/presentation/adapter.ts +533 -26
- package/src/presentation/events.ts +151 -0
- package/src/presentation/model.ts +180 -27
- package/src/presentation/projection.ts +858 -0
- package/src/presentation/reducer.ts +645 -310
- package/src/presentation/store.ts +12 -7
- package/src/providers/anthropic.ts +18 -10
- package/src/providers/responses.ts +2 -2
- package/src/runtime/capability.ts +409 -0
- package/src/runtime/child-execution.ts +274 -0
- package/src/runtime/composition.ts +958 -0
- package/src/runtime/dispatch.ts +591 -0
- package/src/runtime/execution-backend.ts +632 -0
- package/src/runtime/execution-events.ts +272 -0
- package/src/runtime/execution-id.ts +230 -0
- package/src/runtime/execution-journal.ts +926 -0
- package/src/runtime/execution-kernel.ts +456 -0
- package/src/runtime/execution-registry.ts +379 -0
- package/src/runtime/process-supervision.ts +276 -0
- package/src/runtime/production-execution.ts +551 -0
- package/src/runtime/production-runtime.ts +217 -0
- package/src/runtime/recovery-safety.ts +70 -0
- package/src/runtime/recovery.ts +477 -0
- package/src/runtime/runtime-capabilities.ts +179 -0
- package/src/runtime/runtime-diagnostics.ts +141 -0
- package/src/runtime/runtime-host.ts +365 -0
- package/src/runtime/runtime-status-facts.ts +222 -0
- package/src/runtime/runtime-status-provider.ts +74 -0
- package/src/runtime/runtime-status.ts +459 -0
- package/src/runtime/runtime-task-admission.ts +101 -0
- package/src/runtime/supervisor.ts +444 -0
- package/src/session/authority.ts +168 -0
- package/src/session/checkpoint.ts +88 -1
- package/src/session/context-adapter.ts +251 -0
- package/src/session/context-assembly.ts +242 -0
- package/src/session/context-identity.ts +389 -0
- package/src/session/context-projection.ts +248 -0
- package/src/session/context-selector.ts +500 -0
- package/src/session/cross-session-adoption.ts +249 -0
- package/src/session/full-history-fold.ts +171 -0
- package/src/session/identity.ts +192 -0
- package/src/session/journal.ts +805 -102
- package/src/session/open-work-intent.ts +732 -0
- package/src/session/open-work.ts +767 -0
- package/src/session/pending-tools.ts +94 -0
- package/src/session/persistence.ts +3569 -127
- package/src/session/runtime-header.ts +208 -0
- package/src/session/shadow-git.ts +13 -5
- package/src/session/verification.ts +1623 -0
- package/src/task/assignment.ts +136 -0
- package/src/task/autonomous-adapter.ts +168 -0
- package/src/task/autonomous-context.ts +630 -0
- package/src/task/autonomous-policy.ts +490 -0
- package/src/task/continuity.ts +179 -0
- package/src/task/execution-cancellation.ts +165 -0
- package/src/task/graph-validate.ts +379 -0
- package/src/task/graph.ts +305 -0
- package/src/task/identity.ts +230 -0
- package/src/task/model.ts +417 -0
- package/src/task/production-scheduler.ts +293 -0
- package/src/task/readiness.ts +229 -0
- package/src/task/scheduler-observability.ts +387 -0
- package/src/task/scheduler.ts +1197 -0
- package/src/task/scheduling-policy.ts +165 -0
- package/src/task/session-authority.ts +148 -0
- package/src/task/session-ownership.ts +211 -0
- package/src/task/store.ts +2887 -0
- package/src/task/sync.ts +343 -0
- package/src/task/trigger.ts +260 -0
- package/src/tools/bash.ts +377 -211
- package/src/tools/code_run.ts +1 -1
- package/src/tools/delete_file.ts +1 -1
- package/src/tools/edit.ts +33 -6
- package/src/tools/evidence.ts +30 -0
- package/src/tools/git.ts +4 -4
- package/src/tools/glob.ts +12 -3
- package/src/tools/grep.ts +1 -1
- package/src/tools/lsp.ts +4 -4
- package/src/tools/mcp_call.ts +11 -4
- package/src/tools/memory.ts +153 -18
- package/src/tools/move_file.ts +1 -1
- package/src/tools/patch.ts +1 -1
- package/src/tools/read_file.ts +1 -1
- package/src/tools/read_image.ts +1 -1
- package/src/tools/submit_result.ts +1 -1
- package/src/tools/task.ts +437 -41
- package/src/tools/todo.ts +662 -35
- package/src/tools/web_fetch.ts +4 -2
- package/src/tools/web_search.ts +9 -3
- package/src/tools/write_file.ts +1 -1
- package/src/ui/assistant/simple.ts +123 -50
- package/src/ui/assistant/turn-status.ts +17 -3
- package/src/ui/contract.ts +184 -0
- package/src/ui/footer.ts +52 -19
- package/src/ui/i18n/en.ts +58 -6
- package/src/ui/i18n/id.ts +58 -6
- package/src/ui/input/prompt-engine.ts +120 -25
- package/src/ui/render/errors.ts +39 -1
- package/src/ui/render/markdown-table.ts +455 -0
- package/src/ui/render/markdown.ts +22 -1
- package/src/ui/render/table-grid.ts +184 -0
- package/src/ui/render/table.ts +15 -76
- package/src/ui/runtime/screen.ts +7 -2
- package/src/ui/runtime/statusline.ts +25 -6
- package/src/ui/tui/app.ts +507 -169
- package/src/ui/tui/transcript.ts +531 -89
- package/vendor/minicore/VENDOR.md +1 -1
- package/vendor/minicore/src/core/budget.ts +25 -25
- package/vendor/minicore/src/core/compact.ts +75 -75
- package/vendor/minicore/src/core/errors.ts +59 -59
- package/vendor/minicore/src/core/events.ts +73 -73
- package/vendor/minicore/src/core/executor.ts +139 -139
- package/vendor/minicore/src/core/history.ts +31 -31
- package/vendor/minicore/src/core/index.ts +41 -41
- package/vendor/minicore/src/core/loop.ts +355 -355
- package/vendor/minicore/src/core/permission.ts +22 -22
- package/vendor/minicore/src/core/provider.ts +39 -39
- package/vendor/minicore/src/core/recovery.ts +35 -35
- package/vendor/minicore/src/core/session.ts +327 -327
- package/vendor/minicore/src/core/snapshot.ts +146 -146
- package/vendor/minicore/src/core/tokens.ts +107 -107
- package/vendor/minicore/src/core/tool.ts +115 -115
- package/vendor/minicore/src/core/types.ts +50 -50
- package/vendor/minicore/src/providers/openai-compat.ts +417 -417
- package/AGENTS.md +0 -45
- package/PLAN.md +0 -491
- package/docs/ARCHITECTURE.html +0 -1248
- package/docs/CONTROL-PLANE-MAP.md +0 -139
- package/docs/HARNESS.md +0 -150
- package/docs/SUMMARY.md +0 -52
- package/docs/UI_RENDER_PIPELINE.md +0 -169
- package/docs/USAGE.md +0 -11
package/cli/setup.ts
CHANGED
|
@@ -3,24 +3,40 @@
|
|
|
3
3
|
import { readFileSync } from "node:fs"
|
|
4
4
|
import { resolve as resolvePath } from "node:path"
|
|
5
5
|
import type { Message, Session, Tool } from "#minicore"
|
|
6
|
+
import { AgentError } from "#minicore"
|
|
6
7
|
import { createProviderLayer } from "../src/app/provider-layer.ts"
|
|
7
8
|
import { createRagLayer } from "../src/app/rag-layer.ts"
|
|
8
|
-
import {
|
|
9
|
+
import {
|
|
10
|
+
createMinicodeSession,
|
|
11
|
+
type PermissionControl,
|
|
12
|
+
type WorkModeControl,
|
|
13
|
+
} from "../src/app/session.ts"
|
|
9
14
|
import { setupToolLayer } from "../src/app/tool-layer.ts"
|
|
10
15
|
import type { MinicodeConfig } from "../src/config.ts"
|
|
11
16
|
import { loadLastModel, localConfigNotice } from "../src/config.ts"
|
|
12
17
|
import { runRunHooks, shouldRunHooks } from "../src/hooks/run.ts"
|
|
13
18
|
import { homeDir } from "../src/lib/db-path.ts"
|
|
14
|
-
import { closeAllLsp as lspCloseAll } from "../src/lsp/client.ts"
|
|
19
|
+
import { closeAllLsp as lspCloseAll, setLspProcessSupervisor } from "../src/lsp/client.ts"
|
|
15
20
|
import { closeAll as mcpCloseAll } from "../src/mcp/client.ts"
|
|
16
|
-
import { addMemory } from "../src/memory/vector.ts"
|
|
21
|
+
import { addMemory, promoteOrRejectLessonsBySession } from "../src/memory/vector.ts"
|
|
17
22
|
import { createLlmCompaction } from "../src/policy/compaction.ts"
|
|
23
|
+
import {
|
|
24
|
+
type AceFailureType,
|
|
25
|
+
type ConsequenceDecision,
|
|
26
|
+
evaluateConsequence,
|
|
27
|
+
isAceEnabled,
|
|
28
|
+
} from "../src/policy/consequence-engine.ts"
|
|
29
|
+
import type { NoProgressDetector } from "../src/policy/no-progress.ts"
|
|
30
|
+
import type { PermissionAsk } from "../src/policy/permission.ts"
|
|
18
31
|
import type { RateLimiter } from "../src/policy/ratelimit.ts"
|
|
19
32
|
import {
|
|
20
33
|
budgetExceededError,
|
|
21
34
|
createUsageCollector,
|
|
35
|
+
maxTurnsExceededError,
|
|
22
36
|
primePricing,
|
|
37
|
+
type UsageInitialSnapshot,
|
|
23
38
|
watchBudgetLimit,
|
|
39
|
+
watchContextWindowLimit,
|
|
24
40
|
} from "../src/policy/usage.ts"
|
|
25
41
|
import {
|
|
26
42
|
buildBaselineNote,
|
|
@@ -32,11 +48,20 @@ import {
|
|
|
32
48
|
runWithSelfHeal,
|
|
33
49
|
} from "../src/policy/verifier.ts"
|
|
34
50
|
import { createPresentationAdapter, type PresentationAdapter } from "../src/presentation/adapter.ts"
|
|
35
|
-
import type
|
|
51
|
+
import { type DomainEvent, DURABILITY } from "../src/presentation/events.ts"
|
|
36
52
|
import { createInitialState, type PresentationState } from "../src/presentation/model.ts"
|
|
53
|
+
import {
|
|
54
|
+
describeActivity,
|
|
55
|
+
elapsedVisible,
|
|
56
|
+
matchTurnBySummary,
|
|
57
|
+
pendingVerificationObservation,
|
|
58
|
+
projectProvenance,
|
|
59
|
+
} from "../src/presentation/projection.ts"
|
|
37
60
|
import {
|
|
38
61
|
createReducerDiagnostics,
|
|
62
|
+
deriveTurnSummary,
|
|
39
63
|
type ReducerDiagnostics,
|
|
64
|
+
rebuildFromDurable,
|
|
40
65
|
reduce,
|
|
41
66
|
} from "../src/presentation/reducer.ts"
|
|
42
67
|
import {
|
|
@@ -44,6 +69,33 @@ import {
|
|
|
44
69
|
type ContentStore,
|
|
45
70
|
createContentStore,
|
|
46
71
|
} from "../src/presentation/store.ts"
|
|
72
|
+
import {
|
|
73
|
+
createProductionExecutionRunner,
|
|
74
|
+
inspectStartupRecovery,
|
|
75
|
+
type ProductionExecutionRunner,
|
|
76
|
+
type RuntimeProductionMode,
|
|
77
|
+
runtimeModeFor,
|
|
78
|
+
type StartupRecoveryReport,
|
|
79
|
+
} from "../src/runtime/production-execution.ts"
|
|
80
|
+
import {
|
|
81
|
+
createProductionRuntime,
|
|
82
|
+
observeProductionRuntime,
|
|
83
|
+
type ProductionRuntimeHandle,
|
|
84
|
+
runtimeGateFor,
|
|
85
|
+
runtimeJournalPath,
|
|
86
|
+
} from "../src/runtime/production-runtime.ts"
|
|
87
|
+
import { deriveRuntimeView, evaluateResume } from "../src/runtime/runtime-status.ts"
|
|
88
|
+
import type { TaskLayerFacts } from "../src/runtime/runtime-status-facts.ts"
|
|
89
|
+
import { installRuntimeStatusProvider } from "../src/runtime/runtime-status-provider.ts"
|
|
90
|
+
import { admitTaskWork } from "../src/runtime/runtime-task-admission.ts"
|
|
91
|
+
import {
|
|
92
|
+
acquireSessionWriter,
|
|
93
|
+
checkWriterFresh,
|
|
94
|
+
releaseSessionWriter,
|
|
95
|
+
renewSessionWriter,
|
|
96
|
+
StaleWriterError,
|
|
97
|
+
writerTokenFor,
|
|
98
|
+
} from "../src/session/authority.ts"
|
|
47
99
|
import {
|
|
48
100
|
beginTurnSnapshot,
|
|
49
101
|
reconcileUndoRedoPointer,
|
|
@@ -52,14 +104,86 @@ import {
|
|
|
52
104
|
snapshotWorkspace,
|
|
53
105
|
validateResumeWorkspace,
|
|
54
106
|
} from "../src/session/checkpoint.ts"
|
|
107
|
+
import {
|
|
108
|
+
attachHeadlessCompactionBridge,
|
|
109
|
+
type RuntimeContextMetadata,
|
|
110
|
+
runtimeMetadataFromSelection,
|
|
111
|
+
} from "../src/session/context-adapter.ts"
|
|
112
|
+
import {
|
|
113
|
+
assembleContext,
|
|
114
|
+
type ContextOnlyArtifact,
|
|
115
|
+
stripContextOnly,
|
|
116
|
+
} from "../src/session/context-assembly.ts"
|
|
117
|
+
import {
|
|
118
|
+
countDurableCompactions,
|
|
119
|
+
deriveFrontierFromDurable,
|
|
120
|
+
} from "../src/session/context-identity.ts"
|
|
121
|
+
import {
|
|
122
|
+
produceSummaryProjection,
|
|
123
|
+
readConsumableSummaryProjection,
|
|
124
|
+
} from "../src/session/context-projection.ts"
|
|
125
|
+
import { rowsToCanonicalRefs, selectContext } from "../src/session/context-selector.ts"
|
|
126
|
+
import {
|
|
127
|
+
AdoptionRefusedError,
|
|
128
|
+
type AdoptionResult,
|
|
129
|
+
type AdoptTaskSpec,
|
|
130
|
+
adoptUnfinishedTask,
|
|
131
|
+
} from "../src/session/cross-session-adoption.ts"
|
|
132
|
+
import { formatSessionIdentityLine, resolveSessionIdentity } from "../src/session/identity.ts"
|
|
55
133
|
import {
|
|
56
134
|
attachMutationJournal,
|
|
57
135
|
finalizeJournal,
|
|
136
|
+
hashArgs,
|
|
137
|
+
loadJournal,
|
|
58
138
|
planRecoveryForSession,
|
|
59
139
|
} from "../src/session/journal.ts"
|
|
60
|
-
import {
|
|
140
|
+
import {
|
|
141
|
+
beginToolInFlight,
|
|
142
|
+
clearPendingTools,
|
|
143
|
+
endToolInFlight,
|
|
144
|
+
setPendingToolsRun,
|
|
145
|
+
} from "../src/session/pending-tools.ts"
|
|
146
|
+
import {
|
|
147
|
+
appendPresentationEvents,
|
|
148
|
+
backfillHistoryEventIds,
|
|
149
|
+
completeRun,
|
|
150
|
+
createRun,
|
|
151
|
+
DEFAULT_THREAD_ID,
|
|
152
|
+
ensureDefaultThread,
|
|
153
|
+
failRun,
|
|
154
|
+
interruptRun,
|
|
155
|
+
listPersistedTurns,
|
|
156
|
+
loadPresentationEvents,
|
|
157
|
+
loadSession,
|
|
158
|
+
loadSessionUsageSummary,
|
|
159
|
+
loadThreadHistoryWithSeq,
|
|
160
|
+
type PresentationPersistStats,
|
|
161
|
+
RefusedHistoryRewriteError,
|
|
162
|
+
saveSession,
|
|
163
|
+
shrinkThreadHistory,
|
|
164
|
+
ThreadArchivedError,
|
|
165
|
+
terminalizeChildRuns,
|
|
166
|
+
tombstoneDeadRuns,
|
|
167
|
+
tombstoneOrphanChildRuns,
|
|
168
|
+
transitionRun,
|
|
169
|
+
} from "../src/session/persistence.ts"
|
|
170
|
+
import { collectOperationalState } from "../src/session/runtime-header.ts"
|
|
61
171
|
import { snapshotTree } from "../src/session/shadow-git.ts"
|
|
172
|
+
import {
|
|
173
|
+
checkWorkspaceIntegrity,
|
|
174
|
+
collectModifiedFilesFromJournal,
|
|
175
|
+
detectEvaluationTampering,
|
|
176
|
+
} from "../src/session/verification.ts"
|
|
62
177
|
import type { Skill } from "../src/skills/loader.ts"
|
|
178
|
+
import type { AutonomousSessionSpec } from "../src/task/autonomous-context.ts"
|
|
179
|
+
import {
|
|
180
|
+
createProductionScheduler,
|
|
181
|
+
type ProductionSchedulerHandle,
|
|
182
|
+
schedulerGateFor,
|
|
183
|
+
} from "../src/task/production-scheduler.ts"
|
|
184
|
+
import { SchedulerObservability } from "../src/task/scheduler-observability.ts"
|
|
185
|
+
import { SESSION_RENEW_INTERVAL_MS } from "../src/task/session-authority.ts"
|
|
186
|
+
import { createTaskIdentityResolver, settleSessionVerifyingTasks } from "../src/task/sync.ts"
|
|
63
187
|
import {
|
|
64
188
|
classifyToolResult,
|
|
65
189
|
denyReasonOf,
|
|
@@ -68,14 +192,30 @@ import {
|
|
|
68
192
|
} from "../src/telemetry/trace.ts"
|
|
69
193
|
import { setAskApprovalHook, setAskTextFn } from "../src/tools/ask_user.ts"
|
|
70
194
|
import { killAllBackgroundJobs } from "../src/tools/bash.ts"
|
|
71
|
-
import {
|
|
72
|
-
|
|
195
|
+
import {
|
|
196
|
+
setSubAgentExecutionRunner,
|
|
197
|
+
setSubAgentParentRouting,
|
|
198
|
+
setSubAgentParentRunId,
|
|
199
|
+
setSubAgentWorkMode,
|
|
200
|
+
} from "../src/tools/task.ts"
|
|
201
|
+
import {
|
|
202
|
+
reconcileCompletionEvidence,
|
|
203
|
+
setCompletionEvidence,
|
|
204
|
+
todoSession,
|
|
205
|
+
} from "../src/tools/todo.ts"
|
|
73
206
|
import { promptAsk, promptAskText } from "../src/ui/approval/prompt.ts"
|
|
74
207
|
import { attachSimpleLogger } from "../src/ui/assistant/simple.ts"
|
|
75
208
|
import type {
|
|
76
209
|
UiPresentationActivity,
|
|
210
|
+
UiPresentationDiagnostic,
|
|
77
211
|
UiPresentationEvent,
|
|
212
|
+
UiPresentationFinding,
|
|
213
|
+
UiPresentationMessage,
|
|
214
|
+
UiPresentationPlan,
|
|
215
|
+
UiPresentationReasoning,
|
|
216
|
+
UiPresentationResult,
|
|
78
217
|
UiPresentationSnapshot,
|
|
218
|
+
UiPresentationSystem,
|
|
79
219
|
UiPresentationTurn,
|
|
80
220
|
UiToolStatus,
|
|
81
221
|
UiTurnSummary,
|
|
@@ -87,13 +227,25 @@ export interface CliSessionOptions {
|
|
|
87
227
|
cwd?: string
|
|
88
228
|
sessionId: string
|
|
89
229
|
resumeId?: string
|
|
230
|
+
// P2.1: id volatil per proses untuk korelasi diagnostik (tak pernah jadi
|
|
231
|
+
// kunci persistensi). Diisi CLI; bila absen, identity resolver yang mint.
|
|
232
|
+
bootId?: string
|
|
90
233
|
modelOverride?: string
|
|
91
234
|
providerOverride?: string
|
|
92
235
|
prompt: string
|
|
93
236
|
enterRepl: boolean
|
|
237
|
+
machineOutput?: boolean
|
|
94
238
|
verbose: boolean
|
|
95
239
|
allowAll: boolean
|
|
96
240
|
ask: boolean
|
|
241
|
+
/**
|
|
242
|
+
* [P13.6] Pengganti ask permission TTY untuk jalur headless (daemon).
|
|
243
|
+
* Default TIDAK diset: `promptAsk` dipakai, dan non-TTY ⇒ deny (fail-closed)
|
|
244
|
+
* — daemon yang lupa memasang apa pun tidak pernah bisa mengizinkan
|
|
245
|
+
* diam-diam. Daemon memasang `ApprovalBroker.asPermissionAsk` supaya
|
|
246
|
+
* konsumen Desktop yang mengusulkan keputusan lewat op `approval.decide`.
|
|
247
|
+
*/
|
|
248
|
+
permissionAsk?: PermissionAsk
|
|
97
249
|
plan: boolean
|
|
98
250
|
allowlist: boolean
|
|
99
251
|
verify: boolean
|
|
@@ -106,6 +258,51 @@ export interface CliSessionOptions {
|
|
|
106
258
|
budgetStrict?: boolean
|
|
107
259
|
/** Harness-P2: scope tool sesi — explore = subset read-only. */
|
|
108
260
|
toolScope?: "full" | "explore"
|
|
261
|
+
/**
|
|
262
|
+
* P12 S2.2 — WorkMode (lapis intent di ATAS permission mode). Default
|
|
263
|
+
* EXECUTE = perilaku lama. DISCUSS = read-only ceiling; PLAN = ceiling
|
|
264
|
+
* rencana (explore + tool rencana). TIDAK pernah memperluas permission mode
|
|
265
|
+
* (INV-WM1). Diisi CLI dari --work-mode / MINICODE_WORK_MODE; diserahkan ke
|
|
266
|
+
* setupToolLayer (visibilitas) dan createMinicodeSession (handler ceiling).
|
|
267
|
+
*/
|
|
268
|
+
workMode?: "DISCUSS" | "PLAN" | "EXECUTE"
|
|
269
|
+
/**
|
|
270
|
+
* [PHASE 6U] Opt-in autonomous Scheduler. DEFAULT OFF - `undefined` and
|
|
271
|
+
* `false` behave identically, and for both the composition root is never called.
|
|
272
|
+
*
|
|
273
|
+
* [DESIGN DECISION] A CLI flag rather than a config key or an env var, so it
|
|
274
|
+
* cannot be inherited by a sub-agent, an MCP server, or an unrelated project.
|
|
275
|
+
* See `src/task/production-scheduler.ts` for why the alternatives were rejected.
|
|
276
|
+
*/
|
|
277
|
+
schedulerEnabled?: boolean
|
|
278
|
+
/**
|
|
279
|
+
* [P1 M15] Mode produksi runtime. `off` (default) = jalur legacy utuh;
|
|
280
|
+
* `constructed` = runtime + jurnal dibangun, eksekusi masih legacy;
|
|
281
|
+
* `owned` = admission WAJIB lewat M13 → Kernel (satu jalur, fail-closed).
|
|
282
|
+
*
|
|
283
|
+
* [DESIGN DECISION] Mode, bukan boolean. Boolean M14 (`constructed`) tak dapat
|
|
284
|
+
* membedakan "runtime untuk observasi" dari "runtime yang memiliki eksekusi",
|
|
285
|
+
* dan dua klaim itu tidak boleh ter confuse saat rollback. Nilai tak dikenal
|
|
286
|
+
* gagal ke `off`.
|
|
287
|
+
*/
|
|
288
|
+
runtimeMode?: RuntimeProductionMode
|
|
289
|
+
/**
|
|
290
|
+
* [P14] Adopsi eksplisit SATU task unfinished dari sesi sumber. Diisi CLI
|
|
291
|
+
* hanya dari `--adopt-task <source>/<taskId>`.
|
|
292
|
+
*
|
|
293
|
+
* [DESIGN DECISION] Startup-only, bukan slash-command. Transfer mengubah
|
|
294
|
+
* namespace task dan mem-fence penulis sesi sumber; itu keputusan operator
|
|
295
|
+
* yang harus terjadi sebelum turn pertama, bukan di tengah percakapan.
|
|
296
|
+
*/
|
|
297
|
+
adoptTask?: AdoptTaskSpec
|
|
298
|
+
/**
|
|
299
|
+
* [P13.6] Seam injeksi uji deterministik untuk append presentasi —
|
|
300
|
+
* satu-satunya titik tulis durable presentasi. Produksi TIDAK mengeset ini;
|
|
301
|
+
* default = `appendPresentationEvents` sesungguhnya (pagar epoch yang sama).
|
|
302
|
+
* Analog dengan seam checkpoint `openExecutionJournal`: test memakainya
|
|
303
|
+
* untuk memaksa kegagalan/penghalang TANPA tidur arbiter.
|
|
304
|
+
*/
|
|
305
|
+
presentationAppend?: (events: readonly DomainEvent[]) => Promise<PresentationPersistStats>
|
|
109
306
|
maxSteps?: number
|
|
110
307
|
contextWindowTokens?: number
|
|
111
308
|
/** F3.2: override keepRecentTurns kompaksi kernel (berapa turn terakhir
|
|
@@ -130,10 +327,35 @@ export interface CliSession {
|
|
|
130
327
|
cfg: MinicodeConfig
|
|
131
328
|
cwd?: string
|
|
132
329
|
sessionId: string
|
|
330
|
+
// P2.1: identitas kanonik (durable) vs volatil (proses) — jangan tertukar.
|
|
331
|
+
bootId: string
|
|
332
|
+
// P2.2: generasi pagar penulis saat admission (observability; mutasi
|
|
333
|
+
// memakai CAS in-txn, bukan nilai ini). Token otoritas SENGAJA tak
|
|
334
|
+
// diekspos — tak ada konsumen yang butuh mencetaknya.
|
|
335
|
+
writerEpoch: number
|
|
336
|
+
isWriterStale: () => boolean
|
|
337
|
+
writerStaleNote: () => string
|
|
338
|
+
/**
|
|
339
|
+
* [Stage 5B] Bukti kegagalan checkpoint (dicatat, tak hilang senyap).
|
|
340
|
+
* Pesan error internal saja — tak ada credential di jalur ini.
|
|
341
|
+
*/
|
|
342
|
+
checkpointFailures: () => string[]
|
|
343
|
+
/**
|
|
344
|
+
* [Stage 5B] Operasi checkpoint yang masih berjalan. Setelah `close()`
|
|
345
|
+
* selesai HARUS 0 — `close()` adalah barrier lifecycle.
|
|
346
|
+
*/
|
|
347
|
+
pendingCheckpointCount: () => number
|
|
133
348
|
modelRef: { current?: string }
|
|
134
349
|
effectiveInitialModel: string
|
|
135
350
|
effectiveTimeoutMs: number
|
|
136
351
|
permissionMode: string
|
|
352
|
+
/** P12 S2.2 — WorkMode efektif sesi ini (default EXECUTE). Dipakai label/
|
|
353
|
+
* readout TUI; diisi composition root dari flag/env. */
|
|
354
|
+
workMode: "DISCUSS" | "PLAN" | "EXECUTE"
|
|
355
|
+
/** P12 S2.2 Slice 5 — handle kontrol WorkMode runtime (transisi operator
|
|
356
|
+
* lewat command `/work-mode`). Undefined bila sesi memakai handler izin
|
|
357
|
+
* terinjeksi (policy, bukan mode — fail-closed). */
|
|
358
|
+
workModeControl?: WorkModeControl
|
|
137
359
|
sessionTools: Tool[]
|
|
138
360
|
allLoadedSkills: Skill[]
|
|
139
361
|
usage: ReturnType<typeof createUsageCollector>
|
|
@@ -147,10 +369,24 @@ export interface CliSession {
|
|
|
147
369
|
detachSimple: () => void
|
|
148
370
|
persistCurrent: (usageData: unknown) => Promise<void>
|
|
149
371
|
runPromptWithVerify: (prompt: string, signal?: AbortSignal) => Promise<void>
|
|
372
|
+
/**
|
|
373
|
+
* P11.1 — ringkasan hasil verify terakhir, read-only untuk summary mesin
|
|
374
|
+
* (`exec --json`). Null bila verify belum pernah jalan di sesi ini.
|
|
375
|
+
* Hanya ok+command (output verify tetap di stderr/stream, tak ikut
|
|
376
|
+
* summary); snapshot disalin agar pemanggil tak bisa memutasi state sesi.
|
|
377
|
+
*/
|
|
378
|
+
getLastVerifyResult: () => { ok: boolean; command: string } | null
|
|
379
|
+
/**
|
|
380
|
+
* P3.5 — metadata runtime hasil seleksi konteks (host-side, RAM, lifecycle-
|
|
381
|
+
* scoped). Bukan store/otoritas; hanya membawa identity/frontier/revision/
|
|
382
|
+
* basis/freshness melewati batas seed runtime. Undefined bila sesi bukan resume
|
|
383
|
+
* (tidak ada ContextSelection).
|
|
384
|
+
*/
|
|
385
|
+
runtimeContextMetadata?: RuntimeContextMetadata
|
|
150
386
|
/** Kontrol mode permission saat runtime (Shift+Tab / /mode di REPL). */
|
|
151
387
|
permissions?: PermissionControl
|
|
152
388
|
close: () => Promise<void>
|
|
153
|
-
/**
|
|
389
|
+
/** Counter reducer presentasi (divergensi harus 0). */
|
|
154
390
|
getShadowDiagnostics: () => {
|
|
155
391
|
divergence: number
|
|
156
392
|
eventsIn: number
|
|
@@ -159,23 +395,363 @@ export interface CliSession {
|
|
|
159
395
|
orphanTool: number
|
|
160
396
|
orphanApproval: number
|
|
161
397
|
duplicateTurn: number
|
|
398
|
+
unknownEvent: number
|
|
399
|
+
orphanEvidence: number
|
|
400
|
+
unsupportedProjection: number
|
|
162
401
|
}
|
|
163
402
|
/** Content store untuk /expand [id]. */
|
|
164
403
|
expandContent: (toolCallId: string) => ContentEntry[]
|
|
165
404
|
expandAllContent: () => ContentEntry[]
|
|
166
405
|
getPresentationSnapshot: () => UiPresentationSnapshot
|
|
167
406
|
onPresentationEvent: (handler: (event: UiPresentationEvent) => void) => () => void
|
|
407
|
+
/**
|
|
408
|
+
* [P13.5] DomainEvent mentah — bentuk yang SAMA dengan yang dipersist durable.
|
|
409
|
+
*
|
|
410
|
+
* Kenapa terpisah dari `onPresentationEvent`: proyeksi UI memakai field `seq`
|
|
411
|
+
* dan membuang detail domain (eventSeq/sessionId/lineage). Feed daemon
|
|
412
|
+
* membutuhkan bentuk DomainEvent agar live dan replay berbicara bahasa yang
|
|
413
|
+
* sama; melakukan cast proyeksi ke DomainEvent membuat `eventSeq` hilang dan
|
|
414
|
+
* seluruh live feed diam. Subscriber di sini menerima event sebelum proyeksi.
|
|
415
|
+
*/
|
|
416
|
+
onDomainEvent: (handler: (event: DomainEvent) => void) => () => void
|
|
417
|
+
/**
|
|
418
|
+
* [PHASE 6AB] The trigger handle, exposed.
|
|
419
|
+
*
|
|
420
|
+
* 6AA's blocker was precisely that this was NOT here: `createProductionScheduler`
|
|
421
|
+
* returned a real, authority-holding handle that `cli/setup.ts` kept in a local
|
|
422
|
+
* and called exactly one method on - `stop()`. Nothing else in the process could
|
|
423
|
+
* reach `fire()`, so an enabled Scheduler could never be made to do anything.
|
|
424
|
+
*
|
|
425
|
+
* [DESIGN DECISION] Ownership stays with the production runtime, which is what
|
|
426
|
+
* this object is. The handle is deliberately NOT written into TaskStore,
|
|
427
|
+
* TaskGraph, task state or a module-level singleton: it holds an AbortController,
|
|
428
|
+
* a lease token and a subscription, none of which belong in durable state, and a
|
|
429
|
+
* global would make the per-session scoping 6T designed for impossible to keep.
|
|
430
|
+
* Exactly one session owns exactly one handle, and that session is `sessionId`.
|
|
431
|
+
*/
|
|
432
|
+
productionScheduler: ProductionSchedulerHandle
|
|
433
|
+
/** [P1 M14] Operator/runtime projection — the P1 runtime owner of this session. */
|
|
434
|
+
productionRuntime: ProductionRuntimeHandle
|
|
435
|
+
/** [P1 M15] Mode runtime sesi ini (off | constructed | owned). */
|
|
436
|
+
runtimeMode: RuntimeProductionMode
|
|
437
|
+
/** [P1 M15] Admission runtime untuk turn sesi ini. */
|
|
438
|
+
executionRunner: ProductionExecutionRunner
|
|
439
|
+
/** [P1 M15] Bukti durable saat start: integritas jurnal + tafsir M12. */
|
|
440
|
+
startupRecovery: StartupRecoveryReport | null
|
|
441
|
+
/** [PHASE 6AB] Operator projection fed by the Scheduler's own event stream. */
|
|
442
|
+
schedulerObservability: SchedulerObservability
|
|
443
|
+
/**
|
|
444
|
+
* [P14] Hasil adopsi lintas sesi saat startup, atau null bila flag tidak
|
|
445
|
+
* dipakai. Dikembalikan agar tes/operator dapat memeriksa outcome tanpa
|
|
446
|
+
* membaca ulang pesan stderr.
|
|
447
|
+
*/
|
|
448
|
+
adoption: AdoptionResult | null
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
export function toPresentationEvent(event: DomainEvent): UiPresentationEvent | null {
|
|
452
|
+
switch (event.type) {
|
|
453
|
+
case "user.message":
|
|
454
|
+
return {
|
|
455
|
+
type: event.type,
|
|
456
|
+
seq: event.eventSeq,
|
|
457
|
+
turnId: event.turnId,
|
|
458
|
+
text: event.text,
|
|
459
|
+
promptRef: event.promptRef,
|
|
460
|
+
}
|
|
461
|
+
case "turn.started":
|
|
462
|
+
return {
|
|
463
|
+
type: event.type,
|
|
464
|
+
seq: event.eventSeq,
|
|
465
|
+
turnId: event.turnId,
|
|
466
|
+
promptRef: event.promptRef,
|
|
467
|
+
}
|
|
468
|
+
case "turn.completed":
|
|
469
|
+
return {
|
|
470
|
+
type: event.type,
|
|
471
|
+
seq: event.eventSeq,
|
|
472
|
+
turnId: event.turnId,
|
|
473
|
+
summary: event.summary,
|
|
474
|
+
}
|
|
475
|
+
case "turn.failed":
|
|
476
|
+
return {
|
|
477
|
+
type: event.type,
|
|
478
|
+
seq: event.eventSeq,
|
|
479
|
+
turnId: event.turnId,
|
|
480
|
+
error: event.error.message,
|
|
481
|
+
cause: event.error.cause,
|
|
482
|
+
}
|
|
483
|
+
case "turn.cancelled":
|
|
484
|
+
return {
|
|
485
|
+
type: event.type,
|
|
486
|
+
seq: event.eventSeq,
|
|
487
|
+
turnId: event.turnId,
|
|
488
|
+
reason: event.reason,
|
|
489
|
+
}
|
|
490
|
+
case "model.delta":
|
|
491
|
+
return {
|
|
492
|
+
type: event.type,
|
|
493
|
+
seq: event.eventSeq,
|
|
494
|
+
turnId: event.turnId,
|
|
495
|
+
delta: event.delta,
|
|
496
|
+
}
|
|
497
|
+
case "model.completed":
|
|
498
|
+
return {
|
|
499
|
+
type: event.type,
|
|
500
|
+
seq: event.eventSeq,
|
|
501
|
+
turnId: event.turnId,
|
|
502
|
+
text: event.text,
|
|
503
|
+
truncated: event.truncated,
|
|
504
|
+
...(event.expandRef ? { expandRef: event.expandRef } : {}),
|
|
505
|
+
}
|
|
506
|
+
case "reasoning.delta":
|
|
507
|
+
return {
|
|
508
|
+
type: event.type,
|
|
509
|
+
seq: event.eventSeq,
|
|
510
|
+
turnId: event.turnId,
|
|
511
|
+
delta: event.delta,
|
|
512
|
+
}
|
|
513
|
+
case "reasoning.completed":
|
|
514
|
+
return {
|
|
515
|
+
type: event.type,
|
|
516
|
+
seq: event.eventSeq,
|
|
517
|
+
turnId: event.turnId,
|
|
518
|
+
truncated: event.truncated,
|
|
519
|
+
expandRef: event.expandRef,
|
|
520
|
+
}
|
|
521
|
+
case "tool.started":
|
|
522
|
+
return {
|
|
523
|
+
type: event.type,
|
|
524
|
+
seq: event.eventSeq,
|
|
525
|
+
turnId: event.turnId,
|
|
526
|
+
stepId: event.stepId,
|
|
527
|
+
toolCallId: event.toolCallId,
|
|
528
|
+
name: event.identity.name,
|
|
529
|
+
qualified: event.identity.qualified,
|
|
530
|
+
target: event.argsSummary.target,
|
|
531
|
+
status: "running",
|
|
532
|
+
tsStart: event.ts,
|
|
533
|
+
...(event.parentLink ? { parentToolCallId: event.parentLink.parentToolCallId } : {}),
|
|
534
|
+
}
|
|
535
|
+
case "tool.progress":
|
|
536
|
+
return {
|
|
537
|
+
type: event.type,
|
|
538
|
+
seq: event.eventSeq,
|
|
539
|
+
turnId: event.turnId,
|
|
540
|
+
toolCallId: event.toolCallId,
|
|
541
|
+
status: "running",
|
|
542
|
+
message: event.message,
|
|
543
|
+
}
|
|
544
|
+
case "tool.completed":
|
|
545
|
+
return {
|
|
546
|
+
type: event.type,
|
|
547
|
+
seq: event.eventSeq,
|
|
548
|
+
turnId: event.turnId,
|
|
549
|
+
toolCallId: event.toolCallId,
|
|
550
|
+
status: "completed",
|
|
551
|
+
durationMs: event.durationMs,
|
|
552
|
+
toolSummary: event.summary,
|
|
553
|
+
expandRef: event.expandRef,
|
|
554
|
+
...(event.receipt
|
|
555
|
+
? {
|
|
556
|
+
receipt: {
|
|
557
|
+
...(event.receipt.paths ? { paths: event.receipt.paths } : {}),
|
|
558
|
+
...(event.receipt.checkpointId ? { checkpointId: event.receipt.checkpointId } : {}),
|
|
559
|
+
...(event.receipt.stats ? { stats: event.receipt.stats } : {}),
|
|
560
|
+
...(event.receipt.test ? { test: event.receipt.test } : {}),
|
|
561
|
+
...(event.receipt.cmd ? { cmd: event.receipt.cmd } : {}),
|
|
562
|
+
},
|
|
563
|
+
}
|
|
564
|
+
: {}),
|
|
565
|
+
...(event.parentLink ? { parentToolCallId: event.parentLink.parentToolCallId } : {}),
|
|
566
|
+
}
|
|
567
|
+
case "tool.failed":
|
|
568
|
+
return {
|
|
569
|
+
type: event.type,
|
|
570
|
+
seq: event.eventSeq,
|
|
571
|
+
turnId: event.turnId,
|
|
572
|
+
toolCallId: event.toolCallId,
|
|
573
|
+
status: "failed",
|
|
574
|
+
durationMs: event.durationMs,
|
|
575
|
+
message: event.message,
|
|
576
|
+
cause: event.cause,
|
|
577
|
+
...(event.hint ? { hint: event.hint } : {}),
|
|
578
|
+
expandRef: event.expandRef,
|
|
579
|
+
...(event.parentLink ? { parentToolCallId: event.parentLink.parentToolCallId } : {}),
|
|
580
|
+
}
|
|
581
|
+
case "tool.denied":
|
|
582
|
+
return {
|
|
583
|
+
type: event.type,
|
|
584
|
+
seq: event.eventSeq,
|
|
585
|
+
turnId: event.turnId,
|
|
586
|
+
toolCallId: event.toolCallId,
|
|
587
|
+
status: "denied",
|
|
588
|
+
message: event.message,
|
|
589
|
+
reason: event.reason,
|
|
590
|
+
...(event.parentLink ? { parentToolCallId: event.parentLink.parentToolCallId } : {}),
|
|
591
|
+
}
|
|
592
|
+
case "tool.cancelled":
|
|
593
|
+
return {
|
|
594
|
+
type: event.type,
|
|
595
|
+
seq: event.eventSeq,
|
|
596
|
+
turnId: event.turnId,
|
|
597
|
+
toolCallId: event.toolCallId,
|
|
598
|
+
status: "cancelled",
|
|
599
|
+
reason: event.reason,
|
|
600
|
+
...(event.parentLink ? { parentToolCallId: event.parentLink.parentToolCallId } : {}),
|
|
601
|
+
}
|
|
602
|
+
case "approval.requested":
|
|
603
|
+
return {
|
|
604
|
+
type: event.type,
|
|
605
|
+
seq: event.eventSeq,
|
|
606
|
+
turnId: event.turnId,
|
|
607
|
+
approvalId: event.approvalId,
|
|
608
|
+
toolCallId: event.toolCallId,
|
|
609
|
+
name: event.identity.name,
|
|
610
|
+
qualified: event.identity.qualified,
|
|
611
|
+
target: event.argsSummary.target,
|
|
612
|
+
via: event.via,
|
|
613
|
+
}
|
|
614
|
+
case "approval.settled":
|
|
615
|
+
return {
|
|
616
|
+
type: event.type,
|
|
617
|
+
seq: event.eventSeq,
|
|
618
|
+
turnId: event.turnId,
|
|
619
|
+
approvalId: event.approvalId,
|
|
620
|
+
toolCallId: event.toolCallId,
|
|
621
|
+
outcome: event.outcome,
|
|
622
|
+
}
|
|
623
|
+
case "file.changed":
|
|
624
|
+
return {
|
|
625
|
+
type: event.type,
|
|
626
|
+
seq: event.eventSeq,
|
|
627
|
+
turnId: event.turnId,
|
|
628
|
+
toolCallId: event.toolCallId,
|
|
629
|
+
paths: event.paths,
|
|
630
|
+
...(event.journalSeq !== undefined ? { journalSeq: event.journalSeq } : {}),
|
|
631
|
+
...(event.checkpointId ? { checkpointId: event.checkpointId } : {}),
|
|
632
|
+
}
|
|
633
|
+
case "test.completed":
|
|
634
|
+
return {
|
|
635
|
+
type: event.type,
|
|
636
|
+
seq: event.eventSeq,
|
|
637
|
+
turnId: event.turnId,
|
|
638
|
+
toolCallId: event.toolCallId,
|
|
639
|
+
test: { passed: event.passed, failed: event.failed, summary: event.summary },
|
|
640
|
+
}
|
|
641
|
+
case "verification.observed":
|
|
642
|
+
return {
|
|
643
|
+
type: event.type,
|
|
644
|
+
seq: event.eventSeq,
|
|
645
|
+
turnId: event.turnId,
|
|
646
|
+
toolCallId: event.toolCallId,
|
|
647
|
+
invocationId: event.invocationId,
|
|
648
|
+
verification: {
|
|
649
|
+
invocationId: event.invocationId,
|
|
650
|
+
verdict: event.verdict,
|
|
651
|
+
method: event.method,
|
|
652
|
+
observedAt: event.observedAt,
|
|
653
|
+
},
|
|
654
|
+
...(event.parentLink ? { parentToolCallId: event.parentLink.parentToolCallId } : {}),
|
|
655
|
+
}
|
|
656
|
+
case "context.compacted":
|
|
657
|
+
return {
|
|
658
|
+
type: event.type,
|
|
659
|
+
seq: event.eventSeq,
|
|
660
|
+
turnId: event.turnId,
|
|
661
|
+
reason: event.reason,
|
|
662
|
+
compactionReason: event.reason,
|
|
663
|
+
}
|
|
664
|
+
case "plan.updated":
|
|
665
|
+
return {
|
|
666
|
+
type: event.type,
|
|
667
|
+
seq: event.eventSeq,
|
|
668
|
+
turnId: event.turnId,
|
|
669
|
+
planId: event.planId,
|
|
670
|
+
status: event.status === "open" ? "running" : event.status,
|
|
671
|
+
steps: event.steps,
|
|
672
|
+
...(event.expandRef ? { expandRef: event.expandRef } : {}),
|
|
673
|
+
}
|
|
674
|
+
case "finding.detected":
|
|
675
|
+
return {
|
|
676
|
+
type: event.type,
|
|
677
|
+
seq: event.eventSeq,
|
|
678
|
+
turnId: event.turnId,
|
|
679
|
+
findingId: event.findingId,
|
|
680
|
+
category: event.category,
|
|
681
|
+
severity: event.severity,
|
|
682
|
+
text: event.summary,
|
|
683
|
+
evidence: event.evidence,
|
|
684
|
+
...(event.parentLink ? { parentToolCallId: event.parentLink.parentToolCallId } : {}),
|
|
685
|
+
}
|
|
686
|
+
case "result.produced":
|
|
687
|
+
return {
|
|
688
|
+
type: event.type,
|
|
689
|
+
seq: event.eventSeq,
|
|
690
|
+
turnId: event.turnId,
|
|
691
|
+
resultId: event.resultId,
|
|
692
|
+
status: event.status === "completed" ? "completed" : event.status,
|
|
693
|
+
toolSummary: event.summary,
|
|
694
|
+
action: event.action,
|
|
695
|
+
...(event.expandRef ? { expandRef: event.expandRef } : {}),
|
|
696
|
+
}
|
|
697
|
+
case "diagnostic.raised":
|
|
698
|
+
return {
|
|
699
|
+
type: event.type,
|
|
700
|
+
seq: event.eventSeq,
|
|
701
|
+
turnId: event.turnId,
|
|
702
|
+
category: event.category,
|
|
703
|
+
severity: event.severity,
|
|
704
|
+
message: event.message,
|
|
705
|
+
cause: event.cause,
|
|
706
|
+
action: event.action,
|
|
707
|
+
}
|
|
708
|
+
case "checkpoint.created":
|
|
709
|
+
return {
|
|
710
|
+
type: event.type,
|
|
711
|
+
seq: event.eventSeq,
|
|
712
|
+
turnId: event.turnId,
|
|
713
|
+
checkpointId: event.checkpointId,
|
|
714
|
+
paths: event.paths,
|
|
715
|
+
}
|
|
716
|
+
default: {
|
|
717
|
+
const exhaustive: never = event
|
|
718
|
+
void exhaustive
|
|
719
|
+
return null
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
export function parseVerifyTestEvidence(
|
|
725
|
+
command: string,
|
|
726
|
+
output: string,
|
|
727
|
+
): { passed: number; failed: number; summary: string } | undefined {
|
|
728
|
+
if (!/(?:test|vitest|jest|pytest|cargo\s+test)/i.test(command)) return undefined
|
|
729
|
+
const passedMatch = /(\d+)\s+(?:pass(?:ed)?|successful?)/i.exec(output)
|
|
730
|
+
const failedMatch = /(\d+)\s+(?:fail(?:ed|ures?)?|failing)/i.exec(output)
|
|
731
|
+
if (!passedMatch && !failedMatch) return undefined
|
|
732
|
+
return {
|
|
733
|
+
passed: passedMatch ? Number(passedMatch[1]) : 0,
|
|
734
|
+
failed: failedMatch ? Number(failedMatch[1]) : 0,
|
|
735
|
+
summary:
|
|
736
|
+
output
|
|
737
|
+
.split(/\r?\n/)
|
|
738
|
+
.find((line) => /(?:pass|fail)/i.test(line))
|
|
739
|
+
?.trim()
|
|
740
|
+
.slice(0, 500) ?? "verify completed",
|
|
741
|
+
}
|
|
168
742
|
}
|
|
169
743
|
|
|
170
744
|
export async function createCliSession(opts: CliSessionOptions): Promise<CliSession> {
|
|
171
745
|
const {
|
|
172
746
|
cwd,
|
|
173
|
-
sessionId,
|
|
747
|
+
sessionId: sessionFlag,
|
|
174
748
|
resumeId,
|
|
749
|
+
bootId: bootIdOpt,
|
|
175
750
|
modelOverride,
|
|
176
751
|
providerOverride,
|
|
177
752
|
prompt,
|
|
178
753
|
enterRepl,
|
|
754
|
+
machineOutput = false,
|
|
179
755
|
verbose,
|
|
180
756
|
allowAll,
|
|
181
757
|
ask,
|
|
@@ -185,7 +761,11 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
185
761
|
budget,
|
|
186
762
|
budgetStrict,
|
|
187
763
|
toolScope,
|
|
764
|
+
schedulerEnabled,
|
|
765
|
+
runtimeMode,
|
|
766
|
+
adoptTask,
|
|
188
767
|
allowLocalConfig,
|
|
768
|
+
workMode = "EXECUTE",
|
|
189
769
|
maxSteps,
|
|
190
770
|
contextWindowTokens,
|
|
191
771
|
keepRecentTurns,
|
|
@@ -194,6 +774,171 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
194
774
|
sandboxNotice,
|
|
195
775
|
} = opts
|
|
196
776
|
const modelRef = { current: modelOverride }
|
|
777
|
+
// P2.1 — SATU-SATUNYA keputusan identitas sesi. Sesudah baris ini,
|
|
778
|
+
// `sessionId` adalah identitas kanonik durable; id volatil hanya `bootId`
|
|
779
|
+
// (diagnostik). Tak ada jalur persistensi khusus alias: semua turunan
|
|
780
|
+
// (jurnal, checkpoint, todos, runtime journal, scheduler) memakai sid.
|
|
781
|
+
// --resume tak dikenal melempar SessionNotFoundError (eksplisit, bukan
|
|
782
|
+
// sesi baru diam-diam).
|
|
783
|
+
const identity = resolveSessionIdentity({
|
|
784
|
+
sessionFlag: sessionFlag,
|
|
785
|
+
resumeFlag: resumeId,
|
|
786
|
+
cwd,
|
|
787
|
+
...(bootIdOpt ? { bootId: bootIdOpt } : {}),
|
|
788
|
+
})
|
|
789
|
+
const sessionId = identity.sid
|
|
790
|
+
const bootId = identity.bootId
|
|
791
|
+
process.stderr.write(`${c.dim(formatSessionIdentityLine(identity))}\n`)
|
|
792
|
+
|
|
793
|
+
// P2.2 — admission penulis tunggal. Lease = admission; pagar mutasi =
|
|
794
|
+
// writer_epoch (CAS di transaksi tulis). Komposisi ini MEMEGANG lease
|
|
795
|
+
// selama hidupnya (token milik boot ini, dibagi dengan scheduler-nya
|
|
796
|
+
// sendiri) dan melepasnya saat close. Penulis asing yang hidup →REFUSED
|
|
797
|
+
// di sini (fail-closed); penulis basi ditolak di tiap mutasi (CAS).
|
|
798
|
+
const writerToken = writerTokenFor(bootId)
|
|
799
|
+
const admission = acquireSessionWriter({ sessionId, cwd, bootId, token: writerToken })
|
|
800
|
+
if (!admission.ok) throw admission.error
|
|
801
|
+
let expectedEpoch = admission.admission.epoch
|
|
802
|
+
let writerStale = false
|
|
803
|
+
let writerStaleNote = ""
|
|
804
|
+
const markWriterStale = (note: string): void => {
|
|
805
|
+
if (!writerStale) {
|
|
806
|
+
writerStale = true
|
|
807
|
+
writerStaleNote = note
|
|
808
|
+
process.stderr.write(
|
|
809
|
+
`${c.yellow(`[writer] STALE sid=${sessionId} boot=${bootId} epoch=${expectedEpoch}: ${note} — history NOT durable; resume/restart to re-acquire\n`)}`,
|
|
810
|
+
)
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
process.stderr.write(
|
|
814
|
+
`${c.dim(`[writer] admitted sid=${sessionId} boot=${bootId} epoch=${expectedEpoch}${admission.admission.tookOver ? " (takeover)" : ""}${admission.admission.fresh ? " (fresh)" : ""}\n`)}`,
|
|
815
|
+
)
|
|
816
|
+
// [P14] Adopsi eksplisit berjalan SETELAH admission target (token target
|
|
817
|
+
// sudah sah) dan SEBELUM turn pertama. Gagal = lepas lease target lalu
|
|
818
|
+
// lempar error terklasifikasi; jangan pernah meninggalkan target terkunci
|
|
819
|
+
// oleh proses yang tidak jadi berjalan.
|
|
820
|
+
let adoption: AdoptionResult | null = null
|
|
821
|
+
if (adoptTask) {
|
|
822
|
+
adoption = adoptUnfinishedTask({
|
|
823
|
+
sourceSessionId: adoptTask.sourceSessionId,
|
|
824
|
+
targetSessionId: sessionId,
|
|
825
|
+
taskId: adoptTask.taskId,
|
|
826
|
+
targetOwnerToken: writerToken,
|
|
827
|
+
bootId,
|
|
828
|
+
cwd,
|
|
829
|
+
})
|
|
830
|
+
if (adoption.outcome !== "ADOPTED") {
|
|
831
|
+
releaseSessionWriter(sessionId, writerToken, cwd)
|
|
832
|
+
throw new AdoptionRefusedError(adoption)
|
|
833
|
+
}
|
|
834
|
+
const moved = adoption.task
|
|
835
|
+
process.stderr.write(
|
|
836
|
+
`${c.dim(`[adopt] ADOPTED ${adoptTask.taskId} ${adoptTask.sourceSessionId} -> ${sessionId} revision=${moved?.revision ?? "?"} status=${moved?.status ?? "?"} exec=${adoption.transfer?.execGeneration ?? "?"}${adoption.fencedFormerOwner ? " (former owner fenced)" : ""}\n`)}`,
|
|
837
|
+
)
|
|
838
|
+
}
|
|
839
|
+
// P2.6 — kubur residu crash: RUNNING tanpa holder hidup (admission di atas
|
|
840
|
+
// membuktikan tak ada penulis hidup) → INTERRUPTED/UNKNOWN. BUKAN
|
|
841
|
+
// auto-continue/replay; tanpa ini satu crash mengganjal RUNNING unik
|
|
842
|
+
// selamanya. Fenced, idempoten.
|
|
843
|
+
tombstoneDeadRuns(sessionId, cwd, { expectedEpoch })
|
|
844
|
+
// P2.9 — orphan Sub-Agent: Run anak yang masih RUNNING sementara parent
|
|
845
|
+
// sudah terminal/crash → INTERRUPTED + UNKNOWN (P2.6 semantics: kematian tak
|
|
846
|
+
// terobservasi, JANGAN pernah disimpulkan COMPLETED). Tidak ada auto-continue.
|
|
847
|
+
try {
|
|
848
|
+
const orphans = tombstoneOrphanChildRuns(sessionId, cwd, { expectedEpoch })
|
|
849
|
+
if (orphans.length > 0) {
|
|
850
|
+
process.stderr.write(
|
|
851
|
+
`${c.yellow(`[child] ${orphans.length} orphaned sub-agent run(s) tombstoned (INTERRUPTED/UNKNOWN)\n`)}`,
|
|
852
|
+
)
|
|
853
|
+
}
|
|
854
|
+
} catch {}
|
|
855
|
+
// P2.2 — heartbeat lease milik boot ini (pola yang sama dengan scheduler:
|
|
856
|
+
// unref + dibersihkan saat close). Tanpa ini sesi REPL yang idle > lease
|
|
857
|
+
// kehilangan admission dan take-over asing menjadi mungkin di tengah sesi.
|
|
858
|
+
// Perpanjangan TAK PERNAH menyentuh writer_epoch (§16).
|
|
859
|
+
let writerRenewTimer: ReturnType<typeof setInterval> | undefined
|
|
860
|
+
let renewWarned = false
|
|
861
|
+
writerRenewTimer = setInterval(() => {
|
|
862
|
+
const out = renewSessionWriter(sessionId, writerToken, cwd)
|
|
863
|
+
if (out === "AUTHORITY_LOST" && !renewWarned) {
|
|
864
|
+
renewWarned = true
|
|
865
|
+
process.stderr.write(
|
|
866
|
+
`${c.yellow(`[writer] lease lost sid=${sessionId} boot=${bootId} — another writer took over; next mutation will be refused unless re-acquired\n`)}`,
|
|
867
|
+
)
|
|
868
|
+
try {
|
|
869
|
+
if (writerRenewTimer !== undefined) clearInterval(writerRenewTimer)
|
|
870
|
+
} catch {}
|
|
871
|
+
writerRenewTimer = undefined
|
|
872
|
+
}
|
|
873
|
+
}, SESSION_RENEW_INTERVAL_MS)
|
|
874
|
+
writerRenewTimer.unref?.()
|
|
875
|
+
|
|
876
|
+
// P2.2 — pagar pra-turn. JANGAN belanjakan provider untuk turn yang tak
|
|
877
|
+
// bisa persist: basi → lewati turn (histori kernel utuh) + flag untuk
|
|
878
|
+
// exit jujur one-shot / transcript TUI. Tak melempar (aman loop TUI).
|
|
879
|
+
// Akuisisi-ulang di sini menutup kasus lease bersama yang dilepas
|
|
880
|
+
// scheduler-stop di tengah sesi (baris hilang ≠ asing hidup).
|
|
881
|
+
function ensureWriterFresh(): boolean {
|
|
882
|
+
if (writerStale) return false
|
|
883
|
+
const seen = checkWriterFresh(sessionId, writerToken, expectedEpoch, cwd)
|
|
884
|
+
if (seen.fresh) return true
|
|
885
|
+
if (seen.epoch === expectedEpoch) {
|
|
886
|
+
const re = acquireSessionWriter({ sessionId, cwd, bootId, token: writerToken })
|
|
887
|
+
if (re.ok) {
|
|
888
|
+
if (re.admission.epoch !== expectedEpoch) {
|
|
889
|
+
process.stderr.write(
|
|
890
|
+
`${c.dim(`[writer] re-acquired sid=${sessionId} boot=${bootId} epoch=${re.admission.epoch}\n`)}`,
|
|
891
|
+
)
|
|
892
|
+
}
|
|
893
|
+
expectedEpoch = re.admission.epoch
|
|
894
|
+
return true
|
|
895
|
+
}
|
|
896
|
+
markWriterStale("pre-turn authority refused (lease held by another writer)")
|
|
897
|
+
return false
|
|
898
|
+
}
|
|
899
|
+
markWriterStale(`pre-turn epoch mismatch (expected ${expectedEpoch}, actual ${seen.epoch})`)
|
|
900
|
+
return false
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
// P2.6 — Run durably per turn-invokasi (komposisi, BUKAN loop: kernel tak
|
|
904
|
+
// tersentuh). Satu invokasi = satu Run: dibuat RUNNING saat mulai, kursor
|
|
905
|
+
// maju di persistCurrent (atomik histori+kursor), terminal DITANDAI saat
|
|
906
|
+
// turn berikutnya dimulai / close (persist selalu mendahului penandaan,
|
|
907
|
+
// sehingga kursor tak pernah maju di baris terminal). Crash di antaranya =
|
|
908
|
+
// baris RUNNING → kuburan resume (tombstone) menandainya INTERRUPTED/UNKNOWN.
|
|
909
|
+
let currentRunId: string | null = null
|
|
910
|
+
let lastTurnOutcome: "completed" | "failed" | "interrupted" | null = null
|
|
911
|
+
// [Fase 1 / LOOP-INV-03] Handle jurnal yang dipakai barrier pre-efek.
|
|
912
|
+
// Deklarasi SEBELUM session dibuat agar closure `beforeToolEffect` di bawah
|
|
913
|
+
// menangkap binding yang sudah ada (tanpa TDZ), dan diisi tepat setelah
|
|
914
|
+
// `attachMutationJournal` (masih sebelum turn pertama).
|
|
915
|
+
let journalHandle: import("../src/session/journal.ts").MutationJournalHandle | null = null
|
|
916
|
+
|
|
917
|
+
function markPreviousRunTerminal(): void {
|
|
918
|
+
if (currentRunId === null || lastTurnOutcome === null) return
|
|
919
|
+
const runId = currentRunId
|
|
920
|
+
const outcome = lastTurnOutcome
|
|
921
|
+
currentRunId = null
|
|
922
|
+
lastTurnOutcome = null
|
|
923
|
+
// [Fase 1 / LOOP-INV-06, LOOP-INV-10] Hanya run yang berakhir NORMAL yang
|
|
924
|
+
// membersihkan `pending_tool_ids`. Untuk INTERRUPTED/FAILED daftar sengaja
|
|
925
|
+
// DIBIARKAN: ia bukti forensik bahwa operasi masih terbuka, dan recovery
|
|
926
|
+
// tidak boleh menyimpulkan "selesai" dari ketiadaan bukti.
|
|
927
|
+
if (outcome === "completed") clearPendingTools()
|
|
928
|
+
setPendingToolsRun(null, cwd)
|
|
929
|
+
if (outcome === "completed") completeRun(runId, cwd, { expectedEpoch })
|
|
930
|
+
else if (outcome === "interrupted") interruptRun(runId, cwd, { expectedEpoch })
|
|
931
|
+
else failRun(runId, cwd, { expectedEpoch })
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
function classifyTurnError(e: unknown, aborted: boolean): "failed" | "interrupted" {
|
|
935
|
+
if (aborted) return "interrupted"
|
|
936
|
+
// Struktural (tanpa import kelas vendor): kind kernel aborted/timeout =
|
|
937
|
+
// interupsi; sisanya kegagalan. Tak ada tebakan "selesai".
|
|
938
|
+
const kind = (e as { kind?: unknown })?.kind
|
|
939
|
+
if (kind === "aborted" || kind === "timeout") return "interrupted"
|
|
940
|
+
return "failed"
|
|
941
|
+
}
|
|
197
942
|
|
|
198
943
|
// Diagnosis startup lambat: MINICODE_DEBUG_STARTUP=1 mencetak durasi tiap
|
|
199
944
|
// fase session-setup ke stderr (`[startup] rag 8432ms`). Tanpa env = diam.
|
|
@@ -215,6 +960,39 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
215
960
|
process.stderr.write(`[warn] invalid timeout ${effectiveTimeoutMs}, fallback to 900000\n`)
|
|
216
961
|
effectiveTimeoutMs = 900_000
|
|
217
962
|
}
|
|
963
|
+
// [Fase 7 / Live #3] ROOT wall-clock timeout. Sebelumnya `--timeout` hanya
|
|
964
|
+
// dioper ke kernel turn (session.timeoutMs), sehingga setup/retry di luar
|
|
965
|
+
// turn (DB init, system prompt, provider connect) tidak diikat satu
|
|
966
|
+
// deadline — uji live: `--timeout 30000` selesai di TOTAL_MS=71967 karena
|
|
967
|
+
// ~42 dtk setup berada di luar pagar. Signal root ini dibuat di sini
|
|
968
|
+
// (sebelum setup) dan di-compose ke sinyal turn + diperiksa selama setup,
|
|
969
|
+
// jadi TOTAL_MS benar-benar menghormati batas pengguna.
|
|
970
|
+
// [Fase 10 / QF] `AbortSignal.timeout()` menembak dengan reason DOMException
|
|
971
|
+
// (bukan AgentError). `abortError()` kernel lalu mengklasifikasikannya sebagai
|
|
972
|
+
// "aborted" generik — bukan "timeout" — sehingga `--timeout` yang fire di
|
|
973
|
+
// tengah provider menggantung melaporkan "Run was aborted" alih-alih
|
|
974
|
+
// "Run exceeded timeout". Kita buat controller sendiri supaya reason-nya
|
|
975
|
+
// AgentError("timeout") → kernel mempertahankan identitas timeout.
|
|
976
|
+
const rootTimeoutSignal =
|
|
977
|
+
effectiveTimeoutMs === Infinity || effectiveTimeoutMs === 0
|
|
978
|
+
? undefined
|
|
979
|
+
: (() => {
|
|
980
|
+
const rc = new AbortController()
|
|
981
|
+
const timer = setTimeout(
|
|
982
|
+
() =>
|
|
983
|
+
rc.abort(
|
|
984
|
+
new AgentError(
|
|
985
|
+
"timeout",
|
|
986
|
+
`run exceeded root wall-clock timeout (${effectiveTimeoutMs}ms)`,
|
|
987
|
+
),
|
|
988
|
+
),
|
|
989
|
+
effectiveTimeoutMs,
|
|
990
|
+
)
|
|
991
|
+
try {
|
|
992
|
+
;(timer as unknown as { unref?: () => void })?.unref?.()
|
|
993
|
+
} catch {}
|
|
994
|
+
return rc.signal
|
|
995
|
+
})()
|
|
218
996
|
|
|
219
997
|
const permissionMode = allowAll
|
|
220
998
|
? "allow-all"
|
|
@@ -297,21 +1075,178 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
297
1075
|
}),
|
|
298
1076
|
)
|
|
299
1077
|
|
|
300
|
-
// resume: load full history
|
|
1078
|
+
// resume: load full history dari baris kanonik → seed ke ContextStore.
|
|
1079
|
+
// --resume tak dikenal sudah melempar di resolver identitas (eksplisit);
|
|
1080
|
+
// tak ada lagi "not found → sesi baru diam-diam".
|
|
301
1081
|
let initialMessages: readonly Message[] | undefined
|
|
302
1082
|
let resumeTurnCount: number | undefined
|
|
1083
|
+
let resumeUsageSnapshot: UsageInitialSnapshot | undefined
|
|
1084
|
+
// P3.5 — carrier metadata runtime hasil seleksi (host-side, RAM, lifecycle-
|
|
1085
|
+
// scoped). Diisi HANYA di jalur resume yang membangun ContextSelection; sesi
|
|
1086
|
+
// baru tetap undefined (tak ada klaim kesegaran tanpa seleksi).
|
|
1087
|
+
let runtimeContextMetadata: RuntimeContextMetadata | undefined
|
|
303
1088
|
let recoveryAppendix = ""
|
|
304
|
-
|
|
1089
|
+
// P2.8 forensics: artefak context-only yang ditanam di buffer konteks pada
|
|
1090
|
+
// resume ini (bila proyeksi CURRENT). Dipakai persistCurrent untuk membuang
|
|
1091
|
+
// artefak turunan SEBELUM menulis ke histori kanonik. Tanpa deklarasi ini
|
|
1092
|
+
// ringkasan proyeksi bisa bocor ke `messages`.
|
|
1093
|
+
let contextOnlyArtifact: ContextOnlyArtifact | undefined
|
|
1094
|
+
// [Fase 4 / LOOP-13] Header operasional deterministik untuk system prompt
|
|
1095
|
+
// (buffer kedua: selalu dikirim, tak pernah dikompaksi, tak masuk histori).
|
|
1096
|
+
let runtimeStateHeader: string | undefined
|
|
1097
|
+
// [Fase 6A / ACE-01] Keputusan consequence terakhir. Dideklarasikan SEBELUM
|
|
1098
|
+
// blok resume agar `collectOperationalState` bisa menyertakannya pada header
|
|
1099
|
+
// yang dibangun saat sesi dilanjutkan (tidak ada akses ke system prompt
|
|
1100
|
+
// yang sudah dibekukan kernel setelah sesi dibuat).
|
|
1101
|
+
let lastAceDecision: ConsequenceDecision | null = null
|
|
1102
|
+
// Streak kegagalan verify (dipakai ACE sebagai `repeatedFailureCount`).
|
|
1103
|
+
let verifyFailureStreak = 0
|
|
1104
|
+
// Baseline kanonik saat resume (isi `messages` yang SUDAH durable). Setelah
|
|
1105
|
+
// proyeksi menutupi prefix, buffer konteks TIDAK lagi superset histori
|
|
1106
|
+
// kanonik — jadi persist harus menyusun ulang: baseline ++ ekor baru.
|
|
1107
|
+
let contextCanonicalBaseline: readonly unknown[] | undefined
|
|
1108
|
+
if (identity.resumed) {
|
|
1109
|
+
// P2.4: aktivasi default Thread SEBELUM seed kernel — backfill aditif
|
|
1110
|
+
// berpagar (konten/seq tak tersentuh). Basi di sini = gagal loud
|
|
1111
|
+
// (dunia bergerak pasca-admission); warn-swallow di bawah tak berlaku.
|
|
1112
|
+
// P2.5: backfill event_id legacy deterministik (NULL → evt_migr_*,
|
|
1113
|
+
// idempoten) agar SEMUA baris durable beridentitas stabil.
|
|
1114
|
+
const defaultThread = ensureDefaultThread(sessionId, cwd, { expectedEpoch })
|
|
1115
|
+
const backfilled = backfillHistoryEventIds(sessionId, cwd, { expectedEpoch })
|
|
1116
|
+
process.stderr.write(
|
|
1117
|
+
`${c.dim(`[thread sid=${sessionId} tid=${defaultThread.thread_id} head=${defaultThread.head_seq}${backfilled > 0 ? ` backfilled=${backfilled}` : ""}]\n`)}`,
|
|
1118
|
+
)
|
|
305
1119
|
try {
|
|
306
|
-
const prev = loadSession(
|
|
1120
|
+
const prev = loadSession(sessionId, cwd)
|
|
1121
|
+
if (prev) {
|
|
1122
|
+
resumeUsageSnapshot = loadSessionUsageSummary(sessionId, cwd)
|
|
1123
|
+
}
|
|
307
1124
|
if (prev?.messages.length) {
|
|
308
|
-
|
|
1125
|
+
// P2.8 — perakitan konteks (baca-saja, turunan, RAM): pakai ringkasan
|
|
1126
|
+
// proyeksi HANYA bila CURRENT; state lain/absen → fallback histori
|
|
1127
|
+
// kanonik utuh (identik replay sebelum P2.8). Tak pernah menulis apa pun.
|
|
1128
|
+
// `view` tetap dipakai untuk diagnostik + kompatibilitas P2.8.
|
|
1129
|
+
const view = assembleContext(sessionId, defaultThread.thread_id, cwd)
|
|
1130
|
+
|
|
1131
|
+
// [Fase 4 / LOOP-13, LOOP-INV-16] Kumpulkan snapshot state operasional
|
|
1132
|
+
// deterministik dari sumber durable (TaskStore + usage historis) agar
|
|
1133
|
+
// header [RUNTIME_STATE_HEADER] ikut ke konteks resume — tak hilang
|
|
1134
|
+
// walau riwayat dipangkas kompaksi. Sumber usage = snapshot resume
|
|
1135
|
+
// (collector belum ada di titik ini). Best-effort: absen = perilaku lama.
|
|
1136
|
+
let operationalState:
|
|
1137
|
+
| import("../src/session/runtime-header.ts").OperationalStateSnapshot
|
|
1138
|
+
| null = null
|
|
1139
|
+
try {
|
|
1140
|
+
const snapUsage = {
|
|
1141
|
+
getSession: () => ({
|
|
1142
|
+
inputTokens: resumeUsageSnapshot?.inputTokens ?? 0,
|
|
1143
|
+
outputTokens: resumeUsageSnapshot?.outputTokens ?? 0,
|
|
1144
|
+
totalTokens: resumeUsageSnapshot?.totalTokens ?? 0,
|
|
1145
|
+
cost: resumeUsageSnapshot?.totalCostUsd,
|
|
1146
|
+
}),
|
|
1147
|
+
getTurnCount: () => prev.turnCount ?? 0,
|
|
1148
|
+
}
|
|
1149
|
+
operationalState = collectOperationalState(
|
|
1150
|
+
sessionId,
|
|
1151
|
+
cwd ?? process.cwd(),
|
|
1152
|
+
snapUsage,
|
|
1153
|
+
null,
|
|
1154
|
+
lastAceDecision,
|
|
1155
|
+
)
|
|
1156
|
+
} catch {}
|
|
1157
|
+
|
|
1158
|
+
// P3.3 — selector kanonik menjadi produsen view (derived, murni). Ia
|
|
1159
|
+
// MEMBACA data yang sama (rows/revisi/proyeksi) dan menghasilkan
|
|
1160
|
+
// ContextSelection provenance-bound. P2.8 dipakai sebagai sumber
|
|
1161
|
+
// keputusan proyeksi + fallback identik; selector MEMPERLUAS dengan
|
|
1162
|
+
// budget-tail + laporan selectionBasis/freshness. Tak ada tulis kanonik.
|
|
1163
|
+
// Budget pesan = contextWindowTokens dikurangi overhead system+tools;
|
|
1164
|
+
// tanpa konfigurasi → tanpa batas (reproduksi P2.8 persis).
|
|
1165
|
+
const durableEvents = loadPresentationEvents(sessionId, cwd)
|
|
1166
|
+
const revision = countDurableCompactions(durableEvents as readonly { type: string }[])
|
|
1167
|
+
const rowsForSelector = loadThreadHistoryWithSeq(sessionId, defaultThread.thread_id, cwd)
|
|
1168
|
+
// P3.4: proyeksi kanonik durable adalah sumber UTAMA untuk selector
|
|
1169
|
+
// (cakupan-valid: CURRENT atau STALE berjangkar utuh, P3.0 §8 D6),
|
|
1170
|
+
// sehingga `summary-plus-tail` menjadi perilaku produksi nyata. P2.8
|
|
1171
|
+
// `assembleContext` (CURRENT-only) tetap jadi fallback kompatibel.
|
|
1172
|
+
const durableProjection = readConsumableSummaryProjection(
|
|
1173
|
+
sessionId,
|
|
1174
|
+
cwd,
|
|
1175
|
+
defaultThread.thread_id,
|
|
1176
|
+
)
|
|
1177
|
+
const projectionSummary =
|
|
1178
|
+
durableProjection ??
|
|
1179
|
+
(view.source === "projection" && view.summary
|
|
1180
|
+
? { baseSeq: view.coveredSeq, summaryText: view.summary }
|
|
1181
|
+
: undefined)
|
|
1182
|
+
const messageBudget =
|
|
1183
|
+
contextWindowTokens && contextWindowTokens > 0
|
|
1184
|
+
? contextWindowTokens
|
|
1185
|
+
: Number.MAX_SAFE_INTEGER
|
|
1186
|
+
// N1: turunkan frontier kanonis dari baris yang BARU DIBACA (sumber
|
|
1187
|
+
// kebenaran saat ini) dan teruskan ke selector — freshness dihitung
|
|
1188
|
+
// via assessContextFreshness (BUKAN hard-code "fresh"). Selector tetap
|
|
1189
|
+
// deskriptif; putusan publikasi tetap milik saveSession.
|
|
1190
|
+
const selectorRows = rowsForSelector.map((r) => ({ seq: r.seq, message: r.message }))
|
|
1191
|
+
const canonicalFrontier = deriveFrontierFromDurable({
|
|
1192
|
+
sessionId,
|
|
1193
|
+
threadId: defaultThread.thread_id,
|
|
1194
|
+
rows: rowsToCanonicalRefs(selectorRows),
|
|
1195
|
+
revision,
|
|
1196
|
+
})
|
|
1197
|
+
const selection = selectContext({
|
|
1198
|
+
sessionId,
|
|
1199
|
+
threadId: defaultThread.thread_id,
|
|
1200
|
+
rows: selectorRows,
|
|
1201
|
+
revision,
|
|
1202
|
+
...(projectionSummary ? { projection: projectionSummary } : {}),
|
|
1203
|
+
policy: { budgetTokens: messageBudget },
|
|
1204
|
+
canonicalFrontier,
|
|
1205
|
+
})
|
|
1206
|
+
initialMessages = selection.messages as readonly Message[]
|
|
1207
|
+
// [Fase 4 / LOOP-13, LOOP-INV-16] Simpan snapshot state operasional
|
|
1208
|
+
// deterministik untuk dijadikan header di SYSTEM prompt (buffer kedua):
|
|
1209
|
+
// selalu dikirim ke model, tidak pernah dihapus kompaksi, dan TIDAK
|
|
1210
|
+
// pernah masuk histori kanonik (nol risiko duplikasi).
|
|
1211
|
+
if (operationalState) {
|
|
1212
|
+
try {
|
|
1213
|
+
const { buildRuntimeStateHeader } = await import("../src/session/runtime-header.ts")
|
|
1214
|
+
runtimeStateHeader = buildRuntimeStateHeader(operationalState)
|
|
1215
|
+
} catch {}
|
|
1216
|
+
}
|
|
1217
|
+
// P3.5 (N1) — angkut metadata seleksi melewati batas seed runtime.
|
|
1218
|
+
// Hanya `messages` yang masuk kernel (initialMessages); identity/frontier/
|
|
1219
|
+
// revision/basis/freshness/provenance hidup di carrier host-side ini —
|
|
1220
|
+
// bukan pesan model, bukan otoritas, bukan store.
|
|
1221
|
+
runtimeContextMetadata = runtimeMetadataFromSelection(selection, revision)
|
|
1222
|
+
if (selection.contextOnly) {
|
|
1223
|
+
contextOnlyArtifact = selection.contextOnly
|
|
1224
|
+
contextCanonicalBaseline = prev.messages
|
|
1225
|
+
}
|
|
309
1226
|
resumeTurnCount = prev.turnCount
|
|
310
|
-
console.error(
|
|
1227
|
+
console.error(
|
|
1228
|
+
c.dim(
|
|
1229
|
+
// "(N messages)" dipertahankan VERBATIM (kontrak diagnostik yang
|
|
1230
|
+
// sudah dipakai test/CLI); detail perakitan P2.8 menyusul sebagai
|
|
1231
|
+
// segmen terpisah agar tak mengubah string yang sudah diam.
|
|
1232
|
+
`[resumed session ${sessionId} (${prev.messages.length} messages)]\n`,
|
|
1233
|
+
),
|
|
1234
|
+
)
|
|
1235
|
+
console.error(
|
|
1236
|
+
c.dim(
|
|
1237
|
+
`[context sid=${sessionId} source=${view.source} status=${view.status} covered=${view.coveredSeq}]\n`,
|
|
1238
|
+
),
|
|
1239
|
+
)
|
|
1240
|
+
// P3.3 — jejak provenance seleksi (baca-saja; tak mengubah perilaku).
|
|
1241
|
+
console.error(
|
|
1242
|
+
c.dim(
|
|
1243
|
+
`[select sid=${sessionId} basis=${selection.selectionBasis} freshness=${selection.freshness} head=${selection.frontier?.headSeq ?? "-"}]\n`,
|
|
1244
|
+
),
|
|
1245
|
+
)
|
|
311
1246
|
// P3 — validasi resume: bukan replay buta. Bila workspace berubah
|
|
312
1247
|
// sejak checkpoint terakhir (edit manual / run lain), beri tahu —
|
|
313
1248
|
// /undo tersedia bila perlu kembali. Best-effort, tak menggagalkan resume.
|
|
314
|
-
const div = await validateResumeWorkspace(cwd ?? ".",
|
|
1249
|
+
const div = await validateResumeWorkspace(cwd ?? ".", sessionId).catch(() => null)
|
|
315
1250
|
if (div && div.diverged > 0) {
|
|
316
1251
|
console.error(
|
|
317
1252
|
c.yellow(
|
|
@@ -320,11 +1255,13 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
320
1255
|
)
|
|
321
1256
|
}
|
|
322
1257
|
} else {
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
)
|
|
1258
|
+
// Defensif (tak terjangkau normal: resolver menjamin baris ada).
|
|
1259
|
+
console.error(c.yellow(`[resume] session ${sessionId} has no messages yet\n`))
|
|
326
1260
|
}
|
|
327
1261
|
} catch (e) {
|
|
1262
|
+
// P2.2/P2.4: pagar basi TIDAK boleh jadi warning — lempar ulang agar
|
|
1263
|
+
// startup gagal loud (dunia bergerak pasca-admission).
|
|
1264
|
+
if (e instanceof StaleWriterError || e instanceof ThreadArchivedError) throw e
|
|
328
1265
|
process.stderr.write(`[warn] resume failed: ${(e as Error).message}\n`)
|
|
329
1266
|
}
|
|
330
1267
|
}
|
|
@@ -334,8 +1271,8 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
334
1271
|
// teruskan sebagai SYSTEM appendix (bukan pesan user/assistant palsu).
|
|
335
1272
|
// Tanpa jurnal (sesi baru/bersih) = no-op. Tak pernah memblokir resume.
|
|
336
1273
|
try {
|
|
337
|
-
const persistedTurns = listPersistedTurns(
|
|
338
|
-
const rec = await planRecoveryForSession(
|
|
1274
|
+
const persistedTurns = listPersistedTurns(sessionId, cwd)
|
|
1275
|
+
const rec = await planRecoveryForSession(sessionId, cwd, { persistedTurns })
|
|
339
1276
|
for (const w of rec.warnings) process.stderr.write(c.yellow(`[recovery] ${w}\n`))
|
|
340
1277
|
if (rec.directive) {
|
|
341
1278
|
process.stderr.write(
|
|
@@ -347,6 +1284,34 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
347
1284
|
process.stderr.write(`[warn] recovery plan failed: ${(e as Error).message}\n`)
|
|
348
1285
|
}
|
|
349
1286
|
|
|
1287
|
+
let durablePresentationEvents: DomainEvent[] = []
|
|
1288
|
+
try {
|
|
1289
|
+
durablePresentationEvents = loadPresentationEvents(sessionId, cwd)
|
|
1290
|
+
} catch (e) {
|
|
1291
|
+
process.stderr.write(`[warn] presentation replay load failed: ${(e as Error).message}\n`)
|
|
1292
|
+
}
|
|
1293
|
+
let rebuiltPresentation: ReturnType<typeof rebuildFromDurable> | null = null
|
|
1294
|
+
try {
|
|
1295
|
+
rebuiltPresentation = rebuildFromDurable(
|
|
1296
|
+
durablePresentationEvents,
|
|
1297
|
+
createReducerDiagnostics(),
|
|
1298
|
+
sessionId,
|
|
1299
|
+
)
|
|
1300
|
+
} catch (e) {
|
|
1301
|
+
process.stderr.write(`[warn] presentation replay failed: ${(e as Error).message}\n`)
|
|
1302
|
+
}
|
|
1303
|
+
// P2.11 — replay watershed: state.seq sesaat setelah rebuild. Baris snapshot
|
|
1304
|
+
// pada/di bawah ini = replay/reconstructed; di atasnya = live (provenance
|
|
1305
|
+
// absen). null = tak pernah rebuild (semua baris live).
|
|
1306
|
+
const replayedUpToSeq: number | null = rebuiltPresentation ? rebuiltPresentation.state.seq : null
|
|
1307
|
+
const provenanceOf = (
|
|
1308
|
+
entry: { status?: string; incomplete?: boolean },
|
|
1309
|
+
seq: number,
|
|
1310
|
+
): { provenance?: "live" | "replay" | "reconstructed" | "unknown" } => {
|
|
1311
|
+
const provenance = projectProvenance(entry, seq, replayedUpToSeq)
|
|
1312
|
+
return provenance ? { provenance } : {}
|
|
1313
|
+
}
|
|
1314
|
+
|
|
350
1315
|
// P0-3 — pointer undo/redo basi (crash apply→save): adopsi dari marker
|
|
351
1316
|
// jurnal bila valid. Berjalan untuk SEMUA sesi (bukan hanya --resume),
|
|
352
1317
|
// karena --session <id> yang dipakai ulang tanpa --resume pun bisa basi.
|
|
@@ -368,15 +1333,75 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
368
1333
|
// mengamati bus kernel dan memancarkan DomainEvent ke subscriber-nya sendiri.
|
|
369
1334
|
// Dual-subscribe dengan sink lama — perilaku user NOL berubah pada Fase 1.
|
|
370
1335
|
let presentation: PresentationAdapter | null = null
|
|
371
|
-
//
|
|
372
|
-
//
|
|
373
|
-
let shadowState: PresentationState | null = null
|
|
374
|
-
let shadowDiag: ReducerDiagnostics | null =
|
|
1336
|
+
// Reducer memelihara PresentationState yang dipakai snapshot presentasi.
|
|
1337
|
+
// Divergensi = reduce melempar (harusnya 0).
|
|
1338
|
+
let shadowState: PresentationState | null = rebuiltPresentation?.state ?? null
|
|
1339
|
+
let shadowDiag: ReducerDiagnostics | null = rebuiltPresentation
|
|
1340
|
+
? createReducerDiagnostics()
|
|
1341
|
+
: null
|
|
375
1342
|
let shadowDivergence = 0
|
|
1343
|
+
let unsupportedProjection = 0
|
|
376
1344
|
let shadowUnsub: (() => void) | null = null
|
|
1345
|
+
let presentationWriteTail: Promise<void> = Promise.resolve()
|
|
1346
|
+
let presentationFlushTimer: ReturnType<typeof setTimeout> | undefined
|
|
1347
|
+
const pendingPresentationEvents: DomainEvent[] = []
|
|
1348
|
+
// [P13.6] Watermark seq live terakhir yang terkonfirmasi durable. Publish
|
|
1349
|
+
// hanya maju; batch yang gagal append tidak pernah majukan (fail-closed).
|
|
1350
|
+
let durableLiveSeq = -1
|
|
1351
|
+
// [P13.6] Satu titik tulis durable presentasi. Produksi = append asli
|
|
1352
|
+
// (pagar epoch sama); test menyuntik penghalang/kegagalan deterministik
|
|
1353
|
+
// lewat opts.presentationAppend (analog seam checkpoint jurnal).
|
|
1354
|
+
const appendPresentation =
|
|
1355
|
+
opts.presentationAppend ??
|
|
1356
|
+
((events: readonly DomainEvent[]) =>
|
|
1357
|
+
appendPresentationEvents(sessionId, cwd, events, { expectedEpoch }))
|
|
1358
|
+
const flushPresentationEvents = (): void => {
|
|
1359
|
+
if (presentationFlushTimer !== undefined) {
|
|
1360
|
+
clearTimeout(presentationFlushTimer)
|
|
1361
|
+
presentationFlushTimer = undefined
|
|
1362
|
+
}
|
|
1363
|
+
const batch = pendingPresentationEvents.splice(0)
|
|
1364
|
+
if (batch.length === 0) return
|
|
1365
|
+
presentationWriteTail = presentationWriteTail
|
|
1366
|
+
.then(async () => {
|
|
1367
|
+
const stats = await appendPresentation(batch)
|
|
1368
|
+
void stats
|
|
1369
|
+
// [P13.6] LIVE = DURABLE-CONFIRMED: terbitkan event durable hanya
|
|
1370
|
+
// SETELAH append sukses. Watermark menjaga urutan + membuat duplikat
|
|
1371
|
+
// (seq sudah pernah live) tidak dikirim ulang. Batas yang disengaja:
|
|
1372
|
+
// sesi hosted hanya menerima seq segar-adaptif (adapter meneruskan
|
|
1373
|
+
// dari kepala durable saat resume), sehingga collision (baris seq
|
|
1374
|
+
// sudah ada) tak mungkin menyusup ke sini — collision hanya mungkin
|
|
1375
|
+
// lintas-proses dan lintas-proses tak lewat flush ini.
|
|
1376
|
+
for (const event of batch) {
|
|
1377
|
+
if (event.eventSeq > durableLiveSeq) {
|
|
1378
|
+
durableLiveSeq = event.eventSeq
|
|
1379
|
+
publishDomainEvent(event)
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
})
|
|
1383
|
+
.catch((error) => {
|
|
1384
|
+
if (error instanceof StaleWriterError) {
|
|
1385
|
+
markWriterStale(`presentation flush refused (expected epoch ${error.expectedEpoch})`)
|
|
1386
|
+
return
|
|
1387
|
+
}
|
|
1388
|
+
process.stderr.write(
|
|
1389
|
+
`[warn] presentation event persist failed: ${(error as Error).message}\n`,
|
|
1390
|
+
)
|
|
1391
|
+
})
|
|
1392
|
+
}
|
|
1393
|
+
const queuePresentationEvent = (event: DomainEvent): void => {
|
|
1394
|
+
if (!DURABILITY[event.type]?.durable) return
|
|
1395
|
+
pendingPresentationEvents.push(event)
|
|
1396
|
+
if (presentationFlushTimer === undefined) {
|
|
1397
|
+
presentationFlushTimer = setTimeout(flushPresentationEvents, 0)
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
377
1400
|
const presentationSubscribers = new Set<(event: UiPresentationEvent) => void>()
|
|
378
|
-
//
|
|
379
|
-
//
|
|
1401
|
+
// [P13.5] Subscriber DomainEvent mentah. Dipisah dari proyeksi UI supaya feed
|
|
1402
|
+
// daemon bisa memakai `eventSeq` yang sama dengan baris durable.
|
|
1403
|
+
const domainEventSubscribers = new Set<(event: DomainEvent) => void>()
|
|
1404
|
+
// Content store in-memory untuk query /expand; jalur production.
|
|
380
1405
|
let contentStore: ContentStore | null = null
|
|
381
1406
|
const getShadowDiagnostics = (): {
|
|
382
1407
|
divergence: number
|
|
@@ -386,6 +1411,9 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
386
1411
|
orphanTool: number
|
|
387
1412
|
orphanApproval: number
|
|
388
1413
|
duplicateTurn: number
|
|
1414
|
+
unknownEvent: number
|
|
1415
|
+
orphanEvidence: number
|
|
1416
|
+
unsupportedProjection: number
|
|
389
1417
|
} => ({
|
|
390
1418
|
divergence: shadowDivergence,
|
|
391
1419
|
eventsIn: shadowDiag?.eventsIn ?? 0,
|
|
@@ -394,6 +1422,9 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
394
1422
|
orphanTool: shadowDiag?.orphanTool ?? 0,
|
|
395
1423
|
orphanApproval: shadowDiag?.orphanApproval ?? 0,
|
|
396
1424
|
duplicateTurn: shadowDiag?.duplicateTurn ?? 0,
|
|
1425
|
+
unknownEvent: shadowDiag?.unknownEvent ?? 0,
|
|
1426
|
+
orphanEvidence: shadowDiag?.orphanEvidence ?? 0,
|
|
1427
|
+
unsupportedProjection,
|
|
397
1428
|
})
|
|
398
1429
|
const getPresentationSnapshot = (): UiPresentationSnapshot => {
|
|
399
1430
|
if (!shadowState) return { activities: [], turns: [] }
|
|
@@ -436,97 +1467,93 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
436
1467
|
...(a.expandRef
|
|
437
1468
|
? { expandRef: { toolCallId: a.expandRef.toolCallId, idx: a.expandRef.idx } }
|
|
438
1469
|
: {}),
|
|
1470
|
+
...(a.verification
|
|
1471
|
+
? {
|
|
1472
|
+
verification: {
|
|
1473
|
+
invocationId: a.verification.invocationId,
|
|
1474
|
+
verdict: a.verification.verdict,
|
|
1475
|
+
method: a.verification.method,
|
|
1476
|
+
observedAt: a.verification.observedAt,
|
|
1477
|
+
},
|
|
1478
|
+
}
|
|
1479
|
+
: {}),
|
|
1480
|
+
...provenanceOf(a, a.seq),
|
|
439
1481
|
}))
|
|
440
1482
|
const turns: UiPresentationTurn[] = [...shadowState.turns.values()].map((turn) => ({
|
|
441
1483
|
turnId: turn.turnId,
|
|
442
1484
|
status: turn.status,
|
|
443
1485
|
...(turn.summary ? { summary: turn.summary as UiTurnSummary } : {}),
|
|
1486
|
+
...provenanceOf(turn, turn.seq),
|
|
444
1487
|
}))
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
name: event.identity.name,
|
|
515
|
-
qualified: event.identity.qualified,
|
|
516
|
-
target: event.argsSummary.target,
|
|
517
|
-
via: event.via,
|
|
518
|
-
}
|
|
519
|
-
case "approval.settled":
|
|
520
|
-
return {
|
|
521
|
-
type: event.type,
|
|
522
|
-
seq: event.eventSeq,
|
|
523
|
-
turnId: event.turnId,
|
|
524
|
-
approvalId: event.approvalId,
|
|
525
|
-
toolCallId: event.toolCallId,
|
|
526
|
-
outcome: event.outcome,
|
|
527
|
-
}
|
|
528
|
-
default:
|
|
529
|
-
return null
|
|
1488
|
+
const conversation: UiPresentationMessage[] = shadowState.conversation.map((entry) => ({
|
|
1489
|
+
id: entry.id,
|
|
1490
|
+
sessionId: entry.sessionId,
|
|
1491
|
+
turnId: entry.turnId,
|
|
1492
|
+
role: entry.role,
|
|
1493
|
+
text: entry.text,
|
|
1494
|
+
truncated: entry.truncated,
|
|
1495
|
+
...(entry.promptRef ? { promptRef: entry.promptRef } : {}),
|
|
1496
|
+
}))
|
|
1497
|
+
const reasoning: UiPresentationReasoning[] = shadowState.reasoning.map((entry) => ({
|
|
1498
|
+
id: entry.id,
|
|
1499
|
+
sessionId: entry.sessionId,
|
|
1500
|
+
turnId: entry.turnId,
|
|
1501
|
+
truncated: entry.truncated,
|
|
1502
|
+
expandRef: { toolCallId: entry.expandRef.toolCallId, idx: entry.expandRef.idx },
|
|
1503
|
+
}))
|
|
1504
|
+
const system: UiPresentationSystem[] = shadowState.system.map((entry) => ({
|
|
1505
|
+
id: entry.id,
|
|
1506
|
+
sessionId: entry.sessionId,
|
|
1507
|
+
turnId: entry.turnId,
|
|
1508
|
+
kind: entry.systemKind,
|
|
1509
|
+
text: entry.text,
|
|
1510
|
+
...(entry.reason ? { reason: entry.reason } : {}),
|
|
1511
|
+
severity: entry.severity,
|
|
1512
|
+
}))
|
|
1513
|
+
const plans: UiPresentationPlan[] = [...shadowState.plans.values()].map((entry) => ({
|
|
1514
|
+
planId: entry.planId,
|
|
1515
|
+
sessionId: entry.sessionId,
|
|
1516
|
+
turnId: entry.turnId,
|
|
1517
|
+
status: entry.status,
|
|
1518
|
+
steps: entry.steps,
|
|
1519
|
+
}))
|
|
1520
|
+
const findings: UiPresentationFinding[] = [...shadowState.findings.values()].map((entry) => ({
|
|
1521
|
+
findingId: entry.findingId,
|
|
1522
|
+
sessionId: entry.sessionId,
|
|
1523
|
+
turnId: entry.turnId,
|
|
1524
|
+
category: entry.category,
|
|
1525
|
+
severity: entry.severity,
|
|
1526
|
+
summary: entry.summary,
|
|
1527
|
+
evidence: entry.evidence,
|
|
1528
|
+
}))
|
|
1529
|
+
const results: UiPresentationResult[] = [...shadowState.results.values()].map((entry) => ({
|
|
1530
|
+
resultId: entry.resultId,
|
|
1531
|
+
sessionId: entry.sessionId,
|
|
1532
|
+
turnId: entry.turnId,
|
|
1533
|
+
status: entry.status,
|
|
1534
|
+
summary: entry.summary,
|
|
1535
|
+
...(entry.action ? { action: entry.action } : {}),
|
|
1536
|
+
}))
|
|
1537
|
+
const diagnostics: UiPresentationDiagnostic[] = shadowState.diagnostics.map((entry) => ({
|
|
1538
|
+
id: entry.id,
|
|
1539
|
+
sessionId: entry.sessionId,
|
|
1540
|
+
turnId: entry.turnId,
|
|
1541
|
+
category: entry.category,
|
|
1542
|
+
severity: entry.severity,
|
|
1543
|
+
message: entry.message,
|
|
1544
|
+
...(entry.cause ? { cause: entry.cause } : {}),
|
|
1545
|
+
...(entry.action ? { action: entry.action } : {}),
|
|
1546
|
+
}))
|
|
1547
|
+
return {
|
|
1548
|
+
activities,
|
|
1549
|
+
turns,
|
|
1550
|
+
conversation,
|
|
1551
|
+
reasoning,
|
|
1552
|
+
system,
|
|
1553
|
+
plans,
|
|
1554
|
+
findings,
|
|
1555
|
+
results,
|
|
1556
|
+
diagnostics,
|
|
530
1557
|
}
|
|
531
1558
|
}
|
|
532
1559
|
const onPresentationEvent = (handler: (event: UiPresentationEvent) => void): (() => void) => {
|
|
@@ -535,13 +1562,30 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
535
1562
|
}
|
|
536
1563
|
const publishPresentationEvent = (event: Parameters<typeof toPresentationEvent>[0]): void => {
|
|
537
1564
|
const projected = toPresentationEvent(event)
|
|
538
|
-
if (!projected)
|
|
1565
|
+
if (!projected) {
|
|
1566
|
+
unsupportedProjection++
|
|
1567
|
+
return
|
|
1568
|
+
}
|
|
539
1569
|
for (const handler of [...presentationSubscribers]) {
|
|
540
1570
|
try {
|
|
541
1571
|
handler(projected)
|
|
542
1572
|
} catch {}
|
|
543
1573
|
}
|
|
544
1574
|
}
|
|
1575
|
+
const onDomainEvent = (handler: (event: DomainEvent) => void): (() => void) => {
|
|
1576
|
+
domainEventSubscribers.add(handler)
|
|
1577
|
+
return () => domainEventSubscribers.delete(handler)
|
|
1578
|
+
}
|
|
1579
|
+
const publishDomainEvent = (event: DomainEvent): void => {
|
|
1580
|
+
for (const handler of [...domainEventSubscribers]) {
|
|
1581
|
+
// Satu subscriber gagal tak boleh memutus subscriber lain atau
|
|
1582
|
+
// mempersentasikan turn sebagai gagal: ini jalur observasi, bukan
|
|
1583
|
+
// authoritas lifecycle.
|
|
1584
|
+
try {
|
|
1585
|
+
handler(event)
|
|
1586
|
+
} catch {}
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
545
1589
|
const compaction = process.env.DEEPSEEK_API_KEY
|
|
546
1590
|
? createLlmCompaction({
|
|
547
1591
|
apiKey: process.env.DEEPSEEK_API_KEY,
|
|
@@ -564,11 +1608,30 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
564
1608
|
},
|
|
565
1609
|
})
|
|
566
1610
|
: undefined
|
|
567
|
-
const {
|
|
568
|
-
|
|
1611
|
+
const {
|
|
1612
|
+
sessionTools,
|
|
1613
|
+
evidenceMode,
|
|
1614
|
+
setWorkMode: setToolWorkMode,
|
|
1615
|
+
} = await startupPhase("tool-layer", () =>
|
|
1616
|
+
setupToolLayer(
|
|
1617
|
+
cfg,
|
|
1618
|
+
toolScope ?? "full",
|
|
1619
|
+
permissionMode,
|
|
1620
|
+
{
|
|
1621
|
+
sessionId,
|
|
1622
|
+
threadId: DEFAULT_THREAD_ID,
|
|
1623
|
+
cwd: cwd ?? process.cwd(),
|
|
1624
|
+
},
|
|
1625
|
+
// F-03 (P5 §C2): background bash job diikat ke sid kanonik sesi ini —
|
|
1626
|
+
// instance yang diikat sid tidak pernah dipasok lewat argumen tool.
|
|
1627
|
+
sessionId,
|
|
1628
|
+
// P12 S2.2: ceiling WorkMode untuk visibilitas tool (DISCUSS/PLAN).
|
|
1629
|
+
workMode,
|
|
1630
|
+
),
|
|
569
1631
|
)
|
|
570
1632
|
|
|
571
|
-
// todo_write/todo_read menyimpan state per sesi di .minicode/todos/<id>.json
|
|
1633
|
+
// todo_write/todo_read menyimpan state per sesi di .minicode/todos/<id>.json,
|
|
1634
|
+
// terikat pada identitas kanonik (P2.1: satu sid untuk semua komponen).
|
|
572
1635
|
todoSession.id = sessionId
|
|
573
1636
|
todoSession.cwd = cwd
|
|
574
1637
|
// View pertanyaan ask_user — composition root meng-inject, tool menolak
|
|
@@ -585,8 +1648,29 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
585
1648
|
...(rateLimiter ? { rateLimiter } : {}),
|
|
586
1649
|
...(providerOverride ? { defaultProviderId: providerOverride } : {}),
|
|
587
1650
|
})
|
|
1651
|
+
// P2.9 — lineage parent Run untuk anak Sub-Agent. Composition root satu-
|
|
1652
|
+
//-satunya pemilik Run hidup; tooltak pernah mengarang id ini (vendor
|
|
1653
|
+
// ToolContext tak membawa execution id).
|
|
1654
|
+
setSubAgentParentRunId(() => currentRunId)
|
|
1655
|
+
// P12 S2.2 Slice 5 — WorkMode RUNTIME. Handle kontrol diambil dari session
|
|
1656
|
+
// (onWorkMode) lalu dibaca LIVE di mana pun WorkMode dibutuhkan, supaya
|
|
1657
|
+
// transisi operator (command `/work-mode`) berlaku pada sesi yang sedang
|
|
1658
|
+
// berjalan — bukan snapshot saat session dibuat.
|
|
1659
|
+
let workModeControl: WorkModeControl | undefined
|
|
1660
|
+
// Warisan WorkMode ke sub-agen: composition root adalah satu-satunya pemilik
|
|
1661
|
+
// WorkMode efektif. Suntikkan sebagai fn LIVE (dibaca saat delegate_task
|
|
1662
|
+
// execute) supaya delegasi berikutnya mewarisi WorkMode parent yang AKTIF
|
|
1663
|
+
// saat itu — bukan snapshot lama. Tanpa ini ToolContext.permissionMode
|
|
1664
|
+
// (hanya PM, bukan WorkMode) membuat delegate_task melahirkan anak tanpa
|
|
1665
|
+
// ceiling WorkMode.
|
|
1666
|
+
setSubAgentWorkMode(() => workModeControl?.getWorkMode() ?? "EXECUTE")
|
|
588
1667
|
|
|
589
1668
|
let permissions: PermissionControl | undefined
|
|
1669
|
+
let noProgressDetector: NoProgressDetector | null = null
|
|
1670
|
+
const effectiveMaxTurns = (() => {
|
|
1671
|
+
const raw = (opts as { maxTurns?: number }).maxTurns ?? Number(process.env.MINICODE_MAX_TURNS)
|
|
1672
|
+
return typeof raw === "number" && Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : undefined
|
|
1673
|
+
})()
|
|
590
1674
|
// Validasi concurrency: 0, NaN, Infinity → fallback ke default (jangan teruskan 0 ke executor)
|
|
591
1675
|
const safeConcurrency = (() => {
|
|
592
1676
|
const v = opts.concurrency
|
|
@@ -603,19 +1687,55 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
603
1687
|
cwd,
|
|
604
1688
|
permissionMode,
|
|
605
1689
|
allowLocalConfig,
|
|
606
|
-
|
|
1690
|
+
// P12 S2.2 — WorkMode efektif sesi ini (default EXECUTE). Sesi dengan
|
|
1691
|
+
// workMode non-EXECUTE dipasangi ceiling handler di session.ts; sesi
|
|
1692
|
+
// yang memakai permissionHandler terinjeksi (6S/autonomous) akan
|
|
1693
|
+
// di-reject oleh fail-closed di sana (tak pernah melewati ceiling).
|
|
1694
|
+
workMode,
|
|
1695
|
+
// [Fase 4 / LOOP-13, LOOP-INV-16] Header operasional deterministik di
|
|
1696
|
+
// system prompt = buffer kedua yang selalu dikirim dan tak pernah
|
|
1697
|
+
// dikompaksi; tidak pernah masuk histori kanonik. Absen = perilaku lama.
|
|
1698
|
+
systemExtra: `${runtimeStateHeader ? `${runtimeStateHeader}\n\n` : ""}${systemExtra ?? ""}${recoveryAppendix}`,
|
|
607
1699
|
model: modelRef.current,
|
|
608
|
-
ask:
|
|
1700
|
+
// P13.6 — ask permission: composition root boleh menyuntik jalur headless
|
|
1701
|
+
// (daemon → ApprovalBroker). Tanpa injeksi tetap prompt TTY; non-TTY ⇒
|
|
1702
|
+
// deny (fail-closed), bukan izin diam-diam.
|
|
1703
|
+
ask: opts.permissionAsk ?? promptAsk,
|
|
609
1704
|
// Cermin observability persetujuan → adaptor presentasi. Keputusan gate
|
|
610
1705
|
// tetap milik permission handler; hook ini hanya melaporkan.
|
|
611
1706
|
onApprovalEvent: (e) => {
|
|
612
1707
|
presentation?.publishApproval(e)
|
|
613
1708
|
},
|
|
1709
|
+
// [Fase 1 / LOOP-INV-03] Durability-before-effect: intent jurnal ditulis
|
|
1710
|
+
// dan DI-AWAIT sebelum tool dijalankan. Tanpa ini, `execution:started`
|
|
1711
|
+
// memicu penulisan fire-and-forget sehingga efek bisa terjadi lebih dulu.
|
|
1712
|
+
beforeToolEffect: async (call) => {
|
|
1713
|
+
if (journalHandle !== null) await journalHandle.preflightIntent(call)
|
|
1714
|
+
},
|
|
614
1715
|
onPermissions: (ctl) => {
|
|
615
1716
|
permissions = ctl
|
|
616
1717
|
},
|
|
1718
|
+
// P12 S2.2 Slice 5 — handle kontrol WorkMode runtime. Setelah sesi
|
|
1719
|
+
// dibangun, handle ini di-warisi ke sub-agent/hooks/footer sehingga
|
|
1720
|
+
// transisi operator berlaku pada sesi yang sedang berjalan.
|
|
1721
|
+
onWorkMode: (ctl) => {
|
|
1722
|
+
// P12 S2.2 Slice 5 - SATU sumber state: handler WorkMode (ctl).
|
|
1723
|
+
// Visibilitas tool DITURUNKAN dari state yang sama (bukan state
|
|
1724
|
+
// terpisah) supaya ceiling dan daftar tool tak bisa berbeda.
|
|
1725
|
+
workModeControl = {
|
|
1726
|
+
setWorkMode: (m) => {
|
|
1727
|
+
ctl.setWorkMode(m)
|
|
1728
|
+
setToolWorkMode?.(m)
|
|
1729
|
+
},
|
|
1730
|
+
getWorkMode: () => ctl.getWorkMode(),
|
|
1731
|
+
}
|
|
1732
|
+
},
|
|
617
1733
|
...(initialMessages ? { initialMessages } : {}),
|
|
618
1734
|
...(resumeTurnCount !== undefined ? { turnCount: resumeTurnCount } : {}),
|
|
1735
|
+
...(effectiveMaxTurns !== undefined ? { maxTurns: effectiveMaxTurns } : {}),
|
|
1736
|
+
onNoProgress: (detector) => {
|
|
1737
|
+
noProgressDetector = detector
|
|
1738
|
+
},
|
|
619
1739
|
...(maxSteps ? { maxSteps } : {}),
|
|
620
1740
|
...(contextWindowTokens ? { contextWindowTokens } : {}),
|
|
621
1741
|
...(keepRecentTurns ? { keepRecentTurns } : {}),
|
|
@@ -631,24 +1751,50 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
631
1751
|
// Content store Fase 4: adapter menaruh konten completed ke store (put
|
|
632
1752
|
// selalu jalan); expand(id) di tui di belakang flag.
|
|
633
1753
|
contentStore = createContentStore()
|
|
1754
|
+
let initialTurn = 0
|
|
1755
|
+
let initialTurnStartTs = 0
|
|
1756
|
+
for (const turn of shadowState?.turns.values() ?? []) {
|
|
1757
|
+
if (turn.turnId > initialTurn) {
|
|
1758
|
+
initialTurn = turn.turnId
|
|
1759
|
+
initialTurnStartTs = turn.tsStart
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
634
1762
|
// Adaptor mulai mengamati sejak bus hidup (closure onApprovalEvent di atas
|
|
635
1763
|
// aman: check() pertama selalu terjadi setelah wiring ini, saat run()).
|
|
636
1764
|
presentation = createPresentationAdapter(session.events, {
|
|
1765
|
+
// P2.1: identitas kanonik tunggal — payload dan baris memakai sid yang sama.
|
|
637
1766
|
sessionId,
|
|
638
1767
|
...(contentStore ? { contentStore } : {}),
|
|
1768
|
+
// PHASE 4A.4 - canonical task identity for the plan projection. TaskStore is
|
|
1769
|
+
// the authority: an id is reported only when that row really exists for this
|
|
1770
|
+
// session, so an unresolvable plan degrades to the positional shape instead
|
|
1771
|
+
// of emitting a false payloadVersion 2.
|
|
1772
|
+
taskIdentityProvider: createTaskIdentityResolver(cwd ?? process.cwd()),
|
|
1773
|
+
...(shadowState ? { initialSeq: shadowState.seq, initialTurn, initialTurnStartTs } : {}),
|
|
639
1774
|
})
|
|
640
|
-
// Shadow reducer (Fase 3): consume DomainEvent yang sama, hasil dibuang.
|
|
641
|
-
// Shadow reducer berjalan paralel (observability), output TUI/linear memakai
|
|
642
|
-
// proyeksi presentasi yang sama.
|
|
643
1775
|
try {
|
|
644
|
-
shadowState = createInitialState(sessionId)
|
|
645
|
-
shadowDiag = createReducerDiagnostics()
|
|
1776
|
+
if (!shadowState) shadowState = createInitialState(sessionId)
|
|
1777
|
+
if (!shadowDiag) shadowDiag = createReducerDiagnostics()
|
|
1778
|
+
presentation.setTurnSummaryProvider(({ sessionId: eventSessionId, turnId, fallback }) => {
|
|
1779
|
+
return shadowState
|
|
1780
|
+
? deriveTurnSummary(shadowState, eventSessionId, turnId, fallback)
|
|
1781
|
+
: fallback
|
|
1782
|
+
})
|
|
646
1783
|
shadowUnsub = presentation.onEvent((e) => {
|
|
647
1784
|
try {
|
|
648
1785
|
if (shadowState && shadowDiag) reduce(shadowState, e, shadowDiag)
|
|
649
1786
|
} catch {
|
|
650
1787
|
shadowDivergence++
|
|
651
1788
|
}
|
|
1789
|
+
queuePresentationEvent(e)
|
|
1790
|
+
// [P13.6] Event durable TIDAK diterbitkan live di sini — hanya SETELAH
|
|
1791
|
+
// append durable sukses (lihat flushPresentationEvents). Feed live harus
|
|
1792
|
+
// subset dari toko durable: kalau append gagal/crash sebelum flush, event
|
|
1793
|
+
// itu tidak boleh pernah tampak live (konsumen bisa meng-ack-nya, dan
|
|
1794
|
+
// offset durable akan melampaui sejarah yang sebenarnya ada). Event
|
|
1795
|
+
// non-durable (delta) tetap langsung — feed daemon memfilternya dan UI
|
|
1796
|
+
// butuh delta real-time.
|
|
1797
|
+
if (!DURABILITY[e.type]?.durable) publishDomainEvent(e)
|
|
652
1798
|
publishPresentationEvent(e)
|
|
653
1799
|
})
|
|
654
1800
|
} catch {
|
|
@@ -661,15 +1807,40 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
661
1807
|
// terminal di execution:completed — keduanya post-gate kernel. Total:
|
|
662
1808
|
// kegagalan tulis jurnal tak pernah menggagalkan turn (degraded-loud).
|
|
663
1809
|
// Fase 4: onCommitted → file.changed (receipt paths+journalSeq) ke adapter.
|
|
664
|
-
|
|
1810
|
+
// [Fase 1] Simpan handle pre-flight (dipakai barrier di atas) dan pasang
|
|
1811
|
+
// pelacakan operasi in-flight untuk `runs.pending_tool_ids`.
|
|
1812
|
+
//
|
|
1813
|
+
// Penanda in-flight dipasang dari bus event KERNEL, bukan dari barrier:
|
|
1814
|
+
// `execution:started` di-emit secara SINKRON tepat sebelum `tool.execute`
|
|
1815
|
+
// (vendor/minicore/src/core/executor.ts:86 vs :89), sehingga `beginToolInFlight`
|
|
1816
|
+
// (tulis SQLite sinkron) sudah durable saat `tool.execute` mulai. Tool yang
|
|
1817
|
+
// ditolak policy tidak pernah sampai ke event ini, jadi daftar hanya berisi
|
|
1818
|
+
// operasi yang benar-benar akan berjalan.
|
|
1819
|
+
//
|
|
1820
|
+
// Catatan kontrak (revisi Fase 1): jalur UTAMA intent sekarang ditulis oleh
|
|
1821
|
+
// barrier pre-efek yang DI-AWAIT; listener `execution:started` tinggal
|
|
1822
|
+
// fallback untuk tool yang tidak lewat barrier. Konsekuensinya disengaja:
|
|
1823
|
+
// gagal menulis intent = tool DITOLAK (fail-closed), bukan jalan tanpa bukti.
|
|
1824
|
+
journalHandle = attachMutationJournal(session, {
|
|
665
1825
|
sessionId,
|
|
666
1826
|
cwd,
|
|
1827
|
+
evidenceMode,
|
|
667
1828
|
onCommitted: (info) => {
|
|
668
1829
|
try {
|
|
669
1830
|
presentation?.noteFileChanged(info)
|
|
670
1831
|
} catch {}
|
|
671
1832
|
},
|
|
672
1833
|
})
|
|
1834
|
+
session.events.on("execution:started", (e) => {
|
|
1835
|
+
const ev = e as unknown as { execution?: { call?: { id?: unknown } } }
|
|
1836
|
+
const id = typeof ev.execution?.call?.id === "string" ? ev.execution.call.id : ""
|
|
1837
|
+
if (id !== "") beginToolInFlight(id)
|
|
1838
|
+
})
|
|
1839
|
+
session.events.on("execution:completed", (e) => {
|
|
1840
|
+
const ev = e as unknown as { execution?: { call?: { id?: unknown } } }
|
|
1841
|
+
const id = typeof ev.execution?.call?.id === "string" ? ev.execution.call.id : ""
|
|
1842
|
+
if (id !== "") endToolInFlight(id)
|
|
1843
|
+
})
|
|
673
1844
|
|
|
674
1845
|
// ── Shadow checkpoint ──
|
|
675
1846
|
// Repo git: simpan SHA tree pre/post turn (O(delta), tanpa cap file, tidak
|
|
@@ -679,6 +1850,79 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
679
1850
|
type TurnSnapshot = Awaited<ReturnType<typeof beginTurnSnapshot>>
|
|
680
1851
|
let preTurnPromise: Promise<TurnSnapshot> | null = null
|
|
681
1852
|
const postEditSnapshots = new Map<string, { path: string; content: string | null }>()
|
|
1853
|
+
|
|
1854
|
+
// ── Kepemilikan pekerjaan checkpoint (Stage 5B) ──
|
|
1855
|
+
//
|
|
1856
|
+
// Bus kernel memanggil handler SINKRON dan TIDAK menunggu promise yang
|
|
1857
|
+
// dikembalikan handler async. Listener `turn:completed` di bawah memulai
|
|
1858
|
+
// penulisan checkpoint async — tanpa pemilik eksplisit, operasi itu
|
|
1859
|
+
// menjadi yatim: bisa berjalan SETELAH `close()` kembali (rejection →
|
|
1860
|
+
// unhandled error) dan bisa menulis ke direktori yang sudah dibersihkan.
|
|
1861
|
+
//
|
|
1862
|
+
// Kepemilikan: SET promise yang masih berjalan (bukan "promise terakhir"):
|
|
1863
|
+
// beberapa turn bisa memicu beberapa operasi, dan semuanya harus
|
|
1864
|
+
// diselesaikan. Setiap operasi dihapus dari set saat settle (sukses
|
|
1865
|
+
// maupun gagal).
|
|
1866
|
+
const pendingCheckpointWork = new Set<Promise<unknown>>()
|
|
1867
|
+
const checkpointFailureNotes: string[] = []
|
|
1868
|
+
let checkpointUnsub: (() => void) | null = null
|
|
1869
|
+
|
|
1870
|
+
/**
|
|
1871
|
+
* Diagnostic `[warn]` ke stderr (kontrak writer kelas 3: layer non-UI boleh
|
|
1872
|
+
* `process.stderr.write` mentah). Satu helper untuk semua `[warn]` di file
|
|
1873
|
+
* ini — jumlah writer inventory tak naik.
|
|
1874
|
+
*/
|
|
1875
|
+
const warnLine = (message: string): void => {
|
|
1876
|
+
try {
|
|
1877
|
+
process.stderr.write(`[warn] ${message}\n`)
|
|
1878
|
+
} catch {}
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
/**
|
|
1882
|
+
* Daftarkan pekerjaan checkpoint async sebagai milik lifecycle sesi ini.
|
|
1883
|
+
*
|
|
1884
|
+
* Rejection ditangani SEKALI di titik lahirnya (bukan ditunggu di
|
|
1885
|
+
* `close()`): kegagalan jadi tercatat — bukan unhandled rejection, dan
|
|
1886
|
+
* bukan sukses palsu. Yang dicatat hanya pesan error (tak ada credential
|
|
1887
|
+
* di jalur ini: pesan internal filesystem/session).
|
|
1888
|
+
*/
|
|
1889
|
+
const trackCheckpointWork = (work: Promise<unknown>): void => {
|
|
1890
|
+
pendingCheckpointWork.add(work)
|
|
1891
|
+
const settle = (): void => {
|
|
1892
|
+
pendingCheckpointWork.delete(work)
|
|
1893
|
+
}
|
|
1894
|
+
work
|
|
1895
|
+
.catch((err: unknown) => {
|
|
1896
|
+
const reason = (err as Error)?.message ?? String(err)
|
|
1897
|
+
const note = `checkpoint failed: ${reason}`
|
|
1898
|
+
checkpointFailureNotes.push(note)
|
|
1899
|
+
warnLine(note)
|
|
1900
|
+
})
|
|
1901
|
+
.then(settle, settle)
|
|
1902
|
+
.catch(() => {})
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
/**
|
|
1906
|
+
* Drain: TUNGGU seluruh pekerjaan checkpoint yang sudah dimulai.
|
|
1907
|
+
*
|
|
1908
|
+
* Listener dilepas lebih dulu — tak boleh ada operasi checkpoint baru yang
|
|
1909
|
+
* lahir setelah drain (listener itu yang memulainya). Loop, bukan sekali:
|
|
1910
|
+
* pekerjaan yang lahir saat drain berjalan ikut tertunggu.
|
|
1911
|
+
*/
|
|
1912
|
+
const drainCheckpointWork = async (): Promise<void> => {
|
|
1913
|
+
try {
|
|
1914
|
+
checkpointUnsub?.()
|
|
1915
|
+
} catch {}
|
|
1916
|
+
checkpointUnsub = null
|
|
1917
|
+
while (pendingCheckpointWork.size > 0) {
|
|
1918
|
+
const batch = [...pendingCheckpointWork]
|
|
1919
|
+
await Promise.allSettled(batch)
|
|
1920
|
+
// Buang yang sudah selesai — defensif: drain tak boleh bergantung
|
|
1921
|
+
// pada callback settle (kalau tak sempat jalan, loop tak boleh berputar).
|
|
1922
|
+
for (const done of batch) pendingCheckpointWork.delete(done)
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
|
|
682
1926
|
session.events.on("turn:started", () => {
|
|
683
1927
|
preTurnPromise = beginTurnSnapshot(sessionId, cwd ?? ".")
|
|
684
1928
|
})
|
|
@@ -694,30 +1938,66 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
694
1938
|
postEditSnapshots.set(p, { path: p.replace(/\\/g, "/"), content: null })
|
|
695
1939
|
}
|
|
696
1940
|
})
|
|
697
|
-
session.events.on("turn:completed",
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
1941
|
+
checkpointUnsub = session.events.on("turn:completed", (e) => {
|
|
1942
|
+
// Handler SINKRON: bus tak menunggu, jadi seluruh pekerjaan async-nya
|
|
1943
|
+
// diambil alih lifecycle (trackCheckpointWork) dan DILEWATI di close().
|
|
1944
|
+
// Handler async yang dilepas ke bus = rejection tanpa pemilik = unhandled
|
|
1945
|
+
// error (bukti Stage 5A).
|
|
1946
|
+
trackCheckpointWork(
|
|
1947
|
+
(async () => {
|
|
1948
|
+
const pre = await preTurnPromise
|
|
1949
|
+
const redoSnapshots = [...postEditSnapshots.values()]
|
|
1950
|
+
preTurnPromise = null
|
|
1951
|
+
postEditSnapshots.clear()
|
|
1952
|
+
if (!pre) return
|
|
1953
|
+
const turn =
|
|
1954
|
+
typeof e.result?.usage?.turns === "number"
|
|
1955
|
+
? e.result.usage.turns
|
|
1956
|
+
: session.state.turnCount
|
|
1957
|
+
const desc = `turn ${turn}`
|
|
1958
|
+
if (pre.mode === "git") {
|
|
1959
|
+
const after = await snapshotTree(cwd ?? ".", sessionId, `post-${turn}`)
|
|
1960
|
+
const checkpoint = await recordCheckpointFromTrees(
|
|
1961
|
+
sessionId,
|
|
1962
|
+
turn,
|
|
1963
|
+
pre.tree,
|
|
1964
|
+
after?.tree,
|
|
1965
|
+
desc,
|
|
1966
|
+
cwd,
|
|
1967
|
+
)
|
|
1968
|
+
if (checkpoint) {
|
|
1969
|
+
presentation?.noteCheckpoint({
|
|
1970
|
+
checkpointId: checkpoint.id,
|
|
1971
|
+
turnId: turn,
|
|
1972
|
+
paths: [],
|
|
1973
|
+
})
|
|
1974
|
+
}
|
|
1975
|
+
return
|
|
1976
|
+
}
|
|
1977
|
+
if (pre.snapshots.length === 0) return
|
|
1978
|
+
let redo = redoSnapshots
|
|
1979
|
+
try {
|
|
1980
|
+
const { LIMITS } = await import("../src/constants.ts")
|
|
1981
|
+
const post = await snapshotWorkspace(cwd ?? ".", LIMITS.WORKSPACE_SNAPSHOT_LIMIT)
|
|
1982
|
+
if (post.length) redo = post
|
|
1983
|
+
} catch {}
|
|
1984
|
+
const checkpoint = await recordCheckpointFromSnapshots(
|
|
1985
|
+
sessionId,
|
|
1986
|
+
turn,
|
|
1987
|
+
pre.snapshots,
|
|
1988
|
+
desc,
|
|
1989
|
+
cwd,
|
|
1990
|
+
redo,
|
|
1991
|
+
)
|
|
1992
|
+
if (checkpoint) {
|
|
1993
|
+
presentation?.noteCheckpoint({
|
|
1994
|
+
checkpointId: checkpoint.id,
|
|
1995
|
+
turnId: turn,
|
|
1996
|
+
paths: (redo ?? []).map((snapshot) => snapshot.path),
|
|
1997
|
+
})
|
|
1998
|
+
}
|
|
1999
|
+
})(),
|
|
2000
|
+
)
|
|
721
2001
|
})
|
|
722
2002
|
|
|
723
2003
|
// ── Step trace (Harness-P1) ──
|
|
@@ -753,8 +2033,11 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
753
2033
|
// F1.2: token kumulatif sesi saat tool selesai — bahan kurva token.
|
|
754
2034
|
// `usage` dideklarasikan di bawah, tapi callback ini baru jalan setelah
|
|
755
2035
|
// createCliSession selesai — aman dari TDZ.
|
|
2036
|
+
// [Audit #2 B.5] `.catch` di sini redundan: writeStepTrace sudah
|
|
2037
|
+
// menelan seluruh error async di dalamnya (trace.ts), dan argumen
|
|
2038
|
+
// dibangun sinkron di bawah guard `try/catch` di atas.
|
|
756
2039
|
totalTokens: usage.getSession().totalTokens,
|
|
757
|
-
})
|
|
2040
|
+
})
|
|
758
2041
|
} catch {}
|
|
759
2042
|
})
|
|
760
2043
|
session.events.on("step:completed", (e) => {
|
|
@@ -769,8 +2052,88 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
769
2052
|
errors: s.results.filter((r) => r.isError).length,
|
|
770
2053
|
sandbox: process.env.MINICODE_SANDBOX ?? "none",
|
|
771
2054
|
// F1.2: sama seperti baris tool — kumulatif sesi saat step selesai.
|
|
2055
|
+
// [Audit #2 B.5] `.catch` di sini redundan: writeStepTrace sudah
|
|
2056
|
+
// menelan seluruh error async di dalamnya (trace.ts), dan argumen
|
|
2057
|
+
// dibangun sinkron di bawah guard `try/catch` di atas.
|
|
772
2058
|
totalTokens: usage.getSession().totalTokens,
|
|
773
|
-
})
|
|
2059
|
+
})
|
|
2060
|
+
} catch {}
|
|
2061
|
+
})
|
|
2062
|
+
// ── P2.11 observasi verifikasi (observation-only) ──
|
|
2063
|
+
// Bukti kanonik hidup di jurnal mutasi; presentasi hanya mengamatinya.
|
|
2064
|
+
// Setiap tool selesai (dan setiap turn selesai untuk verifikasi susulan),
|
|
2065
|
+
// baca jurnal fire-and-forget lalu terbitkan verification.observed HANYA
|
|
2066
|
+
// bila ada baris verifikasi eksplisit untuk invokasi yang tepat-satu.
|
|
2067
|
+
// Ketiadaan event = UNKNOWN (diturunkan di proyeksi). Tak pernah melempar
|
|
2068
|
+
// ke turn; tak pernah menyimpulkan efek dari teks/status.
|
|
2069
|
+
const verificationEmitted = new Set<string>()
|
|
2070
|
+
const completedToolCalls: Array<{
|
|
2071
|
+
id: string
|
|
2072
|
+
tool: string
|
|
2073
|
+
argsHash: string
|
|
2074
|
+
turn: number | null
|
|
2075
|
+
scopeSession: string
|
|
2076
|
+
}> = []
|
|
2077
|
+
const emitVerificationForCall = (
|
|
2078
|
+
call: { id: string; tool: string; argsHash: string; turn: number | null },
|
|
2079
|
+
scopeSession: string,
|
|
2080
|
+
): void => {
|
|
2081
|
+
void (async () => {
|
|
2082
|
+
try {
|
|
2083
|
+
const { records } = await loadJournal(scopeSession, cwd)
|
|
2084
|
+
const observation = pendingVerificationObservation(
|
|
2085
|
+
{
|
|
2086
|
+
toolCallId: call.id,
|
|
2087
|
+
tool: call.tool,
|
|
2088
|
+
turn: call.turn,
|
|
2089
|
+
argsHash: call.argsHash,
|
|
2090
|
+
sessionId: scopeSession,
|
|
2091
|
+
},
|
|
2092
|
+
records,
|
|
2093
|
+
verificationEmitted,
|
|
2094
|
+
)
|
|
2095
|
+
if (!observation) return
|
|
2096
|
+
verificationEmitted.add(observation.invocationId)
|
|
2097
|
+
try {
|
|
2098
|
+
presentation?.noteVerificationObserved({
|
|
2099
|
+
toolCallId: observation.toolCallId,
|
|
2100
|
+
invocationId: observation.invocationId,
|
|
2101
|
+
verdict: observation.verdict,
|
|
2102
|
+
method: observation.method,
|
|
2103
|
+
observedAt: observation.observedAt,
|
|
2104
|
+
...(scopeSession !== sessionId ? { sessionId: scopeSession } : {}),
|
|
2105
|
+
})
|
|
2106
|
+
} catch {}
|
|
2107
|
+
} catch {}
|
|
2108
|
+
})()
|
|
2109
|
+
}
|
|
2110
|
+
session.events.on("execution:completed", (e) => {
|
|
2111
|
+
try {
|
|
2112
|
+
const call = e.execution?.call as { id?: unknown; name?: unknown; args?: unknown } | undefined
|
|
2113
|
+
if (!call || typeof call.id !== "string" || typeof call.name !== "string") return
|
|
2114
|
+
const childId = (e as { forwardedChild?: unknown }).forwardedChild
|
|
2115
|
+
const scopeSession = typeof childId === "string" && childId ? childId : sessionId
|
|
2116
|
+
const turn = typeof session.state?.turnCount === "number" ? session.state.turnCount : null
|
|
2117
|
+
const descriptor = {
|
|
2118
|
+
id: call.id,
|
|
2119
|
+
tool: call.name,
|
|
2120
|
+
argsHash: hashArgs(call.args ?? {}),
|
|
2121
|
+
turn,
|
|
2122
|
+
scopeSession,
|
|
2123
|
+
}
|
|
2124
|
+
completedToolCalls.push(descriptor)
|
|
2125
|
+
if (completedToolCalls.length > 500) {
|
|
2126
|
+
completedToolCalls.splice(0, completedToolCalls.length - 500)
|
|
2127
|
+
}
|
|
2128
|
+
emitVerificationForCall(descriptor, scopeSession)
|
|
2129
|
+
} catch {}
|
|
2130
|
+
})
|
|
2131
|
+
session.events.on("turn:completed", () => {
|
|
2132
|
+
// Sapu verifikasi susulan dalam turn yang sama (late verification):
|
|
2133
|
+
// baca ulang jurnal untuk call yang selesai tanpa verdict waktu itu.
|
|
2134
|
+
try {
|
|
2135
|
+
const pending = completedToolCalls.splice(0)
|
|
2136
|
+
for (const call of pending) emitVerificationForCall(call, call.scopeSession)
|
|
774
2137
|
} catch {}
|
|
775
2138
|
})
|
|
776
2139
|
// ── Auto-verify & self-heal ──
|
|
@@ -778,6 +2141,170 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
778
2141
|
? (process.env.MINICODE_VERIFY_CMD ?? cfg.verifyCommand ?? detectVerifyCommand(cwd) ?? "")
|
|
779
2142
|
: ""
|
|
780
2143
|
const verifyActive = verifyCommand.length > 0
|
|
2144
|
+
// Sumber bukti completion untuk domain task (INV-003). Menyimpan hasil
|
|
2145
|
+
// verify TERAKHIR: pada saat `todo_write` berjalan, verify untuk turn ini
|
|
2146
|
+
// BELUM pernah jalan (verify terjadi setelah turn selesai), jadi bukti yang
|
|
2147
|
+
// relevan adalah hasil turn sebelumnya. Maknanya persis yang dibutuhkan:
|
|
2148
|
+
// "verify terakhir merah" -> agent tidak boleh menandai task selesai pada
|
|
2149
|
+
// turn berikutnya sebelum memperbaiki yang merah.
|
|
2150
|
+
//
|
|
2151
|
+
// Tanpa `--verify` (opt-in) tidak ada bukti sama sekali → `unverified`:
|
|
2152
|
+
// completion tetap diizinkan, tapi tidak diklaim terverifikasi.
|
|
2153
|
+
let lastVerify: {
|
|
2154
|
+
ok: boolean
|
|
2155
|
+
command: string
|
|
2156
|
+
output: string
|
|
2157
|
+
turn: number | null
|
|
2158
|
+
exitCode: number
|
|
2159
|
+
} | null = null
|
|
2160
|
+
setCompletionEvidence(() => {
|
|
2161
|
+
if (!verifyActive) return { verdict: "unverified" }
|
|
2162
|
+
// [Fase 3 / LOOP-INV-12, LOOP-G20] Saat `--verify` aktif tetapi verifier
|
|
2163
|
+
// belum menghasilkan verdict pertama, tandai `requireVerified: true` agar
|
|
2164
|
+
// klaim `completed` ditahan di `VERIFYING` (bukan diloloskan fail-open).
|
|
2165
|
+
if (!lastVerify) return { verdict: "unverified", requireVerified: true }
|
|
2166
|
+
if (lastVerify.ok)
|
|
2167
|
+
return {
|
|
2168
|
+
verdict: "passed",
|
|
2169
|
+
detail: lastVerify.command,
|
|
2170
|
+
exitCode: lastVerify.exitCode,
|
|
2171
|
+
summary: lastVerify.output.slice(0, 300) || lastVerify.command,
|
|
2172
|
+
requireVerified: true,
|
|
2173
|
+
// P10.1.1: ikat bukti ke turn yang diobservasinya — dibaca sinkron
|
|
2174
|
+
// tepat setelah verify selesai (belum ada turn baru), sehingga cocok
|
|
2175
|
+
// dengan cap `turn` intent jurnal (increment-di-awal di loop.ts).
|
|
2176
|
+
// Absen = tak terikat → hilir perlakukan sebagai unverified.
|
|
2177
|
+
...(typeof lastVerify.turn === "number" ? { turn: lastVerify.turn } : {}),
|
|
2178
|
+
}
|
|
2179
|
+
return {
|
|
2180
|
+
verdict: "failed",
|
|
2181
|
+
detail: `last verification failed (${lastVerify.command}): ${lastVerify.output.slice(0, 200)}`,
|
|
2182
|
+
exitCode: lastVerify.exitCode,
|
|
2183
|
+
summary: lastVerify.output.slice(0, 300),
|
|
2184
|
+
requireVerified: true,
|
|
2185
|
+
}
|
|
2186
|
+
})
|
|
2187
|
+
const runVerifyWithPresentation = async (signal?: AbortSignal) => {
|
|
2188
|
+
const effectiveRoot = cwd ?? process.cwd()
|
|
2189
|
+
const result = await runVerify(verifyCommand, effectiveRoot, undefined, signal)
|
|
2190
|
+
// [Fase 3 / LOOP-INV-12] Tier 1 integrity check pada file yang dimutasi di
|
|
2191
|
+
// jurnal sesi ini sebelum mengizinkan status akhir hijau.
|
|
2192
|
+
let integrityOk = true
|
|
2193
|
+
let integrityDetail = ""
|
|
2194
|
+
let tamperReason = ""
|
|
2195
|
+
const loaded = await loadJournal(sessionId, effectiveRoot).catch(() => null)
|
|
2196
|
+
if (loaded?.status === "valid") {
|
|
2197
|
+
const modified = collectModifiedFilesFromJournal(loaded.records)
|
|
2198
|
+
if (modified.length > 0) {
|
|
2199
|
+
const integrity = await checkWorkspaceIntegrity(modified, effectiveRoot)
|
|
2200
|
+
integrityOk = integrity.ok
|
|
2201
|
+
if (!integrity.ok) integrityDetail = integrity.summary
|
|
2202
|
+
// [Fase 6A / ACE-02] Evaluator/gate yang disentuh membatalkan seluruh
|
|
2203
|
+
// klaim verifikasi (fail-closed) — tidak ada jalan "hijau" via curang.
|
|
2204
|
+
const tamper = await detectEvaluationTampering(modified, effectiveRoot)
|
|
2205
|
+
if (tamper.tampered) tamperReason = tamper.reason
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
const effectiveOk = result.ok && integrityOk && tamperReason === ""
|
|
2209
|
+
const effectiveOutput = !integrityOk
|
|
2210
|
+
? `${integrityDetail}${result.output ? `\n${result.output}` : ""}`
|
|
2211
|
+
: tamperReason
|
|
2212
|
+
? `EVALUATOR_TAMPER_ATTEMPT: ${tamperReason}${result.output ? `\n${result.output}` : ""}`
|
|
2213
|
+
: result.output
|
|
2214
|
+
const effectiveExitCode = effectiveOk ? (result.exitCode ?? 0) : result.exitCode || 1
|
|
2215
|
+
// Turn state kode ini diverifikasi: turnCount SETELAH turn terakhir
|
|
2216
|
+
// selesai = nilai yang dibawa intent mutasi turn itu (turnOf baca live
|
|
2217
|
+
// state yang sama). Diambil sinkron di sini — belum ada turn baru yang
|
|
2218
|
+
// bisa menyela dan menggeser angka.
|
|
2219
|
+
const verifiedTurn =
|
|
2220
|
+
typeof session.state?.turnCount === "number" ? session.state.turnCount : null
|
|
2221
|
+
lastVerify = {
|
|
2222
|
+
ok: effectiveOk,
|
|
2223
|
+
command: verifyCommand,
|
|
2224
|
+
output: effectiveOutput,
|
|
2225
|
+
turn: verifiedTurn,
|
|
2226
|
+
exitCode: effectiveExitCode,
|
|
2227
|
+
}
|
|
2228
|
+
// [Fase 6A / ACE-01] Terjemahkan bukti verifikasi menjadi keputusan
|
|
2229
|
+
// consequence deterministik. `repeatedFailureCount` memakai streak
|
|
2230
|
+
// SEBELUM percobaan ini (kontrak evaluateConsequence).
|
|
2231
|
+
const tampered = tamperReason.length > 0
|
|
2232
|
+
const transient =
|
|
2233
|
+
!effectiveOk &&
|
|
2234
|
+
/ECONN|ETIMEDOUT|timed? ?out|rate.?limit|429|503|network|EAI_AGAIN|socket hang up/i.test(
|
|
2235
|
+
effectiveOutput,
|
|
2236
|
+
)
|
|
2237
|
+
const permissionBlocked =
|
|
2238
|
+
!effectiveOk &&
|
|
2239
|
+
/permission denied|EACCES|EPERM|operation not permitted/i.test(effectiveOutput)
|
|
2240
|
+
const failureType: AceFailureType = effectiveOk ? null : transient ? "timeout" : "functional"
|
|
2241
|
+
const repeatedBefore = verifyFailureStreak
|
|
2242
|
+
verifyFailureStreak = effectiveOk ? 0 : verifyFailureStreak + 1
|
|
2243
|
+
// [Fase 9 / 9.1] Operational rollback switch: `MINICODE_ACE_ENABLED=0`
|
|
2244
|
+
// melewati seluruh evaluasi consequence (baseline murni) — `lastAceDecision`
|
|
2245
|
+
// tetap null sehingga `ace_state` tidak ikut ke RUNTIME_STATE_HEADER, dan
|
|
2246
|
+
// pelajaran kandidat ACE tidak dipromosikan. Hard-safety/tamper-guard TETAP
|
|
2247
|
+
// aktif (sudah diterapkan di atas via `detectEvaluationTampering`).
|
|
2248
|
+
if (isAceEnabled()) {
|
|
2249
|
+
lastAceDecision = evaluateConsequence({
|
|
2250
|
+
verificationPassed: effectiveOk,
|
|
2251
|
+
evaluatorTamperAttempt: tampered,
|
|
2252
|
+
failureType,
|
|
2253
|
+
isTransientError: transient,
|
|
2254
|
+
repeatedFailureCount: repeatedBefore,
|
|
2255
|
+
newEvidenceSinceLastAttempt:
|
|
2256
|
+
noProgressDetector?.snapshot().newEvidenceSinceFailure === true,
|
|
2257
|
+
blockedByPermissionOrExternalBlocker: permissionBlocked,
|
|
2258
|
+
budgetExhausted:
|
|
2259
|
+
typeof effectiveMaxTurns === "number" && session.state.turnCount >= effectiveMaxTurns,
|
|
2260
|
+
insufficientEvidence: !effectiveOk && effectiveOutput.trim().length === 0,
|
|
2261
|
+
baselineContentChanged: false,
|
|
2262
|
+
})
|
|
2263
|
+
if (lastAceDecision && lastAceDecision.verdict === "BLOCKED") {
|
|
2264
|
+
process.stderr.write(
|
|
2265
|
+
c.dim(
|
|
2266
|
+
`[ace] verdict=BLOCKED next_action=${lastAceDecision.nextAction} — ${lastAceDecision.rationale}\n`,
|
|
2267
|
+
),
|
|
2268
|
+
)
|
|
2269
|
+
}
|
|
2270
|
+
// [Fase 6A / ACE-03] Pelajaran kandidat sesi ini dipromosikan hanya bila
|
|
2271
|
+
// verifikasi hijau; kegagalan sementara/human-blocker tidak menghukumnya.
|
|
2272
|
+
const lessonVerdict: "passed" | "failed" | "unknown" = effectiveOk
|
|
2273
|
+
? "passed"
|
|
2274
|
+
: lastAceDecision.failureClass === "TRANSIENT_ENV" ||
|
|
2275
|
+
lastAceDecision.failureClass === "PERMISSION_OR_EXTERNAL_BLOCKER" ||
|
|
2276
|
+
lastAceDecision.failureClass === "INSUFFICIENT_EVIDENCE"
|
|
2277
|
+
? "unknown"
|
|
2278
|
+
: "failed"
|
|
2279
|
+
try {
|
|
2280
|
+
await promoteOrRejectLessonsBySession(sessionId, lessonVerdict, effectiveRoot)
|
|
2281
|
+
} catch {}
|
|
2282
|
+
}
|
|
2283
|
+
if (effectiveOk) {
|
|
2284
|
+
noProgressDetector?.noteVerificationPassed()
|
|
2285
|
+
}
|
|
2286
|
+
try {
|
|
2287
|
+
settleSessionVerifyingTasks(effectiveRoot, sessionId, {
|
|
2288
|
+
ok: effectiveOk,
|
|
2289
|
+
verdict: effectiveOk ? "passed" : "failed",
|
|
2290
|
+
exitCode: effectiveExitCode,
|
|
2291
|
+
command: verifyCommand,
|
|
2292
|
+
summary: effectiveOutput.slice(0, 300) || verifyCommand,
|
|
2293
|
+
integrityOk: integrityOk && !tampered,
|
|
2294
|
+
})
|
|
2295
|
+
} catch {}
|
|
2296
|
+
const evidence = parseVerifyTestEvidence(verifyCommand, effectiveOutput)
|
|
2297
|
+
if (evidence) {
|
|
2298
|
+
presentation?.noteTestCompleted({
|
|
2299
|
+
toolCallId: `verify:${sessionId}`,
|
|
2300
|
+
turnId: session.state.turnCount,
|
|
2301
|
+
...evidence,
|
|
2302
|
+
})
|
|
2303
|
+
}
|
|
2304
|
+
return effectiveOk === result.ok
|
|
2305
|
+
? result
|
|
2306
|
+
: { ok: false, output: effectiveOutput, command: verifyCommand, exitCode: effectiveExitCode }
|
|
2307
|
+
}
|
|
781
2308
|
// Audit #10 P2 observability: perintah verify (bisa dari config repo bila
|
|
782
2309
|
// opt-in, atau package.json) dieksekusi via shell — tampilkan SEBELUM
|
|
783
2310
|
// jalan pertama agar operator tahu persis apa yang dieksekusi.
|
|
@@ -786,15 +2313,21 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
786
2313
|
}
|
|
787
2314
|
// Audit #10 P1: hooks berjalan di luar permission system — di mode tanpa
|
|
788
2315
|
// eksekusi (plan/readonly) hook TETAP mengeksekusi tanpa gate, melanggar
|
|
789
|
-
// kontrak read-only. Lewati + beri tahu sekali per sesi.
|
|
790
|
-
|
|
2316
|
+
// kontrak read-only. Lewati + beri tahu sekali per sesi. P12 S2.2: WorkMode
|
|
2317
|
+
// DISCUSS (posture read-only penuh) juga menahan hooks walau permissionMode
|
|
2318
|
+
// auto — lihat shouldRunHooks.
|
|
2319
|
+
//
|
|
2320
|
+
// P12 S2.2 Slice 5: predicate dievaluasi PER PEMANGGILAN (bukan snapshot
|
|
2321
|
+
// `hooksAllowed` saat session dibuat) supaya transisi WorkMode operator
|
|
2322
|
+
// berlaku pada sesi yang sedang berjalan.
|
|
791
2323
|
let hooksSkippedNotice = false
|
|
792
2324
|
const runHooksGated = async (
|
|
793
2325
|
phase: "pre" | "post",
|
|
794
2326
|
ctx: { phase: "pre" | "post"; prompt: string; cwd?: string; result?: unknown },
|
|
795
2327
|
signal?: AbortSignal,
|
|
796
2328
|
): Promise<void> => {
|
|
797
|
-
|
|
2329
|
+
const liveWorkMode = workModeControl?.getWorkMode() ?? "EXECUTE"
|
|
2330
|
+
if (!shouldRunHooks(permissionMode, liveWorkMode)) {
|
|
798
2331
|
if (!hooksSkippedNotice) {
|
|
799
2332
|
hooksSkippedNotice = true
|
|
800
2333
|
process.stderr.write(
|
|
@@ -807,8 +2340,43 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
807
2340
|
}
|
|
808
2341
|
|
|
809
2342
|
async function runPromptWithVerify(p: string, signal?: AbortSignal): Promise<void> {
|
|
2343
|
+
// [Fase 7 / Live #3] Root wall-clock: kalau timeout CLI sudah lewat saat
|
|
2344
|
+
// turn mau mulai (setup/retry memakan seluruh budget), tolak langsung
|
|
2345
|
+
// dengan alasan jelas — jangan biarkan turn baru melebihi deadline total.
|
|
2346
|
+
if (rootTimeoutSignal?.aborted) {
|
|
2347
|
+
const msg = `run exceeded root wall-clock timeout (${effectiveTimeoutMs}ms) before turn start`
|
|
2348
|
+
process.stderr.write(`[timeout] ${msg}\n`)
|
|
2349
|
+
throw new AgentError("timeout", msg)
|
|
2350
|
+
}
|
|
2351
|
+
// Composit root signal ke sinyal turn: deadline pengguna berlaku untuk
|
|
2352
|
+
// SELURUH fase (setup + turn + retry), bukan hanya kernel turn.
|
|
2353
|
+
const composedSignal = rootTimeoutSignal
|
|
2354
|
+
? signal
|
|
2355
|
+
? AbortSignal.any([signal, rootTimeoutSignal])
|
|
2356
|
+
: rootTimeoutSignal
|
|
2357
|
+
: signal
|
|
2358
|
+
// P2.2: pagar pra-turn (lihat ensureWriterFresh). Basi → turn dilewati
|
|
2359
|
+
// sebelum provider dibelanjakan; histori tak tersentuh.
|
|
2360
|
+
if (!ensureWriterFresh()) return
|
|
2361
|
+
// P2.6: tutup Run sebelumnya (terminal dari outcome-nya), lalu buka Run
|
|
2362
|
+
// RUNNING baru untuk invokasi ini. Urutan penting: terminal LAMA dulu
|
|
2363
|
+
// (UNIQUE RUNNING per sesi), lalu create. Gagal di sini = gagal loud
|
|
2364
|
+
// (lebih baik daripada fork diam-diam).
|
|
2365
|
+
markPreviousRunTerminal()
|
|
2366
|
+
const thread = ensureDefaultThread(sessionId, cwd, { expectedEpoch })
|
|
2367
|
+
const created = createRun(sessionId, thread.thread_id, cwd, { expectedEpoch })
|
|
2368
|
+
transitionRun(created.run_id, "RUNNING", cwd, { expectedEpoch })
|
|
2369
|
+
currentRunId = created.run_id
|
|
2370
|
+
// [Fase 1 / LOOP-INV-10] Ikat pelacakan in-flight ke run yang baru hidup.
|
|
2371
|
+
// Sejak titik ini setiap tool yang dieksekusi dicatat durable ke
|
|
2372
|
+
// `runs.pending_tool_ids` sebelum efeknya, lalu dilepas saat selesai.
|
|
2373
|
+
setPendingToolsRun(created.run_id, cwd)
|
|
2374
|
+
lastTurnOutcome = null
|
|
810
2375
|
// Listener UI segar tiap turn (pagar turn yatim — lihat attachUI).
|
|
811
2376
|
attachUI()
|
|
2377
|
+
try {
|
|
2378
|
+
presentation?.noteUserMessage({ text: p, turnId: session.state.turnCount })
|
|
2379
|
+
} catch {}
|
|
812
2380
|
// Tandai turn aktif: bila proses mati di tengah (segfault/kill), sesi
|
|
813
2381
|
// berikutnya menemukan marker yatim dan memberi tahu (bukan hilang bisu).
|
|
814
2382
|
// Dihapus di finally di bawah pada SEMUA jalur settle.
|
|
@@ -819,8 +2387,19 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
819
2387
|
;(markTurnActive as ((cwd?: string, id?: string) => void) | undefined)?.(cwd, sessionId)
|
|
820
2388
|
} catch {}
|
|
821
2389
|
try {
|
|
822
|
-
await runPromptWithVerifyInner(p,
|
|
2390
|
+
await runPromptWithVerifyInner(p, composedSignal)
|
|
2391
|
+
lastTurnOutcome = "completed"
|
|
2392
|
+
} catch (e) {
|
|
2393
|
+
lastTurnOutcome = classifyTurnError(e, composedSignal?.aborted === true)
|
|
2394
|
+
throw e
|
|
823
2395
|
} finally {
|
|
2396
|
+
// [Fase 1 / LOOP-INV-03] Bukti terminal jurnal harus TUNTAS sebelum turn
|
|
2397
|
+
// dinyatakan selesai (return/throw). Tanpa await ini, turn bisa berakhir
|
|
2398
|
+
// saat append terminal masih di jalan — konsumen melihat "selesai" tanpa
|
|
2399
|
+
// bukti. Best-effort: kegagalan sudah dicatat degraded oleh jurnal.
|
|
2400
|
+
if (journalHandle !== null) {
|
|
2401
|
+
await journalHandle.flushPending().catch(() => {})
|
|
2402
|
+
}
|
|
824
2403
|
detachUI()
|
|
825
2404
|
try {
|
|
826
2405
|
;(clearTurnActive as ((cwd?: string, id?: string) => void) | undefined)?.(cwd, sessionId)
|
|
@@ -851,23 +2430,71 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
851
2430
|
bus: session.events,
|
|
852
2431
|
budget,
|
|
853
2432
|
strict: budgetStrict ?? false,
|
|
2433
|
+
maxTurns: effectiveMaxTurns,
|
|
854
2434
|
getCost: () => usage.getSession().cost,
|
|
855
2435
|
getTokens: () => usage.getSession().totalTokens,
|
|
2436
|
+
getTurns: () => session.state.turnCount,
|
|
856
2437
|
onOver: (st, cost) => {
|
|
857
2438
|
process.stderr.write(
|
|
858
|
-
st === "
|
|
859
|
-
? `[budget]
|
|
860
|
-
:
|
|
2439
|
+
st === "max-turns"
|
|
2440
|
+
? `[budget] max turns (${effectiveMaxTurns}) reached - stopping turn.\n`
|
|
2441
|
+
: st === "over" && cost != null && budget != null
|
|
2442
|
+
? `[budget] ${formatUsd(cost)} > ${formatUsd(budget)} - over budget, stopping turn.\n`
|
|
2443
|
+
: `[budget] cost unknown (model without pricing) - over budget, stopping turn.\n`,
|
|
861
2444
|
)
|
|
862
2445
|
// F-18: abort dengan identitas kind budget_exceeded (bukan Error
|
|
863
2446
|
// polos) agar kernel melaporkannya sebagai budget_exceeded, bukan
|
|
864
2447
|
// "aborted" generik yang tak terbedakan dari Ctrl+C user.
|
|
865
|
-
ctl.abort(
|
|
2448
|
+
ctl.abort(
|
|
2449
|
+
st === "max-turns" && effectiveMaxTurns !== undefined
|
|
2450
|
+
? maxTurnsExceededError(effectiveMaxTurns, session.state.turnCount)
|
|
2451
|
+
: budgetExceededError(),
|
|
2452
|
+
)
|
|
2453
|
+
},
|
|
2454
|
+
})
|
|
2455
|
+
// [Fase 7 / Live #2] Pemutus aliran MID-STREAM untuk `--context-window`.
|
|
2456
|
+
// Kernel hanya mengecek estimasi token pesan SEBELUM request (kompaksi);
|
|
2457
|
+
// model yang menghasilkan respons sangat panjang bisa membakar jutaan
|
|
2458
|
+
// token tanpa henti (uji live: --context-window 2000 → tokens=6.830.639).
|
|
2459
|
+
// Watcher ini membaca token OUTPUT turn berjalan dari usage collector
|
|
2460
|
+
// dan menggugurkan turn begitu melewati allowance output
|
|
2461
|
+
// (max(256, W − estimasiInput)) — murah karena dijalankan per-event usage.
|
|
2462
|
+
const stopCtxWindow = watchContextWindowLimit({
|
|
2463
|
+
bus: session.events,
|
|
2464
|
+
windowTokens: contextWindowTokens ?? 0,
|
|
2465
|
+
getInputTokens: () => usage.get().inputTokens,
|
|
2466
|
+
getOutputTokens: () => usage.get().outputTokens,
|
|
2467
|
+
onOver: (allowed, actual) => {
|
|
2468
|
+
process.stderr.write(
|
|
2469
|
+
`[context] stream truncated: context-window limit reached (output ${actual} > allowance ${allowed} of window ${contextWindowTokens})\n`,
|
|
2470
|
+
)
|
|
2471
|
+
ctl.abort(
|
|
2472
|
+
new AgentError(
|
|
2473
|
+
"budget_exceeded",
|
|
2474
|
+
`context window exceeded: output ${actual} > allowance ${allowed} (window ${contextWindowTokens})`,
|
|
2475
|
+
),
|
|
2476
|
+
)
|
|
866
2477
|
},
|
|
867
2478
|
})
|
|
868
2479
|
try {
|
|
869
2480
|
try {
|
|
870
|
-
|
|
2481
|
+
// [P1 M15] SATU jalur eksekusi turn. Mode `off`/`constructed`:
|
|
2482
|
+
// `session.run` dipanggil apa adanya (perilaku sebelum M15, nol
|
|
2483
|
+
// overhead). Mode `owned`: lebih dulu admission M13 → Kernel, lalu
|
|
2484
|
+
// `session.run` yang SAMA dieksekusi di dalam eksekusi itu dan
|
|
2485
|
+
// didaftarkan ke `track()` (drain M14 menutup turn yang masih jalan).
|
|
2486
|
+
// Tidak pernah dua kali: legacy run tetap SATU-SATUNYA eksekusi fisik.
|
|
2487
|
+
await executionRunner.run(
|
|
2488
|
+
{
|
|
2489
|
+
kind: "turn",
|
|
2490
|
+
schedulerSource: "cli-session",
|
|
2491
|
+
authorityHeld: true,
|
|
2492
|
+
ownerId: sessionId,
|
|
2493
|
+
provenance: { requestedBy: "user", reason: "prompt" },
|
|
2494
|
+
},
|
|
2495
|
+
() => session.run(prompt, { model: modelRef.current, signal: ctl.signal }),
|
|
2496
|
+
{ signal: ctl.signal },
|
|
2497
|
+
)
|
|
871
2498
|
} catch (e) {
|
|
872
2499
|
// Kernel diam pada gagal/abort/timeout (turn:completed hanya sukses):
|
|
873
2500
|
// adaptor merekonstruksi turn.failed/cancelled dari sini. Error asli
|
|
@@ -884,6 +2511,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
884
2511
|
}
|
|
885
2512
|
} finally {
|
|
886
2513
|
stopWatch()
|
|
2514
|
+
stopCtxWindow()
|
|
887
2515
|
if (s) s.removeEventListener("abort", onParentAbort)
|
|
888
2516
|
turnStatus?.endTurn()
|
|
889
2517
|
}
|
|
@@ -901,10 +2529,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
901
2529
|
// apa pun, tempelkan catatan agar agen memperbaiki dulu, bukan menumpuk
|
|
902
2530
|
// fitur di atas baseline rusak (yang hanya memperparah keadaan).
|
|
903
2531
|
let firstPrompt = p
|
|
904
|
-
const broken = await checkBaseline(
|
|
905
|
-
(s) => runVerify(verifyCommand, cwd ?? process.cwd(), undefined, s ?? signal),
|
|
906
|
-
signal,
|
|
907
|
-
)
|
|
2532
|
+
const broken = await checkBaseline((s) => runVerifyWithPresentation(s ?? signal), signal)
|
|
908
2533
|
// Abort saat baseline jalan sudah melempar dari runVerify; cek ini untuk
|
|
909
2534
|
// abort yang datang tepat di sela (tanpa ini turn agen jalan padahal user
|
|
910
2535
|
// sudah Ctrl+C).
|
|
@@ -926,7 +2551,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
926
2551
|
// fallback ke signal turn luar.
|
|
927
2552
|
await runOnce(prompt, s ?? signal)
|
|
928
2553
|
},
|
|
929
|
-
verify: (s) =>
|
|
2554
|
+
verify: (s) => runVerifyWithPresentation(s ?? signal),
|
|
930
2555
|
onCycle: (cycle, max, v) => {
|
|
931
2556
|
if (cycle === max) {
|
|
932
2557
|
process.stderr.write(
|
|
@@ -954,6 +2579,27 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
954
2579
|
},
|
|
955
2580
|
signal,
|
|
956
2581
|
)
|
|
2582
|
+
// PF-01: `todo_write` berjalan SEBELUM verify turn ini, jadi klaim
|
|
2583
|
+
// `completed` bisa sudah tersimpan ketika verify berubah merah (baseline
|
|
2584
|
+
// hijau tidak menutup celah ini - hanya baseline merah yang menutupnya).
|
|
2585
|
+
// Rekonsiliasi harus terjadi SETELAH self-heal selesai, di luar `runOnce`,
|
|
2586
|
+
// supaya verdict final itulah yang membentuk state durable.
|
|
2587
|
+
if (verifyActive && lastVerify && !lastVerify.ok) {
|
|
2588
|
+
// `reconcileCompletionEvidence` sudah best-effort + menulis diagnostik
|
|
2589
|
+
// sendiri, jadi pemanggil tak perlu try/catch (dan tak perlu menambah
|
|
2590
|
+
// writer di file ini — pagu OAP-008).
|
|
2591
|
+
const reconciled = await reconcileCompletionEvidence(sessionId, cwd ?? ".", {
|
|
2592
|
+
verdict: "failed",
|
|
2593
|
+
detail: `last verification failed (${lastVerify.command}): ${lastVerify.output.slice(0, 200)}`,
|
|
2594
|
+
})
|
|
2595
|
+
if (reconciled) {
|
|
2596
|
+
presentation?.notePlanReconciled({
|
|
2597
|
+
todos: reconciled,
|
|
2598
|
+
sessionId: sessionId,
|
|
2599
|
+
turnId: session.state.turnCount,
|
|
2600
|
+
})
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
957
2603
|
await runHooksGated(
|
|
958
2604
|
"post",
|
|
959
2605
|
{ phase: "post", prompt: p, cwd, result: session.state.turnCount },
|
|
@@ -976,7 +2622,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
976
2622
|
// event yatim pun terlihat; tanpa env = tanpa subscribe (zero-cost).
|
|
977
2623
|
const { attachBusDebug } = await import("../src/ui/runtime/bus-debug.ts")
|
|
978
2624
|
const detachBusDebug = attachBusDebug(session.events)
|
|
979
|
-
const usage = createUsageCollector(session.events, effectiveInitialModel)
|
|
2625
|
+
const usage = createUsageCollector(session.events, effectiveInitialModel, resumeUsageSnapshot)
|
|
980
2626
|
// Statusline kaya = opt-in (default mati, shell tetap bersih). Data biaya
|
|
981
2627
|
// disuntik sebagai callback agar UI tak perlu impor lapisan policy.
|
|
982
2628
|
const richStatus = process.env.MINICODE_STATUSLINE === "rich"
|
|
@@ -989,9 +2635,14 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
989
2635
|
// tetap melukis seperti dulu.
|
|
990
2636
|
detachSimple = attachSimpleLogger(session.events, {
|
|
991
2637
|
verbose,
|
|
992
|
-
quiet: enterRepl === true,
|
|
2638
|
+
quiet: enterRepl === true || machineOutput,
|
|
993
2639
|
getSnapshot: getPresentationSnapshot,
|
|
994
2640
|
onPresentationEvent,
|
|
2641
|
+
policy: {
|
|
2642
|
+
describeActivity,
|
|
2643
|
+
matchTurn: matchTurnBySummary,
|
|
2644
|
+
elapsedVisible,
|
|
2645
|
+
},
|
|
995
2646
|
})
|
|
996
2647
|
if (enterRepl === true) {
|
|
997
2648
|
turnStatus = null
|
|
@@ -1000,6 +2651,16 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
1000
2651
|
turnStatus = attachTurnStatus(session.events, {
|
|
1001
2652
|
initialModel: effectiveInitialModel,
|
|
1002
2653
|
getModel: () => modelRef.current ?? effectiveInitialModel,
|
|
2654
|
+
activityFor: (toolCallId: string) => {
|
|
2655
|
+
const activity = getPresentationSnapshot().activities.find(
|
|
2656
|
+
(item) => item.toolCallId === toolCallId,
|
|
2657
|
+
)
|
|
2658
|
+
if (!activity) return undefined
|
|
2659
|
+
return {
|
|
2660
|
+
name: activity.name,
|
|
2661
|
+
...(activity.target ? { target: activity.target } : {}),
|
|
2662
|
+
}
|
|
2663
|
+
},
|
|
1003
2664
|
...(richStatus
|
|
1004
2665
|
? {
|
|
1005
2666
|
getStats: () => {
|
|
@@ -1026,17 +2687,444 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
1026
2687
|
|
|
1027
2688
|
async function persistCurrent(usageData: unknown) {
|
|
1028
2689
|
try {
|
|
1029
|
-
|
|
1030
|
-
|
|
2690
|
+
flushPresentationEvents()
|
|
2691
|
+
await presentationWriteTail
|
|
2692
|
+
// P2.2: pagar generasi di dalam txn saveSession. Basi → markWriterStale
|
|
2693
|
+
// (diagnostik eksplisit + flag untuk exit jujur one-shot); JANGAN
|
|
2694
|
+
// retry buta (akan menimpa penulis baru) dan JANGAN telan diam-diam.
|
|
2695
|
+
// P2.6: runId mengikat baris baru ke Run live + memajukan kursor ke
|
|
2696
|
+
// head DALAM txn yang sama (atomik histori+kursor).
|
|
2697
|
+
// P2.8 forensics: session.state.history adalah buffer KONTEKS vendor —
|
|
2698
|
+
// ia memuat artefak ringkasan proyeksi (context-only) yang TAK BOLEH
|
|
2699
|
+
// jadi histori kanonik. Bila artefak itu masih di depan buffer, buang
|
|
2700
|
+
// DAN susun ulang: baseline kanonik ++ ekor yang benar-benar baru.
|
|
2701
|
+
// (Membuang saja tak cukup: setelah prefix ditutup proyeksi, buffer bukan
|
|
2702
|
+
// lagi superset histori kanonik — memakainya apa adanya akan wiping
|
|
2703
|
+
// histori lewat jalur shrink.) Bila artefak tak ada (fallback / kernel
|
|
2704
|
+
// sudah mengompak), buffer dipakai apa adanya — jalur kompaksi P2.7 yang
|
|
2705
|
+
// sudah bersaproven (migrated_compacted=1).
|
|
2706
|
+
const buffer = session.state.history
|
|
2707
|
+
const tail = stripContextOnly(buffer, contextOnlyArtifact)
|
|
2708
|
+
const durableHistory: readonly unknown[] =
|
|
2709
|
+
contextOnlyArtifact !== undefined &&
|
|
2710
|
+
contextCanonicalBaseline !== undefined &&
|
|
2711
|
+
tail.length !== buffer.length
|
|
2712
|
+
? [...contextCanonicalBaseline, ...tail]
|
|
2713
|
+
: buffer
|
|
2714
|
+
try {
|
|
2715
|
+
await saveSession(sessionId, cwd, undefined, durableHistory, usageData, {
|
|
2716
|
+
expectedEpoch,
|
|
2717
|
+
...(currentRunId ? { runId: currentRunId } : {}),
|
|
2718
|
+
})
|
|
2719
|
+
} catch (e) {
|
|
2720
|
+
// P2.7: histori menyusut/berubah (kompaksi kernel di RAM) — saveSession
|
|
2721
|
+
// append-only MENOLAK rewrite implisit. Rute eksplisit: terminal-mark
|
|
2722
|
+
// run live dulu (shrink melarang RUNNING), lalu shrinkThreadHistory
|
|
2723
|
+
// (provenance + invalidasi proyeksi, satu txn). Sempit: hanya error ini.
|
|
2724
|
+
if (e instanceof RefusedHistoryRewriteError) {
|
|
2725
|
+
// P3.1-retarget (I2): shrink otomatis DILARANG bila kanonik tumbuh
|
|
2726
|
+
// melampaui buffer — itu baris penulis lain, bukan lipatan buffer
|
|
2727
|
+
// sendiri. Tolak dengan jujur (flag + note, tanpa tulis, tanpa
|
|
2728
|
+
// retry) daripada menghancurkan baris yang tak kita kenal.
|
|
2729
|
+
if (e.grewBeyondBuffer) {
|
|
2730
|
+
markWriterStale(
|
|
2731
|
+
`canonical grew beyond buffer (another writer appended): refusing automatic shrink to protect their rows`,
|
|
2732
|
+
)
|
|
2733
|
+
return
|
|
2734
|
+
}
|
|
2735
|
+
markPreviousRunTerminal()
|
|
2736
|
+
const thread = ensureDefaultThread(sessionId, cwd, { expectedEpoch })
|
|
2737
|
+
shrinkThreadHistory(sessionId, thread.thread_id, durableHistory, cwd, {
|
|
2738
|
+
expectedEpoch,
|
|
2739
|
+
})
|
|
2740
|
+
} else {
|
|
2741
|
+
throw e
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
// P3.4 — PRODUSEN proyeksi kanonik durable (best-effort, derived, epoch-
|
|
2745
|
+
// fenced). Menulis HANYA `history_projections` dari state kanonik yang
|
|
2746
|
+
// baru dipersist; TIDAK menyentuh `messages`/head/run. Kegagalan di sini
|
|
2747
|
+
// tidak pernah menggagalkan persist (proyeksi boleh tetap absen/basi).
|
|
2748
|
+
// Ringkasan memakai teks fold yang SUDAH ADA (kernel) via produsen.
|
|
2749
|
+
try {
|
|
2750
|
+
const produced = produceSummaryProjection(sessionId, cwd, {
|
|
2751
|
+
expectedEpoch,
|
|
2752
|
+
policy: { keepRecentTurns: keepRecentTurns && keepRecentTurns > 0 ? keepRecentTurns : 2 },
|
|
2753
|
+
})
|
|
2754
|
+
if (produced.produced) {
|
|
2755
|
+
process.stderr.write(
|
|
2756
|
+
`${c.dim(`[projection sid=${sessionId} base=${produced.baseSeq ?? "-"} status=produced]\n`)}`,
|
|
2757
|
+
)
|
|
2758
|
+
}
|
|
2759
|
+
} catch (e) {
|
|
2760
|
+
warnLine(`projection produce failed: ${(e as Error).message}`)
|
|
2761
|
+
}
|
|
1031
2762
|
// Riwayat durable → mutasi turn ini boleh di-finalize (sweep record).
|
|
1032
2763
|
// Gagal finalize tak menggagalkan persist (warn di dalam).
|
|
1033
2764
|
await finalizeJournal(sessionId, cwd).catch((e) => {
|
|
1034
|
-
|
|
2765
|
+
warnLine(`journal finalize failed: ${(e as Error).message}`)
|
|
1035
2766
|
})
|
|
1036
|
-
} catch {
|
|
2767
|
+
} catch (e) {
|
|
2768
|
+
if (e instanceof StaleWriterError) {
|
|
2769
|
+
markWriterStale(
|
|
2770
|
+
`history persist refused (expected epoch ${e.expectedEpoch}, actual ${e.actualEpoch})`,
|
|
2771
|
+
)
|
|
2772
|
+
return
|
|
2773
|
+
}
|
|
2774
|
+
// Perilaku lama dipertahankan untuk error non-pagar: persist best-effort.
|
|
2775
|
+
}
|
|
1037
2776
|
}
|
|
1038
2777
|
|
|
2778
|
+
// [PHASE 6AB] The operator projection. Created here, unconditionally and cheaply
|
|
2779
|
+
// (a few counters and an empty array - no I/O, no store handle, no Scheduler), so
|
|
2780
|
+
// the OFF case can still ANSWER "is the scheduler on?" with a truthful OFF rather
|
|
2781
|
+
// than by absence. It holds no reference to the Scheduler, the store or the UI:
|
|
2782
|
+
// it is fed events and probed against the handle.
|
|
2783
|
+
const schedulerObservability = new SchedulerObservability()
|
|
2784
|
+
|
|
2785
|
+
// ── [P1 M14] RUNTIME COMPOSITION ───────────────────────────────────────────
|
|
2786
|
+
//
|
|
2787
|
+
// [DESIGN DECISION] One call, behind one MODE that defaults to `off`, with its
|
|
2788
|
+
// dependencies in a THUNK — the same shape as the Scheduler below, on purpose.
|
|
2789
|
+
// The alternative ("just construct it here and ignore it") satisfies the letter
|
|
2790
|
+
// of "gated" while opening a SQLite handle and constructing a host, a kernel
|
|
2791
|
+
// and a supervisor on every single run.
|
|
2792
|
+
//
|
|
2793
|
+
// [DESIGN DECISION] The journal path comes from the canonical SessionId
|
|
2794
|
+
// (P2.1: satu sid untuk semua komponen). Tak ada lagi path ganda
|
|
2795
|
+
// resume-vs-acak; resume yang menempa path baru tidak mungkin terjadi
|
|
2796
|
+
// karena identitas diputus di resolver sebelum wiring apa pun.
|
|
2797
|
+
// Bila sesi resume tak punya runtime journal, jurnal dibuat fresh
|
|
2798
|
+
// AT THAT PATH — tak pernah di path turunan id baru.
|
|
2799
|
+
//
|
|
2800
|
+
// [P1 M15] Placed BEFORE the Scheduler composition on purpose: the runner must
|
|
2801
|
+
// already exist when the scheduler's deps thunk asks for it, and fail-closed
|
|
2802
|
+
// journal open must abort startup before any autonomous machinery is built.
|
|
2803
|
+
const runtimeCwd = cwd ?? process.cwd()
|
|
2804
|
+
// [P13.3] Holder fakta lapisan task. Runtime dibuat lebih dulu daripada
|
|
2805
|
+
// scheduler, jadi nilainya baru ada setelah schedulerconstructed — holder ini
|
|
2806
|
+
// dibaca lewat thunk saat fakta dibutuhkan (bukan saat runtime dibangun).
|
|
2807
|
+
let taskLayerFacts: TaskLayerFacts = { schedulerAttached: null, storeOpen: null }
|
|
2808
|
+
const productionRuntime: ProductionRuntimeHandle = await createProductionRuntime(
|
|
2809
|
+
runtimeGateFor(runtimeMode),
|
|
2810
|
+
() => ({
|
|
2811
|
+
sessionId: sessionId,
|
|
2812
|
+
workspaceCwd: runtimeCwd,
|
|
2813
|
+
journalPath: runtimeJournalPath(runtimeCwd, sessionId),
|
|
2814
|
+
taskLayerFacts: () => taskLayerFacts,
|
|
2815
|
+
}),
|
|
2816
|
+
)
|
|
2817
|
+
|
|
2818
|
+
// ── [P1 M15] EXECUTION RUNNER: admission runtime untuk setiap turn ─────────
|
|
2819
|
+
//
|
|
2820
|
+
// [DESIGN DECISION] Runner hidup di composition root, bukan di dalam Session
|
|
2821
|
+
// atau tool. Alasannya: jalur eksekusi yang DIREMOTE harus tetap punya satu
|
|
2822
|
+
// pemilik (composition root), dan `session.run()` sendiri tidak boleh tahu
|
|
2823
|
+
// soal dispatch/journal — supaya eksekusi legacy (mode off/constructed) tetap
|
|
2824
|
+
// persis seperti sebelumnya M15.
|
|
2825
|
+
const effectiveRuntimeMode = runtimeModeFor(runtimeMode)
|
|
2826
|
+
const executionRunner: ProductionExecutionRunner = createProductionExecutionRunner({
|
|
2827
|
+
mode: effectiveRuntimeMode,
|
|
2828
|
+
runtime: productionRuntime.runtime(),
|
|
2829
|
+
})
|
|
2830
|
+
|
|
2831
|
+
// [P1 M15 §19] Bukti durable dari proses sebelumnya: integritas jurnal +
|
|
2832
|
+
// tafsir M12 untuk eksekusi yang berakhir non-terminal. Sengaja TIDAK
|
|
2833
|
+
// mendispatch (M12 hanya merencanakan; authority/budget/deadline tetap
|
|
2834
|
+
// berlaku) — hasil startup diekspos agar operator/REPL bisa
|
|
2835
|
+
// memutuskan, dan supaya startup punya bukti bahwa restart tidak diam-diam
|
|
2836
|
+
// mengulang pekerjaan.
|
|
2837
|
+
const startupRecovery: StartupRecoveryReport | null = productionRuntime.runtime()
|
|
2838
|
+
? inspectStartupRecovery(productionRuntime.runtime()!, { authorityHeld: false })
|
|
2839
|
+
: null
|
|
2840
|
+
|
|
2841
|
+
// [P1 M15] Runner dipasang ke tool sub-agen HANYA saat runtime memiliki
|
|
2842
|
+
// eksekusi (mode owned). Mode lain: tak ada setter call sama sekali, jadi
|
|
2843
|
+
// jalur legacy anak benar-benar tak tersentuh (nol overhead).
|
|
2844
|
+
if (executionRunner.owns) setSubAgentExecutionRunner(executionRunner)
|
|
2845
|
+
|
|
2846
|
+
// ── [PHASE 6U] AUTONOMOUS SCHEDULER COMPOSITION ────────────────────────────
|
|
2847
|
+
//
|
|
2848
|
+
// [DESIGN DECISION] One call, one function, behind one boolean that defaults to
|
|
2849
|
+
// false. Everything that makes autonomous execution possible — the TaskStore
|
|
2850
|
+
// handle, the session factory, the scheduler, the trigger, the cancellation
|
|
2851
|
+
// subscription — lives INSIDE the `deps` thunk, which
|
|
2852
|
+
// `createProductionScheduler` does not invoke when the gate is shut. So the
|
|
2853
|
+
// default configuration cannot open a database handle, cannot allocate a
|
|
2854
|
+
// provider chain, cannot subscribe to a deletion channel, and cannot start
|
|
2855
|
+
// autonomous work even by accident.
|
|
2856
|
+
//
|
|
2857
|
+
// The gate is read from `schedulerEnabled`, which only `cli/index.ts` sets, and
|
|
2858
|
+
// only from an explicit `--enable-scheduler` token.
|
|
2859
|
+
const productionScheduler: ProductionSchedulerHandle = await createProductionScheduler(
|
|
2860
|
+
schedulerGateFor(schedulerEnabled),
|
|
2861
|
+
async () => {
|
|
2862
|
+
const { TaskStore } = await import("../src/task/store.ts")
|
|
2863
|
+
const { AUTONOMOUS_TOOL_NAMES } = await import("../src/task/autonomous-policy.ts")
|
|
2864
|
+
const store = new TaskStore(cwd, { authority: "SCHEDULER" })
|
|
2865
|
+
const autonomousCwd = cwd ?? process.cwd()
|
|
2866
|
+
|
|
2867
|
+
// [DESIGN DECISION] The REAL tool objects, filtered to the 6S allow-list —
|
|
2868
|
+
// not freshly constructed look-alikes and not the whole session tool set. The
|
|
2869
|
+
// jailing inside the real `read_file` is part of the security boundary, and a
|
|
2870
|
+
// re-implemented tool would be a second implementation to keep correct.
|
|
2871
|
+
// `AUTONOMOUS_TOOL_NAMES` is the 6S matrix's own output, so this cannot widen.
|
|
2872
|
+
const autonomousTools = AUTONOMOUS_TOOL_NAMES.map((name) =>
|
|
2873
|
+
sessionTools.find((t) => t.name === name),
|
|
2874
|
+
).filter((t): t is NonNullable<typeof t> => t !== undefined)
|
|
2875
|
+
|
|
2876
|
+
// [P13.3 Stage C] Retry safety is DERIVED from the tool scope the bridge
|
|
2877
|
+
// actually receives, not asserted here. Every autonomous tool must still
|
|
2878
|
+
// be classified READ_ONLY by the 6S matrix; one unknown/mutating name and
|
|
2879
|
+
// the whole scope becomes UNPROVEN (which means HOLD, never retry).
|
|
2880
|
+
const { retrySafetyForToolScope } = await import("../src/task/continuity.ts")
|
|
2881
|
+
const retrySafety = retrySafetyForToolScope(autonomousTools.map((t) => t.name))
|
|
2882
|
+
|
|
2883
|
+
return {
|
|
2884
|
+
sessionId,
|
|
2885
|
+
cwd: autonomousCwd,
|
|
2886
|
+
store,
|
|
2887
|
+
// P2.2: token penulis milik boot ini — sesi + scheduler-nya SATU
|
|
2888
|
+
// penulis (satu lease). Tanpa ini keduanya saling menolak.
|
|
2889
|
+
authorityToken: writerToken,
|
|
2890
|
+
instruction: "Work autonomously on the assigned task. Report what you found.",
|
|
2891
|
+
model: modelRef.current,
|
|
2892
|
+
adapter: {
|
|
2893
|
+
store,
|
|
2894
|
+
tools: autonomousTools,
|
|
2895
|
+
provider: router,
|
|
2896
|
+
model: modelRef.current,
|
|
2897
|
+
cwdFor: () => autonomousCwd,
|
|
2898
|
+
// [P1 M15] Turn otonom melewati admission runtime yang sama dengan turn
|
|
2899
|
+
// user: M13 → Kernel, lalu eksekusi fisiknya (child session) di dalam
|
|
2900
|
+
// execution itu. `undefined` pada mode selain `owned` = jalur lama.
|
|
2901
|
+
...(executionRunner.owns ? { executionRunner } : {}),
|
|
2902
|
+
// [PHASE 6U] The autonomous child session is a REAL MiniCode session
|
|
2903
|
+
// over the REAL provider chain — the same `router` the user session
|
|
2904
|
+
// uses — so autonomous work does not run a different model or a weaker
|
|
2905
|
+
// tool stack than the interactive session.
|
|
2906
|
+
sessionFactory: async (spec: AutonomousSessionSpec) => {
|
|
2907
|
+
const child = await createMinicodeSession({
|
|
2908
|
+
provider: spec.provider as never,
|
|
2909
|
+
tools: spec.tools as never,
|
|
2910
|
+
cwd: spec.cwd,
|
|
2911
|
+
systemExtra: spec.systemExtra,
|
|
2912
|
+
// [PHASE 6U] The child conversation id is NOT a kernel config field.
|
|
2913
|
+
timeoutMs: spec.timeoutMs,
|
|
2914
|
+
// [PHASE 6U][SECURITY] The 6S handler, not a `readonly` MODE. This
|
|
2915
|
+
// seam is what keeps 6S's policy in force in production: the
|
|
2916
|
+
// mode-derived handler is revocable via `__setMode` and admits
|
|
2917
|
+
// `web_fetch`, both of which 6S ruled out for an unattended run.
|
|
2918
|
+
permissionHandler: spec.permissionHandler as never,
|
|
2919
|
+
permissionMode: "readonly",
|
|
2920
|
+
})
|
|
2921
|
+
// P3.5 (N2) — jembatan kompaksi otonom. Sesi anak ini TANPA
|
|
2922
|
+
// presentation adapter (berbeda dari anak delegate_task yang dipasangi
|
|
2923
|
+
// adapter + flush di cli/index.ts); tanpa jembatan ini, event
|
|
2924
|
+
// `context:compacted` kernel tetap in-memory sehingga marker durable
|
|
2925
|
+
// tak pernah ditulis dan revision undercount. Jembatan best-effort
|
|
2926
|
+
// via primitif durable yang SUDAH ADA (idempoten, tanpa pagar epoch
|
|
2927
|
+
// — sama seperti flush anak yang tak memegang epoch). Langganan
|
|
2928
|
+
// terikat umur sesi anak itu sendiri (tak ada store kedua).
|
|
2929
|
+
attachHeadlessCompactionBridge({
|
|
2930
|
+
sessionId: spec.sessionId,
|
|
2931
|
+
cwd: spec.cwd,
|
|
2932
|
+
events: child.events,
|
|
2933
|
+
})
|
|
2934
|
+
return child
|
|
2935
|
+
},
|
|
2936
|
+
},
|
|
2937
|
+
// [PHASE 6U] The binding is read from DURABLE state at dispatch time. The
|
|
2938
|
+
// claim was accepted microseconds ago, so the store's current generation IS
|
|
2939
|
+
// this claim's generation — and reading it durably means a binding can
|
|
2940
|
+
// never be a guess about in-memory state.
|
|
2941
|
+
bindingFor: (taskId: string) => ({
|
|
2942
|
+
parentSessionId: sessionId,
|
|
2943
|
+
taskId,
|
|
2944
|
+
execGeneration: store.getExecutionLineage(sessionId, taskId)?.execGeneration ?? 0,
|
|
2945
|
+
sessionIncarnation: store.getSessionIncarnation(sessionId),
|
|
2946
|
+
}),
|
|
2947
|
+
// [P13.3 Stage C] ONE evidence source for automatic continuation:
|
|
2948
|
+
// canonical runtime view + admission for `background`, TaskStore and
|
|
2949
|
+
// journal readability, and the read-only tool scope proven above.
|
|
2950
|
+
//
|
|
2951
|
+
// We do NOT infer safety from a missing completion marker, and we do not
|
|
2952
|
+
// redispatch an old runtime execution: a successful reconcile leads to a
|
|
2953
|
+
// FRESH claim (new exec_generation) and a new autonomous turn.
|
|
2954
|
+
continuity: {
|
|
2955
|
+
evidence: ({ authorityHeld, incarnationMatches, ownsSession }) => {
|
|
2956
|
+
try {
|
|
2957
|
+
const view = deriveRuntimeView(observeProductionRuntime(productionRuntime))
|
|
2958
|
+
let storageUsable = false
|
|
2959
|
+
try {
|
|
2960
|
+
// Store readability is a real probe, not "the handle exists".
|
|
2961
|
+
store.getSnapshot(sessionId)
|
|
2962
|
+
const journal = productionRuntime.runtime()?.journal ?? null
|
|
2963
|
+
storageUsable = journal === null || journal.integrityCheck().mismatched.length === 0
|
|
2964
|
+
} catch {
|
|
2965
|
+
storageUsable = false
|
|
2966
|
+
}
|
|
2967
|
+
const resume = evaluateResume({
|
|
2968
|
+
// `ALLOW` already implies ACTIVE + NONE + COMPLETE + capabilities;
|
|
2969
|
+
// evidenceState is repeated so the intent survives future edits.
|
|
2970
|
+
runtimeStateCurrent:
|
|
2971
|
+
view.admission === "ALLOW" && view.evidenceState === "COMPLETE",
|
|
2972
|
+
storageUsable,
|
|
2973
|
+
leaseValid: authorityHeld,
|
|
2974
|
+
authorityCurrent: authorityHeld && ownsSession && incarnationMatches,
|
|
2975
|
+
})
|
|
2976
|
+
return {
|
|
2977
|
+
resume: resume.resume,
|
|
2978
|
+
missing: resume.missing,
|
|
2979
|
+
// Re-evaluated at reconcile time, before any dispatch. A fresh
|
|
2980
|
+
// admission is repeated by the execution runner before the turn.
|
|
2981
|
+
admission: admitTaskWork(view, "background").admission,
|
|
2982
|
+
retrySafety,
|
|
2983
|
+
}
|
|
2984
|
+
} catch {
|
|
2985
|
+
// Evidence unavailable is evidence MISSING, never permission.
|
|
2986
|
+
return {
|
|
2987
|
+
resume: false,
|
|
2988
|
+
missing: ["continuity-evidence-error"],
|
|
2989
|
+
admission: "REFUSE" as const,
|
|
2990
|
+
retrySafety: "UNPROVEN" as const,
|
|
2991
|
+
}
|
|
2992
|
+
}
|
|
2993
|
+
},
|
|
2994
|
+
},
|
|
2995
|
+
// [PHASE 6AB] The sinks 6AA proved nobody passed. Both events were already
|
|
2996
|
+
// produced by 6U/6T's constructors; wiring them here is the entire
|
|
2997
|
+
// observability fix. They live INSIDE the `deps` thunk, so with the gate
|
|
2998
|
+
// shut they are never even constructed.
|
|
2999
|
+
onSchedulerEvent: (e) => schedulerObservability.noteSchedulerEvent(e),
|
|
3000
|
+
onTriggerEvent: (e) => schedulerObservability.noteTriggerEvent(e),
|
|
3001
|
+
}
|
|
3002
|
+
},
|
|
3003
|
+
)
|
|
3004
|
+
|
|
3005
|
+
// ── [P13.1] SEAM STATUS RUNTIME ───────────────────────────────────────────
|
|
3006
|
+
//
|
|
3007
|
+
// [DESIGN DECISION] Composition root memasang SATU penyedia status runtime;
|
|
3008
|
+
// CLI (`minicode stats`, nanti footer TUI) dan daemon membacanya lewat simbol
|
|
3009
|
+
// yang sama. Tanpa seam ini tiap konsumen menghitung statusnya sendiri →
|
|
3010
|
+
// N sumber status, dan itu kelas bug yang repo ini kejar sejak awal.
|
|
3011
|
+
//
|
|
3012
|
+
// Yang dipasang HANYA fakta nyata: gate/constructed/closed dari handle
|
|
3013
|
+
// runtime; scheduler/store dari handle scheduler (lapisan task). Status
|
|
3014
|
+
// supervisi TIDAK lagi diisi manual — dibaca dari komposisi (P13.2). Tak ada
|
|
3015
|
+
// tebakan: yang tak diketahui dilaporkan `null` → fail-closed.
|
|
3016
|
+
//
|
|
3017
|
+
// [P13.3] Fakta lapisan task untuk gerbang admission. Runtime dibuat SEBELUM
|
|
3018
|
+
// scheduler, jadi nilainya baru diketahui setelah scheduler ada — karena itu
|
|
3019
|
+
// facts disimpan di holder dan dibaca lewat thunk (nilai basi akan menyesatkan
|
|
3020
|
+
// gerbang admission dengan alasan yang tak pernah benar).
|
|
3021
|
+
const schedulerAttached: boolean | null = productionScheduler.constructed
|
|
3022
|
+
? true
|
|
3023
|
+
: productionScheduler.enabled
|
|
3024
|
+
? false
|
|
3025
|
+
: null
|
|
3026
|
+
const storeOpen: boolean | null = productionScheduler.constructed
|
|
3027
|
+
? true
|
|
3028
|
+
: productionScheduler.enabled
|
|
3029
|
+
? false
|
|
3030
|
+
: null
|
|
3031
|
+
taskLayerFacts = { schedulerAttached, storeOpen }
|
|
3032
|
+
installRuntimeStatusProvider(() =>
|
|
3033
|
+
deriveRuntimeView(
|
|
3034
|
+
// Satu sumber fakta: komposisi. Fakta lapisan task diambil dari thunk
|
|
3035
|
+
// yang sama dengan yang dipakai gerbang admission.
|
|
3036
|
+
observeProductionRuntime(productionRuntime),
|
|
3037
|
+
),
|
|
3038
|
+
)
|
|
3039
|
+
|
|
3040
|
+
// [P13.2] Registrar proses pertama: server LSP milik runtime ini. Satu
|
|
3041
|
+
// jalur ownership proses — runtime yang memegang daftarnya, dan shutdown
|
|
3042
|
+
// runtime MENUNGGU anak berhenti (tak ada child yang terlepas).
|
|
3043
|
+
setLspProcessSupervisor(productionRuntime.runtime()?.supervision ?? null)
|
|
3044
|
+
|
|
3045
|
+
// ── [P1 M14] RUNTIME COMPOSITION ─────────────────────────────────────────────
|
|
3046
|
+
//
|
|
3047
|
+
// [DESIGN DECISION] One call, behind one boolean that defaults to false, with
|
|
3048
|
+
// its dependencies in a THUNK — the same shape as the Scheduler above, on
|
|
3049
|
+
// purpose. The alternative ("just construct it here and ignore it") satisfies
|
|
3050
|
+
// the letter of "gated" while opening a SQLite handle and constructing a host,
|
|
3051
|
+
// a kernel and a supervisor on every single run.
|
|
3052
|
+
//
|
|
3053
|
+
// [DESIGN DECISION] The journal path comes from the canonical SessionId
|
|
3054
|
+
// (P2.1), not from volatile id. A resume that minted a fresh path would silently start
|
|
3055
|
+
// from an empty history while looking exactly like a successful resume; this is
|
|
3056
|
+
// the class of bug `--resume` exists to prevent. If the resumed session has no
|
|
3057
|
+
// runtime journal at all, the journal is created fresh AT THAT PATH — never at a
|
|
3058
|
+
// new path derived from the new session id, which would strand the old history
|
|
3059
|
+
// and invent a second file for one resume.
|
|
1039
3060
|
async function close(): Promise<void> {
|
|
3061
|
+
// [PHASE 6U] SHUTDOWN ORDERING. Stop autonomous work FIRST, before the
|
|
3062
|
+
// presentation layer is detached and before background jobs are killed.
|
|
3063
|
+
//
|
|
3064
|
+
// [DESIGN DECISION] The scheduler goes first because it is the only thing
|
|
3065
|
+
// here that can still start new work. Detaching UI first would leave a live
|
|
3066
|
+
// autonomous turn running with nothing to report to, and killing background
|
|
3067
|
+
// jobs first would race an autonomous turn that might legitimately use one.
|
|
3068
|
+
//
|
|
3069
|
+
// Idempotent and inert when the gate is off, so this line costs nothing in
|
|
3070
|
+
// the default configuration.
|
|
3071
|
+
try {
|
|
3072
|
+
await productionScheduler.stop("shutdown")
|
|
3073
|
+
// [PHASE 6AB] `Scheduler.stop()` releases authority without emitting a
|
|
3074
|
+
// `cycle:stopped`, so the projection is told explicitly. Otherwise the last
|
|
3075
|
+
// activity line an operator sees after exit would describe work rather than
|
|
3076
|
+
// the shutdown that ended it.
|
|
3077
|
+
if (productionScheduler.constructed) schedulerObservability.noteStopped("shutdown")
|
|
3078
|
+
} catch {
|
|
3079
|
+
// Teardown must not fail because a scheduler could not stop. Durable
|
|
3080
|
+
// recovery remains authoritative for anything still in flight.
|
|
3081
|
+
}
|
|
3082
|
+
// [P1 M14] Runtime goes SECOND: after autonomous work has stopped (so nothing
|
|
3083
|
+
// new can be admitted) but before the UI is detached and background jobs are
|
|
3084
|
+
// killed (so a live kernel transition still has a journal to land in). Its
|
|
3085
|
+
// own close order is: admission latch → host drain → execution/event drain →
|
|
3086
|
+
// journal flush → journal close → host close.
|
|
3087
|
+
//
|
|
3088
|
+
// Inert when the gate is off, so this line costs nothing by default.
|
|
3089
|
+
//
|
|
3090
|
+
// [DESIGN DECISION] NO extra stderr writer for an incomplete shutdown. The
|
|
3091
|
+
// writer inventory (OAP-008) exists so writer count in this file only goes
|
|
3092
|
+
// DOWN, and every other teardown path here is deliberately silent; the truth
|
|
3093
|
+
// is not lost either — `productionRuntime.shutdownResult()` carries the
|
|
3094
|
+
// structured per-phase result (including a non-confirmed durability verdict)
|
|
3095
|
+
// for tests and diagnostics, which is where a teardown warning would end up
|
|
3096
|
+
// anyway. Silent teardown + inspectable result beats a new writer slot.
|
|
3097
|
+
// [P1 M15] Lepas DI sub-agen saat teardown: proses boleh punya beberapa sesi
|
|
3098
|
+
// dalam masa pakainya (test/embed), dan runner milik sesi yang sudah tutup
|
|
3099
|
+
// tak boleh menerima turn baru.
|
|
3100
|
+
if (executionRunner.owns) setSubAgentExecutionRunner(undefined)
|
|
3101
|
+
// [P13.1] Lepas seam status runtime: setelah runtime berhenti, penyedia yang
|
|
3102
|
+
// menunjuk handle tertutup tak boleh presenting status basi.
|
|
3103
|
+
installRuntimeStatusProvider(null)
|
|
3104
|
+
// [P13.2] Lepas registrar proses: tak ada runtime aktif ⇒ tak ada pemilik
|
|
3105
|
+
// proses anak yang boleh diklaim.
|
|
3106
|
+
setLspProcessSupervisor(null)
|
|
3107
|
+
try {
|
|
3108
|
+
await productionRuntime.stop()
|
|
3109
|
+
} catch {
|
|
3110
|
+
// Same rule as the scheduler: teardown never fails on a runtime that could
|
|
3111
|
+
// not close. Whatever is unrecorded stays recoverable from the journal.
|
|
3112
|
+
}
|
|
3113
|
+
// [Stage 5B] Drain checkpoint. POSISI: SESUDAH runtime stop (event
|
|
3114
|
+
// `turn:completed` sudah di-emit saat event-drain runtime, jadi operasi
|
|
3115
|
+
// checkpoint yang dimulai SUDAH tercatat) dan SEBELUM presentation
|
|
3116
|
+
// di-detach (note checkpoint masih bisa sampai ke layar). Listener
|
|
3117
|
+
// checkpoint dilepas di dalam drain → tak ada operasi baru yang lahir
|
|
3118
|
+
// setelah titik ini. close() jadi barrier: setelah kembali, tak ada
|
|
3119
|
+
// pekerjaan checkpoint milik lifecycle ini yang masih berjalan.
|
|
3120
|
+
try {
|
|
3121
|
+
await drainCheckpointWork()
|
|
3122
|
+
} catch {
|
|
3123
|
+
// Drain tak boleh menggagalkan teardown; kegagalan checkpoint sudah
|
|
3124
|
+
// dicatat (checkpointFailureNotes + warn stderr) saat operasi ditolak.
|
|
3125
|
+
}
|
|
3126
|
+
flushPresentationEvents()
|
|
3127
|
+
await presentationWriteTail
|
|
1040
3128
|
detachUI()
|
|
1041
3129
|
detachBusDebug()
|
|
1042
3130
|
try {
|
|
@@ -1044,6 +3132,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
1044
3132
|
} catch {}
|
|
1045
3133
|
shadowUnsub = null
|
|
1046
3134
|
presentationSubscribers.clear()
|
|
3135
|
+
domainEventSubscribers.clear()
|
|
1047
3136
|
shadowState = null
|
|
1048
3137
|
shadowDiag = null
|
|
1049
3138
|
contentStore = null
|
|
@@ -1056,6 +3145,39 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
1056
3145
|
killAllBackgroundJobs()
|
|
1057
3146
|
await mcpCloseAll()
|
|
1058
3147
|
await lspCloseAll()
|
|
3148
|
+
// P2.2 — lepas pagar penulis TERAKHIR (setelah scheduler berhenti, agar
|
|
3149
|
+
// token bersama tak dilepas sebelum stop-nya selesai; token-guarded jadi
|
|
3150
|
+
// urutan tak kritis). Best-effort + diam (kontrak teardown OAP-008).
|
|
3151
|
+
// P2.6 — tutup Run live dari outcome terakhir (shutdown bersih =
|
|
3152
|
+
// INTERRUPTED/FAILED/COMPLETED eksplisit, BUKAN residu RUNNING untuk
|
|
3153
|
+
// kuburan resume). Best-effort + warn (bukan throw teardown).
|
|
3154
|
+
try {
|
|
3155
|
+
if (currentRunId !== null && lastTurnOutcome !== null) {
|
|
3156
|
+
const runId = currentRunId
|
|
3157
|
+
const outcome = lastTurnOutcome
|
|
3158
|
+
currentRunId = null
|
|
3159
|
+
lastTurnOutcome = null
|
|
3160
|
+
if (outcome === "completed") completeRun(runId, cwd, { expectedEpoch })
|
|
3161
|
+
else if (outcome === "interrupted") interruptRun(runId, cwd, { expectedEpoch })
|
|
3162
|
+
else failRun(runId, cwd, { expectedEpoch })
|
|
3163
|
+
} else if (currentRunId !== null) {
|
|
3164
|
+
const runId = currentRunId
|
|
3165
|
+
currentRunId = null
|
|
3166
|
+
lastTurnOutcome = null
|
|
3167
|
+
interruptRun(runId, cwd, { expectedEpoch })
|
|
3168
|
+
}
|
|
3169
|
+
// P2.9 — parent terminal ⇒ anak tak boleh tetap RUNNING. Sweep yang sama
|
|
3170
|
+
// dengan orphan (INTERRUPTED + UNKNOWN): kita tak boleh mengklaim anak
|
|
3171
|
+
// selesai, dan tak boleh meninggalkan eksekusi durable tanpa pelacak.
|
|
3172
|
+
terminalizeChildRuns(sessionId, cwd, { expectedEpoch })
|
|
3173
|
+
} catch (e) {
|
|
3174
|
+
warnLine(`run terminal mark failed: ${(e as Error).message}`)
|
|
3175
|
+
}
|
|
3176
|
+
try {
|
|
3177
|
+
if (writerRenewTimer !== undefined) clearInterval(writerRenewTimer)
|
|
3178
|
+
} catch {}
|
|
3179
|
+
writerRenewTimer = undefined
|
|
3180
|
+
releaseSessionWriter(sessionId, writerToken, cwd)
|
|
1059
3181
|
// SATU-SATUNYA pause() mid-process yang tersisa: teardown sesi. stdin
|
|
1060
3182
|
// TTY kini mengalir seumur proses (tanpa pause per prompt) agar siklus
|
|
1061
3183
|
// pause→resume tak membunuh 'data' di Bun Windows; tanpa pause di sini
|
|
@@ -1073,10 +3195,26 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
1073
3195
|
cfg,
|
|
1074
3196
|
cwd,
|
|
1075
3197
|
sessionId,
|
|
3198
|
+
bootId,
|
|
3199
|
+
// P2.2: pagar penulis — observability tanpa token (token tak pernah keluar).
|
|
3200
|
+
get writerEpoch() {
|
|
3201
|
+
return expectedEpoch
|
|
3202
|
+
},
|
|
3203
|
+
isWriterStale: () => writerStale,
|
|
3204
|
+
writerStaleNote: () => writerStaleNote,
|
|
3205
|
+
// [Stage 5B] Bukti kegagalan checkpoint: tercatat (bukan unhandled
|
|
3206
|
+
// rejection, bukan sukses palsu). Pesan error internal saja — tak ada
|
|
3207
|
+
// credential di jalur ini.
|
|
3208
|
+
checkpointFailures: () => checkpointFailureNotes.slice(),
|
|
3209
|
+
// Operasi checkpoint yang masih berjalan. Setelah `close()` selesai
|
|
3210
|
+
// HARUS 0 — close() jadi barrier lifecycle.
|
|
3211
|
+
pendingCheckpointCount: () => pendingCheckpointWork.size,
|
|
1076
3212
|
modelRef,
|
|
1077
3213
|
effectiveInitialModel,
|
|
1078
3214
|
effectiveTimeoutMs,
|
|
1079
3215
|
permissionMode,
|
|
3216
|
+
workMode,
|
|
3217
|
+
workModeControl,
|
|
1080
3218
|
allowLocalConfig: allowLocalConfig === true,
|
|
1081
3219
|
sessionTools,
|
|
1082
3220
|
allLoadedSkills,
|
|
@@ -1087,12 +3225,35 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
1087
3225
|
detachSimple: () => detachUI(),
|
|
1088
3226
|
persistCurrent,
|
|
1089
3227
|
runPromptWithVerify,
|
|
3228
|
+
// P11.1 — baca TERAKHIR-menang: self-heal menimpa lastVerify tiap
|
|
3229
|
+
// siklus, jadi yang terbaca di sini selalu hasil final. Salin nilai
|
|
3230
|
+
// (bukan referensi) agar summary mesin tak bisa memutasi state sesi.
|
|
3231
|
+
getLastVerifyResult: () =>
|
|
3232
|
+
lastVerify ? { ok: lastVerify.ok, command: lastVerify.command } : null,
|
|
3233
|
+
// P3.5 — carrier metadata runtime (satu sesi, tanpa registry).
|
|
3234
|
+
runtimeContextMetadata,
|
|
1090
3235
|
permissions,
|
|
1091
3236
|
close,
|
|
1092
|
-
|
|
3237
|
+
// [PHASE 6AB] The two objects the operator control surface needs. Exposed on
|
|
3238
|
+
// the session, not through a registry: whoever holds a CliSession can operate
|
|
3239
|
+
// the Scheduler of exactly that session and no other.
|
|
3240
|
+
productionScheduler,
|
|
3241
|
+
schedulerObservability,
|
|
3242
|
+
adoption,
|
|
3243
|
+
// [P1 M14] Same rule as the Scheduler handle above: one session owns one
|
|
3244
|
+
// runtime, reachable only through the session, never through a registry.
|
|
3245
|
+
productionRuntime,
|
|
3246
|
+
/** [P1 M15] Mode runtime yang benar-benar dipakai sesi ini. */
|
|
3247
|
+
runtimeMode: effectiveRuntimeMode,
|
|
3248
|
+
/** [P1 M15] Admission runtime untuk turn sesi ini (mode off = pass-through). */
|
|
3249
|
+
executionRunner,
|
|
3250
|
+
/** [P1 M15] Laporan bukti durable saat start (integritas + tafsir M12). */
|
|
3251
|
+
startupRecovery,
|
|
3252
|
+
/** Counter reducer presentasi (divergensi harus 0). */
|
|
1093
3253
|
getShadowDiagnostics,
|
|
1094
3254
|
getPresentationSnapshot,
|
|
1095
3255
|
onPresentationEvent,
|
|
3256
|
+
onDomainEvent,
|
|
1096
3257
|
expandAllContent: (): ContentEntry[] => contentStore?.expandAll() ?? [],
|
|
1097
3258
|
/** Query content store untuk /expand [id] (buka-ulang identik). */
|
|
1098
3259
|
expandContent: (toolCallId: string): ContentEntry[] => {
|
|
@@ -1101,7 +3262,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
|
|
|
1101
3262
|
// di luar retensi = penanda). Best-effort — miss = tanpa konten.
|
|
1102
3263
|
const durable = (id: string): string | undefined => {
|
|
1103
3264
|
try {
|
|
1104
|
-
const sess = loadSession(
|
|
3265
|
+
const sess = loadSession(sessionId, cwd)
|
|
1105
3266
|
if (!sess) return undefined
|
|
1106
3267
|
for (const m of sess.messages as {
|
|
1107
3268
|
role?: string
|