@deksden-com/dd-flow-cli 0.9.0-beta.13 → 0.9.0-beta.134
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 +687 -0
- package/README.md +101 -1
- package/dist/build-info.json +10 -10
- package/dist/cli/argument-values.js +38 -0
- package/dist/cli/command-inputs.js +306 -0
- package/dist/cli/help.js +88 -12
- package/dist/cli/hook-ingress.js +78 -0
- package/dist/cli/input-preparation.js +116 -0
- package/dist/cli/native-hook-ingress.js +80 -0
- package/dist/cli/run-cli.js +1465 -450
- package/dist/cli/runtime-maintenance-diagnostics.js +46 -0
- package/dist/cli/runtime-maintenance-ingress.js +52 -0
- package/dist/cli/runtime-process.js +153 -0
- package/dist/cli.js +17 -2
- package/dist/domain/stage-catalog.js +1 -1
- package/dist/harness-runtime/DD-ZCODE.md +99 -0
- package/dist/harness-runtime/bin/dd-agy.mjs +56 -0
- package/dist/harness-runtime/bin/dd-codex.mjs +27 -0
- package/dist/harness-runtime/bin/dd-droid.mjs +34 -0
- package/dist/harness-runtime/bin/dd-grok.mjs +40 -0
- package/dist/harness-runtime/bin/dd-opencode.mjs +22 -0
- package/dist/harness-runtime/bin/dd-zcode.mjs +87 -0
- package/dist/harness-runtime/lib/adapter-timeouts.d.mts +5 -0
- package/dist/harness-runtime/lib/adapter-timeouts.mjs +34 -0
- package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
- package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
- package/dist/harness-runtime/lib/codex-capacity-policy.d.mts +10 -0
- package/dist/harness-runtime/lib/codex-capacity-policy.mjs +89 -0
- package/dist/harness-runtime/lib/daemon-observation.d.mts +2 -0
- package/dist/harness-runtime/lib/daemon-observation.mjs +163 -0
- package/dist/harness-runtime/lib/daemon-operations.mjs +370 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.mjs +693 -0
- package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.mjs +190 -0
- package/dist/harness-runtime/lib/dd-codex.d.mts +1 -0
- package/dist/harness-runtime/lib/dd-codex.mjs +805 -0
- package/dist/harness-runtime/lib/dd-droid-daemon.mjs +128 -0
- package/dist/harness-runtime/lib/dd-droid.mjs +561 -0
- package/dist/harness-runtime/lib/dd-grok-daemon.mjs +490 -0
- package/dist/harness-runtime/lib/dd-grok.mjs +177 -0
- package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +255 -0
- package/dist/harness-runtime/lib/dd-opencode.mjs +128 -0
- package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +703 -0
- package/dist/harness-runtime/lib/dd-zcode.mjs +1128 -0
- package/dist/harness-runtime/lib/delegation-instructions.d.mts +13 -0
- package/dist/harness-runtime/lib/delegation-instructions.mjs +144 -0
- package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
- package/dist/harness-runtime/lib/driver-recovery.mjs +139 -0
- package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
- package/dist/harness-runtime/lib/lease-renewal.d.mts +8 -0
- package/dist/harness-runtime/lib/lease-renewal.mjs +36 -0
- package/dist/harness-runtime/lib/lifecycle-command.d.mts +20 -0
- package/dist/harness-runtime/lib/lifecycle-command.mjs +272 -0
- package/dist/harness-runtime/lib/lifecycle-contract.d.mts +10 -0
- package/dist/harness-runtime/lib/lifecycle-contract.mjs +19 -0
- package/dist/harness-runtime/lib/managed-daemon.d.mts +12 -0
- package/dist/harness-runtime/lib/managed-daemon.mjs +619 -0
- package/dist/harness-runtime/lib/model-observations.mjs +101 -0
- package/dist/harness-runtime/lib/native-children.d.mts +14 -0
- package/dist/harness-runtime/lib/native-children.mjs +94 -0
- package/dist/harness-runtime/lib/native-hook-command.d.mts +7 -0
- package/dist/harness-runtime/lib/native-hook-command.mjs +251 -0
- package/dist/harness-runtime/lib/native-streams.mjs +45 -0
- package/dist/harness-runtime/lib/observation-clock.d.mts +18 -0
- package/dist/harness-runtime/lib/observation-clock.mjs +92 -0
- package/dist/harness-runtime/lib/operation-context.mjs +5 -0
- package/dist/harness-runtime/lib/operation-errors.d.mts +14 -0
- package/dist/harness-runtime/lib/operation-errors.mjs +116 -0
- package/dist/harness-runtime/lib/operation-progress.d.mts +7 -0
- package/dist/harness-runtime/lib/operation-progress.mjs +112 -0
- package/dist/harness-runtime/lib/process-json.d.mts +5 -0
- package/dist/harness-runtime/lib/process-json.mjs +201 -0
- package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
- package/dist/harness-runtime/lib/runner-events.mjs +200 -0
- package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
- package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
- package/dist/harness-runtime/lib/setup-progress.d.mts +9 -0
- package/dist/harness-runtime/lib/setup-progress.mjs +51 -0
- package/dist/harness-runtime/lib/tool-observations.d.mts +21 -0
- package/dist/harness-runtime/lib/tool-observations.mjs +228 -0
- package/dist/harness-runtime/lib/zcode-usage.mjs +55 -0
- package/dist/protocol/local-files.js +18 -9
- package/dist/runtime/context.js +8 -4
- package/dist/schemas/agent-profile.schema.json +1 -1
- package/dist/schemas/code-review-result.schema.json +1 -1
- package/dist/schemas/code-verification.schema.json +7 -5
- package/dist/schemas/code-work-batch.schema.json +2 -2
- package/dist/schemas/flow-run.schema.json +2 -0
- package/dist/schemas/plan-review-decision.schema.json +3 -3
- package/dist/schemas/plan-review-result.schema.json +2 -2
- package/dist/schemas/run-control-receipt.schema.json +118 -0
- package/dist/schemas/run-control-request.schema.json +36 -0
- package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
- package/dist/services/branch-context.js +3 -3
- package/dist/services/canon.js +11 -8
- package/dist/services/check-runner-evidence.js +121 -0
- package/dist/services/cleanup.js +133 -40
- package/dist/services/cli-operation-classifier.js +22 -24
- package/dist/services/code-checks.js +851 -109
- package/dist/services/codex-capacity.js +367 -0
- package/dist/services/codex-hook-delivery.js +32 -0
- package/dist/services/command-context.js +80 -0
- package/dist/services/compatibility-preflight.js +13 -3
- package/dist/services/config.js +11 -8
- package/dist/services/continuation-outcome.js +20 -0
- package/dist/services/controller-fanout.js +136 -0
- package/dist/services/dashboard.js +135 -56
- package/dist/services/engines.js +245 -119
- package/dist/services/eval-snapshots.js +1146 -105
- package/dist/services/execution-policy.js +181 -0
- package/dist/services/external-work-launch.js +230 -0
- package/dist/services/harness-adapter.js +329 -36
- package/dist/services/harness-config.js +2 -0
- package/dist/services/hooks.js +753 -325
- package/dist/services/lanes.js +78 -65
- package/dist/services/lifecycle-command.js +1 -288
- package/dist/services/lifecycle-contract.js +1 -0
- package/dist/services/lifecycle-invocations.js +1828 -0
- package/dist/services/managed-daemon-binding.js +38 -0
- package/dist/services/managed-lease-monitor.js +133 -0
- package/dist/services/managed-processes.js +409 -51
- package/dist/services/merge-queue.js +228 -149
- package/dist/services/merge-server.js +163 -35
- package/dist/services/migrations.js +37 -16
- package/dist/services/native-daemon-history.js +49 -0
- package/dist/services/native-session-control.js +39 -0
- package/dist/services/plan-runtime.js +26 -11
- package/dist/services/plans.js +28 -25
- package/dist/services/projects.js +20 -15
- package/dist/services/prompts.js +28 -17
- package/dist/services/protocols.js +163 -87
- package/dist/services/recovery-observation-budget.js +121 -0
- package/dist/services/recovery-snapshot-database.js +145 -0
- package/dist/services/repair-intents.js +42 -0
- package/dist/services/review-copy.js +157 -0
- package/dist/services/review-deferral.js +23 -0
- package/dist/services/run-control-receipt.js +56 -0
- package/dist/services/run-control-worker.js +411 -0
- package/dist/services/run-control.js +985 -0
- package/dist/services/run-controller-adapter.js +399 -0
- package/dist/services/run-controller-capture.js +179 -0
- package/dist/services/run-controller-process.js +187 -0
- package/dist/services/run-controller-recovery.js +289 -0
- package/dist/services/run-controller-state.js +97 -0
- package/dist/services/run-controller.js +1035 -0
- package/dist/services/run-engine-bindings.js +1 -1
- package/dist/services/run-fork.js +147 -0
- package/dist/services/run-observations.js +152 -0
- package/dist/services/run-projection.js +22 -64
- package/dist/services/run-recovery-guard.js +75 -0
- package/dist/services/run-recovery-runtime.js +112 -0
- package/dist/services/run-recovery.js +349 -0
- package/dist/services/runs.js +558 -217
- package/dist/services/runtime-budget.js +430 -0
- package/dist/services/runtime-command.js +43 -0
- package/dist/services/runtime-scope-capture.js +52 -0
- package/dist/services/runtime-scope-control.js +468 -0
- package/dist/services/runtime-scope-resume.js +599 -0
- package/dist/services/runtime-scope-stop.js +180 -0
- package/dist/services/runtime-scope-worker.js +287 -0
- package/dist/services/runtime-service.js +96 -0
- package/dist/services/schema-validation.js +10 -8
- package/dist/services/scope-writer-cleanup.js +27 -0
- package/dist/services/sessions.js +35 -69
- package/dist/services/stage-blocker.js +17 -7
- package/dist/services/stage-context.js +185 -19
- package/dist/services/stage-lifecycle.js +98 -107
- package/dist/services/stage-pause.js +89 -75
- package/dist/services/stage-report-renderer.js +158 -6
- package/dist/services/stage-work-graph.js +35 -0
- package/dist/services/tooling.js +32 -23
- package/dist/services/usage.js +49 -101
- package/dist/services/verification-matrix.js +374 -0
- package/dist/services/vnext-code-review.js +222 -87
- package/dist/services/vnext-code.js +324 -251
- package/dist/services/vnext-contracts.js +10 -1
- package/dist/services/vnext-execution-profile.js +79 -4
- package/dist/services/vnext-fanout.js +182 -17
- package/dist/services/vnext-merge.js +335 -113
- package/dist/services/vnext-plan-review.js +276 -126
- package/dist/services/vnext-plan.js +227 -102
- package/dist/services/vnext-protocolize.js +335 -82
- package/dist/services/vnext-specify.js +119 -81
- package/dist/services/work-registry.js +1083 -194
- package/dist/services/workspace-bootstrap.js +87 -0
- package/dist/services/workspace-files.js +85 -0
- package/dist/services/worktrees.js +98 -44
- package/dist/shared/entity-references.js +8 -0
- package/dist/shared/errors.js +17 -0
- package/dist/storage/agent-output.js +26 -0
- package/dist/storage/database.js +785 -37
- package/dist/storage/foreign-key-transaction.js +39 -0
- package/dist/storage/immutable-input.js +45 -0
- package/dist/storage/import-guard.js +102 -0
- package/dist/storage/native-cleanup.js +52 -0
- package/dist/storage/paths.js +17 -4
- package/dist/storage/projection-lock.js +73 -0
- package/dist/storage/work-references.js +23 -0
- package/dist/storage/writer-contract.js +77 -0
- package/dist/storage/writer-migration.js +85 -0
- package/package.json +30 -13
- package/tools/repair-paused-run-status.mjs +84 -0
package/dist/services/hooks.js
CHANGED
|
@@ -2,18 +2,28 @@ import crypto from "node:crypto";
|
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
|
-
import { parse, stringify } from "smol-toml";
|
|
5
|
+
import { parse, stringify, TomlError } from "smol-toml";
|
|
6
6
|
import { AppError } from "../shared/errors.js";
|
|
7
|
+
import { entityReferenceVariants } from "../shared/entity-references.js";
|
|
7
8
|
import { parseJsonObject } from "../shared/json.js";
|
|
8
|
-
import { ensureDir, resolveProjectRoot } from "../storage/paths.js";
|
|
9
|
+
import { canonicalPath, ensureDir, resolveProjectRoot } from "../storage/paths.js";
|
|
10
|
+
import { resolveWorkReference } from "../storage/work-references.js";
|
|
9
11
|
import { appendAudit } from "./audit.js";
|
|
12
|
+
import { prepareTextFile, prepareJsonText, prepareError } from "../cli/input-preparation.js";
|
|
10
13
|
import { nativeSessionIdentity, storageSessionId } from "./session-identity.js";
|
|
11
|
-
import {
|
|
14
|
+
import { assertRecoveryHookCurrent } from "./run-recovery.js";
|
|
15
|
+
import { observeLifecycleInvocation, observedLifecycleInvocation, managedNativeInvocationScope } from "./lifecycle-invocations.js";
|
|
16
|
+
import { commandHasOption, commandOption, commandPosition, shellSuffixOffset, parseLifecycleCommand, lifecycleCommandFromPayload, continuationCommand } from "./lifecycle-command.js";
|
|
12
17
|
import { registerProject, requireProjectByRoot } from "./projects.js";
|
|
13
|
-
import { activeFlowSessionsForProject,
|
|
18
|
+
import { activeFlowSessionsForProject, recordFlowSessionObservation } from "./sessions.js";
|
|
14
19
|
const defaultProfileName = "default";
|
|
15
20
|
const maxSanitizedSummaryLength = 1600;
|
|
16
|
-
|
|
21
|
+
function lifecycleObservationResult(receipt) {
|
|
22
|
+
return { observed: receipt.disposition === "admitted", duplicate: receipt.duplicate,
|
|
23
|
+
event_key: receipt.authoritativeEventKey, current_event_key: receipt.currentEventKey,
|
|
24
|
+
authoritative_event_key: receipt.authoritativeEventKey, receipt_disposition: receipt.disposition };
|
|
25
|
+
}
|
|
26
|
+
export const codexHomeSharedEntries = [
|
|
17
27
|
"auth.json",
|
|
18
28
|
"auth.bk",
|
|
19
29
|
"sessions",
|
|
@@ -50,22 +60,28 @@ export function planCodexHome(context, input) {
|
|
|
50
60
|
config_path: paths.configPath,
|
|
51
61
|
hooks_path: paths.hooksPath,
|
|
52
62
|
owned_files: ["config.toml", "hooks.json", ".dd-flow-home.json", "log/", ".tmp/", "tmp/"],
|
|
53
|
-
shared_entries:
|
|
63
|
+
shared_entries: codexHomeSharedEntries,
|
|
54
64
|
exists: fs.existsSync(paths.targetHome),
|
|
55
65
|
codex_env: { CODEX_HOME: paths.targetHome }
|
|
56
66
|
};
|
|
57
67
|
}
|
|
58
|
-
export function
|
|
68
|
+
export function prepareCodexHome(context, input) {
|
|
59
69
|
const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
|
|
60
70
|
const profile = resolveProfileName(input.profile);
|
|
61
71
|
const paths = resolveHomePaths(context, project, profile, input);
|
|
72
|
+
if (canonicalPath(paths.sourceHome, false) === canonicalPath(paths.targetHome, false))
|
|
73
|
+
throw new AppError("validation", "Managed Codex home must differ from its source home", 2);
|
|
74
|
+
const config = readTomlIfExists(path.join(paths.sourceHome, "config.toml"));
|
|
75
|
+
return { project, profile, paths, config };
|
|
76
|
+
}
|
|
77
|
+
export function initCodexHome(context, input, prepared = prepareCodexHome(context, input)) {
|
|
78
|
+
const { project, profile, paths, config } = prepared;
|
|
62
79
|
const now = context.now();
|
|
63
80
|
ensureDir(paths.targetHome);
|
|
64
81
|
ensureDir(path.join(paths.targetHome, "log"));
|
|
65
82
|
ensureDir(path.join(paths.targetHome, ".tmp"));
|
|
66
83
|
ensureDir(path.join(paths.targetHome, "tmp"));
|
|
67
84
|
const linked = createSharedLinks(paths.sourceHome, paths.targetHome);
|
|
68
|
-
const config = readTomlIfExists(path.join(paths.sourceHome, "config.toml"));
|
|
69
85
|
fs.writeFileSync(paths.configPath, stringify(withManagedConfig(config, paths.sourceHome, paths.targetHome)));
|
|
70
86
|
writeJsonFile(paths.hooksPath, expectedHooksConfig(project.root));
|
|
71
87
|
writeJsonFile(path.join(paths.targetHome, ".dd-flow-home.json"), {
|
|
@@ -136,7 +152,7 @@ export function printCodexHomeEnv(context, input) {
|
|
|
136
152
|
command_prefix: `CODEX_HOME=${JSON.stringify(record.target_home)}`
|
|
137
153
|
};
|
|
138
154
|
}
|
|
139
|
-
export function
|
|
155
|
+
export function prepareCodexHomeRemoval(context, input) {
|
|
140
156
|
if (!["keep-shared", "remove-owned"].includes(input.mode)) {
|
|
141
157
|
throw new AppError("validation", "--mode must be keep-shared or remove-owned", 2);
|
|
142
158
|
}
|
|
@@ -144,9 +160,30 @@ export function removeCodexHome(context, input) {
|
|
|
144
160
|
const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
|
|
145
161
|
const profile = resolveProfileName(input.profile);
|
|
146
162
|
const record = homeProfile(context, project.id, profile);
|
|
163
|
+
if (record && record.status !== "removed" && fs.existsSync(record.target_home)) {
|
|
164
|
+
let marker;
|
|
165
|
+
try {
|
|
166
|
+
const value = JSON.parse(fs.readFileSync(path.join(record.target_home, ".dd-flow-home.json"), "utf8"));
|
|
167
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
168
|
+
throw new Error("Invalid marker");
|
|
169
|
+
marker = value;
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
throw new AppError("runtime_artifact_invalid", "Managed Codex home ownership marker is missing or invalid; refusing removal", 1, { target_home: record.target_home });
|
|
173
|
+
}
|
|
174
|
+
if (marker.managed_by !== "dd-flow-cli" || marker.project_id !== project.id || marker.profile !== profile || marker.target_home !== record.target_home || marker.source_home !== record.source_home || canonicalPath(record.target_home, false) === canonicalPath(record.source_home, false)) {
|
|
175
|
+
throw new AppError("runtime_artifact_invalid", "Managed Codex home ownership does not match its registration; refusing removal", 1, { target_home: record.target_home });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return { project, profile, record, mode };
|
|
179
|
+
}
|
|
180
|
+
export function removeCodexHome(context, input) {
|
|
181
|
+
const { project, profile, record, mode } = prepareCodexHomeRemoval(context, input);
|
|
147
182
|
if (!record) {
|
|
148
183
|
return { ok: true, removed: false, profile, status: "not_initialized" };
|
|
149
184
|
}
|
|
185
|
+
if (record.status === "removed")
|
|
186
|
+
return { ok: true, removed: false, profile, status: "already_removed" };
|
|
150
187
|
const removedEntries = [];
|
|
151
188
|
for (const relative of ["config.toml", "hooks.json", ".dd-flow-home.json", "log", ".tmp", "tmp"]) {
|
|
152
189
|
const target = path.join(record.target_home, relative);
|
|
@@ -207,7 +244,7 @@ export function getCodexHooksStatus(context, input) {
|
|
|
207
244
|
recorded
|
|
208
245
|
};
|
|
209
246
|
}
|
|
210
|
-
export function
|
|
247
|
+
export function prepareCodexHooks(context, input) {
|
|
211
248
|
const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
|
|
212
249
|
const target = resolveHookTarget(input.target);
|
|
213
250
|
const location = requireHookLocation(context, project, target, resolveProfileName(input.profile));
|
|
@@ -217,9 +254,16 @@ export function installCodexHooks(context, input) {
|
|
|
217
254
|
hooks_path: location.hooksPath
|
|
218
255
|
});
|
|
219
256
|
}
|
|
220
|
-
const
|
|
221
|
-
const
|
|
257
|
+
const text = fs.existsSync(location.hooksPath) ? prepareTextFile(location.hooksPath, "hooks configuration").text : null;
|
|
258
|
+
const existing = text === null ? {} : prepareJsonText(text, { file: location.hooksPath }).value;
|
|
259
|
+
if (!existing || typeof existing !== "object" || Array.isArray(existing) || (existing.hooks !== undefined && (!existing.hooks || typeof existing.hooks !== "object" || Array.isArray(existing.hooks) || Object.values(existing.hooks).some(entries => !Array.isArray(entries)))))
|
|
260
|
+
return prepareError(new AppError("validation", "Hooks configuration requires an object with event arrays", 2), { file: location.hooksPath });
|
|
261
|
+
return { project, target, location, existing, text };
|
|
262
|
+
}
|
|
263
|
+
export function installCodexHooks(context, input, prepared = prepareCodexHooks(context, input)) {
|
|
264
|
+
const { project, target, location, existing, text } = prepared;
|
|
222
265
|
const nextConfig = mergeHooksConfig(existing, project.root);
|
|
266
|
+
const backup = target === "default" && text !== null ? backupFile(location.hooksPath, context.now(), text) : null;
|
|
223
267
|
ensureDir(path.dirname(location.hooksPath));
|
|
224
268
|
writeJsonFile(location.hooksPath, nextConfig);
|
|
225
269
|
recordHookInstallation(context, project.id, installationScope(target, location.profile, location.hooksPath), location.hooksPath, true, "none");
|
|
@@ -238,20 +282,11 @@ export function installCodexHooks(context, input) {
|
|
|
238
282
|
expected_hash: hashObject(expectedHooksConfig(project.root))
|
|
239
283
|
};
|
|
240
284
|
}
|
|
241
|
-
export function removeCodexHooks(context, input) {
|
|
242
|
-
const project
|
|
243
|
-
const target = resolveHookTarget(input.target);
|
|
244
|
-
const location = requireHookLocation(context, project, target, resolveProfileName(input.profile));
|
|
245
|
-
if (target === "default" && !input.yes) {
|
|
246
|
-
throw new AppError("confirmation_required", "Direct default Codex home mutation requires --yes", 1, {
|
|
247
|
-
target,
|
|
248
|
-
hooks_path: location.hooksPath
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
const existing = readJsonIfExists(location.hooksPath) ?? {};
|
|
285
|
+
export function removeCodexHooks(context, input, prepared = prepareCodexHooks(context, input)) {
|
|
286
|
+
const { project, target, location, existing, text } = prepared;
|
|
252
287
|
const hadManaged = hasManagedHooks(existing, project.root);
|
|
253
|
-
const backup = target === "default" && fs.existsSync(location.hooksPath) ? backupFile(location.hooksPath, context.now()) : null;
|
|
254
288
|
const nextConfig = removeManagedHooks(existing, project.root);
|
|
289
|
+
const backup = target === "default" && text !== null ? backupFile(location.hooksPath, context.now(), text) : null;
|
|
255
290
|
ensureDir(path.dirname(location.hooksPath));
|
|
256
291
|
writeJsonFile(location.hooksPath, nextConfig);
|
|
257
292
|
recordHookInstallation(context, project.id, installationScope(target, location.profile, location.hooksPath), location.hooksPath, false, "not_installed");
|
|
@@ -274,98 +309,148 @@ export function handleCodexHook(context, input) {
|
|
|
274
309
|
// therefore the only valid identity for a fresh Work.
|
|
275
310
|
const rawChildProviderSessionId = stringValue(payload.agent_id) ?? null;
|
|
276
311
|
const providerSessionId = rawChildProviderSessionId ?? rootProviderSessionId;
|
|
277
|
-
const parentProviderSessionId = rawChildProviderSessionId ? codexNativeParentId(payload, rawChildProviderSessionId) : null;
|
|
278
312
|
const turnId = stringValue(payload.turn_id);
|
|
279
313
|
const toolName = stringValue(payload.tool_name) ?? toolNameFromPayload(payload);
|
|
280
314
|
const command = lifecycleCommandFromPayload(payload);
|
|
281
315
|
if (!command)
|
|
282
316
|
return { ok: true, observed: false, reason: "non_bash_tool" };
|
|
283
317
|
const lifecycle = lifecycleFacts(command);
|
|
284
|
-
if (!lifecycle)
|
|
318
|
+
if (!lifecycle && !continuationCommand(command))
|
|
285
319
|
return { ok: true, observed: false, reason: "event_not_participating", event: eventName };
|
|
320
|
+
const parentProviderSessionId = rawChildProviderSessionId ? codexNativeParentId(payload, rawChildProviderSessionId) : null;
|
|
286
321
|
// Resume legitimately receives an answer through stdin. It is matched by
|
|
287
322
|
// immutable lifecycle arguments below; never reject or rewrite that pipe.
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
permissionDecision: "deny",
|
|
298
|
-
permissionDecisionReason: `dd-flow lifecycle commands must be standalone. Retry in this same Session: ${lifecycle.invocation.command}`
|
|
299
|
-
}
|
|
300
|
-
};
|
|
323
|
+
const bootstrapStageStart = lifecycle?.bootstrapStageStart;
|
|
324
|
+
const invocationId = lifecycle ? commandOption(lifecycle.invocation, "invocation-id") : undefined;
|
|
325
|
+
if (invocationId || context.env.DD_FLOW_DAEMON_ID) {
|
|
326
|
+
const proof = context.codexHookProof;
|
|
327
|
+
if (!proof || proof.daemonId !== context.env.DD_FLOW_DAEMON_ID || proof.rootSessionId !== rootProviderSessionId
|
|
328
|
+
|| proof.sessionId !== providerSessionId || proof.parentSessionId !== parentProviderSessionId
|
|
329
|
+
|| proof.toolCallId !== payload.tool_use_id || proof.command !== command) {
|
|
330
|
+
throw new AppError("native_hook_unproven", "Managed Codex admission requires its active native hook delivery, not a manual handler call", 1, { ...(invocationId ? { invocation_id: invocationId } : {}), effect: "no_effect" });
|
|
331
|
+
}
|
|
301
332
|
}
|
|
302
|
-
const
|
|
303
|
-
const matchKey = commandProjectRoot ? lifecycleMatchKey(lifecycle, commandProjectRoot) : null;
|
|
333
|
+
const nativeProjectRoot = context.codexHookProof?.projectRoot ?? input.projectRoot;
|
|
304
334
|
// A bootstrap stage is the first stateful command for a new materialized project.
|
|
305
335
|
// Its PreToolUse event arrives before stage start can register that project.
|
|
306
|
-
|
|
307
|
-
|
|
336
|
+
const bootstrapRoot = nativeProjectRoot ?? stringValue(payload.cwd);
|
|
337
|
+
if (bootstrapStageStart && bootstrapRoot) {
|
|
338
|
+
registerProject(context, { root: bootstrapRoot });
|
|
308
339
|
}
|
|
309
|
-
const project = projectForHook(context,
|
|
310
|
-
if (!project)
|
|
340
|
+
const project = projectForHook(context, nativeProjectRoot, stringValue(payload.cwd));
|
|
341
|
+
if (!project) {
|
|
342
|
+
if (invocationId)
|
|
343
|
+
throw new AppError("project_not_registered", "Managed lifecycle invocation has no registered project", 1, { project_root: nativeProjectRoot ?? null });
|
|
311
344
|
return { ok: true, observed: false, reason: "unrelated_cwd" };
|
|
312
|
-
|
|
345
|
+
}
|
|
346
|
+
let matchKey = lifecycle ? lifecycleMatchKey(lifecycle, project.root) : null;
|
|
347
|
+
// Codex retains the root session_id for a thread-spawned child, while the
|
|
348
|
+
// payload transcript belongs to the current agent_id. Keep lineage separate
|
|
349
|
+
// from ownership: otherwise a child overwrites the root transcript binding.
|
|
350
|
+
const eventKey = hookEventKey(payload, eventName, toolName, command);
|
|
313
351
|
const storageId = providerSessionId ? storageSessionId(nativeSessionIdentity("codex-desktop", providerSessionId)) : null;
|
|
314
352
|
const parentSessionId = parentProviderSessionId ? storageSessionId(nativeSessionIdentity("codex-desktop", parentProviderSessionId)) : null;
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
protocolId,
|
|
329
|
-
harness: "codex-desktop",
|
|
330
|
-
providerSessionId: providerSessionId ?? null,
|
|
331
|
-
parentSessionId,
|
|
332
|
-
sessionId: effectiveSessionId,
|
|
333
|
-
agentId: rawChildProviderSessionId ?? null,
|
|
334
|
-
turnId: turnId ?? null,
|
|
335
|
-
eventName,
|
|
336
|
-
toolName: toolName ?? null,
|
|
337
|
-
status: "observed",
|
|
338
|
-
payload,
|
|
339
|
-
eventKey,
|
|
340
|
-
matchKey,
|
|
341
|
-
transcriptPath: binding?.transcript_path ?? null,
|
|
342
|
-
cwd: stringValue(payload.cwd) ?? null
|
|
343
|
-
});
|
|
344
|
-
if (effectiveSessionId) {
|
|
345
|
-
recordFlowSessionObservation(context, {
|
|
353
|
+
const eventCwd = stringValue(payload.cwd) ?? project.root;
|
|
354
|
+
assertHookEventReplay(context, { projectId: project.id, eventKey, harness: "codex-desktop", providerSessionId: providerSessionId ?? null, parentSessionId, daemonId: stringValue(context.env.DD_FLOW_DAEMON_ID) ?? null, sessionId: storageId, turnId: turnId ?? null, eventName, toolName: toolName ?? null, matchKey, cwd: eventCwd });
|
|
355
|
+
const bindingOwnerId = providerSessionId ?? rootProviderSessionId;
|
|
356
|
+
// Resolve legacy transcript discovery before acquiring the receipt write lock.
|
|
357
|
+
const transcriptPath = stringValue(payload.transcript_path)
|
|
358
|
+
?? (bindingOwnerId ? sessionBinding(context, project.id, bindingOwnerId)?.transcript_path ?? locateCodexTranscript(bindingOwnerId, context.env.CODEX_HOME) : null);
|
|
359
|
+
const persist = (scope) => {
|
|
360
|
+
if (scope)
|
|
361
|
+
matchKey = lifecycleMatchKey(lifecycleFacts(scope.command), project.root, scope);
|
|
362
|
+
const binding = bindingOwnerId ? upsertSessionBindingFromPayload(context, project, bindingOwnerId, payload, transcriptPath) : undefined;
|
|
363
|
+
const effectiveSessionId = storageId;
|
|
364
|
+
const protocolId = binding?.protocol_id ?? null;
|
|
365
|
+
const inserted = recordHookEvent(context, {
|
|
346
366
|
projectId: project.id,
|
|
347
|
-
sessionId: effectiveSessionId,
|
|
348
|
-
runId: observedSession?.run_id ?? null,
|
|
349
367
|
protocolId,
|
|
350
|
-
|
|
368
|
+
harness: "codex-desktop",
|
|
369
|
+
providerSessionId: providerSessionId ?? null,
|
|
370
|
+
parentSessionId,
|
|
371
|
+
// Pinned by the owning app-server process, never derived from current RUN
|
|
372
|
+
// state or an agent-supplied shell command/payload.
|
|
373
|
+
daemonId: stringValue(context.env.DD_FLOW_DAEMON_ID) ?? null,
|
|
374
|
+
sessionId: effectiveSessionId,
|
|
375
|
+
agentId: rawChildProviderSessionId ?? null,
|
|
376
|
+
turnId: turnId ?? null,
|
|
377
|
+
eventName,
|
|
351
378
|
toolName: toolName ?? null,
|
|
352
|
-
|
|
379
|
+
status: "observed",
|
|
380
|
+
payload,
|
|
381
|
+
eventKey,
|
|
382
|
+
matchKey,
|
|
383
|
+
transcriptPath: binding?.transcript_path ?? null,
|
|
384
|
+
cwd: stringValue(payload.cwd) ?? project.root
|
|
353
385
|
});
|
|
354
|
-
|
|
355
|
-
|
|
386
|
+
if (effectiveSessionId) {
|
|
387
|
+
recordFlowSessionObservation(context, {
|
|
388
|
+
projectId: project.id,
|
|
389
|
+
sessionId: effectiveSessionId,
|
|
390
|
+
protocolId,
|
|
391
|
+
cwd: eventCwd,
|
|
392
|
+
toolName: toolName ?? null,
|
|
393
|
+
eventKey
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
return { inserted, protocolId };
|
|
397
|
+
};
|
|
398
|
+
const common = {
|
|
356
399
|
ok: true,
|
|
357
|
-
observed: inserted,
|
|
358
|
-
duplicate: !inserted,
|
|
359
400
|
event_key: eventKey,
|
|
360
401
|
session: providerSessionId ? nativeSessionIdentity("codex-desktop", providerSessionId) : null,
|
|
361
402
|
...(parentProviderSessionId ? { parent_session: nativeSessionIdentity("codex-desktop", parentProviderSessionId) } : {}),
|
|
362
|
-
protocol_id:
|
|
363
|
-
|
|
403
|
+
protocol_id: null
|
|
404
|
+
};
|
|
405
|
+
if (!lifecycle) {
|
|
406
|
+
if (providerSessionId)
|
|
407
|
+
assignedLifecycleCwd(context, project.root, null, providerSessionId, command, stringValue(payload.cwd));
|
|
408
|
+
const persisted = context.db.writeTransaction(() => persist());
|
|
409
|
+
return { ...common, observed: persisted.inserted, duplicate: !persisted.inserted };
|
|
410
|
+
}
|
|
411
|
+
if (invocationId || context.env.DD_FLOW_DAEMON_ID) {
|
|
412
|
+
const daemonId = stringValue(context.env.DD_FLOW_DAEMON_ID);
|
|
413
|
+
const toolCallId = stringValue(payload.tool_use_id) ?? stringValue(payload.event_id) ?? stringValue(payload.delivery_id) ?? stringValue(payload.id);
|
|
414
|
+
if (!daemonId || !rootProviderSessionId || !providerSessionId || !toolCallId)
|
|
415
|
+
throw new AppError("codex_identity_missing", "Managed Codex lifecycle hook has no complete native invocation identity", 1, { invocation_id: invocationId });
|
|
416
|
+
const executionCwd = assignedLifecycleCwd(context, project.root, lifecycle, providerSessionId, command, stringValue(payload.cwd), { daemonId, rootSessionId: rootProviderSessionId, sessionId: providerSessionId, parentSessionId: parentProviderSessionId, toolCallId }, "codex-desktop");
|
|
417
|
+
const receipt = observeLifecycleInvocation(context, {
|
|
418
|
+
currentEventKey: eventKey,
|
|
419
|
+
...(invocationId ? { id: invocationId } : {}),
|
|
420
|
+
command,
|
|
421
|
+
harness: "codex-desktop",
|
|
422
|
+
projectId: project.id,
|
|
423
|
+
...(executionCwd ? { executionCwd } : {}),
|
|
424
|
+
identity: { daemonId, rootSessionId: rootProviderSessionId, sessionId: providerSessionId, parentSessionId: parentProviderSessionId, toolCallId },
|
|
425
|
+
recordReceipt: scope => { persist(scope); return eventKey; }
|
|
426
|
+
});
|
|
427
|
+
const stored = context.db.get("SELECT protocol_id FROM hook_events WHERE project_id = ? AND event_key = ?", [project.id, receipt.eventKey]);
|
|
428
|
+
const admittedInvocationId = receipt.invocationId ?? invocationId;
|
|
429
|
+
if (admittedInvocationId)
|
|
430
|
+
return { ...common, protocol_id: stored?.protocol_id ?? null, ...lifecycleObservationResult(receipt), invocation_id: admittedInvocationId };
|
|
431
|
+
return {
|
|
432
|
+
...common,
|
|
433
|
+
protocol_id: stored?.protocol_id ?? null,
|
|
434
|
+
...lifecycleObservationResult(receipt),
|
|
435
|
+
hookSpecificOutput: {
|
|
436
|
+
hookEventName: "PreToolUse",
|
|
437
|
+
permissionDecision: "allow",
|
|
438
|
+
updatedInput: { ...objectRecord(payload.tool_input), command: commandWithHookEvent(command, eventKey) }
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
const persisted = persist();
|
|
443
|
+
return {
|
|
444
|
+
...common,
|
|
445
|
+
protocol_id: persisted.protocolId,
|
|
446
|
+
observed: persisted.inserted,
|
|
447
|
+
duplicate: !persisted.inserted,
|
|
448
|
+
...(providerSessionId
|
|
364
449
|
? {
|
|
365
450
|
hookSpecificOutput: {
|
|
366
451
|
hookEventName: "PreToolUse",
|
|
367
452
|
permissionDecision: "allow",
|
|
368
|
-
updatedInput: { command: commandWithHookEvent(command, eventKey) }
|
|
453
|
+
updatedInput: { ...objectRecord(payload.tool_input), command: commandWithHookEvent(command, eventKey) }
|
|
369
454
|
}
|
|
370
455
|
}
|
|
371
456
|
: {})
|
|
@@ -377,7 +462,24 @@ function codexNativeParentId(payload, childId) {
|
|
|
377
462
|
if (!transcript || !path.isAbsolute(transcript))
|
|
378
463
|
return null;
|
|
379
464
|
try {
|
|
380
|
-
const
|
|
465
|
+
const descriptor = fs.openSync(transcript, "r");
|
|
466
|
+
const chunks = [];
|
|
467
|
+
try {
|
|
468
|
+
for (;;) {
|
|
469
|
+
const buffer = Buffer.alloc(4096);
|
|
470
|
+
const length = fs.readSync(descriptor, buffer, 0, buffer.length, null);
|
|
471
|
+
if (!length)
|
|
472
|
+
break;
|
|
473
|
+
const newline = buffer.subarray(0, length).indexOf(10);
|
|
474
|
+
chunks.push(buffer.subarray(0, newline < 0 ? length : newline));
|
|
475
|
+
if (newline >= 0)
|
|
476
|
+
break;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
finally {
|
|
480
|
+
fs.closeSync(descriptor);
|
|
481
|
+
}
|
|
482
|
+
const firstLine = Buffer.concat(chunks).toString("utf8");
|
|
381
483
|
if (!firstLine)
|
|
382
484
|
return null;
|
|
383
485
|
const record = JSON.parse(firstLine);
|
|
@@ -389,117 +491,141 @@ function codexNativeParentId(payload, childId) {
|
|
|
389
491
|
return null;
|
|
390
492
|
}
|
|
391
493
|
}
|
|
392
|
-
/**
|
|
494
|
+
/** Qualified ACP admission binds public commands to an exact issued assignment.
|
|
495
|
+
* Its provenance is an observation, never a synchronous PreToolUse assertion. */
|
|
393
496
|
export function handleZcodeEvent(context, input) {
|
|
394
497
|
const notification = parseJsonObject(input.stdin || "{}", "zcode ACP notification");
|
|
395
|
-
|
|
498
|
+
const params = objectRecord(notification.params), update = objectRecord(params.update);
|
|
499
|
+
if (notification.method !== "session/update" || update.sessionUpdate !== "tool_call")
|
|
396
500
|
return { ok: true, observed: false, reason: "event_not_participating" };
|
|
397
|
-
const
|
|
398
|
-
const
|
|
399
|
-
if (
|
|
400
|
-
return { ok: true, observed: false, reason: "
|
|
401
|
-
const updateMeta = objectRecord(update._meta);
|
|
402
|
-
const claudeCode = objectRecord(updateMeta.claudeCode);
|
|
403
|
-
const runtime = objectRecord(updateMeta.zcodeRuntime);
|
|
404
|
-
const toolName = stringValue(claudeCode.toolName) ?? stringValue(update.kind);
|
|
405
|
-
const rawInput = objectRecord(update.rawInput);
|
|
501
|
+
const rawInput = objectRecord(update.rawInput), meta = objectRecord(update._meta), native = objectRecord(meta.zcodeRuntime);
|
|
502
|
+
const toolName = stringValue(objectRecord(meta.claudeCode).toolName);
|
|
503
|
+
if (toolName !== "Bash" && toolName !== "bash" && toolName !== "execute")
|
|
504
|
+
return { ok: true, observed: false, reason: "non_bash_tool" };
|
|
406
505
|
const command = stringValue(rawInput.command) ?? stringValue(rawInput.cmd);
|
|
407
|
-
|
|
506
|
+
const parsed = command ? parseLifecycleCommand(command) : { kind: "none", participation: "none" };
|
|
507
|
+
if (parsed.participation === "none" || parsed.participation === "unproven")
|
|
508
|
+
return { ok: true, observed: false, reason: "acp_evidence_only" };
|
|
509
|
+
if (parsed.kind === "none" && !continuationCommand(command))
|
|
510
|
+
throw new AppError("lifecycle_shell_syntax_invalid", "Known lifecycle shell execution is unsupported", 1, { reason: parsed.reason, effect: "unknown", recoverable: false });
|
|
511
|
+
const controlled = objectRecord(objectRecord(notification._meta).ddZcode);
|
|
512
|
+
const providerSessionId = stringValue(native.childSessionId) ?? stringValue(controlled.rootProviderSessionId);
|
|
513
|
+
return recordZcodeLifecycle(context, { projectRoot: input.projectRoot, stdin: JSON.stringify({
|
|
514
|
+
session_id: providerSessionId, tool_use_id: update.toolCallId, tool_name: toolName, tool_input: rawInput,
|
|
515
|
+
agent_id: native.agentId, _meta: { ddZcode: controlled }
|
|
516
|
+
}) }, parsed.kind !== "none" ? commandOption(parsed.invocation, "invocation-id") : undefined);
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Accept the synchronous native ZCode PreToolUse callback. Invocation-ID
|
|
520
|
+
* commands instead rendezvous with their ACP event while the CLI awaits
|
|
521
|
+
* admission; the native hook must not create a competing receipt for them.
|
|
522
|
+
*/
|
|
523
|
+
export function handleZcodeHook(context, input) {
|
|
524
|
+
return recordZcodeLifecycle(context, input, undefined, true);
|
|
525
|
+
}
|
|
526
|
+
function recordZcodeLifecycle(context, input, invocationId, nativePreTool = false) {
|
|
527
|
+
const hook = parseJsonObject(input.stdin || "{}", "ZCode hook event");
|
|
528
|
+
const eventName = stringValue(hook.hook_event_name) ?? stringValue(hook.hookEventName);
|
|
529
|
+
if (eventName && eventName !== "PreToolUse" && eventName !== "pre_tool_use")
|
|
530
|
+
return { ok: true, observed: false, reason: "event_not_participating" };
|
|
531
|
+
const toolName = stringValue(hook.tool_name) ?? stringValue(hook.toolName);
|
|
532
|
+
const rawInput = objectRecord(hook.tool_input ?? hook.toolInput);
|
|
533
|
+
const command = stringValue(rawInput.command) ?? stringValue(rawInput.cmd) ?? stringValue(hook.command);
|
|
534
|
+
if (!command || (toolName && toolName !== "Bash" && toolName !== "bash" && toolName !== "execute"))
|
|
408
535
|
return { ok: true, observed: false, reason: "non_bash_tool" };
|
|
409
|
-
}
|
|
410
536
|
const lifecycle = lifecycleFacts(command);
|
|
411
|
-
if (!lifecycle)
|
|
537
|
+
if (!lifecycle && !continuationCommand(command))
|
|
412
538
|
return { ok: true, observed: false, reason: "event_not_participating" };
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
}
|
|
539
|
+
// ZCode can execute background Bash without emitting the ACP tool_call that admits an issued CLI invocation.
|
|
540
|
+
if (nativePreTool && lifecycle && rawInput.run_in_background === true) {
|
|
541
|
+
const reason = "Run dd-flow lifecycle commands in the foreground; ZCode background Bash does not provide the required admission receipt.";
|
|
542
|
+
return { continue: false, reason, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason } };
|
|
417
543
|
}
|
|
418
|
-
|
|
544
|
+
if (!invocationId && lifecycle && commandOption(lifecycle.invocation, "invocation-id"))
|
|
545
|
+
return { ok: true, observed: false, reason: "cli_invocation_owns_admission" };
|
|
419
546
|
const expectedRoot = resolveProjectRoot(input.projectRoot);
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
547
|
+
const meta = objectRecord(hook._meta);
|
|
548
|
+
const ddZcode = objectRecord(meta.ddZcode);
|
|
549
|
+
const providerSessionId = stringValue(hook.session_id) ?? stringValue(hook.sessionId);
|
|
550
|
+
const rootProviderSessionId = stringValue(ddZcode.rootProviderSessionId);
|
|
551
|
+
const parentProviderSessionId = stringValue(ddZcode.parentProviderSessionId);
|
|
552
|
+
const daemonId = stringValue(ddZcode.daemonId);
|
|
553
|
+
if (!providerSessionId || !rootProviderSessionId || !daemonId) {
|
|
554
|
+
throw new AppError("zcode_identity_missing", "ZCode native hook has no controlled Session identity", 1);
|
|
425
555
|
}
|
|
426
|
-
|
|
427
|
-
|
|
556
|
+
if (providerSessionId === rootProviderSessionId ? parentProviderSessionId : !parentProviderSessionId) {
|
|
557
|
+
throw new AppError("zcode_identity_missing", "ZCode native hook has inconsistent Session ancestry", 1);
|
|
558
|
+
}
|
|
559
|
+
const toolUseId = stringValue(hook.tool_use_id) ?? stringValue(hook.toolUseId) ?? stringValue(hook.event_id) ?? stringValue(hook.eventId);
|
|
560
|
+
if (!toolUseId)
|
|
561
|
+
throw new AppError("zcode_hook_event_missing", "ZCode native hook has no tool-use ID", 1);
|
|
562
|
+
const eventKey = crypto.createHash("sha256").update(JSON.stringify(["zcode-acp", daemonId, providerSessionId, toolUseId])).digest("hex");
|
|
563
|
+
const rewritten = invocationId ? command : commandWithHookEvent(command, eventKey);
|
|
564
|
+
if (lifecycle?.bootstrapStageStart)
|
|
428
565
|
registerProject(context, { root: expectedRoot });
|
|
429
566
|
const project = requireProjectByRoot(context, expectedRoot);
|
|
430
|
-
const envelopeMeta = objectRecord(notification._meta);
|
|
431
|
-
const ddZcode = objectRecord(envelopeMeta.ddZcode);
|
|
432
|
-
const observedProfile = objectRecord(ddZcode.observedProfile);
|
|
433
|
-
const rootProviderSessionId = stringValue(ddZcode.rootProviderSessionId) ?? stringValue(params.sessionId);
|
|
434
|
-
const daemonId = stringValue(ddZcode.daemonId);
|
|
435
|
-
if (!rootProviderSessionId)
|
|
436
|
-
throw new AppError("zcode_identity_missing", "ZCode ACP event has no root provider Session ID", 1);
|
|
437
|
-
const childProviderSessionId = stringValue(runtime.childSessionId);
|
|
438
|
-
const providerSessionId = childProviderSessionId ?? rootProviderSessionId;
|
|
439
567
|
const sessionId = storageSessionId(nativeSessionIdentity("zcode-acp", providerSessionId));
|
|
440
|
-
const parentSessionId =
|
|
441
|
-
const
|
|
442
|
-
const
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
model: stringValue(observedProfile.model),
|
|
461
|
-
reasoning: stringValue(observedProfile.reasoning),
|
|
462
|
-
mode: stringValue(observedProfile.mode),
|
|
463
|
-
agent_type: stringValue(runtime.source)
|
|
568
|
+
const parentSessionId = parentProviderSessionId ? storageSessionId(nativeSessionIdentity("zcode-acp", parentProviderSessionId)) : null;
|
|
569
|
+
const observedProfile = objectRecord(ddZcode.observedProfile);
|
|
570
|
+
const observedCwd = stringValue(hook.cwd) && path.isAbsolute(String(hook.cwd)) ? resolveProjectRoot(String(hook.cwd)) : null;
|
|
571
|
+
let matchKey = lifecycle ? lifecycleMatchKey(lifecycle, expectedRoot) : null;
|
|
572
|
+
const eventNameForReceipt = nativePreTool ? "PreToolUse" : "ToolCallObserved";
|
|
573
|
+
const persist = (scope) => {
|
|
574
|
+
if (scope)
|
|
575
|
+
matchKey = lifecycleMatchKey(lifecycleFacts(scope.command), expectedRoot, scope);
|
|
576
|
+
assertHookEventReplay(context, { projectId: project.id, eventKey, harness: "zcode-acp", providerSessionId, parentSessionId, daemonId, sessionId, turnId: null, eventName: eventNameForReceipt, toolName: toolName ?? "Bash", matchKey, cwd: observedCwd });
|
|
577
|
+
const payload = { ...hook, session_id: providerSessionId, cwd: observedCwd, tool_name: toolName ?? "Bash", tool_input: rawInput,
|
|
578
|
+
command, provider: stringValue(observedProfile.provider), model: stringValue(observedProfile.model), reasoning: stringValue(observedProfile.reasoning), mode: stringValue(observedProfile.mode) };
|
|
579
|
+
const inserted = recordHookEvent(context, {
|
|
580
|
+
projectId: project.id, protocolId: null, harness: "zcode-acp", providerSessionId, parentSessionId,
|
|
581
|
+
daemonId, sessionId, agentId: stringValue(hook.agent_id) ?? stringValue(hook.agentId) ?? null, turnId: null,
|
|
582
|
+
eventName: eventNameForReceipt, toolName: toolName ?? "Bash", status: "observed", payload, eventKey, matchKey,
|
|
583
|
+
transcriptPath: stringValue(hook.transcript_path) ?? null, cwd: observedCwd
|
|
584
|
+
});
|
|
585
|
+
recordFlowSessionObservation(context, { projectId: project.id, sessionId, cwd: observedCwd, toolName: toolName ?? "Bash", eventKey });
|
|
586
|
+
const result = { ok: true, observed: inserted, duplicate: !inserted, event_key: eventKey, harness: "zcode-acp", session: nativeSessionIdentity("zcode-acp", providerSessionId), ...(parentProviderSessionId ? { parent_session: nativeSessionIdentity("zcode-acp", parentProviderSessionId) } : {}), daemon_id: daemonId };
|
|
587
|
+
return { ...result, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { ...rawInput, command: rewritten } } };
|
|
464
588
|
};
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
589
|
+
if (!lifecycle) {
|
|
590
|
+
assignedLifecycleCwd(context, expectedRoot, null, providerSessionId, command, observedCwd ?? undefined);
|
|
591
|
+
return context.db.writeTransaction(() => persist());
|
|
592
|
+
}
|
|
593
|
+
let persistedResult;
|
|
594
|
+
const executionCwd = assignedLifecycleCwd(context, expectedRoot, lifecycle, providerSessionId, command, observedCwd ?? undefined, { daemonId, rootSessionId: rootProviderSessionId, sessionId: providerSessionId, parentSessionId: parentProviderSessionId ?? null, toolCallId: toolUseId }, "zcode-acp");
|
|
595
|
+
const receipt = observeLifecycleInvocation(context, {
|
|
596
|
+
currentEventKey: eventKey,
|
|
597
|
+
...(invocationId ? { id: invocationId } : {}), command,
|
|
468
598
|
harness: "zcode-acp",
|
|
469
|
-
providerSessionId,
|
|
470
|
-
parentSessionId,
|
|
471
|
-
daemonId: daemonId ?? null,
|
|
472
|
-
sessionId,
|
|
473
|
-
agentId: agentId ?? null,
|
|
474
|
-
turnId: null,
|
|
475
|
-
eventName: "PreToolUse",
|
|
476
|
-
toolName: toolName ?? "Bash",
|
|
477
|
-
status: "observed",
|
|
478
|
-
payload,
|
|
479
|
-
eventKey,
|
|
480
|
-
matchKey,
|
|
481
|
-
transcriptPath: null,
|
|
482
|
-
cwd: expectedRoot
|
|
483
|
-
});
|
|
484
|
-
recordFlowSessionObservation(context, {
|
|
485
599
|
projectId: project.id,
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
cwd: expectedRoot,
|
|
490
|
-
toolName: toolName ?? "Bash",
|
|
491
|
-
eventKey
|
|
600
|
+
...(executionCwd ? { executionCwd } : {}),
|
|
601
|
+
identity: { daemonId, rootSessionId: rootProviderSessionId, sessionId: providerSessionId, parentSessionId: parentProviderSessionId ?? null, toolCallId: toolUseId },
|
|
602
|
+
recordReceipt: scope => { persistedResult = persist(scope); return eventKey; }
|
|
492
603
|
});
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
604
|
+
if (receipt.disposition === "replay") {
|
|
605
|
+
// Keep first admission immutable. A second transport is independently
|
|
606
|
+
// retained corroboration, never another claim or an invented ACP cwd.
|
|
607
|
+
const retained = context.db.get("SELECT event_name, match_key, harness, provider_session_id, parent_session_id, daemon_id FROM hook_events WHERE project_id = ? AND event_key = ?", [project.id, receipt.eventKey]);
|
|
608
|
+
if (retained && retained.event_name !== eventNameForReceipt) {
|
|
609
|
+
if (retained.harness !== "zcode-acp" || retained.provider_session_id !== providerSessionId || retained.parent_session_id !== parentSessionId || retained.daemon_id !== daemonId) {
|
|
610
|
+
throw new AppError("hook_event_replay_mismatch", "Corroborating transport has different native ownership", 1, { event_key: receipt.eventKey });
|
|
611
|
+
}
|
|
612
|
+
context.db.writeTransaction(() => recordHookEvent(context, { projectId: project.id, protocolId: null, harness: "zcode-acp", providerSessionId, parentSessionId,
|
|
613
|
+
daemonId, sessionId, agentId: stringValue(hook.agent_id) ?? null, turnId: null, eventName: eventNameForReceipt, toolName: toolName ?? "Bash", status: "corroborating",
|
|
614
|
+
payload: { ...hook, command, corroborates_event_key: receipt.eventKey, admission_transport: nativePreTool ? "native_pre_tool" : "acp_observation" },
|
|
615
|
+
eventKey: `${receipt.eventKey}:${eventNameForReceipt}`, matchKey: null, transcriptPath: stringValue(hook.transcript_path) ?? null, cwd: observedCwd }));
|
|
616
|
+
}
|
|
617
|
+
else if (retained) {
|
|
618
|
+
assertHookEventReplay(context, { projectId: project.id, eventKey: receipt.eventKey, harness: "zcode-acp", providerSessionId, parentSessionId, daemonId,
|
|
619
|
+
sessionId, turnId: null, eventName: eventNameForReceipt, toolName: toolName ?? "Bash", matchKey: retained.match_key, cwd: observedCwd });
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
const admittedInvocationId = receipt.invocationId ?? invocationId;
|
|
623
|
+
if (admittedInvocationId)
|
|
624
|
+
return { ok: true, ...lifecycleObservationResult(receipt), invocation_id: admittedInvocationId };
|
|
625
|
+
// Without an issued managed attempt this is still ordinary hook evidence.
|
|
626
|
+
// Preserve persist()'s replay result instead of overwriting it with the
|
|
627
|
+
// admission layer's non-authoritative duplicate flag.
|
|
628
|
+
return persistedResult ?? persist();
|
|
503
629
|
}
|
|
504
630
|
/** Convert a Grok Build PreToolUse hook into a trusted lifecycle receipt. */
|
|
505
631
|
export function handleGrokEvent(context, input) {
|
|
@@ -515,27 +641,18 @@ export function handleGrokEvent(context, input) {
|
|
|
515
641
|
return { ok: true, observed: false, reason: "non_bash_tool" };
|
|
516
642
|
}
|
|
517
643
|
const lifecycle = lifecycleFacts(command);
|
|
518
|
-
if (!lifecycle)
|
|
644
|
+
if (!lifecycle && !continuationCommand(command))
|
|
519
645
|
return { ok: true, observed: false, reason: "event_not_participating" };
|
|
520
|
-
|
|
521
|
-
throw new AppError("compound_lifecycle_command", "dd-flow lifecycle commands must be a standalone Grok Build tool call", 1, {
|
|
522
|
-
standalone_command: lifecycle.invocation.command
|
|
523
|
-
});
|
|
524
|
-
}
|
|
525
|
-
const { flowPayload, stageStart, stageResume, workStart, bootstrapStageStart, commandProjectRoot } = lifecycle;
|
|
646
|
+
const bootstrapStageStart = lifecycle?.bootstrapStageStart;
|
|
526
647
|
const expectedRoot = resolveProjectRoot(input.projectRoot);
|
|
527
|
-
|
|
528
|
-
throw new AppError("project_mismatch", "Grok Build lifecycle command project root does not match the controlled workspace", 1, {
|
|
529
|
-
expected: expectedRoot, actual: commandProjectRoot
|
|
530
|
-
});
|
|
531
|
-
}
|
|
532
|
-
const matchKey = lifecycleMatchKey(lifecycle, expectedRoot);
|
|
648
|
+
let matchKey = lifecycle ? lifecycleMatchKey(lifecycle, expectedRoot) : null;
|
|
533
649
|
if (bootstrapStageStart)
|
|
534
650
|
registerProject(context, { root: expectedRoot });
|
|
535
651
|
const project = requireProjectByRoot(context, expectedRoot);
|
|
536
652
|
const meta = objectRecord(hook._meta);
|
|
537
653
|
const ddGrok = objectRecord(meta.ddGrok);
|
|
538
654
|
const observedProfile = objectRecord(ddGrok.observedProfile);
|
|
655
|
+
const observedCwd = stringValue(hook.cwd) && path.isAbsolute(String(hook.cwd)) ? resolveProjectRoot(String(hook.cwd)) : null;
|
|
539
656
|
const rootProviderSessionId = stringValue(ddGrok.rootProviderSessionId);
|
|
540
657
|
const providerSessionId = stringValue(hook.session_id) ?? stringValue(hook.sessionId);
|
|
541
658
|
if (!rootProviderSessionId || !providerSessionId)
|
|
@@ -545,41 +662,156 @@ export function handleGrokEvent(context, input) {
|
|
|
545
662
|
const parentSessionId = isChild ? storageSessionId(nativeSessionIdentity("grok-acp", stringValue(ddGrok.parentProviderSessionId) ?? rootProviderSessionId)) : null;
|
|
546
663
|
const daemonId = stringValue(ddGrok.daemonId);
|
|
547
664
|
const agentId = stringValue(hook.agent_id) ?? stringValue(hook.agentId);
|
|
548
|
-
const observedSession = flowPayload ? bindObservedFlowSession(context, project, {
|
|
549
|
-
...flowPayload, harness: "grok-acp", provider_session_id: providerSessionId, agent_id: agentId ?? null, parent_session_id: parentSessionId
|
|
550
|
-
}, sessionId) : undefined;
|
|
551
665
|
const eventKey = stringValue(hook.event_id) ?? stringValue(hook.eventId) ?? crypto.createHash("sha256").update(JSON.stringify({
|
|
552
|
-
harness: "grok-acp", providerSessionId,
|
|
666
|
+
harness: "grok-acp", providerSessionId, toolUseId: hook.tool_use_id ?? hook.toolUseId ?? null,
|
|
667
|
+
promptId: hook.prompt_id ?? hook.promptId ?? null, command, turn: hook.turn_id ?? hook.turnId ?? null
|
|
553
668
|
})).digest("hex");
|
|
554
|
-
const
|
|
555
|
-
|
|
556
|
-
|
|
669
|
+
const persist = (scope) => {
|
|
670
|
+
if (scope)
|
|
671
|
+
matchKey = lifecycleMatchKey(lifecycleFacts(scope.command), expectedRoot, scope);
|
|
672
|
+
assertHookEventReplay(context, { projectId: project.id, eventKey, harness: "grok-acp", providerSessionId, parentSessionId, daemonId: daemonId ?? null, sessionId, turnId: stringValue(hook.turn_id) ?? stringValue(hook.turnId) ?? null, eventName: "PreToolUse", toolName: toolName ?? "Bash", matchKey, cwd: observedCwd });
|
|
673
|
+
const payload = {
|
|
674
|
+
...hook, session_id: providerSessionId, agent_id: agentId, cwd: observedCwd, tool_name: toolName ?? "Bash", tool_input: rawInput,
|
|
675
|
+
command, provider: stringValue(observedProfile.provider), model: stringValue(observedProfile.model), reasoning: stringValue(observedProfile.reasoning), mode: stringValue(observedProfile.mode), agent_type: stringValue(hook.subagent_type) ?? stringValue(hook.subagentType)
|
|
676
|
+
};
|
|
677
|
+
const inserted = recordHookEvent(context, {
|
|
678
|
+
projectId: project.id, protocolId: null, harness: "grok-acp", providerSessionId, parentSessionId,
|
|
679
|
+
daemonId: daemonId ?? null, sessionId, agentId: agentId ?? null, turnId: stringValue(hook.turn_id) ?? stringValue(hook.turnId) ?? null,
|
|
680
|
+
eventName: "PreToolUse", toolName: toolName ?? "Bash", status: "observed", payload, eventKey, matchKey, transcriptPath: null, cwd: observedCwd
|
|
681
|
+
});
|
|
682
|
+
recordFlowSessionObservation(context, { projectId: project.id, sessionId, cwd: observedCwd, toolName: toolName ?? "Bash", eventKey });
|
|
683
|
+
return inserted;
|
|
557
684
|
};
|
|
558
|
-
const
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
685
|
+
const result = (inserted) => ({ ok: true, observed: inserted, duplicate: !inserted, event_key: eventKey, session: nativeSessionIdentity("grok-acp", providerSessionId),
|
|
686
|
+
...(isChild ? { parent_session: nativeSessionIdentity("grok-acp", stringValue(ddGrok.parentProviderSessionId) ?? rootProviderSessionId) } : {}), daemon_id: daemonId ?? null });
|
|
687
|
+
if (!lifecycle) {
|
|
688
|
+
assignedLifecycleCwd(context, expectedRoot, null, providerSessionId, command, observedCwd ?? undefined);
|
|
689
|
+
return { ...result(context.db.writeTransaction(() => persist())), hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { ...rawInput, command: commandWithHookEvent(command, eventKey) } } };
|
|
690
|
+
}
|
|
691
|
+
let inserted = false;
|
|
692
|
+
const executionCwd = assignedLifecycleCwd(context, expectedRoot, lifecycle, providerSessionId, command, observedCwd ?? undefined, { daemonId: daemonId ?? "", rootSessionId: rootProviderSessionId, sessionId: providerSessionId, parentSessionId, toolCallId: eventKey }, "grok-acp");
|
|
693
|
+
const receipt = observeLifecycleInvocation(context, {
|
|
694
|
+
currentEventKey: eventKey,
|
|
695
|
+
command, harness: "grok-acp", projectId: project.id,
|
|
696
|
+
...(executionCwd ? { executionCwd } : {}),
|
|
697
|
+
identity: { daemonId: daemonId ?? "", rootSessionId: rootProviderSessionId, sessionId: providerSessionId, parentSessionId, toolCallId: eventKey },
|
|
698
|
+
recordReceipt: scope => { inserted = persist(scope); return eventKey; }
|
|
566
699
|
});
|
|
567
|
-
|
|
568
|
-
...(isChild ? { parent_session: nativeSessionIdentity("grok-acp", stringValue(ddGrok.parentProviderSessionId) ?? rootProviderSessionId) } : {}), daemon_id: daemonId ?? null };
|
|
569
|
-
return (flowPayload || stageStart || stageResume || workStart)
|
|
570
|
-
? { ...result, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { ...(rawInput ?? {}), command: commandWithHookEvent(command, eventKey) } } }
|
|
571
|
-
: result;
|
|
700
|
+
return { ...result(inserted), ...lifecycleObservationResult(receipt), ...(receipt.invocationId ? { invocation_id: receipt.invocationId } : {}), hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { ...rawInput, command: receipt.eventKey ? commandWithHookEvent(command, receipt.eventKey) : command } } };
|
|
572
701
|
}
|
|
573
702
|
/** Convert a controlled OpenCode tool hook into the shared lifecycle receipt. */
|
|
574
703
|
export function handleOpenCodeEvent(context, input) {
|
|
575
704
|
const event = parseJsonObject(input.stdin || "{}", "OpenCode tool event");
|
|
576
|
-
const agy = event.source_harness === "antigravity-cli";
|
|
577
|
-
const harness = agy ? "antigravity-cli" : "opencode-server";
|
|
578
705
|
if (event.schema_id !== "dd-flow/opencode-tool-event@1")
|
|
579
706
|
throw new AppError("unsupported_opencode_event_schema", "Unsupported OpenCode event schema", 1);
|
|
707
|
+
return handleControlledToolEvent(context, input, event, event.source_harness === "antigravity-cli" ? "antigravity-cli" : "opencode-server");
|
|
708
|
+
}
|
|
709
|
+
/** Accept adapter-observed Factory identity, never a model-supplied Session ID. */
|
|
710
|
+
export function handleDroidEvent(context, input) {
|
|
711
|
+
const event = parseJsonObject(input.stdin || "{}", "Droid tool event");
|
|
712
|
+
if (event.schema_id !== "dd-flow/droid-tool-event@1")
|
|
713
|
+
throw new AppError("unsupported_droid_event_schema", "Unsupported Droid event schema", 1);
|
|
714
|
+
return handleControlledToolEvent(context, input, event, "droid-cli");
|
|
715
|
+
}
|
|
716
|
+
/** Stable project identity is not the native Session's execution workspace. */
|
|
717
|
+
function assignedLifecycleCwd(context, projectRoot, facts, providerSessionId, command, observedCwd, identity, harness) {
|
|
718
|
+
const auxiliary = continuationCommand(command);
|
|
719
|
+
if ((!facts && !auxiliary) || facts?.analysis.supported === false)
|
|
720
|
+
return undefined;
|
|
721
|
+
const proven = identity && harness ? managedNativeInvocationScope(context, projectRoot, identity, harness) : null;
|
|
722
|
+
const constraint = proven ?? (identity ? { projectRoot, daemonId: identity.daemonId, rootSessionId: identity.rootSessionId } : undefined);
|
|
723
|
+
const issuedRunId = facts && !facts.runId && !facts.workId && !facts.bootstrapStageStart && constraint ? observedLifecycleInvocation(context, command, constraint, identity ? { identity } : undefined)?.scope.runId : null;
|
|
724
|
+
if (facts?.invocation.operation.startsWith("stage_") && !facts.bootstrapStageStart && !facts.runId && !issuedRunId)
|
|
725
|
+
throw new AppError("invocation_assignment_missing", "Short lifecycle call has no unique issued RUN assignment; its workspace cannot be inferred", 1, { phase: "prepare", effect: "no_effect", recoverable: false });
|
|
726
|
+
const expected = controlledLifecycleCwd(context, projectRoot, facts, providerSessionId, auxiliary, issuedRunId);
|
|
727
|
+
// Unknown CLI targets have no assigned workspace. Recording their native
|
|
728
|
+
// observation must not turn the stable identity root into cwd authority.
|
|
729
|
+
if (!expected)
|
|
730
|
+
return undefined;
|
|
731
|
+
const route = facts?.invocation.expectedCwd ?? auxiliary?.expectedCwd;
|
|
732
|
+
if (route && resolveProjectRoot(route) !== expected)
|
|
733
|
+
throw new AppError("invocation_directory_mismatch", "Literal lifecycle route differs from the assigned workspace", 1, { expected, actual: route, actual_provenance: "shell_literal_route", phase: "prepare", effect: "no_effect", recoverable: false });
|
|
734
|
+
if (!route && observedCwd && resolveProjectRoot(observedCwd) !== expected)
|
|
735
|
+
throw new AppError("invocation_directory_mismatch", "Native lifecycle directory differs from the assigned workspace", 1, { expected, actual: observedCwd, actual_provenance: "native_tool_cwd", phase: "prepare", effect: "no_effect", recoverable: false });
|
|
736
|
+
// ACP without native cwd still binds assigned authority; CLI confirms the
|
|
737
|
+
// physical process directory, rather than inventing native observation.
|
|
738
|
+
return expected;
|
|
739
|
+
}
|
|
740
|
+
function controlledLifecycleCwd(context, projectRoot, facts, providerSessionId, auxiliary, issuedRunId) {
|
|
741
|
+
if (facts?.bootstrapStageStart)
|
|
742
|
+
return projectRoot;
|
|
743
|
+
const project = context.db.get("SELECT id FROM projects WHERE root = ?", [projectRoot]);
|
|
744
|
+
if (!project)
|
|
745
|
+
return undefined;
|
|
746
|
+
if (facts?.invocation.operation === "merge_apply" || facts?.invocation.operation === "merge_repair") {
|
|
747
|
+
const requestId = commandPosition(facts.invocation, 0);
|
|
748
|
+
const request = requestId && context.db.get("SELECT target_workspace FROM merge_requests WHERE project_id = ? AND merge_request_id = ?", [project.id, requestId]);
|
|
749
|
+
if (request)
|
|
750
|
+
return resolveProjectRoot(request.target_workspace);
|
|
751
|
+
}
|
|
752
|
+
let work;
|
|
753
|
+
if (facts?.workId) {
|
|
754
|
+
try {
|
|
755
|
+
work = resolveWorkReference(context, facts.workId, { projectId: project.id });
|
|
756
|
+
}
|
|
757
|
+
catch (error) {
|
|
758
|
+
if (!(error instanceof AppError) || !["not_found", "ambiguous_work_alias"].includes(error.code))
|
|
759
|
+
throw error;
|
|
760
|
+
}
|
|
761
|
+
if (!work)
|
|
762
|
+
return undefined;
|
|
763
|
+
}
|
|
764
|
+
const reference = work?.run_id ?? facts?.runId ?? auxiliary?.args.options.get("run")?.[0] ?? auxiliary?.args.positional[2] ?? issuedRunId;
|
|
765
|
+
if (!reference)
|
|
766
|
+
return undefined;
|
|
767
|
+
const run = context.db.get("SELECT id, run_root, workspace_root FROM runs WHERE project_id = ? AND (id = ? OR short_id = ?)", [project.id, reference, reference]);
|
|
768
|
+
if (!run)
|
|
769
|
+
return undefined; // Hook ingress does not validate a mistyped CLI target.
|
|
770
|
+
if (work) {
|
|
771
|
+
// PROTOCOLIZE provisions the feature checkout after its coordinator
|
|
772
|
+
// Session has launched in the stable project root. Its transition Work
|
|
773
|
+
// must keep that physical route until the Stage is complete. Child Works
|
|
774
|
+
// share stage membership, not the root coordinator's execution directory.
|
|
775
|
+
if (work.parent_work_id === null && context.db.get("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'stage_work_memberships'")
|
|
776
|
+
&& context.db.get("SELECT 1 FROM stage_work_memberships WHERE project_id = ? AND run_id = ? AND work_id = ? AND stage IN ('specify','protocolize') LIMIT 1", [project.id, run.id, work.work_id]))
|
|
777
|
+
return projectRoot;
|
|
778
|
+
const merge = context.db.get("SELECT target_workspace FROM merge_requests WHERE executor_work_id = ? AND run_id = ?", [work.work_id, run.id]);
|
|
779
|
+
if (merge)
|
|
780
|
+
return resolveProjectRoot(merge.target_workspace);
|
|
781
|
+
if (context.db.get("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'work_launches'")) {
|
|
782
|
+
const launch = context.db.get("SELECT provider_session_id, profile_json FROM work_launches WHERE work_id = ? AND status IN ('launching', 'start_requested')", [work.work_id]);
|
|
783
|
+
if (launch?.provider_session_id === providerSessionId && run.run_root) {
|
|
784
|
+
const copy = JSON.parse(launch.profile_json).review_copy?.root;
|
|
785
|
+
if (copy) {
|
|
786
|
+
const target = path.resolve(run.run_root, copy);
|
|
787
|
+
const relative = path.relative(run.run_root, target);
|
|
788
|
+
if (relative === ".." || relative.startsWith(`..${path.sep}`))
|
|
789
|
+
throw new AppError("read_only_workspace_unbound", "Review copy escapes its owning RUN", 1);
|
|
790
|
+
return resolveProjectRoot(target);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
if (facts?.stageName === "specify" || facts?.stageName === "protocolize")
|
|
796
|
+
return projectRoot;
|
|
797
|
+
if (facts?.stageName === "merge" || facts?.invocation.operation === "merge_apply" || facts?.invocation.operation === "merge_repair") {
|
|
798
|
+
const pending = context.db.all("SELECT target_workspace FROM merge_requests WHERE project_id = ? AND run_id = ? AND status IN ('dispatching','active','action_required') ORDER BY updated_at DESC", [project.id, run.id]);
|
|
799
|
+
const targets = [...new Set(pending.map(item => resolveProjectRoot(item.target_workspace)))];
|
|
800
|
+
if (targets.length > 1)
|
|
801
|
+
throw new AppError("merge_workspace_ambiguous", "Current MERGE requests disagree on the native execution workspace", 1, { run_id: run.id, target_workspaces: targets });
|
|
802
|
+
if (targets.length === 1)
|
|
803
|
+
return targets[0];
|
|
804
|
+
}
|
|
805
|
+
return resolveProjectRoot(run.workspace_root);
|
|
806
|
+
}
|
|
807
|
+
function handleControlledToolEvent(context, input, event, harness) {
|
|
808
|
+
const agy = harness === "antigravity-cli";
|
|
809
|
+
const droid = harness === "droid-cli";
|
|
810
|
+
const label = droid ? "Droid" : agy ? "Antigravity" : "OpenCode";
|
|
811
|
+
const errorPrefix = droid ? "droid" : agy ? "agy" : "opencode";
|
|
580
812
|
const phase = stringValue(event.phase);
|
|
581
813
|
if (phase !== "before" && phase !== "after")
|
|
582
|
-
throw new AppError(
|
|
814
|
+
throw new AppError(`unsupported_${errorPrefix}_event_schema`, `${label} event phase must be before or after`, 1);
|
|
583
815
|
const session = objectRecord(event.session);
|
|
584
816
|
const profile = objectRecord(event.profile);
|
|
585
817
|
const rawInput = objectRecord(event.input);
|
|
@@ -587,16 +819,16 @@ export function handleOpenCodeEvent(context, input) {
|
|
|
587
819
|
const nativeParentId = stringValue(session.parent_provider_session_id);
|
|
588
820
|
const daemonId = stringValue(event.daemon_id);
|
|
589
821
|
const toolCallId = stringValue(event.tool_call_id);
|
|
590
|
-
const eventId = stringValue(event.event_id) ?? toolCallId;
|
|
822
|
+
const eventId = stringValue(event.event_id) ?? (droid ? undefined : toolCallId);
|
|
591
823
|
const toolName = stringValue(event.tool);
|
|
592
824
|
const directory = stringValue(session.directory);
|
|
593
|
-
if (!providerSessionId || !daemonId || !toolCallId || !eventId || !toolName || !directory || !path.isAbsolute(directory)) {
|
|
594
|
-
throw new AppError(
|
|
825
|
+
if (!providerSessionId || !daemonId || (!droid && !toolCallId) || !eventId || !toolName || !directory || !path.isAbsolute(directory)) {
|
|
826
|
+
throw new AppError(`${errorPrefix}_session_identity_invalid`, `${label} event is missing trusted physical identity`, 1);
|
|
595
827
|
}
|
|
596
828
|
const expectedRoot = resolveProjectRoot(input.projectRoot);
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
829
|
+
const observedCwd = resolveProjectRoot(directory);
|
|
830
|
+
if (droid && nativeParentId === providerSessionId)
|
|
831
|
+
throw new AppError("droid_session_identity_invalid", "A Droid Session cannot parent itself", 1);
|
|
600
832
|
const sessionId = storageSessionId(nativeSessionIdentity(harness, providerSessionId));
|
|
601
833
|
const parentSessionId = nativeParentId ? storageSessionId(nativeSessionIdentity(harness, nativeParentId)) : null;
|
|
602
834
|
const command = stringValue(rawInput.command) ?? stringValue(rawInput.cmd) ?? stringValue(rawInput.CommandLine);
|
|
@@ -606,67 +838,124 @@ export function handleOpenCodeEvent(context, input) {
|
|
|
606
838
|
const inserted = recordHookEvent(context, {
|
|
607
839
|
projectId: project.id, protocolId: null, harness, providerSessionId, parentSessionId,
|
|
608
840
|
daemonId, sessionId, agentId: stringValue(session.agent_id) ?? null, turnId: stringValue(event.message_id) ?? null,
|
|
609
|
-
eventName: "PostToolUse", toolName, status: "observed", payload: { session_id: providerSessionId, cwd:
|
|
610
|
-
eventKey: baseKey, matchKey: null, transcriptPath: null, cwd:
|
|
841
|
+
eventName: "PostToolUse", toolName, status: "observed", payload: { session_id: providerSessionId, cwd: observedCwd, tool_name: toolName, status: objectRecord(event.outcome).status },
|
|
842
|
+
eventKey: baseKey, matchKey: null, transcriptPath: droid ? stringValue(event.transcript_path) ?? null : null, cwd: observedCwd
|
|
611
843
|
});
|
|
612
844
|
return { ok: true, observed: inserted, duplicate: !inserted, event_key: baseKey, phase, harness, session: nativeSessionIdentity(harness, providerSessionId), ...(nativeParentId ? { parent_session: nativeSessionIdentity(harness, nativeParentId) } : {}) };
|
|
613
845
|
}
|
|
614
|
-
if (!command || !["bash", "Bash", "run_command", "run_terminal_command", "RunTerminalCommand"].includes(toolName)) {
|
|
846
|
+
if (!command || !(droid ? ["Execute"] : ["bash", "Bash", "run_command", "run_terminal_command", "RunTerminalCommand"]).includes(toolName)) {
|
|
615
847
|
return { ok: true, observed: false, reason: command ? "non_bash_tool" : "event_not_participating" };
|
|
616
848
|
}
|
|
617
849
|
const lifecycle = lifecycleFacts(command);
|
|
618
|
-
|
|
850
|
+
const auxiliary = continuationCommand(command);
|
|
851
|
+
if (!lifecycle && !auxiliary)
|
|
619
852
|
return { ok: true, observed: false, reason: "event_not_participating" };
|
|
620
|
-
|
|
621
|
-
|
|
853
|
+
// Syntax refusal precedes assignment/cwd lookup: an unsupported AST cannot
|
|
854
|
+
// supply a route or execution authority, including a short public Stage call.
|
|
855
|
+
const shellRefusal = lifecycle?.analysis.supported === false;
|
|
856
|
+
const nativeIdentity = { daemonId, rootSessionId: nativeParentId ?? providerSessionId, sessionId: providerSessionId, parentSessionId: nativeParentId ?? null, toolCallId: toolCallId };
|
|
857
|
+
const provenScope = lifecycle && !shellRefusal ? managedNativeInvocationScope(context, expectedRoot, nativeIdentity, harness) : null;
|
|
858
|
+
const issuedRunId = lifecycle && !lifecycle.runId && !lifecycle.workId && !lifecycle.bootstrapStageStart
|
|
859
|
+
? observedLifecycleInvocation(context, command, provenScope ?? { projectRoot: expectedRoot, daemonId, rootSessionId: nativeIdentity.rootSessionId }, { identity: nativeIdentity })?.scope.runId : null;
|
|
860
|
+
if (!shellRefusal && lifecycle && lifecycle.invocation.operation.startsWith("stage_") && !lifecycle.bootstrapStageStart && !lifecycle.runId && !issuedRunId) {
|
|
861
|
+
throw new AppError("invocation_assignment_missing", "Short lifecycle call has no unique issued RUN assignment; its workspace cannot be inferred", 1, { effect: "no_effect", recoverable: false });
|
|
862
|
+
}
|
|
863
|
+
// These controlled platforms additionally qualify their native launch
|
|
864
|
+
// route against the stable project root when no CLI target is assigned.
|
|
865
|
+
const expectedCwd = shellRefusal ? observedCwd : controlledLifecycleCwd(context, expectedRoot, lifecycle, providerSessionId, auxiliary, issuedRunId) ?? expectedRoot;
|
|
866
|
+
const executionRoute = shellRefusal ? undefined : lifecycle?.invocation.expectedCwd ?? auxiliary?.expectedCwd;
|
|
867
|
+
if (executionRoute && resolveProjectRoot(executionRoute) !== expectedCwd) {
|
|
868
|
+
throw new AppError(`${errorPrefix}_directory_mismatch`, "Literal shell cd route does not match the assigned lifecycle workspace", 1, { expected: expectedCwd, actual: executionRoute, actual_provenance: "shell_literal_route", effect: "no_effect", recoverable: false });
|
|
622
869
|
}
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
throw new AppError("project_mismatch", "OpenCode lifecycle command project root does not match the controlled workspace", 1, { expected: expectedRoot, actual: commandProjectRoot });
|
|
870
|
+
if (!executionRoute && observedCwd !== expectedCwd) {
|
|
871
|
+
throw new AppError(`${errorPrefix}_directory_mismatch`, `${label} ${agy ? "launch route" : "Session directory"} does not match the assigned execution workspace`, 1, { expected: expectedCwd, actual: observedCwd, effect: "no_effect", recoverable: false, ...(agy ? { actual_provenance: stringValue(event.cwd_provenance) ?? "unknown" } : {}) });
|
|
626
872
|
}
|
|
627
|
-
const
|
|
873
|
+
const bootstrapStageStart = !shellRefusal && lifecycle?.bootstrapStageStart;
|
|
874
|
+
let matchKey = lifecycle && !shellRefusal ? lifecycleMatchKey(lifecycle, expectedRoot) : null;
|
|
628
875
|
if (bootstrapStageStart)
|
|
629
876
|
registerProject(context, { root: expectedRoot });
|
|
630
877
|
const project = requireProjectByRoot(context, expectedRoot);
|
|
878
|
+
if (droid) {
|
|
879
|
+
const existing = context.db.get("SELECT harness, provider_session_id, parent_session_id, daemon_id, match_key, tool_name FROM hook_events WHERE project_id = ? AND event_key = ?", [project.id, baseKey]);
|
|
880
|
+
if (existing && (existing.harness !== harness || existing.provider_session_id !== providerSessionId || existing.parent_session_id !== parentSessionId || existing.daemon_id !== daemonId || existing.match_key !== matchKey || existing.tool_name !== toolName)) {
|
|
881
|
+
throw new AppError("droid_event_replay_mismatch", "Droid event ID was already observed with different lifecycle identity", 1);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
631
884
|
const agentId = stringValue(session.agent_id);
|
|
632
|
-
const
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
885
|
+
const persist = (scope) => {
|
|
886
|
+
if (scope)
|
|
887
|
+
matchKey = lifecycleMatchKey(lifecycleFacts(scope.command), expectedRoot, scope);
|
|
888
|
+
assertHookEventReplay(context, { projectId: project.id, eventKey: baseKey, harness, providerSessionId, parentSessionId, daemonId, sessionId, turnId: stringValue(event.message_id) ?? null, eventName: "PreToolUse", toolName, matchKey, cwd: observedCwd });
|
|
889
|
+
const payload = {
|
|
890
|
+
session_id: providerSessionId, agent_id: agentId, cwd: observedCwd, tool_name: toolName, tool_input: rawInput, command,
|
|
891
|
+
...(agy ? { cwd_provenance: stringValue(event.cwd_provenance) ?? "unknown" } : {}),
|
|
892
|
+
...(executionRoute ? { lifecycle_execution_cwd: expectedCwd, lifecycle_execution_cwd_provenance: "literal_cd_intent_requires_cli_confirmation" } : {}),
|
|
893
|
+
provider: stringValue(profile.provider), model: stringValue(profile.model), reasoning: stringValue(droid ? profile.reasoning : profile.variant),
|
|
894
|
+
mode: stringValue(droid ? profile.mode : profile.agent), agent_type: stringValue(droid ? profile.agent_type : profile.agent)
|
|
895
|
+
};
|
|
896
|
+
const inserted = recordHookEvent(context, {
|
|
897
|
+
projectId: project.id, protocolId: null, harness, providerSessionId, parentSessionId,
|
|
898
|
+
daemonId, sessionId, agentId: agentId ?? null, turnId: stringValue(event.message_id) ?? null, eventName: "PreToolUse", toolName,
|
|
899
|
+
status: "observed", payload, eventKey: baseKey, matchKey, transcriptPath: droid ? stringValue(event.transcript_path) ?? null : null, cwd: observedCwd
|
|
900
|
+
});
|
|
901
|
+
recordFlowSessionObservation(context, { projectId: project.id, sessionId, cwd: observedCwd, toolName, eventKey: baseKey });
|
|
902
|
+
return inserted;
|
|
642
903
|
};
|
|
643
|
-
const
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
904
|
+
const result = (inserted) => ({ ok: true, observed: inserted, duplicate: !inserted, event_key: baseKey, phase, harness, session: nativeSessionIdentity(harness, providerSessionId), ...(nativeParentId ? { parent_session: nativeSessionIdentity(harness, nativeParentId) } : {}), daemon_id: daemonId });
|
|
905
|
+
if (lifecycle) {
|
|
906
|
+
let inserted = false;
|
|
907
|
+
const receipt = observeLifecycleInvocation(context, {
|
|
908
|
+
currentEventKey: baseKey,
|
|
909
|
+
command, harness, projectId: project.id, ...(!shellRefusal ? { executionCwd: expectedCwd } : {}), identity: { daemonId, rootSessionId: nativeParentId ?? providerSessionId, sessionId: providerSessionId, parentSessionId: nativeParentId ?? null, toolCallId: toolCallId },
|
|
910
|
+
recordReceipt: scope => { inserted = persist(scope); return baseKey; }
|
|
911
|
+
});
|
|
912
|
+
const admitted = { ...result(inserted), ...lifecycleObservationResult(receipt), ...(receipt.invocationId ? { invocation_id: receipt.invocationId } : {}) };
|
|
913
|
+
return agy || shellRefusal ? admitted : { ...admitted, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { ...rawInput, command: receipt.eventKey ? commandWithHookEvent(command, receipt.eventKey) : command } } };
|
|
914
|
+
}
|
|
915
|
+
const inserted = context.db.writeTransaction(() => persist());
|
|
916
|
+
return agy ? result(inserted) : { ...result(inserted), hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { ...rawInput, command: commandWithHookEvent(command, baseKey) } } };
|
|
651
917
|
}
|
|
652
918
|
/** Convert an Antigravity CLI tool hook into the shared lifecycle receipt. */
|
|
653
919
|
export function handleAgyEvent(context, input) {
|
|
654
920
|
const event = parseJsonObject(input.stdin || "{}", "Antigravity tool event");
|
|
655
921
|
if (event.schema_id !== "dd-flow/agy-tool-event@1")
|
|
656
922
|
throw new AppError("unsupported_agy_event_schema", "Unsupported Antigravity event schema", 1);
|
|
657
|
-
|
|
658
|
-
|
|
923
|
+
// workspacePaths lists available workspaces; its first element is not a
|
|
924
|
+
// native selected-cwd observation. The daemon's spawn cwd is a separate,
|
|
925
|
+
// launch-bound route, and the list only corroborates its membership.
|
|
926
|
+
const workspacePaths = Array.isArray(event.workspace_paths)
|
|
927
|
+
? event.workspace_paths.filter((value) => typeof value === "string" && path.isAbsolute(value)) : [];
|
|
928
|
+
const launchCwd = stringValue(event.launch_cwd);
|
|
929
|
+
const qualifiedLaunchCwd = launchCwd && path.isAbsolute(launchCwd) ? launchCwd : undefined;
|
|
930
|
+
const directory = qualifiedLaunchCwd ?? (workspacePaths.length === 1 ? workspacePaths[0] : undefined);
|
|
931
|
+
if (!directory && workspacePaths.length > 1)
|
|
932
|
+
throw new AppError("agy_workspace_route_unproven", "Antigravity did not identify the active route among multiple workspaces", 1, { workspace_paths: workspacePaths });
|
|
933
|
+
if (directory && qualifiedLaunchCwd && workspacePaths.length
|
|
934
|
+
&& !workspacePaths.some(value => resolveProjectRoot(value) === resolveProjectRoot(directory))) {
|
|
935
|
+
throw new AppError("agy_workspace_route_unproven", "Antigravity launch cwd is absent from the native workspace list", 1, { launch_cwd: directory, workspace_paths: workspacePaths });
|
|
936
|
+
}
|
|
659
937
|
const providerSessionId = stringValue(event.conversation_id);
|
|
660
938
|
const daemonId = stringValue(event.daemon_id);
|
|
661
939
|
const eventId = stringValue(event.event_id);
|
|
662
940
|
const toolName = stringValue(event.tool);
|
|
663
941
|
if (!directory || !providerSessionId || !daemonId || !eventId || !toolName)
|
|
664
942
|
throw new AppError("agy_session_identity_invalid", "Antigravity event is missing trusted physical identity", 1);
|
|
943
|
+
const rawInput = objectRecord(event.input);
|
|
944
|
+
const command = stringValue(rawInput.command) ?? stringValue(rawInput.cmd) ?? stringValue(rawInput.CommandLine);
|
|
945
|
+
if (command && (lifecycleFacts(command) || continuationCommand(command)) && !qualifiedLaunchCwd) {
|
|
946
|
+
throw new AppError("agy_workspace_route_unproven", "Managed Antigravity call has no launch-bound execution cwd", 1, { phase: "prepare", effect: "no_effect", recoverable: false, workspace_paths: workspacePaths });
|
|
947
|
+
}
|
|
948
|
+
const invalidStep = !Number.isSafeInteger(event.step_index) || Number(event.step_index) < 0;
|
|
949
|
+
const invalidExecution = event.execution_num !== undefined && (!Number.isSafeInteger(event.execution_num) || Number(event.execution_num) < 0);
|
|
950
|
+
if (event.phase === "before" && command && (lifecycleFacts(command) || continuationCommand(command)) && (invalidStep || invalidExecution)) {
|
|
951
|
+
throw new AppError("agy_native_call_identity_missing", "Participating Antigravity lifecycle calls require a native step identity and a valid execution identity when provided", 1, { phase: "prepare", effect: "no_effect", recoverable: false });
|
|
952
|
+
}
|
|
665
953
|
const translated = {
|
|
666
954
|
schema_id: "dd-flow/opencode-tool-event@1", source_harness: "antigravity-cli", phase: event.phase, event_id: eventId,
|
|
667
955
|
daemon_id: daemonId, tool_call_id: eventId, tool: toolName, input: event.input,
|
|
668
956
|
message_id: event.step_index === undefined ? null : String(event.step_index),
|
|
669
957
|
session: { provider_session_id: providerSessionId, parent_provider_session_id: event.parent_conversation_id, directory },
|
|
958
|
+
cwd_provenance: qualifiedLaunchCwd ? "launch_bound" : "workspace_paths_singleton",
|
|
670
959
|
profile: { provider: objectRecord(event.profile).provider, model: objectRecord(event.profile).model, variant: objectRecord(event.profile).reasoning, agent: objectRecord(event.profile).mode },
|
|
671
960
|
outcome: { status: stringValue(event.error) ? "error" : "completed" }
|
|
672
961
|
};
|
|
@@ -694,15 +983,25 @@ export function isolatedDdFlowHomeFromHookStdin(stdin) {
|
|
|
694
983
|
* hook contract intentionally narrow: unwrap only that whole-command form,
|
|
695
984
|
* then apply the same lifecycle parser to its actual shell payload.
|
|
696
985
|
*/
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
986
|
+
/**
|
|
987
|
+
* Adds the receipt to the command that the shell will execute. Heredoc input
|
|
988
|
+
* belongs to that command too, but an option appended after its delimiter is a
|
|
989
|
+
* second shell command rather than an argument, so insert it before `<<`.
|
|
990
|
+
*/
|
|
991
|
+
export function commandWithHookEvent(command, eventKey) {
|
|
702
992
|
const analysis = parseLifecycleCommand(command);
|
|
703
|
-
if (analysis.kind
|
|
993
|
+
if (analysis.kind === "none" || analysis.supported === false)
|
|
704
994
|
return command;
|
|
705
|
-
|
|
995
|
+
if (commandHasOption(analysis.invocation, "hook-event-id")) {
|
|
996
|
+
return command;
|
|
997
|
+
}
|
|
998
|
+
const option = `--hook-event-id '${eventKey.replaceAll("'", "'\\''")}'`;
|
|
999
|
+
if (analysis.invocation.rewriteSafe) {
|
|
1000
|
+
const index = analysis.invocation.sourceRange?.end ?? shellSuffixOffset(command);
|
|
1001
|
+
const suffix = command.slice(index);
|
|
1002
|
+
return `${command.slice(0, index)} ${option}${suffix ? /^\s/.test(suffix) ? suffix : ` ${suffix}` : ""}`;
|
|
1003
|
+
}
|
|
1004
|
+
return command;
|
|
706
1005
|
}
|
|
707
1006
|
/**
|
|
708
1007
|
* Recognise the small shell surface used by generated dd-flow lifecycle
|
|
@@ -719,29 +1018,46 @@ export function analyzeLifecycleShellCommand(command, includeSessionRegister = f
|
|
|
719
1018
|
}
|
|
720
1019
|
function lifecycleFacts(command) {
|
|
721
1020
|
const analysis = parseLifecycleCommand(command);
|
|
1021
|
+
if (analysis.kind === "none" && analysis.unresolved && ["lifecycle", "auxiliary"].includes(analysis.participation))
|
|
1022
|
+
throw new AppError("lifecycle_shell_syntax_invalid", "Known lifecycle execution is unsupported; use a literal issued command", 1, { phase: "prepare", effect: "no_effect", recoverable: true, disposition: "pre_cli_shell_refusal", reason: analysis.reason });
|
|
722
1023
|
if (analysis.kind === "none")
|
|
723
1024
|
return null;
|
|
724
1025
|
const invocation = analysis.invocation;
|
|
725
1026
|
const stageStart = invocation.operation === "stage_start";
|
|
1027
|
+
const stageFinish = invocation.operation === "stage_finish";
|
|
1028
|
+
const stagePause = invocation.operation === "stage_pause";
|
|
726
1029
|
const stageResume = invocation.operation === "stage_resume";
|
|
727
1030
|
const workStart = invocation.operation === "work_start";
|
|
1031
|
+
const workFinish = invocation.operation === "work_finish";
|
|
1032
|
+
const workFail = invocation.operation === "work_fail";
|
|
728
1033
|
return {
|
|
729
1034
|
analysis,
|
|
730
1035
|
invocation,
|
|
731
|
-
flowPayload: flowSessionPayloadFromRegisterCommand(invocation),
|
|
732
1036
|
stageStart,
|
|
1037
|
+
stageFinish,
|
|
1038
|
+
stagePause,
|
|
733
1039
|
stageResume,
|
|
734
|
-
workStart,
|
|
1040
|
+
workStart, workFinish, workFail,
|
|
735
1041
|
bootstrapStageStart: stageStart && commandHasOption(invocation, "bootstrap"),
|
|
736
1042
|
commandProjectRoot: commandOption(invocation, "project-root"),
|
|
737
|
-
stageName: stageStart || stageResume ? commandOption(invocation, "stage") : undefined,
|
|
738
|
-
runId: stageStart || stageResume ? commandPosition(invocation, 0) : undefined,
|
|
739
|
-
workId: stageResume ? commandOption(invocation, "work") : workStart ? commandPosition(invocation, 0) : undefined,
|
|
1043
|
+
stageName: stageStart || stageFinish || stagePause || stageResume ? commandOption(invocation, "stage") : undefined,
|
|
1044
|
+
runId: stageStart || stageFinish || stagePause || stageResume ? commandPosition(invocation, 0) : undefined,
|
|
1045
|
+
workId: stagePause || stageResume ? commandOption(invocation, "work") : workStart || workFinish || workFail ? commandPosition(invocation, 0) : undefined,
|
|
740
1046
|
contextSha256: commandOption(invocation, "context-sha256")
|
|
741
1047
|
};
|
|
742
1048
|
}
|
|
743
|
-
function lifecycleMatchKey(facts, projectRoot) {
|
|
744
|
-
|
|
1049
|
+
function lifecycleMatchKey(facts, projectRoot, scope) {
|
|
1050
|
+
// Observe the actual argument without validating it. A mistyped project
|
|
1051
|
+
// must not leave a receipt matching a later, corrected non-rewriting call.
|
|
1052
|
+
if (!scope && facts.commandProjectRoot && canonicalPath(facts.commandProjectRoot, false) !== canonicalPath(projectRoot, false))
|
|
1053
|
+
return null;
|
|
1054
|
+
const { invocation, bootstrapStageStart, stageStart, stageFinish, stagePause, stageResume, workStart, workFinish, workFail, stageName, runId, workId, contextSha256 } = facts;
|
|
1055
|
+
const effectiveRoot = scope?.projectRoot ?? projectRoot;
|
|
1056
|
+
const effectiveRunId = scope?.runId ?? runId;
|
|
1057
|
+
if (invocation.operation === "recovery_accept") {
|
|
1058
|
+
const run = commandPosition(invocation, 0), recovery = commandOption(invocation, "recovery-id");
|
|
1059
|
+
return (scope?.runId ?? run) && recovery ? recoveryAcceptMatchKey((scope?.runId ?? run), recovery, effectiveRoot) : null;
|
|
1060
|
+
}
|
|
745
1061
|
if (bootstrapStageStart)
|
|
746
1062
|
return bootstrapMatchKey({
|
|
747
1063
|
projectRoot,
|
|
@@ -749,14 +1065,100 @@ function lifecycleMatchKey(facts, projectRoot) {
|
|
|
749
1065
|
intakeMode: contextSha256 ? "context" : commandHasOption(invocation, "intake-stdin") ? "stdin" : "file",
|
|
750
1066
|
...(contextSha256 ? { contextSha256 } : {})
|
|
751
1067
|
});
|
|
752
|
-
if (stageStart &&
|
|
753
|
-
return stageStartMatchKey(
|
|
754
|
-
if (
|
|
755
|
-
return
|
|
1068
|
+
if (stageStart && effectiveRunId && stageName)
|
|
1069
|
+
return stageStartMatchKey(effectiveRunId, stageName, effectiveRoot, contextSha256);
|
|
1070
|
+
if (stageFinish && effectiveRunId && stageName)
|
|
1071
|
+
return stageLifecycleMatchKey("stage_finish", effectiveRunId, stageName, effectiveRoot);
|
|
1072
|
+
if (stagePause && effectiveRunId && stageName && workId)
|
|
1073
|
+
return stageLifecycleMatchKey("stage_pause", effectiveRunId, stageName, effectiveRoot, workId);
|
|
1074
|
+
if (stageResume && effectiveRunId && stageName && workId)
|
|
1075
|
+
return stageResumeMatchKey(effectiveRunId, stageName, workId, effectiveRoot);
|
|
756
1076
|
if (workStart && workId)
|
|
757
|
-
return workStartMatchKey(workId,
|
|
1077
|
+
return workStartMatchKey(workId, effectiveRoot, commandOption(invocation, "recovery-id"));
|
|
1078
|
+
if (workFinish && workId)
|
|
1079
|
+
return workLifecycleMatchKey("work_finish", workId, effectiveRoot);
|
|
1080
|
+
if (workFail && workId)
|
|
1081
|
+
return workLifecycleMatchKey("work_fail", workId, effectiveRoot);
|
|
758
1082
|
return null;
|
|
759
1083
|
}
|
|
1084
|
+
/** Observe exact immutable command attribution before reading model-supplied
|
|
1085
|
+
* result files. This does not claim or authorize the lifecycle mutation. */
|
|
1086
|
+
export function observeCommandHook(context, command) {
|
|
1087
|
+
const facts = lifecycleFacts(command);
|
|
1088
|
+
if (!facts || facts.analysis.kind !== "standalone" || !facts.commandProjectRoot)
|
|
1089
|
+
return;
|
|
1090
|
+
const project = context.db.get("SELECT id FROM projects WHERE root = ?", [resolveProjectRoot(facts.commandProjectRoot)]);
|
|
1091
|
+
if (!project)
|
|
1092
|
+
return; // Bootstrap has not registered a project yet.
|
|
1093
|
+
const matchKey = lifecycleMatchKey(facts, facts.commandProjectRoot);
|
|
1094
|
+
if (!matchKey)
|
|
1095
|
+
return;
|
|
1096
|
+
let key = commandOption(facts.invocation, "hook-event-id");
|
|
1097
|
+
if (!key && commandOption(facts.invocation, "invocation-id"))
|
|
1098
|
+
return;
|
|
1099
|
+
if (!key) {
|
|
1100
|
+
try {
|
|
1101
|
+
key = findRecentMatchingHookEvent(context, { projectId: project.id, matchKey, errorCode: "trusted_session_binding_required", operation: facts.invocation.operation }).eventKey;
|
|
1102
|
+
}
|
|
1103
|
+
catch {
|
|
1104
|
+
return;
|
|
1105
|
+
} // Dispatch still owns its mandatory admission error.
|
|
1106
|
+
}
|
|
1107
|
+
const event = context.db.get("SELECT id FROM hook_events WHERE project_id = ? AND event_key = ? AND match_key = ? AND status = 'observed'", [project.id, key, matchKey]);
|
|
1108
|
+
if (event)
|
|
1109
|
+
context.observeLifecycleHook?.(project.id, event.id);
|
|
1110
|
+
}
|
|
1111
|
+
export function stageLifecycleMatchKey(operation, runId, stage, projectRoot, workId) {
|
|
1112
|
+
return crypto.createHash("sha256").update(JSON.stringify({ operation, run_id: runId, stage, project_root: resolveProjectRoot(projectRoot), ...(workId ? { work_id: workId } : {}) })).digest("hex");
|
|
1113
|
+
}
|
|
1114
|
+
export function recoveryAcceptMatchKey(runId, recoveryId, projectRoot) {
|
|
1115
|
+
return crypto.createHash("sha256").update(JSON.stringify({ operation: "recovery_accept", run_id: runId, recovery_id: recoveryId, project_root: resolveProjectRoot(projectRoot) })).digest("hex");
|
|
1116
|
+
}
|
|
1117
|
+
export function workLifecycleMatchKey(operation, workId, projectRoot) {
|
|
1118
|
+
return crypto.createHash("sha256").update(JSON.stringify({ operation, work_id: workId, project_root: resolveProjectRoot(projectRoot) })).digest("hex");
|
|
1119
|
+
}
|
|
1120
|
+
function workLifecycleMatchKeys(operation, workId, projectRoot) {
|
|
1121
|
+
return entityReferenceVariants(workId).map((reference) => workLifecycleMatchKey(operation, reference, projectRoot));
|
|
1122
|
+
}
|
|
1123
|
+
function stageLifecycleMatchKeys(operation, runId, stage, projectRoot, workId) {
|
|
1124
|
+
const runReferences = entityReferenceVariants(runId);
|
|
1125
|
+
const workReferences = workId ? entityReferenceVariants(workId) : [undefined];
|
|
1126
|
+
return [...new Set(runReferences.flatMap((runReference) => workReferences.map((workReference) => stageLifecycleMatchKey(operation, runReference, stage, projectRoot, workReference))))];
|
|
1127
|
+
}
|
|
1128
|
+
/** Claims a Work terminal command only after its exact hook receipt has proved
|
|
1129
|
+
* the physical Session that issued it. Work code performs the owner check. */
|
|
1130
|
+
export function claimWorkLifecycleHookEvent(context, input) {
|
|
1131
|
+
const matchKeys = workLifecycleMatchKeys(input.operation, input.workId, input.projectRoot);
|
|
1132
|
+
const eventKey = input.eventKey ?? findRecentMatchingHookEvent(context, {
|
|
1133
|
+
projectId: input.projectId, matchKey: matchKeys, errorCode: "trusted_session_binding_required", operation: input.operation.replace("_", " ")
|
|
1134
|
+
}).eventKey;
|
|
1135
|
+
const event = context.db.get("SELECT id, session_id, match_key, status FROM hook_events WHERE project_id = ? AND event_key = ?", [input.projectId, eventKey]);
|
|
1136
|
+
if (!event?.session_id || event.status !== "observed" || !event.match_key || !matchKeys.includes(event.match_key)) {
|
|
1137
|
+
const reason = !event ? "event_missing" : !event.session_id ? "identity_missing" : event.status !== "observed" ? "event_consumed" : "target_mismatch";
|
|
1138
|
+
throw new AppError("trusted_session_binding_required", `${input.operation.replace("_", " ")} requires one fresh matching PreToolUse hook event`, 1, { work_id: input.workId, event_key: eventKey, reason, observed_status: event?.status ?? null });
|
|
1139
|
+
}
|
|
1140
|
+
const claimed = context.db.run("UPDATE hook_events SET status = 'claimed', claimed_at = ? WHERE id = ? AND status = 'observed'", [context.now(), event.id]);
|
|
1141
|
+
if (claimed.changes !== 1)
|
|
1142
|
+
throw new AppError("trusted_session_binding_required", "matching Work lifecycle hook event was already claimed", 1, { work_id: input.workId });
|
|
1143
|
+
return hookSessionIdentity(context, input.projectId, eventKey);
|
|
1144
|
+
}
|
|
1145
|
+
/** Claims a lifecycle command only after its exact hook receipt has proved the
|
|
1146
|
+
* physical Session that issued it. Stage code performs the Work-owner check. */
|
|
1147
|
+
export function claimStageLifecycleHookEvent(context, input) {
|
|
1148
|
+
const matchKeys = stageLifecycleMatchKeys(input.operation, input.runId, input.stage, input.projectRoot, input.workId);
|
|
1149
|
+
const eventKey = input.eventKey ?? findRecentMatchingHookEvent(context, {
|
|
1150
|
+
projectId: input.projectId, matchKey: matchKeys, errorCode: "trusted_session_binding_required", operation: input.operation.replace("_", " ")
|
|
1151
|
+
}).eventKey;
|
|
1152
|
+
const event = context.db.get("SELECT id, session_id, match_key, status FROM hook_events WHERE project_id = ? AND event_key = ?", [input.projectId, eventKey]);
|
|
1153
|
+
if (!event?.session_id || event.status !== "observed" || !event.match_key || !matchKeys.includes(event.match_key)) {
|
|
1154
|
+
const reason = !event ? "event_missing" : !event.session_id ? "identity_missing" : event.status !== "observed" ? "event_consumed" : "target_mismatch";
|
|
1155
|
+
throw new AppError("trusted_session_binding_required", `${input.operation.replace("_", " ")} requires one fresh matching PreToolUse hook event`, 1, { run_id: input.runId, stage: input.stage, event_key: eventKey, reason, observed_status: event?.status ?? null });
|
|
1156
|
+
}
|
|
1157
|
+
const claimed = context.db.run("UPDATE hook_events SET status = 'claimed', claimed_at = ? WHERE id = ? AND status = 'observed'", [context.now(), event.id]);
|
|
1158
|
+
if (claimed.changes !== 1)
|
|
1159
|
+
throw new AppError("trusted_session_binding_required", "matching lifecycle hook event was already claimed", 1, { run_id: input.runId, stage: input.stage });
|
|
1160
|
+
return hookSessionIdentity(context, input.projectId, eventKey);
|
|
1161
|
+
}
|
|
760
1162
|
/** Trusted session identity is created by PreToolUse, never supplied by an agent. */
|
|
761
1163
|
export function sessionIdForHookEvent(context, projectId, eventKey) {
|
|
762
1164
|
const event = context.db.get("SELECT session_id FROM hook_events WHERE project_id = ? AND event_key = ?", [projectId, eventKey]);
|
|
@@ -772,6 +1174,7 @@ export function hookSessionIdentity(context, projectId, eventKey) {
|
|
|
772
1174
|
WHERE he.project_id = ? AND he.event_key = ?`, [projectId, eventKey]);
|
|
773
1175
|
if (!event?.session_id)
|
|
774
1176
|
throw new AppError("hook_event_not_found", "stage start requires a trusted PreToolUse hook event", 1, { event_key: eventKey });
|
|
1177
|
+
context.observeLifecycleHook?.(projectId, event.id);
|
|
775
1178
|
return {
|
|
776
1179
|
hookEventId: event.id,
|
|
777
1180
|
harness: event.harness,
|
|
@@ -808,21 +1211,30 @@ export function claimRecentMatchingHookEvent(context, input) {
|
|
|
808
1211
|
/** Finds the trusted event that a stage- or Work-specific claimant will atomically claim. */
|
|
809
1212
|
export function findRecentMatchingHookEvent(context, input) {
|
|
810
1213
|
const freshAfter = new Date(Date.parse(context.now()) - 60_000).toISOString();
|
|
811
|
-
const
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
1214
|
+
const matchKeys = Array.isArray(input.matchKey) ? [...new Set(input.matchKey)] : [input.matchKey];
|
|
1215
|
+
const placeholders = matchKeys.map(() => "?").join(", ");
|
|
1216
|
+
const find = () => context.db.all(`SELECT id, event_key FROM hook_events
|
|
1217
|
+
WHERE project_id = ? AND match_key IN (${placeholders}) AND status = 'observed' AND created_at >= ?
|
|
1218
|
+
AND NOT (COALESCE(json_extract(outcome_json, '$.effect'), '') = 'no_effect'
|
|
1219
|
+
AND COALESCE(json_extract(outcome_json, '$.disposition'), '') IN ('correctable', 'fatal'))
|
|
1220
|
+
AND harness IN ('codex-desktop', 'antigravity-cli')
|
|
1221
|
+
AND (? IS NULL OR session_id = ?)
|
|
1222
|
+
ORDER BY id DESC LIMIT 2`, [input.projectId, ...matchKeys, freshAfter, input.sessionId ?? null, input.sessionId ?? null]);
|
|
1223
|
+
let events = find();
|
|
1224
|
+
// Only the qualified non-rewriting transports may correlate the original
|
|
1225
|
+
// command: Codex Desktop and Antigravity. New harnesses fail closed by default.
|
|
817
1226
|
const deadline = Date.now() + 250;
|
|
818
|
-
while (
|
|
1227
|
+
while (events.length === 0 && Date.now() < deadline) {
|
|
819
1228
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
|
|
820
|
-
|
|
1229
|
+
events = find();
|
|
821
1230
|
}
|
|
822
|
-
if (!
|
|
823
|
-
throw new AppError(input.errorCode, `${input.operation} requires
|
|
1231
|
+
if (events.length === 0 || !events[0]?.event_key) {
|
|
1232
|
+
throw new AppError(input.errorCode, `${input.operation} requires a trusted lifecycle receipt. Check native hook delivery; managed commands are admitted from committed native identity, not from model-supplied invocation IDs or updatedInput.`, 1, { reason: "event_missing" });
|
|
824
1233
|
}
|
|
825
|
-
|
|
1234
|
+
if (events.length > 1) {
|
|
1235
|
+
throw new AppError("ambiguous_lifecycle_receipt", `${input.operation} has more than one fresh matching lifecycle event; stop and let the controller reconcile native delivery`, 1, { reason: "multiple_live_events", match_keys: matchKeys, event_keys: events.map((event) => event.event_key) });
|
|
1236
|
+
}
|
|
1237
|
+
return { id: events[0].id, eventKey: events[0].event_key };
|
|
826
1238
|
}
|
|
827
1239
|
/** Fallback for Desktop paths that execute the original command after a hook rewrite. */
|
|
828
1240
|
export function claimBootstrapHookEvent(context, input) {
|
|
@@ -845,9 +1257,9 @@ export function bootstrapMatchKey(input) {
|
|
|
845
1257
|
})).digest("hex");
|
|
846
1258
|
}
|
|
847
1259
|
export function claimWorkStartHookEvent(context, input) {
|
|
848
|
-
const expected =
|
|
1260
|
+
const expected = entityReferenceVariants(input.workId).map((reference) => workStartMatchKey(reference, input.projectRoot, input.recoveryId));
|
|
849
1261
|
const event = context.db.get("SELECT id, session_id, agent_id, turn_id, transcript_path, model, agent_type, match_key, status FROM hook_events WHERE project_id = ? AND event_key = ?", [input.projectId, input.eventKey]);
|
|
850
|
-
if (!event?.session_id || event.status !== "observed" || !event.match_key || !expected.
|
|
1262
|
+
if (!event?.session_id || event.status !== "observed" || !event.match_key || !expected.includes(event.match_key)) {
|
|
851
1263
|
throw new AppError("trusted_work_launch_required", "work start requires one fresh matching PreToolUse event", 1, { work_id: input.workId, event_key: input.eventKey });
|
|
852
1264
|
}
|
|
853
1265
|
const claimed = context.db.run("UPDATE hook_events SET status = 'claimed', claimed_at = ? WHERE id = ? AND status = 'observed'", [context.now(), event.id]);
|
|
@@ -855,15 +1267,16 @@ export function claimWorkStartHookEvent(context, input) {
|
|
|
855
1267
|
throw new AppError("trusted_work_launch_required", "matching work-start hook event was already claimed", 1, { work_id: input.workId });
|
|
856
1268
|
return hookSessionIdentity(context, input.projectId, input.eventKey);
|
|
857
1269
|
}
|
|
858
|
-
function shortWorkReference(id) { return /^WRK-\d{3,}(?:-|$)/.exec(id)?.[0]?.replace(/-$/, "") ?? id; }
|
|
859
1270
|
/** Claims the exact non-bootstrap stage entry which starts a coordinator Work. */
|
|
860
1271
|
export function assertStageStartHookEvent(context, input) {
|
|
861
|
-
const expected =
|
|
1272
|
+
const expected = entityReferenceVariants(input.runId).map((reference) => stageStartMatchKey(reference, input.stage, input.projectRoot, input.contextSha256));
|
|
862
1273
|
const event = context.db.get("SELECT session_id, match_key, status FROM hook_events WHERE project_id = ? AND event_key = ?", [input.projectId, input.eventKey]);
|
|
863
|
-
if (!event?.session_id || event.status !== "observed" || event.match_key
|
|
864
|
-
throw new AppError("trusted_stage_launch_required", "stage start requires one fresh matching PreToolUse event", 1, { run_id: input.runId, stage: input.stage, event_key: input.eventKey,
|
|
1274
|
+
if (!event?.session_id || event.status !== "observed" || !event.match_key || !expected.includes(event.match_key)) {
|
|
1275
|
+
throw new AppError("trusted_stage_launch_required", "stage start requires one fresh matching PreToolUse event", 1, { run_id: input.runId, stage: input.stage, event_key: input.eventKey, expected_match_keys: expected, observed_match_key: event?.match_key ?? null, observed_status: event?.status ?? null });
|
|
865
1276
|
}
|
|
866
|
-
|
|
1277
|
+
const identity = hookSessionIdentity(context, input.projectId, input.eventKey);
|
|
1278
|
+
assertRecoveryHookCurrent(context, input.projectId, input.runId, identity);
|
|
1279
|
+
return identity;
|
|
867
1280
|
}
|
|
868
1281
|
export function claimStageStartHookEvent(context, input) {
|
|
869
1282
|
assertStageStartHookEvent(context, input);
|
|
@@ -893,24 +1306,25 @@ export function stageResumeMatchKey(runId, stage, workId, projectRoot) {
|
|
|
893
1306
|
}
|
|
894
1307
|
/** Claims the resume command observed in the Session that received the user answer. */
|
|
895
1308
|
export function claimStageResumeHookEvent(context, input) {
|
|
896
|
-
const
|
|
897
|
-
const
|
|
898
|
-
const event = input.eventKey
|
|
899
|
-
|
|
900
|
-
: context.db.get("SELECT id, event_key, session_id, match_key, status FROM hook_events WHERE project_id = ? AND session_id = ? AND match_key = ? AND status = 'observed' AND created_at >= ? ORDER BY id DESC LIMIT 1", [input.projectId, input.sessionId ?? "", matchKey, freshAfter]);
|
|
901
|
-
if (!event?.event_key || !event.session_id || event.match_key !== matchKey || event.status !== "observed") {
|
|
1309
|
+
const matchKeys = entityReferenceVariants(input.runId).flatMap((runReference) => entityReferenceVariants(input.workId).map((workReference) => stageResumeMatchKey(runReference, input.stage, workReference, input.projectRoot)));
|
|
1310
|
+
const eventKey = input.eventKey ?? findRecentMatchingHookEvent(context, { projectId: input.projectId, matchKey: matchKeys, sessionId: input.sessionId ?? "", errorCode: "trusted_stage_resume_required", operation: "stage resume" }).eventKey;
|
|
1311
|
+
const event = context.db.get("SELECT id, event_key, session_id, match_key, status FROM hook_events WHERE project_id = ? AND event_key = ?", [input.projectId, eventKey]);
|
|
1312
|
+
if (!event?.event_key || !event.session_id || !event.match_key || !matchKeys.includes(event.match_key) || event.status !== "observed") {
|
|
902
1313
|
throw new AppError("trusted_stage_resume_required", "stage resume requires one fresh matching PreToolUse event", 1, { run_id: input.runId, stage: input.stage, work_id: input.workId });
|
|
903
1314
|
}
|
|
1315
|
+
const identity = hookSessionIdentity(context, input.projectId, event.event_key);
|
|
1316
|
+
assertRecoveryHookCurrent(context, input.projectId, input.runId, identity);
|
|
904
1317
|
const claimed = context.db.run("UPDATE hook_events SET status = 'claimed', claimed_at = ? WHERE id = ? AND status = 'observed'", [context.now(), event.id]);
|
|
905
1318
|
if (claimed.changes !== 1)
|
|
906
1319
|
throw new AppError("trusted_stage_resume_required", "matching stage-resume hook event was already claimed", 1, { run_id: input.runId, stage: input.stage });
|
|
907
|
-
return
|
|
1320
|
+
return identity;
|
|
908
1321
|
}
|
|
909
|
-
export function workStartMatchKey(workId, projectRoot) {
|
|
1322
|
+
export function workStartMatchKey(workId, projectRoot, recoveryId) {
|
|
910
1323
|
return crypto.createHash("sha256").update(JSON.stringify({
|
|
911
1324
|
operation: "work_start",
|
|
912
1325
|
work_id: workId,
|
|
913
|
-
project_root: resolveProjectRoot(projectRoot)
|
|
1326
|
+
project_root: resolveProjectRoot(projectRoot),
|
|
1327
|
+
...(recoveryId ? { recovery_id: recoveryId } : {})
|
|
914
1328
|
})).digest("hex");
|
|
915
1329
|
}
|
|
916
1330
|
export function hookStatusForProject(context, projectId) {
|
|
@@ -950,6 +1364,8 @@ export function codexHookEventsForProject(context, projectId) {
|
|
|
950
1364
|
FROM hook_events WHERE project_id = ? ORDER BY created_at DESC, id DESC LIMIT 20`, [projectId]);
|
|
951
1365
|
}
|
|
952
1366
|
function resolveProfileName(profile) {
|
|
1367
|
+
if (profile !== undefined && (typeof profile !== "string" || !profile.trim()))
|
|
1368
|
+
throw new AppError("validation", "--profile must be nonempty text", 2);
|
|
953
1369
|
return sanitizeProfile(profile ?? defaultProfileName);
|
|
954
1370
|
}
|
|
955
1371
|
function sanitizeProfile(value) {
|
|
@@ -977,11 +1393,12 @@ function readTomlIfExists(file) {
|
|
|
977
1393
|
if (!fs.existsSync(file)) {
|
|
978
1394
|
return {};
|
|
979
1395
|
}
|
|
1396
|
+
const { text } = prepareTextFile(file, "Codex config");
|
|
980
1397
|
try {
|
|
981
|
-
return parse(
|
|
1398
|
+
return parse(text);
|
|
982
1399
|
}
|
|
983
1400
|
catch (error) {
|
|
984
|
-
throw new AppError("validation", `Invalid TOML in ${file}
|
|
1401
|
+
throw new AppError("validation", `Invalid TOML in ${file}`, 2, { file, ...(error instanceof TomlError ? { line: error.line, column: error.column } : {}) });
|
|
985
1402
|
}
|
|
986
1403
|
}
|
|
987
1404
|
function withManagedConfig(config, sourceHome, targetHome) {
|
|
@@ -1000,7 +1417,7 @@ function objectTable(value) {
|
|
|
1000
1417
|
function createSharedLinks(sourceHome, targetHome) {
|
|
1001
1418
|
const linked = [];
|
|
1002
1419
|
const skipped = [];
|
|
1003
|
-
for (const entry of
|
|
1420
|
+
for (const entry of codexHomeSharedEntries) {
|
|
1004
1421
|
const source = path.join(sourceHome, entry);
|
|
1005
1422
|
const target = path.join(targetHome, entry);
|
|
1006
1423
|
if (!fs.existsSync(source)) {
|
|
@@ -1023,7 +1440,7 @@ function createSharedLinks(sourceHome, targetHome) {
|
|
|
1023
1440
|
return { linked, skipped };
|
|
1024
1441
|
}
|
|
1025
1442
|
function removeSharedSymlinks(targetHome) {
|
|
1026
|
-
for (const entry of
|
|
1443
|
+
for (const entry of codexHomeSharedEntries) {
|
|
1027
1444
|
const target = path.join(targetHome, entry);
|
|
1028
1445
|
if (fs.existsSync(target) && fs.lstatSync(target).isSymbolicLink()) {
|
|
1029
1446
|
fs.rmSync(target);
|
|
@@ -1036,7 +1453,7 @@ function removeDirIfEmpty(dir) {
|
|
|
1036
1453
|
}
|
|
1037
1454
|
}
|
|
1038
1455
|
function sharedEntryStatus(sourceHome, targetHome) {
|
|
1039
|
-
return
|
|
1456
|
+
return codexHomeSharedEntries.map((entry) => {
|
|
1040
1457
|
const source = path.join(sourceHome, entry);
|
|
1041
1458
|
const target = path.join(targetHome, entry);
|
|
1042
1459
|
return {
|
|
@@ -1057,11 +1474,15 @@ function hookEntry(matcher, command, statusMessage) {
|
|
|
1057
1474
|
return { matcher, hooks: [commandHook(command, statusMessage)] };
|
|
1058
1475
|
}
|
|
1059
1476
|
function commandHook(command, statusMessage) {
|
|
1060
|
-
|
|
1477
|
+
// Hook admission is synchronous (the CLI must see a committed receipt), but
|
|
1478
|
+
// the old 5s budget was shorter than a cold CLI/store open under fan-out.
|
|
1479
|
+
// Startup owns migrations; this budget only covers the bounded hot path.
|
|
1480
|
+
return { type: "command", command, timeout: 30, statusMessage };
|
|
1061
1481
|
}
|
|
1062
1482
|
function hookCommand(event) {
|
|
1063
|
-
const
|
|
1064
|
-
|
|
1483
|
+
const args = `codex hook handle --event ${event} --json`;
|
|
1484
|
+
const handler = `if [ -n "\${DD_FLOW_BIN:-}" ]; then "$DD_FLOW_BIN" ${args}; else dd-flow ${args}; fi`;
|
|
1485
|
+
return `/bin/bash -c 'export PATH="\${DD_FLOW_HOME:+\${DD_FLOW_HOME}/bin:}\${PATH}:\${HOME}/Library/pnpm:/opt/homebrew/bin:/usr/local/bin"; log_dir="\${DD_FLOW_HOME:-\${HOME}/.dd-flow}/logs"; mkdir -p "$log_dir"; log="$log_dir/codex-hook.log"; printf "%s event=${event} phase=start pid=%s\\n" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$$" >>"$log"; ${handler} 2> >(tee -a "$log" >&2); status=$?; printf "%s event=${event} phase=finish pid=%s exit=%s\\n" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$$" "$status" >>"$log"; exit "$status"'`;
|
|
1065
1486
|
}
|
|
1066
1487
|
function resolveHookTarget(target) {
|
|
1067
1488
|
if (!target || target === "isolated") {
|
|
@@ -1236,11 +1657,10 @@ function recordHookInstallation(context, projectId, scope, configPath, installed
|
|
|
1236
1657
|
function installationScope(target, profile, hooksPath) {
|
|
1237
1658
|
return target === "isolated" ? `isolated:${profile}` : `default:${path.dirname(hooksPath)}`;
|
|
1238
1659
|
}
|
|
1239
|
-
function upsertSessionBindingFromPayload(context, project, sessionId, payload) {
|
|
1660
|
+
function upsertSessionBindingFromPayload(context, project, sessionId, payload, transcriptPath) {
|
|
1240
1661
|
const existing = sessionBinding(context, project.id, sessionId);
|
|
1241
1662
|
const now = context.now();
|
|
1242
1663
|
const cwd = stringValue(payload.cwd) ?? existing?.cwd ?? null;
|
|
1243
|
-
const transcriptPath = stringValue(payload.transcript_path) ?? existing?.transcript_path ?? locateCodexTranscript(sessionId, context.env.CODEX_HOME);
|
|
1244
1664
|
context.db.run(`INSERT INTO codex_session_bindings
|
|
1245
1665
|
(session_id, project_id, protocol_id, handshake_id, cwd, transcript_path, status, created_at, updated_at)
|
|
1246
1666
|
VALUES (?, ?, NULL, NULL, ?, ?, 'active', ?, ?)
|
|
@@ -1294,12 +1714,11 @@ function sessionBinding(context, projectId, sessionId) {
|
|
|
1294
1714
|
return context.db.get("SELECT * FROM codex_session_bindings WHERE project_id = ? AND session_id = ?", [projectId, sessionId]);
|
|
1295
1715
|
}
|
|
1296
1716
|
function recordHookEvent(context, input) {
|
|
1297
|
-
|
|
1298
|
-
if (existing)
|
|
1717
|
+
if (assertHookEventReplay(context, input))
|
|
1299
1718
|
return false;
|
|
1300
1719
|
context.db.run(`INSERT INTO hook_events
|
|
1301
|
-
|
|
1302
|
-
|
|
1720
|
+
(project_id, protocol_id, harness, provider_session_id, parent_session_id, daemon_id, session_id, agent_id, turn_id, transcript_path, provider, model, reasoning, mode, agent_type, cwd, event_key, match_key, event_name, tool_name, status, sanitized_summary, created_at)
|
|
1721
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
1303
1722
|
input.projectId,
|
|
1304
1723
|
input.protocolId,
|
|
1305
1724
|
input.harness,
|
|
@@ -1326,6 +1745,23 @@ function recordHookEvent(context, input) {
|
|
|
1326
1745
|
]);
|
|
1327
1746
|
return true;
|
|
1328
1747
|
}
|
|
1748
|
+
/** A duplicate delivery is harmless only when all durable identity facts match. */
|
|
1749
|
+
function assertHookEventReplay(context, input) {
|
|
1750
|
+
const existing = context.db.get(`SELECT harness, provider_session_id, parent_session_id, daemon_id, session_id, turn_id, event_name, tool_name, match_key, cwd
|
|
1751
|
+
FROM hook_events WHERE project_id = ? AND event_key = ?`, [input.projectId, input.eventKey]);
|
|
1752
|
+
if (existing) {
|
|
1753
|
+
const observed = {
|
|
1754
|
+
harness: input.harness, provider_session_id: input.providerSessionId, parent_session_id: input.parentSessionId,
|
|
1755
|
+
daemon_id: input.daemonId ?? null, session_id: input.sessionId, turn_id: input.turnId,
|
|
1756
|
+
event_name: input.eventName, tool_name: input.toolName, match_key: input.matchKey, cwd: input.cwd
|
|
1757
|
+
};
|
|
1758
|
+
if (Object.entries(observed).some(([key, value]) => existing[key] !== value)) {
|
|
1759
|
+
throw new AppError("hook_event_replay_mismatch", "Lifecycle event ID was already observed with different immutable identity", 1, { event_key: input.eventKey });
|
|
1760
|
+
}
|
|
1761
|
+
return true;
|
|
1762
|
+
}
|
|
1763
|
+
return false;
|
|
1764
|
+
}
|
|
1329
1765
|
function projectForHook(context, explicitRoot, cwd) {
|
|
1330
1766
|
if (explicitRoot)
|
|
1331
1767
|
return requireProjectByRoot(context, resolveProjectRoot(explicitRoot));
|
|
@@ -1352,14 +1788,6 @@ function hookEventKey(payload, eventName, toolName, command) {
|
|
|
1352
1788
|
command
|
|
1353
1789
|
})).digest("hex");
|
|
1354
1790
|
}
|
|
1355
|
-
function commandFromPayload(payload) {
|
|
1356
|
-
const direct = stringValue(payload.command);
|
|
1357
|
-
if (direct) {
|
|
1358
|
-
return direct;
|
|
1359
|
-
}
|
|
1360
|
-
const toolInput = objectRecord(payload.tool_input);
|
|
1361
|
-
return stringValue(toolInput.command) ?? stringValue(toolInput.cmd);
|
|
1362
|
-
}
|
|
1363
1791
|
function toolNameFromPayload(payload) {
|
|
1364
1792
|
const toolInput = objectRecord(payload.tool_input);
|
|
1365
1793
|
return stringValue(toolInput.name);
|
|
@@ -1402,10 +1830,10 @@ function writeJsonFile(file, value) {
|
|
|
1402
1830
|
ensureDir(path.dirname(file));
|
|
1403
1831
|
fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);
|
|
1404
1832
|
}
|
|
1405
|
-
function backupFile(file, now) {
|
|
1833
|
+
function backupFile(file, now, text) {
|
|
1406
1834
|
const suffix = now.replace(/[:.]/g, "-");
|
|
1407
1835
|
const backup = `${file}.${suffix}.bak`;
|
|
1408
|
-
fs.
|
|
1836
|
+
fs.writeFileSync(backup, text, { mode: 0o600 });
|
|
1409
1837
|
return backup;
|
|
1410
1838
|
}
|
|
1411
1839
|
function hashObject(value) {
|