@zhivex-ai/harness 0.11.0 → 1.0.0-rc.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/README.md +9 -8
  3. package/ROADMAP.md +31 -8
  4. package/SECURITY.md +4 -2
  5. package/SUPPORT.md +4 -2
  6. package/contracts/public-api.json +1359 -0
  7. package/contracts/security-controls.json +15 -0
  8. package/contracts/stable-api-signatures.json +490 -0
  9. package/dist/cli-options.d.ts +40 -0
  10. package/dist/cli-stream.d.ts +15 -15
  11. package/dist/cli.d.ts +20 -6
  12. package/dist/cli.js +2103 -496
  13. package/dist/config.d.ts +14 -0
  14. package/dist/errors.d.ts +68 -0
  15. package/dist/file-security.d.ts +29 -0
  16. package/dist/hostile-repository-demo.js +793 -329
  17. package/dist/index.d.ts +12 -4
  18. package/dist/index.js +7392 -5216
  19. package/dist/json-contracts.d.ts +1707 -0
  20. package/dist/operations.d.ts +1 -1
  21. package/dist/providers.d.ts +5 -0
  22. package/dist/state-backup.d.ts +148 -0
  23. package/dist/time-to-safe-fix.d.ts +43 -2
  24. package/dist/verify-historical-migrations.js +7667 -0
  25. package/dist/zhx.js +2103 -496
  26. package/docs/CLI.md +21 -4
  27. package/docs/DEPRECATIONS.md +9 -0
  28. package/docs/DURABLE_OPERATIONS.md +18 -1
  29. package/docs/EXTENSIBILITY.md +3 -3
  30. package/docs/GA_READINESS.md +23 -0
  31. package/docs/GEMINI_1_0_DECISION.md +9 -0
  32. package/docs/LIVE_CERTIFICATION.md +22 -2
  33. package/docs/PUBLIC_SECURITY.md +39 -0
  34. package/docs/RELEASE.md +17 -10
  35. package/docs/ROLLBACK.md +9 -0
  36. package/docs/SECURITY_REVIEW_EVIDENCE.md +15 -0
  37. package/docs/STABILITY.md +13 -0
  38. package/docs/SUPPORT_MATRIX.md +17 -0
  39. package/docs/THREAT_MODEL.md +28 -0
  40. package/docs/TIME_TO_SAFE_FIX.md +2 -2
  41. package/docs/ga-readiness.json +235 -0
  42. package/docs/support-matrix.json +29 -0
  43. package/evaluations/representative-assembly-matrix.json +138 -0
  44. package/evaluations/representative-matrix.json +179 -0
  45. package/evaluations/representative-repositories.jsonl +7 -0
  46. package/examples/mcp-config.json +1 -1
  47. package/fixtures/contracts/v1/doctor.json +45 -0
  48. package/fixtures/contracts/v1/error.json +9 -0
  49. package/fixtures/contracts/v1/observational-documents.json +34 -0
  50. package/fixtures/contracts/v1/providers.json +17 -0
  51. package/fixtures/contracts/v1/run-result-forward.json +37 -0
  52. package/fixtures/contracts/v1/run-result.json +34 -0
  53. package/fixtures/contracts/v1/run-stream-result.jsonl +1 -0
  54. package/fixtures/migrations/0.10.0.json +315 -0
  55. package/fixtures/migrations/0.10.0.sqlite +0 -0
  56. package/fixtures/migrations/0.11.1.json +319 -0
  57. package/fixtures/migrations/0.11.1.sqlite +0 -0
  58. package/fixtures/migrations/README.md +20 -0
  59. package/package.json +16 -9
package/dist/cli.js CHANGED
@@ -2,13 +2,14 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { createInterface } from "node:readline/promises";
5
- import { randomUUID as randomUUID6 } from "node:crypto";
6
- import { constants as fsConstants3, realpathSync as realpathSync2 } from "node:fs";
7
- import { access, lstat as lstat9, readFile as readFile4, stat as stat4 } from "node:fs/promises";
8
- import path12 from "node:path";
5
+ import { randomUUID as randomUUID7 } from "node:crypto";
6
+ import { constants as fsConstants4, realpathSync as realpathSync2 } from "node:fs";
7
+ import { access, lstat as lstat10, stat as stat4 } from "node:fs/promises";
8
+ import path13 from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
- import { z as z6 } from "zod";
10
+ import { z as z7 } from "zod";
11
11
  import {
12
+ createRedactionPolicy as createRedactionPolicy4,
12
13
  getAgentBudgetStatus as getAgentBudgetStatus3
13
14
  } from "@zhivex-ai/agents";
14
15
 
@@ -17,8 +18,142 @@ import { createHash as createHash2 } from "node:crypto";
17
18
  import { realpathSync } from "node:fs";
18
19
  import path from "node:path";
19
20
 
21
+ // src/errors.ts
22
+ var HARNESS_ERROR_CODES = [
23
+ "CONFIG_INVALID",
24
+ "CLI_USAGE_INVALID",
25
+ "WORKSPACE_UNSAFE",
26
+ "STATE_CONFLICT",
27
+ "PROVIDER_UNAVAILABLE",
28
+ "APPROVAL_REQUIRED",
29
+ "EXECUTION_FAILED"
30
+ ];
31
+ var HARNESS_ERROR_SCHEMA_VERSION = 1;
32
+
33
+ class HarnessError extends Error {
34
+ code;
35
+ category;
36
+ retryable;
37
+ constructor(message, options) {
38
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
39
+ this.name = "HarnessError";
40
+ this.code = options.code;
41
+ this.category = options.category;
42
+ this.retryable = options.retryable ?? false;
43
+ }
44
+ }
45
+
46
+ class HarnessConfigError extends HarnessError {
47
+ constructor(message, options = {}) {
48
+ super(message, {
49
+ code: "CONFIG_INVALID",
50
+ category: "configuration",
51
+ ...options.cause === undefined ? {} : { cause: options.cause }
52
+ });
53
+ this.name = "HarnessConfigError";
54
+ }
55
+ }
56
+
57
+ class HarnessWorkspaceError extends HarnessError {
58
+ constructor(message, options = {}) {
59
+ super(message, {
60
+ code: "WORKSPACE_UNSAFE",
61
+ category: "workspace",
62
+ ...options.cause === undefined ? {} : { cause: options.cause }
63
+ });
64
+ this.name = "HarnessWorkspaceError";
65
+ }
66
+ }
67
+
68
+ class HarnessStateConflictError extends HarnessError {
69
+ constructor(message, options = {}) {
70
+ super(message, {
71
+ code: "STATE_CONFLICT",
72
+ category: "state",
73
+ retryable: options.retryable ?? false,
74
+ ...options.cause === undefined ? {} : { cause: options.cause }
75
+ });
76
+ this.name = "HarnessStateConflictError";
77
+ }
78
+ }
79
+
80
+ class HarnessProviderError extends HarnessError {
81
+ constructor(message, options = {}) {
82
+ super(message, {
83
+ code: "PROVIDER_UNAVAILABLE",
84
+ category: "provider",
85
+ retryable: options.retryable ?? true,
86
+ ...options.cause === undefined ? {} : { cause: options.cause }
87
+ });
88
+ this.name = "HarnessProviderError";
89
+ }
90
+ }
91
+
92
+ class HarnessApprovalError extends HarnessError {
93
+ constructor(message, options = {}) {
94
+ super(message, {
95
+ code: "APPROVAL_REQUIRED",
96
+ category: "approval",
97
+ ...options.cause === undefined ? {} : { cause: options.cause }
98
+ });
99
+ this.name = "HarnessApprovalError";
100
+ }
101
+ }
102
+
103
+ class HarnessExecutionError extends HarnessError {
104
+ constructor(message, options = {}) {
105
+ super(message, {
106
+ code: "EXECUTION_FAILED",
107
+ category: "execution",
108
+ retryable: options.retryable ?? false,
109
+ ...options.cause === undefined ? {} : { cause: options.cause }
110
+ });
111
+ this.name = "HarnessExecutionError";
112
+ }
113
+ }
114
+ var harnessErrorDocument = (error) => {
115
+ const normalized = normalizeHarnessError(error);
116
+ return {
117
+ schemaVersion: HARNESS_ERROR_SCHEMA_VERSION,
118
+ kind: "error",
119
+ error: {
120
+ code: normalized.code,
121
+ category: normalized.category,
122
+ retryable: normalized.retryable
123
+ }
124
+ };
125
+ };
126
+ var numericStatuses = (error) => {
127
+ if (!error || typeof error !== "object")
128
+ return;
129
+ const record = error;
130
+ const values = [record.status, record.statusCode].filter((value) => typeof value === "number" && Number.isSafeInteger(value));
131
+ return values.length > 0 ? values : undefined;
132
+ };
133
+ var normalizeHarnessError = (error) => {
134
+ if (error instanceof HarnessError)
135
+ return error;
136
+ const message = error instanceof Error ? error.message : "Harness execution failed.";
137
+ const statuses = numericStatuses(error) ?? [];
138
+ if (statuses.some((status) => status === 429 || status >= 500 && status <= 599)) {
139
+ return new HarnessProviderError(message, { cause: error, retryable: true });
140
+ }
141
+ const name = error && typeof error === "object" && typeof error.name === "string" ? error.name : "";
142
+ const code = error && typeof error === "object" && typeof error.code === "string" ? error.code : "";
143
+ if (name === "ConflictError" || code === "SQLITE_BUSY" || code === "SQLITE_LOCKED") {
144
+ return new HarnessStateConflictError(message, {
145
+ cause: error,
146
+ retryable: code === "SQLITE_BUSY" || code === "SQLITE_LOCKED"
147
+ });
148
+ }
149
+ return new HarnessExecutionError(message, { cause: error });
150
+ };
151
+
20
152
  // src/providers.ts
21
153
  import { createHash } from "node:crypto";
154
+ import {
155
+ wrapLanguageModel
156
+ } from "@zhivex-ai/core";
22
157
  import { createGemini } from "@zhivex-ai/gemini";
23
158
  import { createMeta } from "@zhivex-ai/meta";
24
159
  import { createOpenAI } from "@zhivex-ai/openai";
@@ -277,6 +412,76 @@ var optionalQwenRegion = (value) => {
277
412
  }
278
413
  throw new Error(`Invalid QWEN_REGION: ${value}.`);
279
414
  };
415
+ var generatedToolCallId = (model, input, index, toolCall) => `harness_call_${createHash("sha256").update(JSON.stringify({
416
+ provider: model.provider,
417
+ modelId: model.modelId,
418
+ messages: input.messages,
419
+ index,
420
+ name: toolCall.name,
421
+ input: toolCall.input
422
+ })).digest("hex").slice(0, 48)}`;
423
+ var existingToolCallIds = (messages) => new Set(messages.flatMap((message) => message.parts.flatMap((part) => {
424
+ if (part.type === "tool-call")
425
+ return [part.toolCall.id];
426
+ if (part.type === "tool-result")
427
+ return [part.toolResult.toolCallId];
428
+ return [];
429
+ }).filter((id) => typeof id === "string" && id.length > 0)));
430
+ var normalizedToolCall = (model, input, index, toolCall, seenIds) => {
431
+ const providerId = typeof toolCall.id === "string" ? toolCall.id.trim() : "";
432
+ const id = providerId.length > 0 && !/^\d+$/.test(providerId) ? providerId : generatedToolCallId(model, input, index, toolCall);
433
+ if (seenIds.has(id)) {
434
+ throw new QwenToolCallIdError(`Qwen returned a duplicate tool-call id: ${id}.`);
435
+ }
436
+ seenIds.add(id);
437
+ return id === toolCall.id ? toolCall : { ...toolCall, id };
438
+ };
439
+
440
+ class QwenToolCallIdError extends Error {
441
+ diagnosticCode = "QWEN_DUPLICATE_TOOL_CALL_ID";
442
+ constructor(message) {
443
+ super(message);
444
+ this.name = "QwenToolCallIdError";
445
+ }
446
+ }
447
+ var normalizeMessageToolCallIds = (model, input, messages, seenIds = existingToolCallIds(input.messages)) => {
448
+ let index = 0;
449
+ return messages.map((message) => ({
450
+ ...message,
451
+ parts: message.parts.map((part) => part.type === "tool-call" ? {
452
+ ...part,
453
+ toolCall: normalizedToolCall(model, input, index++, part.toolCall, seenIds)
454
+ } : part)
455
+ }));
456
+ };
457
+ var normalizeGenerateToolCallIds = (model, input, result) => {
458
+ const messages = result.messages ? normalizeMessageToolCallIds(model, input, result.messages) : undefined;
459
+ const message = result.message ? normalizeMessageToolCallIds(model, input, [result.message])[0] : undefined;
460
+ return {
461
+ ...result,
462
+ ...message ? { message } : {},
463
+ ...messages ? { messages } : {}
464
+ };
465
+ };
466
+ var normalizeStreamToolCallIds = async function* (model, input, events) {
467
+ let index = 0;
468
+ const seenIds = existingToolCallIds(input.messages);
469
+ for await (const event of events) {
470
+ if (event.type !== "tool-call") {
471
+ yield event;
472
+ continue;
473
+ }
474
+ yield {
475
+ ...event,
476
+ toolCall: normalizedToolCall(model, input, index++, event.toolCall, seenIds)
477
+ };
478
+ }
479
+ };
480
+ var withQwenDurableToolCallIds = (model) => wrapLanguageModel(model, [{
481
+ name: "harness-qwen-durable-tool-call-ids",
482
+ wrapGenerate: async ({ input }, next) => normalizeGenerateToolCallIds(model, input, await next()),
483
+ wrapStream: async ({ input }, next) => normalizeStreamToolCallIds(model, input, await next())
484
+ }]);
280
485
  var BUILTIN_PROVIDER_REGISTRATIONS = Object.freeze([
281
486
  {
282
487
  descriptor: {
@@ -318,12 +523,12 @@ var BUILTIN_PROVIDER_REGISTRATIONS = Object.freeze([
318
523
  const baseURL = env.QWEN_BASE_URL?.trim();
319
524
  const workspaceId = env.QWEN_WORKSPACE_ID?.trim();
320
525
  const region = optionalQwenRegion(env.QWEN_REGION?.trim());
321
- return createQwen({
526
+ return withQwenDurableToolCallIds(createQwen({
322
527
  apiKey: credentials.require(),
323
528
  ...baseURL ? { baseURL } : {},
324
529
  ...workspaceId ? { workspaceId } : {},
325
530
  ...region ? { region } : {}
326
- })(model);
531
+ })(model));
327
532
  }
328
533
  },
329
534
  {
@@ -369,6 +574,7 @@ var PROVIDER_DESCRIPTORS = DEFAULT_PROVIDER_REGISTRY.descriptors;
369
574
  // src/config.ts
370
575
  var DEFAULT_ALLOWED_CHECKS = ["test", "typecheck", "lint", "build"];
371
576
  var HARNESS_CONFIG_SCHEMA_VERSION = 5;
577
+ var HARNESS_CONFIG_MIGRATABLE_SCHEMA_VERSIONS = [4, 5];
372
578
  var HARNESS_STORE_BACKENDS = ["sqlite", "file"];
373
579
  var HARNESS_EXECUTION_BACKENDS = ["none", "oci"];
374
580
  var HARNESS_OCI_RUNTIMES = ["docker", "podman"];
@@ -424,10 +630,41 @@ var DEFAULT_SUBAGENT_BUDGET = {
424
630
  maxTotalTokens: 36000,
425
631
  includeChildRuns: false
426
632
  };
633
+ var migrateHarnessConfigInput = (input) => {
634
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
635
+ throw new HarnessConfigError("Harness config migration requires an object.");
636
+ }
637
+ const fromVersion = input.schemaVersion;
638
+ if (fromVersion !== 4 && fromVersion !== HARNESS_CONFIG_SCHEMA_VERSION) {
639
+ throw new HarnessConfigError(`Unsupported config schema version for migration: ${String(fromVersion)}. ` + `Supported source versions: ${HARNESS_CONFIG_MIGRATABLE_SCHEMA_VERSIONS.join(", ")}.`);
640
+ }
641
+ if (fromVersion === HARNESS_CONFIG_SCHEMA_VERSION) {
642
+ return {
643
+ fromVersion,
644
+ toVersion: HARNESS_CONFIG_SCHEMA_VERSION,
645
+ config: { ...input },
646
+ notes: []
647
+ };
648
+ }
649
+ return {
650
+ fromVersion,
651
+ toVersion: HARNESS_CONFIG_SCHEMA_VERSION,
652
+ config: {
653
+ ...input,
654
+ schemaVersion: HARNESS_CONFIG_SCHEMA_VERSION,
655
+ projectContext: false,
656
+ ...input.executionBackend === "oci" ? { ociShellMode: "deny" } : {}
657
+ },
658
+ notes: [
659
+ "Project context remains disabled to preserve schema 4 behavior; enable it explicitly after reviewing repository instructions.",
660
+ ...input.executionBackend === "oci" ? ["OCI shell exposure remains denied to preserve schema 4 behavior."] : []
661
+ ]
662
+ };
663
+ };
427
664
  var integerOption = (name, input, envValue, fallback, minimum, maximum) => {
428
665
  const value = input ?? (envValue === undefined ? fallback : Number(envValue));
429
666
  if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
430
- throw new Error(`${name} must be an integer between ${minimum} and ${maximum}.`);
667
+ throw new HarnessConfigError(`${name} must be an integer between ${minimum} and ${maximum}.`);
431
668
  }
432
669
  return value;
433
670
  };
@@ -438,7 +675,10 @@ var scopeValue = (name, value, fallback) => {
438
675
  return;
439
676
  }
440
677
  if (normalized.length > 128 || /[\u0000-\u001f\u007f]/.test(normalized)) {
441
- throw new Error(`${name} must contain 1-128 printable characters.`);
678
+ throw new HarnessConfigError(`${name} must contain 1-128 printable characters.`);
679
+ }
680
+ if (name === "userId" && normalized === "*") {
681
+ throw new HarnessConfigError('userId cannot be the reserved "*" scope marker.');
442
682
  }
443
683
  return normalized;
444
684
  };
@@ -448,7 +688,7 @@ var nonNegativeNumberOption = (name, input, envValue) => {
448
688
  }
449
689
  const value = input ?? Number(envValue);
450
690
  if (!Number.isFinite(value) || value < 0) {
451
- throw new Error(`${name} must be a non-negative number.`);
691
+ throw new HarnessConfigError(`${name} must be a non-negative number.`);
452
692
  }
453
693
  return value;
454
694
  };
@@ -466,11 +706,11 @@ var resolveAllowedChecks = (configured) => {
466
706
  const source = configured ?? (process.env.ZHIVEX_HARNESS_ALLOWED_CHECKS === undefined ? DEFAULT_ALLOWED_CHECKS : process.env.ZHIVEX_HARNESS_ALLOWED_CHECKS.split(","));
467
707
  const checks = [...new Set(source.map((value) => value.trim()).filter(Boolean))];
468
708
  if (checks.length > 50) {
469
- throw new Error("allowedChecks cannot contain more than 50 script names.");
709
+ throw new HarnessConfigError("allowedChecks cannot contain more than 50 script names.");
470
710
  }
471
711
  const invalid = checks.find((value) => !/^[A-Za-z0-9][A-Za-z0-9:_-]{0,63}$/.test(value));
472
712
  if (invalid) {
473
- throw new Error(`Invalid allowed check name: ${invalid}. Use 1-64 letters, digits, colon, underscore, or hyphen.`);
713
+ throw new HarnessConfigError(`Invalid allowed check name: ${invalid}. Use 1-64 letters, digits, colon, underscore, or hyphen.`);
474
714
  }
475
715
  return checks;
476
716
  };
@@ -480,7 +720,7 @@ var resolveRequiredCapabilities = (configured) => {
480
720
  const capabilities = [...new Set(values.map((value) => value.trim()).filter(Boolean))];
481
721
  const invalid = capabilities.find((value) => !HARNESS_REQUIRED_CAPABILITIES.includes(value));
482
722
  if (invalid) {
483
- throw new Error(`Unknown required capability: ${invalid}. Use ${HARNESS_REQUIRED_CAPABILITIES.join(", ")}.`);
723
+ throw new HarnessConfigError(`Unknown required capability: ${invalid}. Use ${HARNESS_REQUIRED_CAPABILITIES.join(", ")}.`);
484
724
  }
485
725
  return capabilities;
486
726
  };
@@ -489,7 +729,7 @@ var resolveSubagentProfiles = (configured) => {
489
729
  const profiles = [...new Set(values.map((value) => value.trim()).filter(Boolean))];
490
730
  const invalid = profiles.find((value) => !HARNESS_SUBAGENT_PROFILES.includes(value));
491
731
  if (invalid) {
492
- throw new Error(`Unknown subagent profile: ${invalid}. Use ${HARNESS_SUBAGENT_PROFILES.join(", ")}.`);
732
+ throw new HarnessConfigError(`Unknown subagent profile: ${invalid}. Use ${HARNESS_SUBAGENT_PROFILES.join(", ")}.`);
493
733
  }
494
734
  return profiles;
495
735
  };
@@ -497,41 +737,41 @@ var resolveOciAllowedCommands = (configured) => {
497
737
  const values = commaSeparatedValues(configured, process.env.ZHIVEX_HARNESS_OCI_ALLOWED_COMMANDS, DEFAULT_OCI_EXECUTION.allowedCommands);
498
738
  const commands = [...new Set(values.map((value) => value.trim()).filter(Boolean))];
499
739
  if (commands.length === 0 || commands.length > 50) {
500
- throw new Error("ociAllowedCommands must contain between 1 and 50 executable names.");
740
+ throw new HarnessConfigError("ociAllowedCommands must contain between 1 and 50 executable names.");
501
741
  }
502
742
  const invalid = commands.find((value) => !/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/.test(value));
503
743
  if (invalid) {
504
- throw new Error(`Invalid OCI command name: ${invalid}. Use a bare executable name without a path.`);
744
+ throw new HarnessConfigError(`Invalid OCI command name: ${invalid}. Use a bare executable name without a path.`);
505
745
  }
506
746
  if (!commands.some((command) => ["npm", "pnpm", "yarn", "bun"].includes(command))) {
507
- throw new Error("ociAllowedCommands must include npm, pnpm, yarn, or bun so declared package checks remain available.");
747
+ throw new HarnessConfigError("ociAllowedCommands must include npm, pnpm, yarn, or bun so declared package checks remain available.");
508
748
  }
509
749
  return commands;
510
750
  };
511
751
  var resolveExecutionConfig = (input) => {
512
752
  const backend = (input.executionBackend ?? process.env.ZHIVEX_HARNESS_EXECUTION ?? "none").trim().toLowerCase();
513
753
  if (!HARNESS_EXECUTION_BACKENDS.includes(backend)) {
514
- throw new Error(`executionBackend must be one of: ${HARNESS_EXECUTION_BACKENDS.join(", ")}.`);
754
+ throw new HarnessConfigError(`executionBackend must be one of: ${HARNESS_EXECUTION_BACKENDS.join(", ")}.`);
515
755
  }
516
756
  if (backend === "none") {
517
757
  return { backend: "none" };
518
758
  }
519
759
  const runtime = (input.ociRuntime ?? process.env.ZHIVEX_HARNESS_OCI_RUNTIME ?? DEFAULT_OCI_EXECUTION.runtime).trim().toLowerCase();
520
760
  if (!HARNESS_OCI_RUNTIMES.includes(runtime)) {
521
- throw new Error(`ociRuntime must be one of: ${HARNESS_OCI_RUNTIMES.join(", ")}.`);
761
+ throw new HarnessConfigError(`ociRuntime must be one of: ${HARNESS_OCI_RUNTIMES.join(", ")}.`);
522
762
  }
523
763
  const image = (input.ociImage ?? process.env.ZHIVEX_HARNESS_OCI_IMAGE ?? DEFAULT_OCI_EXECUTION.image).trim();
524
764
  if (!image || image.length > 512 || /[\u0000-\u001f\u007f\s]/.test(image) || image.startsWith("-")) {
525
- throw new Error("ociImage must be a non-empty OCI image reference without whitespace or control characters.");
765
+ throw new HarnessConfigError("ociImage must be a non-empty OCI image reference without whitespace or control characters.");
526
766
  }
527
767
  const shellMode = (input.ociShellMode ?? process.env.ZHIVEX_HARNESS_OCI_SHELL ?? DEFAULT_OCI_EXECUTION.shellMode).trim().toLowerCase();
528
768
  if (!HARNESS_OCI_SHELL_MODES.includes(shellMode)) {
529
- throw new Error(`ociShellMode must be one of: ${HARNESS_OCI_SHELL_MODES.join(", ")}.`);
769
+ throw new HarnessConfigError(`ociShellMode must be one of: ${HARNESS_OCI_SHELL_MODES.join(", ")}.`);
530
770
  }
531
771
  const maxWorkspaceBytes = integerOption("ociMaxWorkspaceBytes", input.ociMaxWorkspaceBytes, process.env.ZHIVEX_HARNESS_OCI_MAX_WORKSPACE_BYTES, DEFAULT_OCI_EXECUTION.maxWorkspaceBytes, 1024 * 1024, 1024 * 1024 * 1024);
532
772
  const maxFileWriteBytes = integerOption("ociMaxFileWriteBytes", input.ociMaxFileWriteBytes, process.env.ZHIVEX_HARNESS_OCI_MAX_FILE_WRITE_BYTES, DEFAULT_OCI_EXECUTION.maxFileWriteBytes, 1024, 16 * 1024 * 1024);
533
773
  if (maxFileWriteBytes > maxWorkspaceBytes) {
534
- throw new Error("ociMaxFileWriteBytes cannot exceed ociMaxWorkspaceBytes.");
774
+ throw new HarnessConfigError("ociMaxFileWriteBytes cannot exceed ociMaxWorkspaceBytes.");
535
775
  }
536
776
  return {
537
777
  backend: "oci",
@@ -563,15 +803,23 @@ var canonicalProjectContextFile = (requestedWorkspace, canonicalWorkspace, confi
563
803
  const candidate = canonicalWorkspaceFile(requestedWorkspace, canonicalWorkspace, configured);
564
804
  const relative = path.relative(canonicalWorkspace, candidate);
565
805
  if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
566
- throw new Error("contextConfigPath must resolve inside the workspace.");
806
+ throw new HarnessConfigError("contextConfigPath must resolve inside the workspace.");
567
807
  }
568
808
  return candidate;
569
809
  };
570
- var parseProvider = (value, registry = DEFAULT_PROVIDER_REGISTRY) => registry.parse(value);
810
+ var parseProvider = (value, registry = DEFAULT_PROVIDER_REGISTRY) => {
811
+ try {
812
+ return registry.parse(value);
813
+ } catch (error) {
814
+ if (error instanceof HarnessConfigError)
815
+ throw error;
816
+ throw new HarnessConfigError(error instanceof Error ? error.message : String(error), { cause: error });
817
+ }
818
+ };
571
819
  var providerDescriptor = (provider, registry = DEFAULT_PROVIDER_REGISTRY) => registry.descriptor(provider);
572
820
  var resolveHarnessConfig = (input = {}, registry = DEFAULT_PROVIDER_REGISTRY) => {
573
821
  if (input.schemaVersion !== undefined && input.schemaVersion !== HARNESS_CONFIG_SCHEMA_VERSION) {
574
- throw new Error(`Unsupported config schema version: ${input.schemaVersion}. Expected ${HARNESS_CONFIG_SCHEMA_VERSION}.`);
822
+ throw new HarnessConfigError(`Unsupported config schema version: ${input.schemaVersion}. Expected ${HARNESS_CONFIG_SCHEMA_VERSION}.`);
575
823
  }
576
824
  const provider = parseProvider(input.provider ?? process.env.ZHIVEX_HARNESS_PROVIDER, registry);
577
825
  const descriptor = providerDescriptor(provider, registry);
@@ -583,7 +831,7 @@ var resolveHarnessConfig = (input = {}, registry = DEFAULT_PROVIDER_REGISTRY) =>
583
831
  const maxSteps = integerOption("maxSteps", input.maxSteps, process.env.ZHIVEX_HARNESS_MAX_STEPS, 12, 1, 50);
584
832
  const storeBackend = (input.storeBackend ?? process.env.ZHIVEX_HARNESS_STORE ?? "sqlite").trim().toLowerCase();
585
833
  if (!HARNESS_STORE_BACKENDS.includes(storeBackend)) {
586
- throw new Error(`storeBackend must be one of: ${HARNESS_STORE_BACKENDS.join(", ")}.`);
834
+ throw new HarnessConfigError(`storeBackend must be one of: ${HARNESS_STORE_BACKENDS.join(", ")}.`);
587
835
  }
588
836
  const tenantId = scopeValue("tenantId", input.tenantId ?? process.env.ZHIVEX_HARNESS_TENANT_ID, "local");
589
837
  const userId = scopeValue("userId", input.userId ?? process.env.ZHIVEX_HARNESS_USER_ID);
@@ -599,16 +847,16 @@ var resolveHarnessConfig = (input = {}, registry = DEFAULT_PROVIDER_REGISTRY) =>
599
847
  includeChildRuns: true
600
848
  };
601
849
  if (budget.maxTotalTokens < budget.maxInputTokens || budget.maxTotalTokens < budget.maxOutputTokens) {
602
- throw new Error("maxTotalTokens must be greater than or equal to the input and output token limits.");
850
+ throw new HarnessConfigError("maxTotalTokens must be greater than or equal to the input and output token limits.");
603
851
  }
604
852
  const maxCostUsd = nonNegativeNumberOption("maxCostUsd", input.maxCostUsd, process.env.ZHIVEX_HARNESS_MAX_COST_USD);
605
853
  const inputCostPerMillion = nonNegativeNumberOption("inputCostPerMillion", input.inputCostPerMillion, process.env.ZHIVEX_HARNESS_INPUT_COST_PER_MILLION);
606
854
  const outputCostPerMillion = nonNegativeNumberOption("outputCostPerMillion", input.outputCostPerMillion, process.env.ZHIVEX_HARNESS_OUTPUT_COST_PER_MILLION);
607
855
  if (maxCostUsd !== undefined && inputCostPerMillion === undefined && outputCostPerMillion === undefined) {
608
- throw new Error("maxCostUsd requires inputCostPerMillion or outputCostPerMillion pricing.");
856
+ throw new HarnessConfigError("maxCostUsd requires inputCostPerMillion or outputCostPerMillion pricing.");
609
857
  }
610
858
  if (maxCostUsd === undefined && (inputCostPerMillion !== undefined || outputCostPerMillion !== undefined)) {
611
- throw new Error("Token pricing requires maxCostUsd.");
859
+ throw new HarnessConfigError("Token pricing requires maxCostUsd.");
612
860
  }
613
861
  const compaction = {
614
862
  maxMessages: integerOption("compactionMaxMessages", input.compactionMaxMessages, process.env.ZHIVEX_HARNESS_COMPACTION_MAX_MESSAGES, DEFAULT_HARNESS_COMPACTION.maxMessages, 4, 1e4),
@@ -616,7 +864,7 @@ var resolveHarnessConfig = (input = {}, registry = DEFAULT_PROVIDER_REGISTRY) =>
616
864
  keepRecentMessages: integerOption("compactionKeepRecentMessages", input.compactionKeepRecentMessages, process.env.ZHIVEX_HARNESS_COMPACTION_KEEP_RECENT, DEFAULT_HARNESS_COMPACTION.keepRecentMessages, 2, 1000)
617
865
  };
618
866
  if (compaction.keepRecentMessages >= compaction.maxMessages) {
619
- throw new Error("compactionKeepRecentMessages must be smaller than compactionMaxMessages.");
867
+ throw new HarnessConfigError("compactionKeepRecentMessages must be smaller than compactionMaxMessages.");
620
868
  }
621
869
  const childBudget = {
622
870
  maxSteps: integerOption("subagentMaxSteps", input.subagentMaxSteps, process.env.ZHIVEX_HARNESS_SUBAGENT_MAX_STEPS, DEFAULT_SUBAGENT_BUDGET.maxSteps, 1, 30),
@@ -628,7 +876,7 @@ var resolveHarnessConfig = (input = {}, registry = DEFAULT_PROVIDER_REGISTRY) =>
628
876
  includeChildRuns: false
629
877
  };
630
878
  if (childBudget.maxTotalTokens < childBudget.maxInputTokens || childBudget.maxTotalTokens < childBudget.maxOutputTokens) {
631
- throw new Error("subagentMaxTotalTokens must be greater than or equal to the child input and output token limits.");
879
+ throw new HarnessConfigError("subagentMaxTotalTokens must be greater than or equal to the child input and output token limits.");
632
880
  }
633
881
  const orchestration = {
634
882
  profiles: resolveSubagentProfiles(input.subagentProfiles),
@@ -674,7 +922,16 @@ var resolveHarnessConfig = (input = {}, registry = DEFAULT_PROVIDER_REGISTRY) =>
674
922
  ...mcpConfigPath ? { mcpConfigPath } : {}
675
923
  };
676
924
  };
677
- var createProviderModel = (config, env = process.env, registry = DEFAULT_PROVIDER_REGISTRY) => registry.createModel(config, env);
925
+ var createProviderModel = (config, env = process.env, registry = DEFAULT_PROVIDER_REGISTRY) => {
926
+ try {
927
+ return registry.createModel(config, env);
928
+ } catch (error) {
929
+ throw new HarnessProviderError(`Provider ${config.provider} could not be initialized.`, {
930
+ cause: error,
931
+ retryable: false
932
+ });
933
+ }
934
+ };
678
935
  var providerAvailability = (env = process.env, registry = DEFAULT_PROVIDER_REGISTRY) => registry.availability(env);
679
936
 
680
937
  // src/harness.ts
@@ -759,13 +1016,14 @@ var MAX_EDIT_FILE_BYTES = 1024 * 1024;
759
1016
  var MAX_EDIT_PROPOSAL_BYTES = 4 * 1024 * 1024;
760
1017
  var SHA256_DIGEST_PATTERN = /^sha256:[a-f0-9]{64}$/;
761
1018
  var fileDigestSchema = z.string().regex(SHA256_DIGEST_PATTERN, "Digest must use the format sha256:<64 lowercase hexadecimal characters>.");
1019
+ var expectedEditDigestSchema = fileDigestSchema.nullable().describe("Required. Use the inspected sha256 digest for an existing file, or explicit JSON null for a create-only target. Never omit this field.");
762
1020
  var workspaceFilePathSchema = z.string().min(1).max(1024).refine((value) => !value.includes("\x00"), "Path cannot contain a NUL byte.").refine((value) => !path2.isAbsolute(value) && !/^[A-Za-z]:[\\/]/.test(value), "Path must be relative.").refine((value) => {
763
1021
  const segments = value.split(/[\\/]+/);
764
1022
  return segments.every((segment) => segment !== "" && segment !== "." && segment !== "..");
765
1023
  }, "Path must be normalized and cannot contain empty, dot, or parent segments.");
766
1024
  var editChangeSchema = z.strictObject({
767
1025
  path: workspaceFilePathSchema,
768
- expectedDigest: fileDigestSchema.nullable(),
1026
+ expectedDigest: expectedEditDigestSchema,
769
1027
  content: z.string()
770
1028
  }).superRefine((change, context) => {
771
1029
  if (Buffer.byteLength(change.content, "utf8") > MAX_EDIT_FILE_BYTES) {
@@ -806,7 +1064,7 @@ var editProposalInputSchema = z.strictObject({
806
1064
  });
807
1065
  var editProposalChangeSchema = z.strictObject({
808
1066
  path: workspaceFilePathSchema,
809
- expectedDigest: fileDigestSchema.nullable(),
1067
+ expectedDigest: expectedEditDigestSchema,
810
1068
  contentDigest: fileDigestSchema,
811
1069
  bytes: z.number().int().min(0).max(MAX_EDIT_FILE_BYTES)
812
1070
  });
@@ -885,9 +1143,97 @@ var editContractDocument = (kind, result) => ({
885
1143
 
886
1144
  // src/workspace.ts
887
1145
  import { createHash as createHash4, randomUUID } from "node:crypto";
888
- import { link, lstat as lstat2, mkdir, open, readFile, readdir, realpath, rename, stat, unlink } from "node:fs/promises";
1146
+ import { link, lstat as lstat2, mkdir, open as open2, readdir, realpath, rename, stat, unlink } from "node:fs/promises";
889
1147
  import path4 from "node:path";
890
1148
 
1149
+ // src/file-security.ts
1150
+ import { constants as fsConstants } from "node:fs";
1151
+ import { open } from "node:fs/promises";
1152
+ var sameOpenFile = (before, after) => before.dev === after.dev && before.ino === after.ino && before.size === after.size && before.mtimeMs === after.mtimeMs && before.ctimeMs === after.ctimeMs && before.mode === after.mode && before.nlink === after.nlink;
1153
+
1154
+ class UnsafeFileTypeError extends Error {
1155
+ constructor(label) {
1156
+ super(`${label} must be a regular file and must not be a symbolic link.`);
1157
+ this.name = "UnsafeFileTypeError";
1158
+ }
1159
+ }
1160
+
1161
+ class FileSizeLimitError extends Error {
1162
+ label;
1163
+ maxBytes;
1164
+ constructor(label, maxBytes) {
1165
+ super(`${label} exceeds the ${maxBytes}-byte limit.`);
1166
+ this.label = label;
1167
+ this.maxBytes = maxBytes;
1168
+ this.name = "FileSizeLimitError";
1169
+ }
1170
+ }
1171
+
1172
+ class FileChangedWhileReadingError extends Error {
1173
+ constructor(label) {
1174
+ super(`${label} changed while it was being read.`);
1175
+ this.name = "FileChangedWhileReadingError";
1176
+ }
1177
+ }
1178
+ var invalidFileError = (label) => new UnsafeFileTypeError(label);
1179
+ var openRegularFileNoFollow = async (target, label) => {
1180
+ try {
1181
+ return await open(target, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
1182
+ } catch (error) {
1183
+ const code = error.code;
1184
+ if (code === "ELOOP" || code === "EMLINK")
1185
+ throw invalidFileError(label);
1186
+ throw error;
1187
+ }
1188
+ };
1189
+ var statRegularFileNoFollow = async (target, options) => {
1190
+ const handle = await openRegularFileNoFollow(target, options.label);
1191
+ try {
1192
+ const stat = await handle.stat();
1193
+ if (!stat.isFile() || options.requireSingleLink && stat.nlink !== 1) {
1194
+ throw invalidFileError(options.label);
1195
+ }
1196
+ return stat;
1197
+ } finally {
1198
+ await handle.close();
1199
+ }
1200
+ };
1201
+ var readRegularFileNoFollow = async (target, options) => {
1202
+ const handle = await openRegularFileNoFollow(target, options.label);
1203
+ try {
1204
+ const before = await handle.stat();
1205
+ if (!before.isFile() || options.requireSingleLink && before.nlink !== 1) {
1206
+ throw invalidFileError(options.label);
1207
+ }
1208
+ if (!Number.isSafeInteger(before.size) || before.size < 0) {
1209
+ throw new Error(`${options.label} has an unsupported size.`);
1210
+ }
1211
+ if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 0) {
1212
+ throw new Error(`${options.label} has an invalid byte limit.`);
1213
+ }
1214
+ if (before.size > options.maxBytes) {
1215
+ throw new FileSizeLimitError(options.label, options.maxBytes);
1216
+ }
1217
+ const contents = Buffer.alloc(before.size);
1218
+ let offset = 0;
1219
+ while (offset < contents.byteLength) {
1220
+ const { bytesRead } = await handle.read(contents, offset, contents.byteLength - offset, offset);
1221
+ if (bytesRead === 0)
1222
+ break;
1223
+ offset += bytesRead;
1224
+ }
1225
+ const probe = Buffer.allocUnsafe(1);
1226
+ const { bytesRead: extraBytes } = await handle.read(probe, 0, 1, before.size);
1227
+ const after = await handle.stat();
1228
+ if (offset !== before.size || extraBytes !== 0 || !sameOpenFile(before, after) || options.requireSingleLink && after.nlink !== 1) {
1229
+ throw new FileChangedWhileReadingError(options.label);
1230
+ }
1231
+ return { contents, stat: after };
1232
+ } finally {
1233
+ await handle.close();
1234
+ }
1235
+ };
1236
+
891
1237
  // src/package-manager.ts
892
1238
  import { lstat } from "node:fs/promises";
893
1239
  import path3 from "node:path";
@@ -1068,9 +1414,11 @@ var runPortableProcess = async (command, options = {}) => {
1068
1414
  const argv = [...command];
1069
1415
  const stdout = new BoundedTextCapture(maxOutputCharacters);
1070
1416
  const stderr = new BoundedTextCapture(maxOutputCharacters);
1417
+ const useProcessGroup = process.platform !== "win32";
1071
1418
  const child = spawn(argv[0], argv.slice(1), {
1072
1419
  ...options.cwd ? { cwd: options.cwd } : {},
1073
1420
  env: processEnvironment(options.env),
1421
+ detached: useProcessGroup,
1074
1422
  shell: false,
1075
1423
  stdio: ["ignore", "pipe", "pipe"],
1076
1424
  windowsHide: true
@@ -1080,13 +1428,27 @@ var runPortableProcess = async (command, options = {}) => {
1080
1428
  let terminationTimer;
1081
1429
  child.stdout.on("data", (chunk) => stdout.write(chunk));
1082
1430
  child.stderr?.on("data", (chunk) => stderr.write(chunk));
1431
+ const signalProcessTree = (signal) => {
1432
+ if (useProcessGroup && child.pid !== undefined) {
1433
+ try {
1434
+ process.kill(-child.pid, signal);
1435
+ return;
1436
+ } catch (error) {
1437
+ if (error.code !== "ESRCH") {
1438
+ child.kill(signal);
1439
+ return;
1440
+ }
1441
+ }
1442
+ }
1443
+ if (child.exitCode === null && child.signalCode === null)
1444
+ child.kill(signal);
1445
+ };
1083
1446
  const terminate = () => {
1084
- if (child.exitCode !== null || child.signalCode !== null)
1447
+ if (terminationTimer)
1085
1448
  return;
1086
- child.kill("SIGTERM");
1449
+ signalProcessTree("SIGTERM");
1087
1450
  terminationTimer = setTimeout(() => {
1088
- if (child.exitCode === null && child.signalCode === null)
1089
- child.kill("SIGKILL");
1451
+ signalProcessTree("SIGKILL");
1090
1452
  }, DEFAULT_TERMINATION_GRACE_MS);
1091
1453
  terminationTimer.unref?.();
1092
1454
  };
@@ -1161,7 +1523,7 @@ var cursorDecode = (value) => {
1161
1523
  try {
1162
1524
  return JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
1163
1525
  } catch {
1164
- throw new Error("The pagination cursor is invalid.");
1526
+ throw new HarnessWorkspaceError("The pagination cursor is invalid.");
1165
1527
  }
1166
1528
  };
1167
1529
  var firstPathAtLeast = (files, target) => {
@@ -1271,32 +1633,42 @@ class Workspace {
1271
1633
  this.root = root;
1272
1634
  }
1273
1635
  static async open(root) {
1274
- const resolved = await realpath(path4.resolve(root));
1275
- if (!(await stat(resolved)).isDirectory())
1276
- throw new Error(`The workspace is not a directory: ${root}`);
1277
- return new Workspace(resolved);
1636
+ try {
1637
+ const resolved = await realpath(path4.resolve(root));
1638
+ if (!(await stat(resolved)).isDirectory()) {
1639
+ throw new HarnessWorkspaceError(`The workspace is not a directory: ${root}`);
1640
+ }
1641
+ return new Workspace(resolved);
1642
+ } catch (error) {
1643
+ if (error instanceof HarnessWorkspaceError)
1644
+ throw error;
1645
+ throw new HarnessWorkspaceError(`The workspace could not be opened safely: ${root}`, { cause: error });
1646
+ }
1278
1647
  }
1279
1648
  lexicalPath(relativePath) {
1280
1649
  if (!relativePath || relativePath.includes("\x00"))
1281
- throw new Error("The path must be a valid relative path.");
1650
+ throw new HarnessWorkspaceError("The path must be a valid relative path.");
1282
1651
  const candidate = path4.resolve(this.root, relativePath);
1283
1652
  if (!isInside(this.root, candidate))
1284
- throw new Error(`The path escapes the workspace: ${relativePath}`);
1653
+ throw new HarnessWorkspaceError(`The path escapes the workspace: ${relativePath}`);
1285
1654
  const relative = wirePath(path4.relative(this.root, candidate));
1286
1655
  if (relative && isHardIgnored(relative)) {
1287
1656
  const blocked = relative.split("/").find((segment) => HARD_IGNORES.has(segment.toLocaleLowerCase()) || isSensitiveName(segment));
1288
- throw new Error(`The path is protected by the harness policy: ${blocked}`);
1657
+ throw new HarnessWorkspaceError(`The path is protected by the harness policy: ${blocked}`);
1289
1658
  }
1290
1659
  return candidate;
1291
1660
  }
1292
1661
  async safePath(relativePath, options = {}) {
1293
1662
  const candidate = this.lexicalPath(relativePath);
1294
1663
  if (candidate === this.root && options.requireFile)
1295
- throw new Error("The workspace root is not a regular file.");
1664
+ throw new HarnessWorkspaceError("The workspace root is not a regular file.");
1296
1665
  const segments = path4.relative(this.root, candidate).split(path4.sep).filter(Boolean);
1297
1666
  let current = this.root;
1298
1667
  for (let index = 0;index < segments.length; index += 1) {
1299
1668
  current = path4.join(current, segments[index]);
1669
+ const leaf = index === segments.length - 1;
1670
+ if (leaf && options.skipLeafValidation)
1671
+ continue;
1300
1672
  let entry;
1301
1673
  try {
1302
1674
  entry = await lstat2(current);
@@ -1307,35 +1679,31 @@ class Workspace {
1307
1679
  throw error;
1308
1680
  }
1309
1681
  if (entry.isSymbolicLink()) {
1310
- throw new Error(`The path resolves outside the workspace or through a symbolic link: ${relativePath}`);
1682
+ throw new HarnessWorkspaceError(`The path resolves outside the workspace or through a symbolic link: ${relativePath}`);
1311
1683
  }
1312
- const leaf = index === segments.length - 1;
1313
1684
  if (!leaf && !entry.isDirectory())
1314
- throw new Error(`A path ancestor is not a directory: ${relativePath}`);
1685
+ throw new HarnessWorkspaceError(`A path ancestor is not a directory: ${relativePath}`);
1315
1686
  if (leaf && options.requireFile && !entry.isFile())
1316
- throw new Error("The path does not point to a regular file.");
1687
+ throw new HarnessWorkspaceError("The path does not point to a regular file.");
1317
1688
  }
1318
1689
  return { path: candidate, exists: true };
1319
1690
  }
1320
1691
  async readStableFile(relativePath, allowBinary = true) {
1321
1692
  this.indexMetrics.stableFileReads += 1;
1322
- const safe = await this.safePath(relativePath, { requireFile: true });
1323
- const before = await lstat2(safe.path);
1324
- if (before.size > MAX_FILE_BYTES)
1325
- throw new Error(`The file exceeds the ${MAX_FILE_BYTES}-byte limit.`);
1326
- const contents = await readFile(safe.path);
1327
- const after = await lstat2(safe.path);
1328
- if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs) {
1329
- throw new Error(`The file changed while it was being read: ${relativePath}`);
1330
- }
1693
+ const safe = await this.safePath(relativePath, { skipLeafValidation: true });
1694
+ const file = await readRegularFileNoFollow(safe.path, {
1695
+ label: "The file",
1696
+ maxBytes: MAX_FILE_BYTES
1697
+ });
1698
+ const { contents } = file;
1331
1699
  if (!allowBinary && contents.includes(0))
1332
- throw new Error("The file appears to be binary and cannot be read as text.");
1700
+ throw new HarnessWorkspaceError("The file appears to be binary and cannot be read as text.");
1333
1701
  return {
1334
1702
  path: wirePath(path4.relative(this.root, safe.path)),
1335
1703
  absolutePath: safe.path,
1336
1704
  contents,
1337
1705
  digest: digestBytes(contents),
1338
- mode: before.mode & 511
1706
+ mode: file.stat.mode & 511
1339
1707
  };
1340
1708
  }
1341
1709
  fingerprint(relativePath, kind, entry, digest2) {
@@ -1358,23 +1726,20 @@ class Workspace {
1358
1726
  for (const filename of IGNORE_FILES) {
1359
1727
  try {
1360
1728
  const ignorePath = path4.join(directory, filename);
1361
- const before = await lstat2(ignorePath);
1362
- if (before.isSymbolicLink() || !before.isFile())
1729
+ const inspected = await statRegularFileNoFollow(ignorePath, { label: "The ignore file" });
1730
+ if (inspected.size > MAX_FILE_BYTES) {
1731
+ ignoreFiles.push(this.fingerprint(wirePath(path4.relative(this.root, ignorePath)), "ignore-file", inspected));
1363
1732
  continue;
1364
- if (before.size <= MAX_FILE_BYTES) {
1365
- const contents = await readFile(ignorePath);
1366
- const after = await lstat2(ignorePath);
1367
- if (after.isSymbolicLink() || !after.isFile() || !this.sameFingerprint(after, this.fingerprint("", "ignore-file", before))) {
1368
- throw new Error(`The ignore file changed while the workspace was being indexed: ${wirePath(path4.relative(this.root, ignorePath))}`);
1369
- }
1370
- const digest2 = digestBytes(contents);
1371
- ignoreFiles.push(this.fingerprint(wirePath(path4.relative(this.root, ignorePath)), "ignore-file", after, digest2));
1372
- rules.push(...parseIgnoreRules(contents.toString("utf8"), base));
1373
- } else {
1374
- ignoreFiles.push(this.fingerprint(wirePath(path4.relative(this.root, ignorePath)), "ignore-file", before));
1375
1733
  }
1734
+ const file = await readRegularFileNoFollow(ignorePath, {
1735
+ label: "The ignore file",
1736
+ maxBytes: MAX_FILE_BYTES
1737
+ });
1738
+ const digest2 = digestBytes(file.contents);
1739
+ ignoreFiles.push(this.fingerprint(wirePath(path4.relative(this.root, ignorePath)), "ignore-file", file.stat, digest2));
1740
+ rules.push(...parseIgnoreRules(file.contents.toString("utf8"), base));
1376
1741
  } catch (error) {
1377
- if (error.code !== "ENOENT")
1742
+ if (error.code !== "ENOENT" && !(error instanceof UnsafeFileTypeError))
1378
1743
  throw error;
1379
1744
  }
1380
1745
  }
@@ -1387,7 +1752,7 @@ class Workspace {
1387
1752
  const walk = async (directory, base, inherited) => {
1388
1753
  const directoryEntry = await lstat2(directory);
1389
1754
  if (directoryEntry.isSymbolicLink() || !directoryEntry.isDirectory()) {
1390
- throw new Error(`A workspace directory changed while it was being indexed: ${base || "."}`);
1755
+ throw new HarnessWorkspaceError(`A workspace directory changed while it was being indexed: ${base || "."}`);
1391
1756
  }
1392
1757
  directories.push(this.fingerprint(base, "directory", directoryEntry));
1393
1758
  const rules = await this.rulesForDirectory(directory, base, inherited, ignoreFiles);
@@ -1417,13 +1782,17 @@ class Workspace {
1417
1782
  }
1418
1783
  for (const fingerprint of index.ignoreFiles) {
1419
1784
  const absolute = path4.join(this.root, fingerprint.path);
1420
- const before = await lstat2(absolute);
1421
- if (before.isSymbolicLink() || !before.isFile() || !this.sameFingerprint(before, fingerprint))
1422
- return false;
1423
1785
  if (fingerprint.digest) {
1424
- const contents = await readFile(absolute);
1425
- const after = await lstat2(absolute);
1426
- if (after.isSymbolicLink() || !after.isFile() || !this.sameFingerprint(after, fingerprint) || digestBytes(contents) !== fingerprint.digest)
1786
+ const file = await readRegularFileNoFollow(absolute, {
1787
+ label: "The ignore file",
1788
+ maxBytes: MAX_FILE_BYTES
1789
+ });
1790
+ if (!this.sameFingerprint(file.stat, fingerprint) || digestBytes(file.contents) !== fingerprint.digest) {
1791
+ return false;
1792
+ }
1793
+ } else {
1794
+ const inspected = await statRegularFileNoFollow(absolute, { label: "The ignore file" });
1795
+ if (!this.sameFingerprint(inspected, fingerprint))
1427
1796
  return false;
1428
1797
  }
1429
1798
  }
@@ -1450,7 +1819,7 @@ class Workspace {
1450
1819
  throw error;
1451
1820
  }
1452
1821
  }
1453
- throw new Error("The workspace kept changing while its file index was being built.");
1822
+ throw new HarnessWorkspaceError("The workspace kept changing while its file index was being built.");
1454
1823
  }
1455
1824
  async getWorkspaceIndex() {
1456
1825
  const cached = this.workspaceIndex;
@@ -1497,26 +1866,26 @@ class Workspace {
1497
1866
  async listFiles(relativePath = ".", options = {}) {
1498
1867
  const start = await this.safePath(relativePath);
1499
1868
  if (!(await lstat2(start.path)).isDirectory())
1500
- throw new Error("list_files requires a directory.");
1869
+ throw new HarnessWorkspaceError("list_files requires a directory.");
1501
1870
  const requestPath = wirePath(path4.relative(this.root, start.path)) || ".";
1502
1871
  const input = typeof options === "number" ? { limit: options } : options;
1503
1872
  const limit = input.limit ?? 200;
1504
1873
  const includeDigests = input.includeDigests ?? true;
1505
1874
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 5000)
1506
- throw new Error("limit must be between 1 and 5000.");
1875
+ throw new HarnessWorkspaceError("limit must be between 1 and 5000.");
1507
1876
  let after = "";
1508
1877
  let cursorIndexVersion;
1509
1878
  if (input.cursor) {
1510
1879
  const parsed = cursorDecode(input.cursor);
1511
1880
  if (parsed.v !== 2 || parsed.kind !== "list" || parsed.path !== requestPath || parsed.limit !== limit || parsed.includeDigests !== includeDigests || typeof parsed.indexVersion !== "string" || typeof parsed.after !== "string") {
1512
- throw new Error("The pagination cursor does not match this list request.");
1881
+ throw new HarnessWorkspaceError("The pagination cursor does not match this list request.");
1513
1882
  }
1514
1883
  after = parsed.after;
1515
1884
  cursorIndexVersion = parsed.indexVersion;
1516
1885
  }
1517
1886
  const index = await this.getWorkspaceIndex();
1518
1887
  if (cursorIndexVersion && cursorIndexVersion !== index.version) {
1519
- throw new Error("The pagination cursor is stale because the workspace changed.");
1888
+ throw new HarnessWorkspaceError("The pagination cursor is stale because the workspace changed.");
1520
1889
  }
1521
1890
  const prefix = requestPath === "." ? "" : `${requestPath}/`;
1522
1891
  let candidateIndex = after ? firstPathAfter(index.files, after) : requestPath === "." ? 0 : firstPathAtLeast(index.files, prefix);
@@ -1559,9 +1928,9 @@ class Workspace {
1559
1928
  }
1560
1929
  renderReadFile(file, startLine = 1, endLine) {
1561
1930
  if (!Number.isSafeInteger(startLine) || startLine < 1)
1562
- throw new Error("startLine must be a positive integer.");
1931
+ throw new HarnessWorkspaceError("startLine must be a positive integer.");
1563
1932
  if (endLine !== undefined && (!Number.isSafeInteger(endLine) || endLine < startLine)) {
1564
- throw new Error("endLine must be greater than or equal to startLine.");
1933
+ throw new HarnessWorkspaceError("endLine must be greater than or equal to startLine.");
1565
1934
  }
1566
1935
  const lines = file.contents.toString("utf8").split(/\r?\n/);
1567
1936
  const boundedEnd = Math.min(endLine ?? startLine + 399, startLine + 1999, lines.length);
@@ -1581,7 +1950,7 @@ class Workspace {
1581
1950
  }
1582
1951
  async readFiles(requests) {
1583
1952
  if (!Array.isArray(requests) || requests.length < 1 || requests.length > MAX_READ_BATCH_FILES) {
1584
- throw new Error(`readFiles requires between 1 and ${MAX_READ_BATCH_FILES} file requests.`);
1953
+ throw new HarnessWorkspaceError(`readFiles requires between 1 and ${MAX_READ_BATCH_FILES} file requests.`);
1585
1954
  }
1586
1955
  const ordered = requests.map((request) => ({
1587
1956
  ...request,
@@ -1591,14 +1960,14 @@ class Workspace {
1591
1960
  let totalBytes = 0;
1592
1961
  for (const request of ordered) {
1593
1962
  if (!Number.isSafeInteger(request.startLine ?? 1) || (request.startLine ?? 1) < 1 || request.endLine !== undefined && (!Number.isSafeInteger(request.endLine) || request.endLine < (request.startLine ?? 1))) {
1594
- throw new Error(`Invalid line range for ${request.path}.`);
1963
+ throw new HarnessWorkspaceError(`Invalid line range for ${request.path}.`);
1595
1964
  }
1596
1965
  if (stableFiles.has(request.path))
1597
1966
  continue;
1598
1967
  const file = await this.readStableFile(request.path, false);
1599
1968
  totalBytes += file.contents.byteLength;
1600
1969
  if (totalBytes > MAX_READ_BATCH_BYTES) {
1601
- throw new Error(`readFiles exceeds the aggregate ${MAX_READ_BATCH_BYTES}-byte source limit.`);
1970
+ throw new HarnessWorkspaceError(`readFiles exceeds the aggregate ${MAX_READ_BATCH_BYTES}-byte source limit.`);
1602
1971
  }
1603
1972
  stableFiles.set(request.path, file);
1604
1973
  }
@@ -1618,14 +1987,14 @@ class Workspace {
1618
1987
  }
1619
1988
  async searchFiles(query, relativePath = ".", options = {}) {
1620
1989
  if (!query || query.length > 200)
1621
- throw new Error("The search query must be between 1 and 200 characters.");
1990
+ throw new HarnessWorkspaceError("The search query must be between 1 and 200 characters.");
1622
1991
  const start = await this.safePath(relativePath);
1623
1992
  if (!(await lstat2(start.path)).isDirectory())
1624
- throw new Error("search_files requires a directory.");
1993
+ throw new HarnessWorkspaceError("search_files requires a directory.");
1625
1994
  const requestPath = wirePath(path4.relative(this.root, start.path)) || ".";
1626
1995
  const limit = options.limit ?? options.maxMatches ?? 100;
1627
1996
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
1628
- throw new Error("limit must be between 1 and 500.");
1997
+ throw new HarnessWorkspaceError("limit must be between 1 and 500.");
1629
1998
  const caseSensitive = options.caseSensitive ?? false;
1630
1999
  let afterPath = "";
1631
2000
  let afterLine = 0;
@@ -1633,7 +2002,7 @@ class Workspace {
1633
2002
  if (options.cursor) {
1634
2003
  const parsed = cursorDecode(options.cursor);
1635
2004
  if (parsed.v !== 2 || parsed.kind !== "search" || parsed.path !== requestPath || parsed.query !== query || parsed.caseSensitive !== caseSensitive || parsed.limit !== limit || typeof parsed.afterPath !== "string" || !Number.isSafeInteger(parsed.afterLine) || typeof parsed.indexVersion !== "string") {
1636
- throw new Error("The pagination cursor does not match this search request.");
2005
+ throw new HarnessWorkspaceError("The pagination cursor does not match this search request.");
1637
2006
  }
1638
2007
  afterPath = parsed.afterPath;
1639
2008
  afterLine = parsed.afterLine;
@@ -1641,7 +2010,7 @@ class Workspace {
1641
2010
  }
1642
2011
  const index = await this.getWorkspaceIndex();
1643
2012
  if (cursorIndexVersion && cursorIndexVersion !== index.version) {
1644
- throw new Error("The pagination cursor is stale because the workspace changed.");
2013
+ throw new HarnessWorkspaceError("The pagination cursor is stale because the workspace changed.");
1645
2014
  }
1646
2015
  const prefix = requestPath === "." ? "" : `${requestPath}/`;
1647
2016
  const needle = caseSensitive ? query : query.toLocaleLowerCase();
@@ -1696,20 +2065,20 @@ class Workspace {
1696
2065
  }
1697
2066
  async searchMany(queries, relativePath = ".", options = {}) {
1698
2067
  if (!Array.isArray(queries) || queries.length < 1 || queries.length > MAX_SEARCH_MANY_QUERIES) {
1699
- throw new Error(`searchMany requires between 1 and ${MAX_SEARCH_MANY_QUERIES} queries.`);
2068
+ throw new HarnessWorkspaceError(`searchMany requires between 1 and ${MAX_SEARCH_MANY_QUERIES} queries.`);
1700
2069
  }
1701
2070
  const limitPerQuery = options.limitPerQuery ?? 50;
1702
2071
  if (!Number.isSafeInteger(limitPerQuery) || limitPerQuery < 1 || limitPerQuery > MAX_SEARCH_MANY_MATCHES || limitPerQuery * queries.length > MAX_SEARCH_MANY_MATCHES) {
1703
- throw new Error(`searchMany allows at most ${MAX_SEARCH_MANY_MATCHES} aggregate matches.`);
2072
+ throw new HarnessWorkspaceError(`searchMany allows at most ${MAX_SEARCH_MANY_MATCHES} aggregate matches.`);
1704
2073
  }
1705
2074
  const seen = new Set;
1706
2075
  const states = queries.map((input) => {
1707
2076
  if (!input.query || input.query.length > 200)
1708
- throw new Error("Each search query must be between 1 and 200 characters.");
2077
+ throw new HarnessWorkspaceError("Each search query must be between 1 and 200 characters.");
1709
2078
  const caseSensitive = input.caseSensitive ?? false;
1710
2079
  const key = `${caseSensitive ? "1" : "0"}\x00${input.query}`;
1711
2080
  if (seen.has(key))
1712
- throw new Error("searchMany queries must be unique.");
2081
+ throw new HarnessWorkspaceError("searchMany queries must be unique.");
1713
2082
  seen.add(key);
1714
2083
  return {
1715
2084
  query: input.query,
@@ -1721,7 +2090,7 @@ class Workspace {
1721
2090
  });
1722
2091
  const start = await this.safePath(relativePath);
1723
2092
  if (!(await lstat2(start.path)).isDirectory())
1724
- throw new Error("searchMany requires a directory.");
2093
+ throw new HarnessWorkspaceError("searchMany requires a directory.");
1725
2094
  const requestPath = wirePath(path4.relative(this.root, start.path)) || ".";
1726
2095
  const prefix = requestPath === "." ? "" : `${requestPath}/`;
1727
2096
  const index = await this.getWorkspaceIndex();
@@ -1773,7 +2142,7 @@ class Workspace {
1773
2142
  async secureWorkspaceDirectory(directory, mode = 493) {
1774
2143
  const resolvedInput = path4.resolve(directory);
1775
2144
  if (!isInside(this.root, resolvedInput)) {
1776
- throw new Error("A mutation directory escapes the workspace.");
2145
+ throw new HarnessWorkspaceError("A mutation directory escapes the workspace.");
1777
2146
  }
1778
2147
  const segments = path4.relative(this.root, resolvedInput).split(path4.sep).filter(Boolean);
1779
2148
  let current = this.root;
@@ -1782,9 +2151,9 @@ class Workspace {
1782
2151
  try {
1783
2152
  const entry = await lstat2(current);
1784
2153
  if (entry.isSymbolicLink())
1785
- throw new Error("A mutation directory must not contain a symbolic link.");
2154
+ throw new HarnessWorkspaceError("A mutation directory must not contain a symbolic link.");
1786
2155
  if (!entry.isDirectory())
1787
- throw new Error("A mutation directory contains a non-directory entry.");
2156
+ throw new HarnessWorkspaceError("A mutation directory contains a non-directory entry.");
1788
2157
  } catch (error) {
1789
2158
  if (error.code !== "ENOENT")
1790
2159
  throw error;
@@ -1795,20 +2164,20 @@ class Workspace {
1795
2164
  throw mkdirError;
1796
2165
  const raced = await lstat2(current);
1797
2166
  if (raced.isSymbolicLink() || !raced.isDirectory()) {
1798
- throw new Error("A mutation directory changed during creation.");
2167
+ throw new HarnessWorkspaceError("A mutation directory changed during creation.");
1799
2168
  }
1800
2169
  }
1801
2170
  }
1802
2171
  }
1803
2172
  const canonical = await realpath(current);
1804
2173
  if (!isInside(this.root, canonical))
1805
- throw new Error("A mutation directory resolves outside the workspace.");
2174
+ throw new HarnessWorkspaceError("A mutation directory resolves outside the workspace.");
1806
2175
  return canonical;
1807
2176
  }
1808
2177
  async stageFile(target, contents, mode) {
1809
2178
  const directory = await this.secureWorkspaceDirectory(path4.dirname(target));
1810
2179
  const temporary = path4.join(directory, `.${path4.basename(target)}.zhivex-${randomUUID()}.tmp`);
1811
- const handle = await open(temporary, "wx", mode);
2180
+ const handle = await open2(temporary, "wx", mode);
1812
2181
  try {
1813
2182
  await handle.writeFile(contents);
1814
2183
  await handle.chmod(mode);
@@ -1829,11 +2198,11 @@ class Workspace {
1829
2198
  const targetPaths = new Set(proposal.changes.map((change) => change.path));
1830
2199
  for (const [targetPath, binding] of modes) {
1831
2200
  if (!targetPaths.has(targetPath)) {
1832
- throw new Error(`Patch mode binding has no matching content target: ${targetPath}.`);
2201
+ throw new HarnessWorkspaceError(`Patch mode binding has no matching content target: ${targetPath}.`);
1833
2202
  }
1834
2203
  for (const [label, mode] of [["before", binding.beforeMode], ["after", binding.afterMode]]) {
1835
2204
  if (mode !== undefined && (!Number.isSafeInteger(mode) || mode < 0 || mode > 511)) {
1836
- throw new Error(`Patch ${label} mode must be an integer between 0 and 0777: ${targetPath}.`);
2205
+ throw new HarnessWorkspaceError(`Patch ${label} mode must be an integer between 0 and 0777: ${targetPath}.`);
1837
2206
  }
1838
2207
  }
1839
2208
  }
@@ -1842,7 +2211,7 @@ class Workspace {
1842
2211
  const previous = ordered[index - 1];
1843
2212
  const current = ordered[index];
1844
2213
  if (previous && current && current.path.startsWith(`${previous.path}/`)) {
1845
- throw new Error(`Patch targets conflict as ancestor and descendant: ${previous.path}, ${current.path}.`);
2214
+ throw new HarnessWorkspaceError(`Patch targets conflict as ancestor and descendant: ${previous.path}, ${current.path}.`);
1846
2215
  }
1847
2216
  }
1848
2217
  const prepared = [];
@@ -1853,19 +2222,19 @@ class Workspace {
1853
2222
  let before;
1854
2223
  if (change.expectedDigest === null) {
1855
2224
  if (safe.exists)
1856
- throw new Error(`The patch target already exists: ${change.path}.`);
2225
+ throw new HarnessWorkspaceError(`The patch target already exists: ${change.path}.`);
1857
2226
  if (modeBinding?.beforeMode !== undefined) {
1858
- throw new Error(`Create-only patch mode binding cannot declare a before mode: ${change.path}.`);
2227
+ throw new HarnessWorkspaceError(`Create-only patch mode binding cannot declare a before mode: ${change.path}.`);
1859
2228
  }
1860
2229
  } else {
1861
2230
  if (!safe.exists)
1862
- throw new Error(`The patch target no longer exists: ${change.path}.`);
2231
+ throw new HarnessWorkspaceError(`The patch target no longer exists: ${change.path}.`);
1863
2232
  before = await this.readStableFile(change.path);
1864
2233
  if (before.digest !== change.expectedDigest) {
1865
- throw new Error(`Stale patch rejected for ${change.path}: expected ${change.expectedDigest}, found ${before.digest}.`);
2234
+ throw new HarnessWorkspaceError(`Stale patch rejected for ${change.path}: expected ${change.expectedDigest}, found ${before.digest}.`);
1866
2235
  }
1867
2236
  if (modeBinding?.beforeMode !== undefined && before.mode !== modeBinding.beforeMode) {
1868
- throw new Error(`Stale patch mode rejected for ${change.path}: expected ${modeBinding.beforeMode.toString(8)}, found ${before.mode.toString(8)}.`);
2237
+ throw new HarnessWorkspaceError(`Stale patch mode rejected for ${change.path}: expected ${modeBinding.beforeMode.toString(8)}, found ${before.mode.toString(8)}.`);
1869
2238
  }
1870
2239
  }
1871
2240
  const temporary = await this.stageFile(safe.path, change.content, modeBinding?.afterMode ?? before?.mode ?? 420);
@@ -1888,9 +2257,9 @@ class Workspace {
1888
2257
  if (item.before) {
1889
2258
  const current = await this.readStableFile(item.change.path);
1890
2259
  if (current.digest !== item.change.expectedDigest)
1891
- throw new Error(`Stale patch rejected for ${item.change.path}.`);
2260
+ throw new HarnessWorkspaceError(`Stale patch rejected for ${item.change.path}.`);
1892
2261
  if (item.modeBinding?.beforeMode !== undefined && current.mode !== item.modeBinding.beforeMode) {
1893
- throw new Error(`Stale patch mode rejected for ${item.change.path}.`);
2262
+ throw new HarnessWorkspaceError(`Stale patch mode rejected for ${item.change.path}.`);
1894
2263
  }
1895
2264
  await rename(item.temporary, item.target);
1896
2265
  } else {
@@ -1898,7 +2267,7 @@ class Workspace {
1898
2267
  await link(item.temporary, item.target);
1899
2268
  } catch (error) {
1900
2269
  if (error.code === "EEXIST") {
1901
- throw new Error(`The patch target was created concurrently: ${item.change.path}.`);
2270
+ throw new HarnessWorkspaceError(`The patch target was created concurrently: ${item.change.path}.`);
1902
2271
  }
1903
2272
  throw error;
1904
2273
  }
@@ -1937,7 +2306,7 @@ class Workspace {
1937
2306
  async writeFile(relativePath, content, overwrite = false) {
1938
2307
  const safe = await this.safePath(relativePath, { allowMissing: true });
1939
2308
  if (safe.exists && !overwrite)
1940
- throw new Error("The file already exists; use applyPatch with its expected digest.");
2309
+ throw new HarnessWorkspaceError("The file already exists; use applyPatch with its expected digest.");
1941
2310
  const before = safe.exists ? await this.readStableFile(relativePath) : undefined;
1942
2311
  const changes = [{ path: relativePath, expectedDigest: before?.digest ?? null, content }];
1943
2312
  const proposal = createEditProposal({ changes });
@@ -1946,12 +2315,12 @@ class Workspace {
1946
2315
  }
1947
2316
  async replaceInFile(relativePath, oldText, newText) {
1948
2317
  if (!oldText)
1949
- throw new Error("oldText cannot be empty.");
2318
+ throw new HarnessWorkspaceError("oldText cannot be empty.");
1950
2319
  const before = await this.readStableFile(relativePath, false);
1951
2320
  const contents = before.contents.toString("utf8");
1952
2321
  const occurrences = contents.split(oldText).length - 1;
1953
2322
  if (occurrences !== 1)
1954
- throw new Error(`oldText must occur exactly once; found ${occurrences} occurrences.`);
2323
+ throw new HarnessWorkspaceError(`oldText must occur exactly once; found ${occurrences} occurrences.`);
1955
2324
  const updated = contents.replace(oldText, newText);
1956
2325
  const changes = [{ path: relativePath, expectedDigest: before.digest, content: updated }];
1957
2326
  const proposal = createEditProposal({ changes });
@@ -1962,23 +2331,23 @@ class Workspace {
1962
2331
  const parsed = moveFileInputSchema.parse(input);
1963
2332
  const source = await this.readStableFile(parsed.source);
1964
2333
  if (source.digest !== parsed.expectedDigest)
1965
- throw new Error(`Stale move rejected for ${parsed.source}.`);
2334
+ throw new HarnessWorkspaceError(`Stale move rejected for ${parsed.source}.`);
1966
2335
  const destination = await this.safePath(parsed.destination, { allowMissing: true });
1967
2336
  if (destination.exists)
1968
- throw new Error(`Move destination already exists: ${parsed.destination}.`);
2337
+ throw new HarnessWorkspaceError(`Move destination already exists: ${parsed.destination}.`);
1969
2338
  await this.secureWorkspaceDirectory(path4.dirname(destination.path));
1970
2339
  const destinationRecheck = await this.safePath(parsed.destination, { allowMissing: true });
1971
2340
  if (destinationRecheck.exists)
1972
- throw new Error(`Move destination already exists: ${parsed.destination}.`);
2341
+ throw new HarnessWorkspaceError(`Move destination already exists: ${parsed.destination}.`);
1973
2342
  if ((await this.readStableFile(parsed.source)).digest !== parsed.expectedDigest)
1974
- throw new Error(`Stale move rejected for ${parsed.source}.`);
2343
+ throw new HarnessWorkspaceError(`Stale move rejected for ${parsed.source}.`);
1975
2344
  let linked = false;
1976
2345
  try {
1977
2346
  await link(source.absolutePath, destination.path);
1978
2347
  linked = true;
1979
2348
  const linkedFile = await this.readStableFile(parsed.destination);
1980
2349
  if (linkedFile.digest !== source.digest) {
1981
- throw new Error(`Move destination changed before commit: ${parsed.destination}.`);
2350
+ throw new HarnessWorkspaceError(`Move destination changed before commit: ${parsed.destination}.`);
1982
2351
  }
1983
2352
  await unlink(source.absolutePath);
1984
2353
  } catch (error) {
@@ -1998,10 +2367,10 @@ class Workspace {
1998
2367
  try {
1999
2368
  const entry = await lstat2(current);
2000
2369
  if (entry.isSymbolicLink()) {
2001
- throw new Error("Harness quarantine must not resolve through a symbolic link.");
2370
+ throw new HarnessWorkspaceError("Harness quarantine must not resolve through a symbolic link.");
2002
2371
  }
2003
2372
  if (!entry.isDirectory()) {
2004
- throw new Error("Harness quarantine path contains a non-directory entry.");
2373
+ throw new HarnessWorkspaceError("Harness quarantine path contains a non-directory entry.");
2005
2374
  }
2006
2375
  } catch (error) {
2007
2376
  if (error.code !== "ENOENT" || !create)
@@ -2013,14 +2382,14 @@ class Workspace {
2013
2382
  throw mkdirError;
2014
2383
  const racedEntry = await lstat2(current);
2015
2384
  if (racedEntry.isSymbolicLink() || !racedEntry.isDirectory()) {
2016
- throw new Error("Harness quarantine path changed during creation.");
2385
+ throw new HarnessWorkspaceError("Harness quarantine path changed during creation.");
2017
2386
  }
2018
2387
  }
2019
2388
  }
2020
2389
  }
2021
2390
  const resolved = await realpath(current);
2022
2391
  if (!isInside(this.root, resolved))
2023
- throw new Error("Harness quarantine resolves outside the workspace.");
2392
+ throw new HarnessWorkspaceError("Harness quarantine resolves outside the workspace.");
2024
2393
  return resolved;
2025
2394
  }
2026
2395
  async writeManifest(manifest) {
@@ -2031,32 +2400,22 @@ class Workspace {
2031
2400
  await rename(temporary, target);
2032
2401
  }
2033
2402
  async readInternalRegularFile(target, label, maxBytes) {
2034
- const before = await lstat2(target);
2035
- if (before.isSymbolicLink() || !before.isFile())
2036
- throw new Error(`${label} must be a regular non-symlink file.`);
2037
- if (before.size > maxBytes)
2038
- throw new Error(`${label} exceeds its size limit.`);
2039
- const contents = await readFile(target);
2040
- const after = await lstat2(target);
2041
- if (after.isSymbolicLink() || !after.isFile() || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs) {
2042
- throw new Error(`${label} changed while it was being read.`);
2043
- }
2044
- return { contents, stat: before };
2403
+ return await readRegularFileNoFollow(target, { label, maxBytes });
2045
2404
  }
2046
2405
  async quarantineFile(input) {
2047
2406
  const parsed = quarantineFileInputSchema.parse(input);
2048
2407
  const source = await this.readStableFile(parsed.path);
2049
2408
  if (source.digest !== parsed.expectedDigest)
2050
- throw new Error(`Stale quarantine rejected for ${parsed.path}.`);
2409
+ throw new HarnessWorkspaceError(`Stale quarantine rejected for ${parsed.path}.`);
2051
2410
  const quarantineId = `${Date.now()}-${randomUUID()}`;
2052
2411
  const directory = await this.secureQuarantineDirectory(true);
2053
2412
  const dataPath = path4.join(directory, `${quarantineId}.data`);
2054
2413
  if ((await this.readStableFile(parsed.path)).digest !== parsed.expectedDigest)
2055
- throw new Error(`Stale quarantine rejected for ${parsed.path}.`);
2414
+ throw new HarnessWorkspaceError(`Stale quarantine rejected for ${parsed.path}.`);
2056
2415
  await link(source.absolutePath, dataPath);
2057
- if (digestBytes(await readFile(dataPath)) !== source.digest) {
2416
+ if (digestBytes((await this.readInternalRegularFile(dataPath, "Quarantine payload", MAX_FILE_BYTES)).contents) !== source.digest) {
2058
2417
  await unlink(dataPath).catch(() => {});
2059
- throw new Error(`Quarantine payload changed before commit: ${parsed.path}.`);
2418
+ throw new HarnessWorkspaceError(`Quarantine payload changed before commit: ${parsed.path}.`);
2060
2419
  }
2061
2420
  const manifest = {
2062
2421
  schemaVersion: 1,
@@ -2087,34 +2446,34 @@ class Workspace {
2087
2446
  const manifestFile = await this.readInternalRegularFile(path4.join(directory, `${parsed.quarantineId}.json`), "Quarantine manifest", 64 * 1024);
2088
2447
  manifest = JSON.parse(manifestFile.contents.toString("utf8"));
2089
2448
  } catch {
2090
- throw new Error(`Quarantine entry was not found: ${parsed.quarantineId}.`);
2449
+ throw new HarnessWorkspaceError(`Quarantine entry was not found: ${parsed.quarantineId}.`);
2091
2450
  }
2092
2451
  if (manifest.schemaVersion !== 1 || manifest.quarantineId !== parsed.quarantineId || manifest.status !== "quarantined") {
2093
- throw new Error(`Quarantine entry is not restorable: ${parsed.quarantineId}.`);
2452
+ throw new HarnessWorkspaceError(`Quarantine entry is not restorable: ${parsed.quarantineId}.`);
2094
2453
  }
2095
2454
  const dataPath = path4.join(directory, `${parsed.quarantineId}.data`);
2096
2455
  const dataFile = await this.readInternalRegularFile(dataPath, "Quarantine payload", MAX_FILE_BYTES);
2097
2456
  const digest2 = digestBytes(dataFile.contents);
2098
2457
  if (digest2 !== manifest.digest || parsed.expectedDigest && parsed.expectedDigest !== digest2) {
2099
- throw new Error(`Quarantine digest mismatch: ${parsed.quarantineId}.`);
2458
+ throw new HarnessWorkspaceError(`Quarantine digest mismatch: ${parsed.quarantineId}.`);
2100
2459
  }
2101
2460
  const destinationPath = parsed.destination ?? manifest.originalPath;
2102
2461
  const destination = await this.safePath(destinationPath, { allowMissing: true });
2103
2462
  if (destination.exists)
2104
- throw new Error(`Restore destination already exists: ${destinationPath}.`);
2463
+ throw new HarnessWorkspaceError(`Restore destination already exists: ${destinationPath}.`);
2105
2464
  await this.secureWorkspaceDirectory(path4.dirname(destination.path));
2106
2465
  const destinationRecheck = await this.safePath(destinationPath, { allowMissing: true });
2107
2466
  if (destinationRecheck.exists)
2108
- throw new Error(`Restore destination already exists: ${destinationPath}.`);
2467
+ throw new HarnessWorkspaceError(`Restore destination already exists: ${destinationPath}.`);
2109
2468
  const dataRecheck = await lstat2(dataPath);
2110
2469
  if (dataRecheck.isSymbolicLink() || !dataRecheck.isFile() || dataRecheck.dev !== dataFile.stat.dev || dataRecheck.ino !== dataFile.stat.ino || dataRecheck.size !== dataFile.stat.size || dataRecheck.mtimeMs !== dataFile.stat.mtimeMs) {
2111
- throw new Error("Quarantine payload changed before restore commit.");
2470
+ throw new HarnessWorkspaceError("Quarantine payload changed before restore commit.");
2112
2471
  }
2113
2472
  await link(dataPath, destination.path);
2114
- const linkedDestination = await lstat2(destination.path);
2115
- if (linkedDestination.isSymbolicLink() || !linkedDestination.isFile() || linkedDestination.dev !== dataFile.stat.dev || linkedDestination.ino !== dataFile.stat.ino || digestBytes(await readFile(destination.path)) !== digest2) {
2473
+ const linkedDestination = await this.readInternalRegularFile(destination.path, "Restore destination", MAX_FILE_BYTES);
2474
+ if (linkedDestination.stat.dev !== dataFile.stat.dev || linkedDestination.stat.ino !== dataFile.stat.ino || digestBytes(linkedDestination.contents) !== digest2) {
2116
2475
  await unlink(destination.path).catch(() => {});
2117
- throw new Error("Restore destination did not match the quarantined payload.");
2476
+ throw new HarnessWorkspaceError("Restore destination did not match the quarantined payload.");
2118
2477
  }
2119
2478
  const restoredManifest = {
2120
2479
  ...manifest,
@@ -2154,7 +2513,7 @@ class Workspace {
2154
2513
  manifest = JSON.parse((await this.readStableFile("package.json", false)).contents.toString("utf8"));
2155
2514
  } catch (error) {
2156
2515
  if (error.code === "ENOENT")
2157
- throw new Error("The workspace does not contain a package.json file.");
2516
+ throw new HarnessWorkspaceError("The workspace does not contain a package.json file.");
2158
2517
  throw error;
2159
2518
  }
2160
2519
  const resolved = await resolvePackageCheckCommand(this.root, manifest, check, expectedScript, allowedChecks);
@@ -2175,7 +2534,7 @@ class Workspace {
2175
2534
  }
2176
2535
 
2177
2536
  // src/operations.ts
2178
- import { chmod, lstat as lstat4, mkdir as mkdir2, open as open2 } from "node:fs/promises";
2537
+ import { chmod, lstat as lstat4, mkdir as mkdir2, open as open3 } from "node:fs/promises";
2179
2538
  import path6 from "node:path";
2180
2539
  import {
2181
2540
  cancelAgentRun,
@@ -2271,22 +2630,22 @@ var isInside2 = (root, candidate) => {
2271
2630
  };
2272
2631
  var validateStateDirectory = async (workspace, stateDirectory) => {
2273
2632
  if (stateDirectory === workspace || stateDirectory === path5.parse(stateDirectory).root) {
2274
- throw new Error("The state directory cannot be the workspace or filesystem root.");
2633
+ throw new HarnessWorkspaceError("The state directory cannot be the workspace or filesystem root.");
2275
2634
  }
2276
2635
  const insideWorkspace = isInside2(workspace, stateDirectory);
2277
2636
  const relativeSegments = insideWorkspace ? path5.relative(workspace, stateDirectory).split(path5.sep).filter(Boolean) : stateDirectory.slice(path5.parse(stateDirectory).root.length).split(path5.sep).filter(Boolean);
2278
2637
  const sensitiveSegment = insideWorkspace ? relativeSegments.find((segment) => SENSITIVE_STATE_SEGMENTS.has(segment)) : undefined;
2279
2638
  if (sensitiveSegment) {
2280
- throw new Error(`The state directory is inside the protected workspace path: ${sensitiveSegment}.`);
2639
+ throw new HarnessWorkspaceError(`The state directory is inside the protected workspace path: ${sensitiveSegment}.`);
2281
2640
  }
2282
2641
  if (!insideWorkspace) {
2283
2642
  try {
2284
2643
  const externalEntry = await lstat3(stateDirectory);
2285
2644
  if (externalEntry.isSymbolicLink()) {
2286
- throw new Error(`The state directory must not be a symbolic link: ${stateDirectory}.`);
2645
+ throw new HarnessWorkspaceError(`The state directory must not be a symbolic link: ${stateDirectory}.`);
2287
2646
  }
2288
2647
  if (!externalEntry.isDirectory()) {
2289
- throw new Error(`The state directory is not a directory: ${stateDirectory}.`);
2648
+ throw new HarnessWorkspaceError(`The state directory is not a directory: ${stateDirectory}.`);
2290
2649
  }
2291
2650
  } catch (error) {
2292
2651
  if (error.code !== "ENOENT") {
@@ -2301,10 +2660,10 @@ var validateStateDirectory = async (workspace, stateDirectory) => {
2301
2660
  try {
2302
2661
  const entry = await lstat3(current);
2303
2662
  if (entry.isSymbolicLink()) {
2304
- throw new Error(`The state directory must not resolve through a symbolic link: ${current}.`);
2663
+ throw new HarnessWorkspaceError(`The state directory must not resolve through a symbolic link: ${current}.`);
2305
2664
  }
2306
2665
  if (!entry.isDirectory()) {
2307
- throw new Error(`The state directory path contains a non-directory entry: ${current}.`);
2666
+ throw new HarnessWorkspaceError(`The state directory path contains a non-directory entry: ${current}.`);
2308
2667
  }
2309
2668
  } catch (error) {
2310
2669
  if (error.code === "ENOENT") {
@@ -2346,7 +2705,7 @@ var runSummary = (state) => {
2346
2705
  };
2347
2706
  var listHarnessRuns = async (store, config, query = {}) => {
2348
2707
  if (!store.list) {
2349
- throw new Error(`The ${config.storeBackend} run store does not support listing.`);
2708
+ throw new HarnessStateConflictError(`The ${config.storeBackend} run store does not support listing.`);
2350
2709
  }
2351
2710
  const page = await store.list(query, config.scope);
2352
2711
  return {
@@ -2361,7 +2720,7 @@ var listHarnessRuns = async (store, config, query = {}) => {
2361
2720
  var inspectHarnessRun = async (store, config, runId) => {
2362
2721
  const state = await store.load(runId, config.scope);
2363
2722
  if (!state) {
2364
- throw new Error(`Run ${runId} was not found in ${config.stateDirectory}.`);
2723
+ throw new HarnessStateConflictError(`Run ${runId} was not found in ${config.stateDirectory}.`);
2365
2724
  }
2366
2725
  const redaction = createRedactionPolicy({ includeEmails: true });
2367
2726
  const traceOptions = createProductionTraceOptions({
@@ -2428,7 +2787,7 @@ var cancelHarnessRun = async (store, config, runId, options = {}) => {
2428
2787
  };
2429
2788
  const result = options.cascade ? await cancelAgentRunTree(store, runId, cancellationOptions) : await cancelAgentRun(store, runId, cancellationOptions);
2430
2789
  if (!result || "parent" in result && !result.parent) {
2431
- throw new Error(`Run ${runId} was not found in ${config.stateDirectory}.`);
2790
+ throw new HarnessStateConflictError(`Run ${runId} was not found in ${config.stateDirectory}.`);
2432
2791
  }
2433
2792
  return {
2434
2793
  schemaVersion: HARNESS_OPERATIONS_SCHEMA_VERSION,
@@ -2442,7 +2801,7 @@ var cancelHarnessRun = async (store, config, runId, options = {}) => {
2442
2801
  };
2443
2802
  var cleanupHarnessRuns = async (store, config, options) => {
2444
2803
  if (!store.deleteExpired) {
2445
- throw new Error(`The ${config.storeBackend} run store does not support retention cleanup.`);
2804
+ throw new HarnessStateConflictError(`The ${config.storeBackend} run store does not support retention cleanup.`);
2446
2805
  }
2447
2806
  const statuses = options.statuses?.length ? options.statuses : [...TERMINAL_RUN_STATUSES];
2448
2807
  const deleted = await store.deleteExpired({
@@ -2488,7 +2847,7 @@ var ensurePrivateStateDirectory = async (directory) => {
2488
2847
  await mkdir2(directory, { recursive: true, mode: 448 });
2489
2848
  const entry = await lstat4(directory);
2490
2849
  if (entry.isSymbolicLink() || !entry.isDirectory()) {
2491
- throw new Error(`The state directory must be a real directory: ${directory}.`);
2850
+ throw new HarnessWorkspaceError(`The state directory must be a real directory: ${directory}.`);
2492
2851
  }
2493
2852
  await chmod(directory, 448);
2494
2853
  };
@@ -2552,23 +2911,16 @@ var openHarnessPersistence = async (config, options = {}) => {
2552
2911
  const databasePath = path6.join(config.stateDirectory, HARNESS_SQLITE_FILE);
2553
2912
  let databaseEntry;
2554
2913
  try {
2914
+ const handle = await open3(databasePath, "wx", 384);
2915
+ await handle.close();
2555
2916
  databaseEntry = await lstat4(databasePath);
2556
2917
  } catch (error) {
2557
- if (error.code !== "ENOENT") {
2918
+ if (error.code !== "EEXIST")
2558
2919
  throw error;
2559
- }
2560
- try {
2561
- const handle = await open2(databasePath, "wx", 384);
2562
- await handle.close();
2563
- } catch (creationError) {
2564
- if (creationError.code !== "EEXIST") {
2565
- throw creationError;
2566
- }
2567
- }
2568
2920
  databaseEntry = await lstat4(databasePath);
2569
2921
  }
2570
2922
  if (databaseEntry.isSymbolicLink() || !databaseEntry.isFile()) {
2571
- throw new Error(`The SQLite state path must be a real file: ${databasePath}.`);
2923
+ throw new HarnessWorkspaceError(`The SQLite state path must be a real file: ${databasePath}.`);
2572
2924
  }
2573
2925
  const database = new SqliteDatabase(databasePath, { create: false, strict: true });
2574
2926
  let closed = false;
@@ -2581,7 +2933,7 @@ var openHarnessPersistence = async (config, options = {}) => {
2581
2933
  try {
2582
2934
  const openedEntry = await lstat4(databasePath);
2583
2935
  if (openedEntry.isSymbolicLink() || !openedEntry.isFile() || openedEntry.dev !== databaseEntry.dev || openedEntry.ino !== databaseEntry.ino) {
2584
- throw new Error(`The SQLite state path changed while it was being opened: ${databasePath}.`);
2936
+ throw new HarnessWorkspaceError(`The SQLite state path changed while it was being opened: ${databasePath}.`);
2585
2937
  }
2586
2938
  database.exec("PRAGMA journal_mode = WAL");
2587
2939
  database.exec("PRAGMA busy_timeout = 5000");
@@ -2606,7 +2958,7 @@ var openHarnessPersistence = async (config, options = {}) => {
2606
2958
  };
2607
2959
 
2608
2960
  // src/mcp.ts
2609
- import { lstat as lstat5, readFile as readFile2, realpath as realpath2 } from "node:fs/promises";
2961
+ import { lstat as lstat5, readFile, realpath as realpath2 } from "node:fs/promises";
2610
2962
  import path7 from "node:path";
2611
2963
  import {
2612
2964
  createMcpToolSet,
@@ -2640,6 +2992,7 @@ var HARNESS_MCP_PERMISSIONS = [
2640
2992
  ];
2641
2993
  var identifier = z2.string().min(1).max(64).regex(/^[A-Za-z][A-Za-z0-9_-]*$/);
2642
2994
  var toolName = z2.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9_.:/-]*$/);
2995
+ var mcpCredentialEnvironmentVariable = z2.string().min(12).max(128).regex(/^ZHIVEX_MCP_[A-Z0-9_]+$/);
2643
2996
  var serverSchema = z2.object({
2644
2997
  name: identifier,
2645
2998
  transport: z2.enum(["http", "custom"]),
@@ -2648,7 +3001,7 @@ var serverSchema = z2.object({
2648
3001
  excludeTools: z2.array(toolName).max(200).default([]),
2649
3002
  toolNamePrefix: z2.string().min(1).max(80).regex(/^[A-Za-z][A-Za-z0-9_]*$/).optional(),
2650
3003
  permissions: z2.array(z2.enum(HARNESS_MCP_PERMISSIONS)).min(1).max(4),
2651
- headerEnv: z2.record(z2.string().min(1).max(128).regex(/^[A-Za-z0-9-]+$/), z2.string().min(1).max(128).regex(/^[A-Za-z_][A-Za-z0-9_]*$/)).default({}),
3004
+ headerEnv: z2.record(z2.string().min(1).max(128).regex(/^[A-Za-z0-9-]+$/), mcpCredentialEnvironmentVariable).default({}),
2652
3005
  trustServerToolAnnotations: z2.boolean().default(false),
2653
3006
  maxListPages: z2.number().int().min(1).max(20).default(5),
2654
3007
  maxListedTools: z2.number().int().min(1).max(500).default(100),
@@ -2689,7 +3042,11 @@ var forbiddenHeaders = new Set([
2689
3042
  "mcp-session-id",
2690
3043
  "transfer-encoding"
2691
3044
  ]);
2692
- var normalizeHarnessMcpConfiguration = (value) => {
3045
+ var credentialHeaders = new Map([
3046
+ ["authorization", "authorization"],
3047
+ ["x-api-key", "x-api-key"]
3048
+ ]);
3049
+ var normalizeHarnessMcpConfigurationUnsafe = (value) => {
2693
3050
  const parsed = configurationSchema.parse(value);
2694
3051
  const names = new Set;
2695
3052
  const prefixes = new Set;
@@ -2708,10 +3065,20 @@ var normalizeHarnessMcpConfiguration = (value) => {
2708
3065
  if (includeTools.some((name) => excludeTools.includes(name))) {
2709
3066
  throw new Error(`MCP server ${server.name} includes and excludes the same tool.`);
2710
3067
  }
2711
- for (const header of Object.keys(server.headerEnv)) {
2712
- if (forbiddenHeaders.has(header.toLowerCase())) {
3068
+ const headerEnv = {};
3069
+ for (const [header, variable] of Object.entries(server.headerEnv)) {
3070
+ const lowerHeader = header.toLowerCase();
3071
+ if (forbiddenHeaders.has(lowerHeader)) {
2713
3072
  throw new Error(`MCP server ${server.name} cannot configure header ${header}.`);
2714
3073
  }
3074
+ const canonicalHeader = credentialHeaders.get(lowerHeader);
3075
+ if (!canonicalHeader) {
3076
+ throw new Error(`MCP server ${server.name} supports only authorization and x-api-key credential headers.`);
3077
+ }
3078
+ if (headerEnv[canonicalHeader]) {
3079
+ throw new Error(`MCP server ${server.name} configures duplicate header ${canonicalHeader}.`);
3080
+ }
3081
+ headerEnv[canonicalHeader] = variable;
2715
3082
  }
2716
3083
  if (server.transport === "http" && !server.url) {
2717
3084
  throw new Error(`MCP server ${server.name} requires url for HTTP transport.`);
@@ -2734,7 +3101,7 @@ var normalizeHarnessMcpConfiguration = (value) => {
2734
3101
  excludeTools,
2735
3102
  toolNamePrefix: prefix,
2736
3103
  permissions: [...new Set(server.permissions)],
2737
- headerEnv: { ...server.headerEnv },
3104
+ headerEnv,
2738
3105
  trustServerToolAnnotations: server.trustServerToolAnnotations,
2739
3106
  maxListPages: server.maxListPages,
2740
3107
  maxListedTools: server.maxListedTools,
@@ -2745,29 +3112,49 @@ var normalizeHarnessMcpConfiguration = (value) => {
2745
3112
  });
2746
3113
  return { schemaVersion: HARNESS_MCP_CONFIG_SCHEMA_VERSION, servers };
2747
3114
  };
2748
- var loadHarnessMcpConfiguration = async (workspace, configPath) => {
3115
+ var normalizeHarnessMcpConfiguration = (value) => {
3116
+ try {
3117
+ return normalizeHarnessMcpConfigurationUnsafe(value);
3118
+ } catch (error) {
3119
+ if (error instanceof HarnessError)
3120
+ throw error;
3121
+ throw new HarnessConfigError(error instanceof Error ? error.message : "Harness MCP configuration is invalid.", { cause: error });
3122
+ }
3123
+ };
3124
+ var loadHarnessMcpConfigurationUnsafe = async (workspace, configPath) => {
2749
3125
  const entry = await lstat5(configPath);
2750
3126
  if (entry.isSymbolicLink() || !entry.isFile()) {
2751
- throw new Error(`MCP configuration must be a regular non-symlink file: ${configPath}.`);
3127
+ throw new HarnessWorkspaceError(`MCP configuration must be a regular non-symlink file: ${configPath}.`);
2752
3128
  }
2753
3129
  if (entry.size > 1024 * 1024) {
2754
- throw new Error("MCP configuration cannot exceed 1 MiB.");
3130
+ throw new HarnessConfigError("MCP configuration cannot exceed 1 MiB.");
2755
3131
  }
2756
3132
  const [canonicalWorkspace, canonicalConfig] = await Promise.all([
2757
3133
  realpath2(workspace),
2758
3134
  realpath2(configPath)
2759
3135
  ]);
2760
3136
  if (!isInsidePath(canonicalWorkspace, canonicalConfig)) {
2761
- throw new Error("MCP configuration must remain inside the canonical workspace.");
3137
+ throw new HarnessWorkspaceError("MCP configuration must remain inside the canonical workspace.");
2762
3138
  }
2763
3139
  let value;
2764
3140
  try {
2765
- value = JSON.parse(await readFile2(canonicalConfig, "utf8"));
3141
+ value = JSON.parse(await readFile(canonicalConfig, "utf8"));
2766
3142
  } catch (error) {
2767
- throw new Error("MCP configuration is not valid JSON.", { cause: error });
3143
+ throw new HarnessConfigError("MCP configuration is not valid JSON.", { cause: error });
2768
3144
  }
2769
3145
  return normalizeHarnessMcpConfiguration(value);
2770
3146
  };
3147
+ var loadHarnessMcpConfiguration = async (workspace, configPath) => {
3148
+ try {
3149
+ return await loadHarnessMcpConfigurationUnsafe(workspace, configPath);
3150
+ } catch (error) {
3151
+ if (error instanceof HarnessError)
3152
+ throw error;
3153
+ throw new HarnessWorkspaceError(`MCP configuration could not be read safely: ${configPath}.`, {
3154
+ cause: error
3155
+ });
3156
+ }
3157
+ };
2771
3158
  var promptInjectionPatterns = [
2772
3159
  /ignore\s+(?:all\s+|any\s+|the\s+)?(?:previous|prior|earlier)\s+instructions/i,
2773
3160
  /(?:system|developer)\s+(?:message|prompt|instruction)/i,
@@ -2778,7 +3165,7 @@ var assertSafeMcpPayload = (serverName, value) => {
2778
3165
  const serialized = JSON.stringify(value);
2779
3166
  const matched = promptInjectionPatterns.find((pattern) => pattern.test(serialized));
2780
3167
  if (matched) {
2781
- throw new Error(`MCP server ${serverName} returned probable prompt-injection content.`);
3168
+ throw new HarnessExecutionError(`MCP server ${serverName} returned probable prompt-injection content.`);
2782
3169
  }
2783
3170
  return serialized;
2784
3171
  };
@@ -2787,7 +3174,7 @@ var boundedClient = (client, server) => ({
2787
3174
  const result = await client.listTools(input, options);
2788
3175
  const serialized = assertSafeMcpPayload(server.name, result);
2789
3176
  if (new TextEncoder().encode(serialized).byteLength > server.maxOutputBytes) {
2790
- throw new Error(`MCP server ${server.name} tool discovery exceeded ${server.maxOutputBytes} bytes.`);
3177
+ throw new HarnessExecutionError(`MCP server ${server.name} tool discovery exceeded ${server.maxOutputBytes} bytes.`);
2791
3178
  }
2792
3179
  return result;
2793
3180
  },
@@ -2795,7 +3182,7 @@ var boundedClient = (client, server) => ({
2795
3182
  const result = await client.callTool(input, options);
2796
3183
  const serialized = assertSafeMcpPayload(server.name, result);
2797
3184
  if (new TextEncoder().encode(serialized).byteLength > server.maxOutputBytes) {
2798
- throw new Error(`MCP server ${server.name} result exceeded ${server.maxOutputBytes} bytes.`);
3185
+ throw new HarnessExecutionError(`MCP server ${server.name} result exceeded ${server.maxOutputBytes} bytes.`);
2799
3186
  }
2800
3187
  return result;
2801
3188
  }
@@ -2829,7 +3216,7 @@ var readBoundedBody = async (response, limit) => {
2829
3216
  total += value.byteLength;
2830
3217
  if (total > limit) {
2831
3218
  await reader.cancel();
2832
- throw new Error(`MCP HTTP response exceeded ${limit} bytes.`);
3219
+ throw new HarnessExecutionError(`MCP HTTP response exceeded ${limit} bytes.`);
2833
3220
  }
2834
3221
  chunks.push(value);
2835
3222
  }
@@ -2858,29 +3245,45 @@ var parseHttpPayload = (body, contentType) => {
2858
3245
  };
2859
3246
  var createHttpMcpClient = (server, env = process.env, fetchImplementation = fetch) => {
2860
3247
  if (server.transport !== "http" || !server.url) {
2861
- throw new Error(`MCP server ${server.name} is not configured for HTTP transport.`);
3248
+ throw new HarnessConfigError(`MCP server ${server.name} is not configured for HTTP transport.`);
3249
+ }
3250
+ let staticHeaders;
3251
+ try {
3252
+ staticHeaders = resolveHeaders(server, env);
3253
+ } catch (error) {
3254
+ throw new HarnessConfigError(`MCP server ${server.name} headers are not configured safely.`, { cause: error });
2862
3255
  }
2863
- const staticHeaders = resolveHeaders(server, env);
2864
3256
  let sessionId;
2865
3257
  let requestId = 0;
2866
3258
  let initialization;
2867
3259
  const post = async (payload, options = {}, expectResponse = true) => {
2868
- const response = await fetchImplementation(server.url, {
2869
- method: "POST",
2870
- redirect: "error",
2871
- headers: {
2872
- ...staticHeaders,
2873
- "content-type": "application/json",
2874
- accept: "application/json, text/event-stream",
2875
- "mcp-protocol-version": "2025-06-18",
2876
- ...sessionId ? { "mcp-session-id": sessionId } : {}
2877
- },
2878
- body: JSON.stringify(payload),
2879
- ...options.abortSignal ? { signal: options.abortSignal } : {}
2880
- });
3260
+ let response;
3261
+ try {
3262
+ response = await fetchImplementation(server.url, {
3263
+ method: "POST",
3264
+ redirect: "error",
3265
+ headers: {
3266
+ ...staticHeaders,
3267
+ "content-type": "application/json",
3268
+ accept: "application/json, text/event-stream",
3269
+ "mcp-protocol-version": "2025-06-18",
3270
+ ...sessionId ? { "mcp-session-id": sessionId } : {}
3271
+ },
3272
+ body: JSON.stringify(payload),
3273
+ ...options.abortSignal ? { signal: options.abortSignal } : {}
3274
+ });
3275
+ } catch (error) {
3276
+ throw new HarnessProviderError(`MCP server ${server.name} could not be reached.`, {
3277
+ cause: error,
3278
+ retryable: true
3279
+ });
3280
+ }
2881
3281
  if (!response.ok) {
2882
3282
  await response.body?.cancel();
2883
- throw new Error(`MCP server ${server.name} returned HTTP ${response.status}.`);
3283
+ throw new HarnessProviderError(`MCP server ${server.name} returned HTTP ${response.status}.`, {
3284
+ cause: Object.assign(new Error("MCP HTTP failure"), { status: response.status }),
3285
+ retryable: response.status === 429 || response.status >= 500
3286
+ });
2884
3287
  }
2885
3288
  sessionId = response.headers.get("mcp-session-id") ?? sessionId;
2886
3289
  if (!expectResponse) {
@@ -2888,21 +3291,25 @@ var createHttpMcpClient = (server, env = process.env, fetchImplementation = fetc
2888
3291
  return;
2889
3292
  }
2890
3293
  const body = await readBoundedBody(response, server.maxOutputBytes);
2891
- return parseHttpPayload(body, response.headers.get("content-type"));
3294
+ try {
3295
+ return parseHttpPayload(body, response.headers.get("content-type"));
3296
+ } catch (error) {
3297
+ throw new HarnessExecutionError(`MCP server ${server.name} returned an invalid response.`, { cause: error });
3298
+ }
2892
3299
  };
2893
3300
  const rpc = async (method, params, options = {}) => {
2894
3301
  const id = ++requestId;
2895
3302
  const payload = await post({ jsonrpc: "2.0", id, method, params }, options);
2896
3303
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
2897
- throw new Error(`MCP server ${server.name} returned an invalid JSON-RPC response.`);
3304
+ throw new HarnessExecutionError(`MCP server ${server.name} returned an invalid JSON-RPC response.`);
2898
3305
  }
2899
3306
  const record = payload;
2900
3307
  if (record.id !== id) {
2901
- throw new Error(`MCP server ${server.name} returned a mismatched JSON-RPC id.`);
3308
+ throw new HarnessExecutionError(`MCP server ${server.name} returned a mismatched JSON-RPC id.`);
2902
3309
  }
2903
3310
  if (record.error && typeof record.error === "object") {
2904
3311
  const message = record.error.message;
2905
- throw new Error(`MCP server ${server.name} JSON-RPC error: ${typeof message === "string" ? message : "unknown error"}.`);
3312
+ throw new HarnessExecutionError(`MCP server ${server.name} JSON-RPC error: ${typeof message === "string" ? message : "unknown error"}.`);
2906
3313
  }
2907
3314
  return record.result;
2908
3315
  };
@@ -2914,11 +3321,11 @@ var createHttpMcpClient = (server, env = process.env, fetchImplementation = fetc
2914
3321
  clientInfo: { name: "zhivex-harness", version: HARNESS_VERSION }
2915
3322
  }, options);
2916
3323
  if (!result || typeof result !== "object" || Array.isArray(result)) {
2917
- throw new Error(`MCP server ${server.name} returned an invalid initialize result.`);
3324
+ throw new HarnessExecutionError(`MCP server ${server.name} returned an invalid initialize result.`);
2918
3325
  }
2919
3326
  const negotiatedVersion = result.protocolVersion;
2920
3327
  if (negotiatedVersion !== "2025-06-18") {
2921
- throw new Error(`MCP server ${server.name} negotiated unsupported protocol version ${String(negotiatedVersion)}.`);
3328
+ throw new HarnessExecutionError(`MCP server ${server.name} negotiated unsupported protocol version ${String(negotiatedVersion)}.`);
2922
3329
  }
2923
3330
  await post({ jsonrpc: "2.0", method: "notifications/initialized" }, options, false);
2924
3331
  })().catch((error) => {
@@ -2932,11 +3339,11 @@ var createHttpMcpClient = (server, env = process.env, fetchImplementation = fetc
2932
3339
  await ensureInitialized(options);
2933
3340
  const result = await rpc("tools/list", input, options);
2934
3341
  if (!result || typeof result !== "object" || Array.isArray(result)) {
2935
- throw new Error(`MCP server ${server.name} returned an invalid tools/list result.`);
3342
+ throw new HarnessExecutionError(`MCP server ${server.name} returned an invalid tools/list result.`);
2936
3343
  }
2937
3344
  const tools = result.tools;
2938
3345
  if (!Array.isArray(tools)) {
2939
- throw new Error(`MCP server ${server.name} tools/list result has no tools array.`);
3346
+ throw new HarnessExecutionError(`MCP server ${server.name} tools/list result has no tools array.`);
2940
3347
  }
2941
3348
  return result;
2942
3349
  },
@@ -2955,7 +3362,7 @@ var createHarnessMcpTools = async (configuration, options = {}) => {
2955
3362
  const injected = options.clients?.[server.name];
2956
3363
  const client = injected ?? (server.transport === "http" ? createHttpMcpClient(server, options.env ?? process.env, options.fetchImplementation ?? fetch) : undefined);
2957
3364
  if (!client) {
2958
- throw new Error(`MCP server ${server.name} requires an injected custom client.`);
3365
+ throw new HarnessConfigError(`MCP server ${server.name} requires an injected custom client.`);
2959
3366
  }
2960
3367
  const discovered = await createMcpToolSet(boundedClient(client, server), {
2961
3368
  toolNamePrefix: server.toolNamePrefix,
@@ -2971,10 +3378,10 @@ var createHarnessMcpTools = async (configuration, options = {}) => {
2971
3378
  const requiresApproval = server.permissions.some((permission) => permission !== "read");
2972
3379
  for (const [name, definition] of Object.entries(discovered)) {
2973
3380
  if (tools[name]) {
2974
- throw new Error(`Duplicate harness tool name after MCP discovery: ${name}.`);
3381
+ throw new HarnessExecutionError(`Duplicate harness tool name after MCP discovery: ${name}.`);
2975
3382
  }
2976
3383
  if (!("execute" in definition)) {
2977
- throw new Error(`MCP server ${server.name} produced a non-callable tool ${name}.`);
3384
+ throw new HarnessExecutionError(`MCP server ${server.name} produced a non-callable tool ${name}.`);
2978
3385
  }
2979
3386
  const effectiveRequiresApproval = requiresApproval || definition.requiresApproval === true;
2980
3387
  tools[name] = {
@@ -3134,19 +3541,19 @@ ${options.contextInstructions}` : ""}`,
3134
3541
  var runHarnessReviewGroup = async (runtime, input, profiles = ["explorer", "reviewer"]) => {
3135
3542
  const uniqueProfiles = [...new Set(profiles)];
3136
3543
  if (uniqueProfiles.length === 0) {
3137
- throw new Error("A review group requires at least one profile.");
3544
+ throw new HarnessConfigError("A review group requires at least one profile.");
3138
3545
  }
3139
3546
  if (uniqueProfiles.length > runtime.config.orchestration.maxParallelReviews) {
3140
- throw new Error(`Review group exceeds maxParallelReviews=${runtime.config.orchestration.maxParallelReviews}.`);
3547
+ throw new HarnessConfigError(`Review group exceeds maxParallelReviews=${runtime.config.orchestration.maxParallelReviews}.`);
3141
3548
  }
3142
3549
  const unsafe = uniqueProfiles.find((profile) => profile !== "explorer" && profile !== "reviewer");
3143
3550
  if (unsafe) {
3144
- throw new Error(`Parallel review accepts read-only explorer/reviewer profiles, not ${unsafe}.`);
3551
+ throw new HarnessConfigError(`Parallel review accepts read-only explorer/reviewer profiles, not ${unsafe}.`);
3145
3552
  }
3146
3553
  const members = uniqueProfiles.map((profile) => {
3147
3554
  const agent = runtime.subagents.get(profile);
3148
3555
  if (!agent) {
3149
- throw new Error(`Subagent profile ${profile} is not enabled.`);
3556
+ throw new HarnessConfigError(`Subagent profile ${profile} is not enabled.`);
3150
3557
  }
3151
3558
  return { name: profile, agent };
3152
3559
  });
@@ -3176,13 +3583,12 @@ var runHarnessReviewGroup = async (runtime, input, profiles = ["explorer", "revi
3176
3583
  // src/execution-environment.ts
3177
3584
  import { createHash as createHash6, randomUUID as randomUUID3 } from "node:crypto";
3178
3585
  import { spawn as spawn2 } from "node:child_process";
3179
- import { constants as fsConstants } from "node:fs";
3586
+ import { constants as fsConstants2 } from "node:fs";
3180
3587
  import {
3181
3588
  chmod as chmod2,
3182
3589
  copyFile,
3183
3590
  lstat as lstat6,
3184
3591
  mkdir as mkdir3,
3185
- readFile as readFile3,
3186
3592
  readdir as readdir2,
3187
3593
  realpath as realpath3,
3188
3594
  rename as rename2,
@@ -3201,6 +3607,8 @@ var TERMINAL_STATUSES = new Set([
3201
3607
  "cancelled",
3202
3608
  "timed_out"
3203
3609
  ]);
3610
+ var EXECUTION_ARTIFACT_DIRECTORY_PATTERN = /^[a-f0-9]{24}$/;
3611
+ var STAGED_EXECUTION_ARTIFACT_DIRECTORY_PATTERN = /^\.cleanup-([a-f0-9]{24})-[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;
3204
3612
  var BUILT_IN_TOOL_NAMES = new Set([
3205
3613
  "list_files",
3206
3614
  "read_file",
@@ -3372,7 +3780,9 @@ var validateSynchronizedSnapshot = async (stagedRoot, previousRoot, maxWorkspace
3372
3780
  const seal = createHash6("sha256");
3373
3781
  const metadata = createHash6("sha256");
3374
3782
  const visit = async (directory, relativeDirectory = "") => {
3375
- for (const name of (await readdir2(directory)).sort()) {
3783
+ const children = (await readdir2(directory, { withFileTypes: true })).sort((left, right) => left.name.localeCompare(right.name));
3784
+ for (const child of children) {
3785
+ const name = child.name;
3376
3786
  const relative = relativeDirectory ? `${relativeDirectory}/${name}` : name;
3377
3787
  const absolute = path8.join(directory, name);
3378
3788
  if (!isInside3(stagedRoot, absolute) || relative.length > 1024) {
@@ -3386,37 +3796,53 @@ var validateSynchronizedSnapshot = async (stagedRoot, previousRoot, maxWorkspace
3386
3796
  await rm(absolute, { recursive: true, force: true });
3387
3797
  continue;
3388
3798
  }
3389
- const entry = await lstat6(absolute);
3390
- if (entry.isSymbolicLink()) {
3799
+ if (child.isSymbolicLink()) {
3391
3800
  throw new Error(`OCI workspace export contains a symbolic link: ${relative}.`);
3392
3801
  }
3393
- if (entry.isDirectory()) {
3394
- updateSnapshotMetadata(metadata, "directory", relative, entry);
3395
- seal.update(`directory\x00${relative}\x00${entry.mode & 511}\x00`);
3802
+ if (child.isDirectory()) {
3803
+ const directoryEntry = await lstat6(absolute);
3804
+ if (directoryEntry.isSymbolicLink() || !directoryEntry.isDirectory()) {
3805
+ throw new Error(`OCI workspace export directory changed while it was being validated: ${relative}.`);
3806
+ }
3807
+ updateSnapshotMetadata(metadata, "directory", relative, directoryEntry);
3808
+ seal.update(`directory\x00${relative}\x00${directoryEntry.mode & 511}\x00`);
3396
3809
  await visit(absolute, relative);
3397
3810
  continue;
3398
3811
  }
3399
- if (!entry.isFile() || entry.nlink !== 1) {
3812
+ if (!child.isFile()) {
3400
3813
  throw new Error(`OCI workspace export contains a special or linked file: ${relative}.`);
3401
3814
  }
3402
- const contents = await readFile3(absolute);
3403
- const after = await lstat6(absolute);
3404
- if (after.isSymbolicLink() || !after.isFile() || after.nlink !== 1 || entry.dev !== after.dev || entry.ino !== after.ino || entry.size !== after.size || entry.mtimeMs !== after.mtimeMs || entry.ctimeMs !== after.ctimeMs || (entry.mode & 511) !== (after.mode & 511)) {
3405
- throw new Error(`OCI workspace export changed while it was being validated: ${relative}.`);
3815
+ let file;
3816
+ try {
3817
+ file = await readRegularFileNoFollow(absolute, {
3818
+ label: `OCI workspace export file ${relative}`,
3819
+ maxBytes: maxWorkspaceBytes - totalBytes,
3820
+ requireSingleLink: true
3821
+ });
3822
+ } catch (error) {
3823
+ if (error instanceof FileSizeLimitError) {
3824
+ throw new Error(`OCI workspace export exceeds the ${maxWorkspaceBytes}-byte workspace limit.`);
3825
+ }
3826
+ throw error;
3406
3827
  }
3828
+ const contents = file.contents;
3829
+ const entry = file.stat;
3407
3830
  totalBytes += entry.size;
3408
3831
  if (totalBytes > maxWorkspaceBytes) {
3409
3832
  throw new Error(`OCI workspace export exceeds the ${maxWorkspaceBytes}-byte workspace limit.`);
3410
3833
  }
3411
3834
  const contentDigest = digest2(contents);
3412
- updateSnapshotMetadata(metadata, "file", relative, after);
3835
+ updateSnapshotMetadata(metadata, "file", relative, entry);
3413
3836
  seal.update(`file\x00${relative}\x00${entry.mode & 511}\x00${entry.size}\x00${contentDigest}\x00`);
3414
3837
  if (entry.size > maxFileWriteBytes) {
3415
3838
  const previous = path8.join(previousRoot, ...relative.split("/"));
3416
3839
  let unchanged = false;
3417
3840
  try {
3418
- const previousEntry = await lstat6(previous);
3419
- unchanged = previousEntry.isFile() && !previousEntry.isSymbolicLink() && previousEntry.size === entry.size && digest2(await readFile3(previous)) === contentDigest;
3841
+ const previousFile = await readRegularFileNoFollow(previous, {
3842
+ label: `Previous OCI workspace file ${relative}`,
3843
+ maxBytes: entry.size
3844
+ });
3845
+ unchanged = previousFile.stat.size === entry.size && digest2(previousFile.contents) === contentDigest;
3420
3846
  } catch (error) {
3421
3847
  if (error.code !== "ENOENT")
3422
3848
  throw error;
@@ -4081,17 +4507,14 @@ var readSnapshotFile = async (workspace, expected, metrics) => {
4081
4507
  if (!isInside3(workspace.root, absolute)) {
4082
4508
  throw new Error(`Snapshot file escaped its workspace: ${expected.path}.`);
4083
4509
  }
4084
- const before = await lstat6(absolute);
4085
- if (before.isSymbolicLink() || !before.isFile()) {
4086
- throw new Error(`Snapshot source is not a regular file: ${expected.path}.`);
4087
- }
4088
- const contents = await readFile3(absolute);
4089
- const after = await lstat6(absolute);
4090
- if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || (before.mode & 511) !== (after.mode & 511)) {
4091
- throw new Error(`Snapshot source changed while reading: ${expected.path}.`);
4092
- }
4510
+ const file = await readRegularFileNoFollow(absolute, {
4511
+ label: `Snapshot source ${expected.path}`,
4512
+ maxBytes: expected.bytes
4513
+ });
4514
+ const { contents } = file;
4515
+ const entry = file.stat;
4093
4516
  const actualDigest = digest2(contents);
4094
- if (actualDigest !== expected.digest || contents.byteLength !== expected.bytes || (before.mode & 511) !== expected.mode) {
4517
+ if (actualDigest !== expected.digest || contents.byteLength !== expected.bytes || (entry.mode & 511) !== expected.mode) {
4095
4518
  throw new Error(`Snapshot source changed after inventory: ${expected.path}.`);
4096
4519
  }
4097
4520
  if (metrics) {
@@ -4102,7 +4525,7 @@ var readSnapshotFile = async (workspace, expected, metrics) => {
4102
4525
  };
4103
4526
  var copySnapshotFile = async (source, target, metrics) => {
4104
4527
  try {
4105
- await copyFile(source, target, fsConstants.COPYFILE_FICLONE_FORCE);
4528
+ await copyFile(source, target, fsConstants2.COPYFILE_FICLONE_FORCE);
4106
4529
  } catch (error) {
4107
4530
  const code = error.code;
4108
4531
  if (!code || !COPY_ON_WRITE_UNSUPPORTED_CODES.has(code))
@@ -4297,7 +4720,7 @@ var harnessExecutionSession = (context) => {
4297
4720
  const candidate = context?.executionEnvironment;
4298
4721
  return candidate?.kind === "zhivex-oci" ? candidate : undefined;
4299
4722
  };
4300
- var createHarnessOciExecutionEnvironment = async (options) => {
4723
+ var createHarnessOciExecutionEnvironmentUnsafe = async (options) => {
4301
4724
  const runtime = options.runtime ?? new CliOciRuntimeAdapter(options.config.runtime);
4302
4725
  const image = await runtime.inspectImage(options.config.image);
4303
4726
  const workspaceIdentity = digest2(options.workspace.root);
@@ -4382,10 +4805,11 @@ var createHarnessOciExecutionEnvironment = async (options) => {
4382
4805
  const snapshotRoot = path8.join(directory, "workspace");
4383
4806
  let metadata;
4384
4807
  try {
4385
- const entry = await lstat6(metadataPath);
4386
- if (entry.isSymbolicLink() || !entry.isFile())
4387
- throw new Error("Execution metadata must be a regular file.");
4388
- metadata = JSON.parse(await readFile3(metadataPath, "utf8"));
4808
+ const metadataFile = await readRegularFileNoFollow(metadataPath, {
4809
+ label: "Execution metadata",
4810
+ maxBytes: 1024 * 1024
4811
+ });
4812
+ metadata = JSON.parse(metadataFile.contents.toString("utf8"));
4389
4813
  if (metadata.schemaVersion !== HARNESS_EXECUTION_ARTIFACT_SCHEMA_VERSION || metadata.runId !== request.runId || metadata.hostWorkspace !== options.workspace.root || metadata.binding.fingerprint !== binding.fingerprint || metadata.binding.workspaceId !== binding.workspaceId) {
4390
4814
  throw new Error(`Execution artifact binding changed for run ${request.runId}.`);
4391
4815
  }
@@ -4601,7 +5025,11 @@ var createHarnessOciExecutionEnvironment = async (options) => {
4601
5025
  async runCheck(check, expectedScript, allowedChecks, context) {
4602
5026
  let manifestDocument;
4603
5027
  try {
4604
- manifestDocument = JSON.parse(await readFile3(path8.join(snapshotRoot, "package.json"), "utf8"));
5028
+ const manifestFile = await readRegularFileNoFollow(path8.join(snapshotRoot, "package.json"), {
5029
+ label: "Snapshot package.json",
5030
+ maxBytes: 1024 * 1024
5031
+ });
5032
+ manifestDocument = JSON.parse(manifestFile.contents.toString("utf8"));
4605
5033
  } catch (error) {
4606
5034
  if (error.code === "ENOENT") {
4607
5035
  throw new Error("The environment snapshot does not contain package.json.");
@@ -4634,6 +5062,46 @@ var createHarnessOciExecutionEnvironment = async (options) => {
4634
5062
  }
4635
5063
  };
4636
5064
  };
5065
+ var executionBoundaryError = (error, message) => {
5066
+ if (error instanceof HarnessError || error instanceof Error && error.name === "ToolExecutionSuspendedError") {
5067
+ throw error;
5068
+ }
5069
+ throw new HarnessExecutionError(error instanceof Error ? error.message : message, {
5070
+ cause: error,
5071
+ retryable: true
5072
+ });
5073
+ };
5074
+ var typedExecutionSession = (session) => new Proxy(session, {
5075
+ get(target, property, receiver) {
5076
+ const value = Reflect.get(target, property, receiver);
5077
+ if (typeof value !== "function")
5078
+ return value;
5079
+ return async (...args) => {
5080
+ try {
5081
+ return await Reflect.apply(value, target, args);
5082
+ } catch (error) {
5083
+ return executionBoundaryError(error, "Enforced execution session failed.");
5084
+ }
5085
+ };
5086
+ }
5087
+ });
5088
+ var createHarnessOciExecutionEnvironment = async (options) => {
5089
+ try {
5090
+ const environment = await createHarnessOciExecutionEnvironmentUnsafe(options);
5091
+ return {
5092
+ ...environment,
5093
+ async acquire(request) {
5094
+ try {
5095
+ return typedExecutionSession(await environment.acquire(request));
5096
+ } catch (error) {
5097
+ return executionBoundaryError(error, "Enforced execution environment acquisition failed.");
5098
+ }
5099
+ }
5100
+ };
5101
+ } catch (error) {
5102
+ return executionBoundaryError(error, "Enforced execution environment could not be created.");
5103
+ }
5104
+ };
4637
5105
  var cleanupHarnessExecutionArtifacts = async (stateDirectory, before) => {
4638
5106
  const root = path8.join(stateDirectory, "environments");
4639
5107
  const result = { scanned: 0, deleted: 0, skipped: 0 };
@@ -4646,30 +5114,56 @@ var cleanupHarnessExecutionArtifacts = async (stateDirectory, before) => {
4646
5114
  throw error;
4647
5115
  }
4648
5116
  for (const entry of entries) {
4649
- if (!entry.isDirectory() || entry.isSymbolicLink() || !/^[a-f0-9]{24}$/.test(entry.name)) {
5117
+ const stagedMatch = STAGED_EXECUTION_ARTIFACT_DIRECTORY_PATTERN.exec(entry.name);
5118
+ const artifactName = EXECUTION_ARTIFACT_DIRECTORY_PATTERN.test(entry.name) ? entry.name : stagedMatch?.[1];
5119
+ if (!entry.isDirectory() || entry.isSymbolicLink() || !artifactName) {
4650
5120
  result.skipped += 1;
4651
5121
  continue;
4652
5122
  }
4653
5123
  result.scanned += 1;
4654
5124
  const directory = path8.join(root, entry.name);
4655
- const resolved = await realpath3(directory);
4656
- if (!isInside3(root, resolved)) {
4657
- result.skipped += 1;
4658
- continue;
4659
- }
4660
5125
  try {
5126
+ const resolved = await realpath3(directory);
5127
+ if (!isInside3(root, resolved))
5128
+ throw new Error("unsafe execution artifact directory");
5129
+ const directoryEntry = await lstat6(directory);
5130
+ if (directoryEntry.isSymbolicLink() || !directoryEntry.isDirectory()) {
5131
+ throw new Error("unsafe execution artifact directory");
5132
+ }
4661
5133
  const metadataPath = path8.join(directory, "environment.json");
4662
- const metadataEntry = await lstat6(metadataPath);
4663
- if (metadataEntry.isSymbolicLink() || !metadataEntry.isFile())
4664
- throw new Error("unsafe metadata");
4665
- const metadata = JSON.parse(await readFile3(metadataPath, "utf8"));
5134
+ const metadataFile = await readRegularFileNoFollow(metadataPath, {
5135
+ label: "Execution cleanup metadata",
5136
+ maxBytes: 1024 * 1024
5137
+ });
5138
+ const metadata = JSON.parse(metadataFile.contents.toString("utf8"));
4666
5139
  const releasedAt = metadata.releasedAt ? Date.parse(metadata.releasedAt) : Number.NaN;
4667
5140
  if (!metadata.status || !TERMINAL_STATUSES.has(metadata.status) || !Number.isFinite(releasedAt) || releasedAt >= before) {
4668
5141
  result.skipped += 1;
4669
5142
  continue;
4670
5143
  }
4671
- await rm(directory, { recursive: true, force: true });
4672
- result.deleted += 1;
5144
+ const stagedDirectory = path8.join(root, `.cleanup-${artifactName}-${randomUUID3()}`);
5145
+ let staged = false;
5146
+ try {
5147
+ await rename2(directory, stagedDirectory);
5148
+ staged = true;
5149
+ const movedEntry = await lstat6(stagedDirectory);
5150
+ if (movedEntry.isSymbolicLink() || !movedEntry.isDirectory() || movedEntry.dev !== directoryEntry.dev || movedEntry.ino !== directoryEntry.ino) {
5151
+ throw new Error("execution artifact directory changed before cleanup");
5152
+ }
5153
+ const recheckedMetadata = await readRegularFileNoFollow(path8.join(stagedDirectory, "environment.json"), { label: "Execution cleanup metadata", maxBytes: 1024 * 1024 });
5154
+ if (!recheckedMetadata.contents.equals(metadataFile.contents)) {
5155
+ throw new Error("execution artifact metadata changed before cleanup");
5156
+ }
5157
+ await rm(stagedDirectory, { recursive: true, force: true });
5158
+ staged = false;
5159
+ result.deleted += 1;
5160
+ } catch (error) {
5161
+ if (staged)
5162
+ await rename2(stagedDirectory, directory).catch(() => {
5163
+ return;
5164
+ });
5165
+ throw error;
5166
+ }
4673
5167
  } catch {
4674
5168
  result.skipped += 1;
4675
5169
  }
@@ -4685,8 +5179,7 @@ var describeOciCommand = (command, args) => commandDisplay([command, ...args]);
4685
5179
 
4686
5180
  // src/context-engineering.ts
4687
5181
  import { createHash as createHash7 } from "node:crypto";
4688
- import { constants as fsConstants2 } from "node:fs";
4689
- import { lstat as lstat7, open as open3, readdir as readdir3 } from "node:fs/promises";
5182
+ import { lstat as lstat7, readdir as readdir3 } from "node:fs/promises";
4690
5183
  import path9 from "node:path";
4691
5184
  import { z as z3 } from "zod";
4692
5185
  var HARNESS_CONTEXT_CONFIG_SCHEMA_VERSION = 1;
@@ -4765,7 +5258,6 @@ var validateRelativePath = (value) => {
4765
5258
  }
4766
5259
  return normalized;
4767
5260
  };
4768
- var stableEntry = (before, after) => before.dev === after.dev && before.ino === after.ino && before.size === after.size && before.mtimeMs === after.mtimeMs && before.ctimeMs === after.ctimeMs;
4769
5261
  var resolveSafeWorkspaceEntry = async (workspace, relativePath, options = {}) => {
4770
5262
  const normalized = validateRelativePath(relativePath);
4771
5263
  const absolutePath = path9.resolve(workspace.root, normalized);
@@ -4777,6 +5269,9 @@ var resolveSafeWorkspaceEntry = async (workspace, relativePath, options = {}) =>
4777
5269
  const segments = normalized.split("/");
4778
5270
  for (let index = 0;index < segments.length; index += 1) {
4779
5271
  current = path9.join(current, segments[index]);
5272
+ const leaf = index === segments.length - 1;
5273
+ if (leaf && options.skipLeafValidation)
5274
+ continue;
4780
5275
  let entry;
4781
5276
  try {
4782
5277
  entry = await lstat7(current);
@@ -4788,7 +5283,6 @@ var resolveSafeWorkspaceEntry = async (workspace, relativePath, options = {}) =>
4788
5283
  if (entry.isSymbolicLink()) {
4789
5284
  throw new Error(`The harness context path cannot contain a symbolic link: ${relativePath}`);
4790
5285
  }
4791
- const leaf = index === segments.length - 1;
4792
5286
  if (!leaf && !entry.isDirectory()) {
4793
5287
  throw new Error(`A harness context path ancestor is not a directory: ${relativePath}`);
4794
5288
  }
@@ -4802,42 +5296,39 @@ var resolveSafeWorkspaceEntry = async (workspace, relativePath, options = {}) =>
4802
5296
  return { path: absolutePath, relativePath: normalized };
4803
5297
  };
4804
5298
  var readStableWorkspaceText = async (workspace, relativePath, maxBytes, allowMissing = false) => {
4805
- const resolved = await resolveSafeWorkspaceEntry(workspace, relativePath, { allowMissing });
5299
+ const resolved = await resolveSafeWorkspaceEntry(workspace, relativePath, {
5300
+ allowMissing,
5301
+ skipLeafValidation: true
5302
+ });
4806
5303
  if (!resolved)
4807
5304
  return;
4808
- const before = await lstat7(resolved.path);
4809
- if (before.size > maxBytes) {
4810
- throw new Error(`Harness context file ${resolved.relativePath} exceeds the ${maxBytes}-byte limit.`);
5305
+ let file;
5306
+ try {
5307
+ file = await readRegularFileNoFollow(resolved.path, {
5308
+ label: `Harness context file ${resolved.relativePath}`,
5309
+ maxBytes
5310
+ });
5311
+ } catch (error) {
5312
+ if (allowMissing && error.code === "ENOENT")
5313
+ return;
5314
+ throw error;
4811
5315
  }
4812
- const handle = await open3(resolved.path, fsConstants2.O_RDONLY | fsConstants2.O_NOFOLLOW);
5316
+ const { contents } = file;
5317
+ if (contents.includes(0)) {
5318
+ throw new Error(`Harness context file must be UTF-8 text: ${resolved.relativePath}`);
5319
+ }
5320
+ let content;
4813
5321
  try {
4814
- const opened = await handle.stat();
4815
- if (!opened.isFile() || !stableEntry(before, opened)) {
4816
- throw new Error(`Harness context file changed while opening: ${resolved.relativePath}`);
4817
- }
4818
- const contents = await handle.readFile();
4819
- const after = await handle.stat();
4820
- if (!stableEntry(opened, after) || contents.byteLength !== after.size) {
4821
- throw new Error(`Harness context file changed while reading: ${resolved.relativePath}`);
4822
- }
4823
- if (contents.includes(0)) {
4824
- throw new Error(`Harness context file must be UTF-8 text: ${resolved.relativePath}`);
4825
- }
4826
- let content;
4827
- try {
4828
- content = new TextDecoder("utf-8", { fatal: true }).decode(contents);
4829
- } catch {
4830
- throw new Error(`Harness context file must be valid UTF-8: ${resolved.relativePath}`);
4831
- }
4832
- return {
4833
- path: resolved.relativePath,
4834
- digest: digestBytes2(contents),
4835
- bytes: contents.byteLength,
4836
- content
4837
- };
4838
- } finally {
4839
- await handle.close();
5322
+ content = new TextDecoder("utf-8", { fatal: true }).decode(contents);
5323
+ } catch {
5324
+ throw new Error(`Harness context file must be valid UTF-8: ${resolved.relativePath}`);
4840
5325
  }
5326
+ return {
5327
+ path: resolved.relativePath,
5328
+ digest: digestBytes2(contents),
5329
+ bytes: contents.byteLength,
5330
+ content
5331
+ };
4841
5332
  };
4842
5333
  var parseConfiguration = (file) => {
4843
5334
  let document;
@@ -5646,36 +6137,70 @@ var createProviderCompatibleBudget = (config) => {
5646
6137
  };
5647
6138
  var createHarness = async (options = {}) => {
5648
6139
  const config = resolveHarnessConfig(options, options.providerRegistry);
5649
- const workspace = await Workspace.open(config.workspace);
6140
+ let workspace;
6141
+ try {
6142
+ workspace = await Workspace.open(config.workspace);
6143
+ } catch (error) {
6144
+ throw new HarnessWorkspaceError("Harness workspace could not be opened safely.", { cause: error });
6145
+ }
5650
6146
  await validateStateDirectory(config.workspace, config.stateDirectory);
5651
6147
  const contextManifestPath = path10.relative(config.workspace, config.context.configPath).split(path10.sep).join("/");
5652
- const contextBundle = config.context.enabled ? await loadHarnessProjectContext(workspace, {
5653
- manifestPath: contextManifestPath,
5654
- requireManifest: contextManifestPath !== DEFAULT_HARNESS_CONTEXT_MANIFEST
5655
- }) : createEmptyHarnessContextBundle();
6148
+ let contextBundle;
6149
+ try {
6150
+ contextBundle = config.context.enabled ? await loadHarnessProjectContext(workspace, {
6151
+ manifestPath: contextManifestPath,
6152
+ requireManifest: contextManifestPath !== DEFAULT_HARNESS_CONTEXT_MANIFEST
6153
+ }) : createEmptyHarnessContextBundle();
6154
+ } catch (error) {
6155
+ throw new HarnessConfigError("Harness project context configuration is invalid.", { cause: error });
6156
+ }
5656
6157
  const contextInstructions = renderHarnessContextInstructions(contextBundle);
5657
6158
  const lifecycleHooks = [...options.lifecycleHooks ?? []];
5658
6159
  const dispatchLifecycle = createHarnessLifecycleDispatcher(lifecycleHooks, options.onLifecycleHookError);
5659
- const executionEnvironment = config.execution.backend === "oci" ? await createHarnessOciExecutionEnvironment({
5660
- config: config.execution,
5661
- workspace,
5662
- stateDirectory: config.stateDirectory,
5663
- ...options.ociRuntimeAdapter ? { runtime: options.ociRuntimeAdapter } : {}
5664
- }) : undefined;
6160
+ let executionEnvironment;
6161
+ if (config.execution.backend === "oci") {
6162
+ try {
6163
+ executionEnvironment = await createHarnessOciExecutionEnvironment({
6164
+ config: config.execution,
6165
+ workspace,
6166
+ stateDirectory: config.stateDirectory,
6167
+ ...options.ociRuntimeAdapter ? { runtime: options.ociRuntimeAdapter } : {}
6168
+ });
6169
+ } catch (error) {
6170
+ throw new HarnessExecutionError("Enforced execution environment could not be created.", {
6171
+ cause: error,
6172
+ retryable: true
6173
+ });
6174
+ }
6175
+ }
5665
6176
  const model = options.modelInstance ?? createProviderModel(config, options.env ?? process.env, options.providerRegistry);
5666
6177
  const capabilityRequirements = [...new Set([
5667
6178
  ...config.requiredCapabilities,
5668
6179
  ...config.orchestration.profiles.length > 0 || contextBundle.skills.length > 0 || config.mcpConfigPath || options.mcpConfiguration ? ["tools", "streaming"] : []
5669
6180
  ])];
5670
- const capabilities = assertHarnessModelCapabilities(model, capabilityRequirements, "harness run");
5671
- for (const [profile, subagentModel] of Object.entries(options.subagentModels ?? {})) {
5672
- if (subagentModel) {
5673
- assertHarnessModelCapabilities(subagentModel, ["streaming", "tools"], `${profile} subagent`);
6181
+ let capabilities;
6182
+ try {
6183
+ capabilities = assertHarnessModelCapabilities(model, capabilityRequirements, "harness run");
6184
+ for (const [profile, subagentModel] of Object.entries(options.subagentModels ?? {})) {
6185
+ if (subagentModel) {
6186
+ assertHarnessModelCapabilities(subagentModel, ["streaming", "tools"], `${profile} subagent`);
6187
+ }
5674
6188
  }
6189
+ } catch (error) {
6190
+ throw new HarnessConfigError("Harness model capabilities do not satisfy the configured requirements.", {
6191
+ cause: error
6192
+ });
6193
+ }
6194
+ let mcpConfiguration;
6195
+ try {
6196
+ mcpConfiguration = options.mcpConfiguration === undefined ? config.mcpConfigPath ? await loadHarnessMcpConfiguration(config.workspace, config.mcpConfigPath) : { schemaVersion: HARNESS_MCP_CONFIG_SCHEMA_VERSION, servers: [] } : normalizeHarnessMcpConfiguration(options.mcpConfiguration);
6197
+ } catch (error) {
6198
+ if (error instanceof HarnessError)
6199
+ throw error;
6200
+ throw new HarnessConfigError("Harness MCP configuration is invalid.", { cause: error });
5675
6201
  }
5676
- const mcpConfiguration = options.mcpConfiguration === undefined ? config.mcpConfigPath ? await loadHarnessMcpConfiguration(config.workspace, config.mcpConfigPath) : { schemaVersion: HARNESS_MCP_CONFIG_SCHEMA_VERSION, servers: [] } : normalizeHarnessMcpConfiguration(options.mcpConfiguration);
5677
6202
  if (executionEnvironment && mcpConfiguration.servers.length > 0) {
5678
- throw new Error("Enforced OCI execution denies MCP tools before discovery because they execute outside the declared no-network environment boundary.");
6203
+ throw new HarnessConfigError("Enforced OCI execution denies MCP tools before discovery because they execute outside the declared no-network environment boundary.");
5679
6204
  }
5680
6205
  const allWorkspaceTools = createWorkspaceTools(workspace, config.allowedChecks);
5681
6206
  const workspaceTools = executionEnvironment ? Object.fromEntries(Object.entries(allWorkspaceTools).filter(([name]) => name !== "git_diff")) : allWorkspaceTools;
@@ -5689,14 +6214,21 @@ var createHarness = async (options = {}) => {
5689
6214
  execute: async (input) => serializeJsonValue2(await loadHarnessSkill(workspace, contextBundle, input))
5690
6215
  })
5691
6216
  };
5692
- const mcpTools = await createHarnessMcpTools(mcpConfiguration, {
5693
- ...options.mcpClients ? { clients: options.mcpClients } : {},
5694
- env: options.env ?? process.env,
5695
- ...options.fetchImplementation ? { fetchImplementation: options.fetchImplementation } : {}
5696
- });
6217
+ let mcpTools;
6218
+ try {
6219
+ mcpTools = await createHarnessMcpTools(mcpConfiguration, {
6220
+ ...options.mcpClients ? { clients: options.mcpClients } : {},
6221
+ env: options.env ?? process.env,
6222
+ ...options.fetchImplementation ? { fetchImplementation: options.fetchImplementation } : {}
6223
+ });
6224
+ } catch (error) {
6225
+ if (error instanceof HarnessError)
6226
+ throw error;
6227
+ throw new HarnessExecutionError("Harness MCP tool discovery failed.", { cause: error, retryable: true });
6228
+ }
5697
6229
  for (const name of Object.keys(mcpTools)) {
5698
6230
  if (name in workspaceTools || name in executionTools || name in contextTools) {
5699
- throw new Error(`MCP tool ${name} conflicts with a built-in workspace tool.`);
6231
+ throw new HarnessConfigError(`MCP tool ${name} conflicts with a built-in workspace tool.`);
5700
6232
  }
5701
6233
  }
5702
6234
  const tools = { ...workspaceTools, ...executionTools, ...contextTools, ...mcpTools };
@@ -6130,7 +6662,7 @@ var runHarness = async (harness, input, options = {}) => {
6130
6662
  const expected = harness.agent.harness;
6131
6663
  const actual = nextInput.state.harness;
6132
6664
  if (actual.id !== expected.id || actual.version !== expected.version || actual.fingerprint !== expected.fingerprint) {
6133
- throw new Error(`Run ${nextInput.state.runId} was created by a different harness fingerprint and cannot be resumed.`);
6665
+ throw new HarnessStateConflictError(`Run ${nextInput.state.runId} was created by a different harness fingerprint and cannot be resumed.`);
6134
6666
  }
6135
6667
  }
6136
6668
  const streamed = harness.agent.stream(nextInput);
@@ -6177,12 +6709,12 @@ var runHarness = async (harness, input, options = {}) => {
6177
6709
  approvals: [...approvals]
6178
6710
  };
6179
6711
  }
6180
- throw new Error("The run exceeded the limit of 50 approval rounds.");
6712
+ throw new HarnessExecutionError("The run exceeded the limit of 50 approval rounds.");
6181
6713
  } catch (error) {
6182
6714
  if (!lifecycleFinished) {
6183
6715
  await harness.dispatchLifecycle({ type: "run-finished", runId, status: "failed" });
6184
6716
  }
6185
- throw error;
6717
+ throw normalizeHarnessError(error);
6186
6718
  }
6187
6719
  };
6188
6720
  var appendUserMessage = (messages, text) => [
@@ -6340,7 +6872,7 @@ var streamResultDocument = (result, sequence = 0) => {
6340
6872
  }
6341
6873
  return {
6342
6874
  schemaVersion: CLI_EVENT_SCHEMA_VERSION,
6343
- kind: "run-result",
6875
+ kind: "run-stream-result",
6344
6876
  sequence,
6345
6877
  runId: result.runId,
6346
6878
  status: result.status,
@@ -6422,28 +6954,28 @@ var byteLength = (value) => Buffer.byteLength(value, "utf8");
6422
6954
  var boundedInteger = (name, value, fallback, minimum) => {
6423
6955
  const resolved = value ?? fallback;
6424
6956
  if (!Number.isSafeInteger(resolved) || resolved < minimum) {
6425
- throw new Error(`${name} must be an integer greater than or equal to ${minimum}.`);
6957
+ throw new HarnessConfigError(`${name} must be an integer greater than or equal to ${minimum}.`);
6426
6958
  }
6427
6959
  return resolved;
6428
6960
  };
6429
6961
  var assertTimestamp = (name, value) => {
6430
6962
  if (!Number.isSafeInteger(value) || value < 0) {
6431
- throw new Error(`${name} must be a non-negative integer timestamp.`);
6963
+ throw new HarnessConfigError(`${name} must be a non-negative integer timestamp.`);
6432
6964
  }
6433
6965
  };
6434
6966
  var assertIdentifier = (name, value) => {
6435
6967
  if (!ID_PATTERN.test(value)) {
6436
- throw new Error(`${name} contains unsupported characters or exceeds 256 bytes.`);
6968
+ throw new HarnessConfigError(`${name} contains unsupported characters or exceeds 256 bytes.`);
6437
6969
  }
6438
6970
  if (metadataRedaction.redactText(value) !== value) {
6439
- throw new Error(`${name} resembles sensitive metadata and cannot be stored in the session index.`);
6971
+ throw new HarnessConfigError(`${name} resembles sensitive metadata and cannot be stored in the session index.`);
6440
6972
  }
6441
6973
  return value;
6442
6974
  };
6443
6975
  var assertScopeSegment = (name, value) => {
6444
6976
  const normalized = value.trim();
6445
6977
  if (!normalized || normalized.length > 128 || /[\u0000-\u001f\u007f]/.test(normalized)) {
6446
- throw new Error(`${name} must contain 1-128 printable characters.`);
6978
+ throw new HarnessConfigError(`${name} must contain 1-128 printable characters.`);
6447
6979
  }
6448
6980
  return normalized;
6449
6981
  };
@@ -6453,10 +6985,10 @@ var normalizeTitle = (value, maxMetadataBytes) => {
6453
6985
  }
6454
6986
  const normalized = metadataRedaction.redactText(value).replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
6455
6987
  if (!normalized) {
6456
- throw new Error("Session title must not be empty.");
6988
+ throw new HarnessConfigError("Session title must not be empty.");
6457
6989
  }
6458
6990
  if (byteLength(normalized) > maxMetadataBytes) {
6459
- throw new Error(`Session title exceeds the ${maxMetadataBytes}-byte metadata limit.`);
6991
+ throw new HarnessConfigError(`Session title exceeds the ${maxMetadataBytes}-byte metadata limit.`);
6460
6992
  }
6461
6993
  return normalized;
6462
6994
  };
@@ -6469,37 +7001,29 @@ var normalizeScope = (scope) => {
6469
7001
  var stableKey = (kind, value) => createHash9("sha256").update(kind).update("\x00").update(value).digest("hex");
6470
7002
  var sessionId = () => `ses_${randomUUID5()}`;
6471
7003
  var turnId = () => `turn_${randomUUID5()}`;
6472
- var isMissing = (error) => error.code === "ENOENT";
6473
7004
  var ensurePrivateDatabase = async (workspace, stateDirectory) => {
6474
7005
  const requestedStateDirectory = path11.resolve(stateDirectory);
6475
7006
  await validateStateDirectory(workspace, requestedStateDirectory);
6476
7007
  await mkdir4(requestedStateDirectory, { recursive: true, mode: 448 });
6477
7008
  const directoryEntry = await lstat8(requestedStateDirectory);
6478
7009
  if (directoryEntry.isSymbolicLink() || !directoryEntry.isDirectory()) {
6479
- throw new Error(`The session state directory must be a real directory: ${requestedStateDirectory}.`);
7010
+ throw new HarnessWorkspaceError(`The session state directory must be a real directory: ${requestedStateDirectory}.`);
6480
7011
  }
6481
7012
  await chmod3(requestedStateDirectory, 448);
6482
7013
  const canonicalStateDirectory2 = await realpath4(requestedStateDirectory);
6483
7014
  const databasePath = path11.join(canonicalStateDirectory2, HARNESS_SESSION_INDEX_FILE);
6484
7015
  let databaseEntry;
6485
7016
  try {
7017
+ const handle = await open4(databasePath, "wx", 384);
7018
+ await handle.close();
6486
7019
  databaseEntry = await lstat8(databasePath);
6487
7020
  } catch (error) {
6488
- if (!isMissing(error)) {
7021
+ if (error.code !== "EEXIST")
6489
7022
  throw error;
6490
- }
6491
- try {
6492
- const handle = await open4(databasePath, "wx", 384);
6493
- await handle.close();
6494
- } catch (creationError) {
6495
- if (creationError.code !== "EEXIST") {
6496
- throw creationError;
6497
- }
6498
- }
6499
7023
  databaseEntry = await lstat8(databasePath);
6500
7024
  }
6501
7025
  if (databaseEntry.isSymbolicLink() || !databaseEntry.isFile()) {
6502
- throw new Error(`The session SQLite path must be a real file: ${databasePath}.`);
7026
+ throw new HarnessWorkspaceError(`The session SQLite path must be a real file: ${databasePath}.`);
6503
7027
  }
6504
7028
  await chmod3(databasePath, 384);
6505
7029
  return { databasePath, databaseEntry };
@@ -6523,7 +7047,7 @@ var openCliSessionStore = async (options) => {
6523
7047
  const workspace = await realpath4(path11.resolve(options.workspace));
6524
7048
  const workspaceEntry = await stat3(workspace);
6525
7049
  if (!workspaceEntry.isDirectory()) {
6526
- throw new Error(`The session workspace is not a directory: ${workspace}.`);
7050
+ throw new HarnessWorkspaceError(`The session workspace is not a directory: ${workspace}.`);
6527
7051
  }
6528
7052
  const scopeValue2 = normalizeScope(options.scope);
6529
7053
  const workspaceKey = stableKey("workspace", workspace);
@@ -6539,7 +7063,7 @@ var openCliSessionStore = async (options) => {
6539
7063
  let closed = false;
6540
7064
  const assertOpen = () => {
6541
7065
  if (closed) {
6542
- throw new Error("The CLI session store is closed.");
7066
+ throw new HarnessStateConflictError("The CLI session store is closed.");
6543
7067
  }
6544
7068
  };
6545
7069
  const transaction = (operation) => {
@@ -6554,7 +7078,7 @@ var openCliSessionStore = async (options) => {
6554
7078
  AS size
6555
7079
  `).get(workspaceKey, scopeKey)?.size ?? 0;
6556
7080
  if (size > maxIndexBytes) {
6557
- throw new Error(`Session index metadata exceeds the ${maxIndexBytes}-byte limit.`);
7081
+ throw new HarnessStateConflictError(`Session index metadata exceeds the ${maxIndexBytes}-byte limit.`);
6558
7082
  }
6559
7083
  database.exec("COMMIT");
6560
7084
  return result;
@@ -6567,7 +7091,7 @@ var openCliSessionStore = async (options) => {
6567
7091
  };
6568
7092
  const ensureRevision = (row, expected) => {
6569
7093
  if (expected !== undefined && row.revision !== expected) {
6570
- throw new Error(`Session ${row.session_id} changed concurrently (expected revision ${expected}, found ${row.revision}).`);
7094
+ throw new HarnessStateConflictError(`Session ${row.session_id} changed concurrently (expected revision ${expected}, found ${row.revision}).`, { retryable: true });
6571
7095
  }
6572
7096
  };
6573
7097
  const selectSessionRow = (candidateSessionId, includeDeleted = false) => {
@@ -6583,7 +7107,7 @@ var openCliSessionStore = async (options) => {
6583
7107
  const requireSessionRow = (candidateSessionId, includeDeleted = false) => {
6584
7108
  const row = selectSessionRow(candidateSessionId, includeDeleted);
6585
7109
  if (!row) {
6586
- throw new Error(`Session ${candidateSessionId} was not found in this workspace and scope.`);
7110
+ throw new HarnessStateConflictError(`Session ${candidateSessionId} was not found in this workspace and scope.`);
6587
7111
  }
6588
7112
  return row;
6589
7113
  };
@@ -6628,7 +7152,7 @@ var openCliSessionStore = async (options) => {
6628
7152
  const assertNoActiveRun = (candidateSessionId, action) => {
6629
7153
  const latest = latestRunRow(candidateSessionId);
6630
7154
  if (latest && ACTIVE_STATUSES.has(latest.status)) {
6631
- throw new Error(`Cannot ${action} session ${candidateSessionId} while run ${latest.run_id} is ${latest.status}.`);
7155
+ throw new HarnessStateConflictError(`Cannot ${action} session ${candidateSessionId} while run ${latest.run_id} is ${latest.status}.`);
6632
7156
  }
6633
7157
  };
6634
7158
  const insertRun = (candidateSessionId, input, sequence, sourceTurnId) => {
@@ -6638,13 +7162,13 @@ var openCliSessionStore = async (options) => {
6638
7162
  const role = input.role === undefined ? null : assertIdentifier("role", input.role);
6639
7163
  const status = input.status ?? "created";
6640
7164
  if (!SESSION_RUN_STATUSES.includes(status)) {
6641
- throw new Error(`Unsupported session run status: ${String(status)}.`);
7165
+ throw new HarnessConfigError(`Unsupported session run status: ${String(status)}.`);
6642
7166
  }
6643
7167
  const createdAt = input.createdAt ?? now();
6644
7168
  assertTimestamp("createdAt", createdAt);
6645
7169
  const entryBytes = metadataSize({ runId, provider, model, role });
6646
7170
  if (entryBytes > maxMetadataBytes) {
6647
- throw new Error(`Run reference metadata exceeds the ${maxMetadataBytes}-byte limit.`);
7171
+ throw new HarnessConfigError(`Run reference metadata exceeds the ${maxMetadataBytes}-byte limit.`);
6648
7172
  }
6649
7173
  const candidateTurnId = turnId();
6650
7174
  database.query(`
@@ -6657,7 +7181,7 @@ var openCliSessionStore = async (options) => {
6657
7181
  try {
6658
7182
  const openedEntry = await lstat8(databasePath);
6659
7183
  if (openedEntry.isSymbolicLink() || !openedEntry.isFile() || openedEntry.dev !== databaseEntry.dev || openedEntry.ino !== databaseEntry.ino) {
6660
- throw new Error(`The session SQLite path changed while it was being opened: ${databasePath}.`);
7184
+ throw new HarnessWorkspaceError(`The session SQLite path changed while it was being opened: ${databasePath}.`);
6661
7185
  }
6662
7186
  database.exec("PRAGMA journal_mode = WAL");
6663
7187
  database.exec("PRAGMA busy_timeout = 5000");
@@ -6712,7 +7236,7 @@ var openCliSessionStore = async (options) => {
6712
7236
  `);
6713
7237
  const schemaVersion = database.query("SELECT version FROM zhivex_cli_session_schema WHERE singleton = 1").get()?.version;
6714
7238
  if (schemaVersion !== HARNESS_SESSION_SCHEMA_VERSION) {
6715
- throw new Error(`Unsupported CLI session schema version: ${String(schemaVersion)}.`);
7239
+ throw new HarnessStateConflictError(`Unsupported CLI session schema version: ${String(schemaVersion)}.`);
6716
7240
  }
6717
7241
  await chmod3(databasePath, 384);
6718
7242
  } catch (error) {
@@ -6753,7 +7277,7 @@ var openCliSessionStore = async (options) => {
6753
7277
  WHERE workspace_key = ?1 AND scope_key = ?2
6754
7278
  `).get(workspaceKey, scopeKey)?.count ?? 0;
6755
7279
  if (count >= maxSessions) {
6756
- throw new Error(`Session limit reached for this workspace and scope (${maxSessions}). Archive and prune an older session.`);
7280
+ throw new HarnessStateConflictError(`Session limit reached for this workspace and scope (${maxSessions}). Archive and prune an older session.`);
6757
7281
  }
6758
7282
  const createdAt = now();
6759
7283
  assertTimestamp("now", createdAt);
@@ -6781,7 +7305,7 @@ var openCliSessionStore = async (options) => {
6781
7305
  assertOpen();
6782
7306
  const limit = boundedInteger("limit", query.limit, 50, 1);
6783
7307
  if (limit > MAX_LIST_LIMIT) {
6784
- throw new Error(`limit cannot exceed ${MAX_LIST_LIMIT}.`);
7308
+ throw new HarnessConfigError(`limit cannot exceed ${MAX_LIST_LIMIT}.`);
6785
7309
  }
6786
7310
  const rows = database.query(`
6787
7311
  SELECT session_id, title, parent_session_id, forked_from_turn_id, revision, activity_seq,
@@ -6848,7 +7372,7 @@ var openCliSessionStore = async (options) => {
6848
7372
  const row = requireSessionRow(candidateSessionId);
6849
7373
  ensureRevision(row, appendOptions.expectedRevision);
6850
7374
  if (row.archived_at !== null) {
6851
- throw new Error(`Cannot append a run to archived session ${candidateSessionId}.`);
7375
+ throw new HarnessStateConflictError(`Cannot append a run to archived session ${candidateSessionId}.`);
6852
7376
  }
6853
7377
  const existing = database.query(`
6854
7378
  SELECT turn_id, source_turn_id, ordinal, run_id, provider, model, role, status,
@@ -6860,12 +7384,12 @@ var openCliSessionStore = async (options) => {
6860
7384
  if (existing.provider === input.provider && existing.model === input.model && (existing.role ?? undefined) === input.role && existing.status === requestedStatus) {
6861
7385
  return hydrate(row);
6862
7386
  }
6863
- throw new Error(`Run ${input.runId} is already immutably bound to ${existing.provider}/${existing.model} in this session.`);
7387
+ throw new HarnessStateConflictError(`Run ${input.runId} is already immutably bound to ${existing.provider}/${existing.model} in this session.`);
6864
7388
  }
6865
7389
  assertNoActiveRun(candidateSessionId, "start another run in");
6866
7390
  const count = database.query("SELECT COUNT(*) AS count FROM zhivex_cli_session_runs WHERE session_id = ?1").get(candidateSessionId)?.count ?? 0;
6867
7391
  if (count >= maxRuns) {
6868
- throw new Error(`Run-reference limit reached for session ${candidateSessionId} (${maxRuns}).`);
7392
+ throw new HarnessStateConflictError(`Run-reference limit reached for session ${candidateSessionId} (${maxRuns}).`);
6869
7393
  }
6870
7394
  insertRun(candidateSessionId, input, count);
6871
7395
  const updatedAt = now();
@@ -6889,21 +7413,21 @@ var openCliSessionStore = async (options) => {
6889
7413
  FROM zhivex_cli_session_runs WHERE session_id = ?1 AND run_id = ?2
6890
7414
  `).get(candidateSessionId, runId);
6891
7415
  if (!run) {
6892
- throw new Error(`Run ${runId} is not linked to session ${candidateSessionId}.`);
7416
+ throw new HarnessStateConflictError(`Run ${runId} is not linked to session ${candidateSessionId}.`);
6893
7417
  }
6894
7418
  if (!STATUS_TRANSITIONS[run.status].has(input.status)) {
6895
- throw new Error(`Run ${runId} cannot transition from ${run.status} to ${input.status}.`);
7419
+ throw new HarnessStateConflictError(`Run ${runId} cannot transition from ${run.status} to ${input.status}.`);
6896
7420
  }
6897
7421
  const updatedAt = input.updatedAt ?? now();
6898
7422
  assertTimestamp("updatedAt", updatedAt);
6899
7423
  if (updatedAt < run.updated_at) {
6900
- throw new Error(`Run ${runId} update timestamp cannot move backwards.`);
7424
+ throw new HarnessStateConflictError(`Run ${runId} update timestamp cannot move backwards.`);
6901
7425
  }
6902
7426
  const completedAt = isTerminal(input.status) ? input.completedAt ?? updatedAt : null;
6903
7427
  if (completedAt !== null) {
6904
7428
  assertTimestamp("completedAt", completedAt);
6905
7429
  if (completedAt < run.created_at || completedAt > updatedAt) {
6906
- throw new Error("completedAt must be between the run creation and update timestamps.");
7430
+ throw new HarnessConfigError("completedAt must be between the run creation and update timestamps.");
6907
7431
  }
6908
7432
  }
6909
7433
  database.query(`
@@ -6929,7 +7453,7 @@ var openCliSessionStore = async (options) => {
6929
7453
  if (input.atTurnId) {
6930
7454
  const index = sourceRuns.findIndex((run) => run.turnId === input.atTurnId);
6931
7455
  if (index < 0) {
6932
- throw new Error(`Turn ${input.atTurnId} is not part of session ${candidateSessionId}.`);
7456
+ throw new HarnessStateConflictError(`Turn ${input.atTurnId} is not part of session ${candidateSessionId}.`);
6933
7457
  }
6934
7458
  forkRuns = sourceRuns.slice(0, index + 1);
6935
7459
  forkedFromTurnId = input.atTurnId;
@@ -6938,17 +7462,17 @@ var openCliSessionStore = async (options) => {
6938
7462
  }
6939
7463
  const branchPoint = forkRuns.at(-1);
6940
7464
  if (branchPoint && !isTerminal(branchPoint.status)) {
6941
- throw new Error(`Cannot fork from non-terminal run ${branchPoint.runId} (${branchPoint.status}).`);
7465
+ throw new HarnessStateConflictError(`Cannot fork from non-terminal run ${branchPoint.runId} (${branchPoint.status}).`);
6942
7466
  }
6943
7467
  if (forkRuns.length > maxRuns) {
6944
- throw new Error(`Fork history exceeds the ${maxRuns}-run limit.`);
7468
+ throw new HarnessStateConflictError(`Fork history exceeds the ${maxRuns}-run limit.`);
6945
7469
  }
6946
7470
  const count = database.query(`
6947
7471
  SELECT COUNT(*) AS count FROM zhivex_cli_sessions
6948
7472
  WHERE workspace_key = ?1 AND scope_key = ?2
6949
7473
  `).get(workspaceKey, scopeKey)?.count ?? 0;
6950
7474
  if (count >= maxSessions) {
6951
- throw new Error(`Session limit reached for this workspace and scope (${maxSessions}).`);
7475
+ throw new HarnessStateConflictError(`Session limit reached for this workspace and scope (${maxSessions}).`);
6952
7476
  }
6953
7477
  const createdAt = now();
6954
7478
  assertTimestamp("now", createdAt);
@@ -7684,6 +8208,928 @@ var formatTerminalHeader = (input, options = {}) => {
7684
8208
  ` + `session ${sanitizeTerminalText(input.sessionId)}${title}`;
7685
8209
  };
7686
8210
 
8211
+ // src/cli-options.ts
8212
+ var repeatableOptions = new Set([
8213
+ "--route",
8214
+ "--oci-allow-command",
8215
+ "--allow-check",
8216
+ "--require-capability",
8217
+ "--subagent",
8218
+ "--reviewer",
8219
+ "--status"
8220
+ ]);
8221
+ var conflicts = {
8222
+ "--json": ["--jsonl"],
8223
+ "--jsonl": ["--json"],
8224
+ "--session": ["--continue"],
8225
+ "--continue": ["--session"],
8226
+ "--approve": ["--deny"],
8227
+ "--deny": ["--approve"]
8228
+ };
8229
+ var CLI_OPTION_NAMES = [
8230
+ "--provider",
8231
+ "--model",
8232
+ "--route",
8233
+ "--workspace",
8234
+ "--state-dir",
8235
+ "--mcp-config",
8236
+ "--context-config",
8237
+ "--no-project-context",
8238
+ "--patch",
8239
+ "--preconditions",
8240
+ "--now",
8241
+ "--execution",
8242
+ "--oci-runtime",
8243
+ "--oci-image",
8244
+ "--oci-allow-command",
8245
+ "--oci-shell",
8246
+ "--oci-max-process-runtime-ms",
8247
+ "--oci-max-process-output-bytes",
8248
+ "--oci-max-memory-mb",
8249
+ "--oci-max-pids",
8250
+ "--oci-max-cpus",
8251
+ "--oci-max-workspace-bytes",
8252
+ "--oci-max-file-write-bytes",
8253
+ "--oci-tmpfs-mb",
8254
+ "--store",
8255
+ "--tenant",
8256
+ "--user",
8257
+ "--namespace",
8258
+ "--idempotency-key",
8259
+ "--max-steps",
8260
+ "--timeout-ms",
8261
+ "--max-tool-calls",
8262
+ "--max-tool-errors",
8263
+ "--max-input-tokens",
8264
+ "--max-output-tokens",
8265
+ "--max-total-tokens",
8266
+ "--subagent-max-steps",
8267
+ "--subagent-max-tool-calls",
8268
+ "--subagent-max-tool-errors",
8269
+ "--subagent-max-input-tokens",
8270
+ "--subagent-max-output-tokens",
8271
+ "--subagent-max-total-tokens",
8272
+ "--subagent-timeout-ms",
8273
+ "--max-parallel-reviews",
8274
+ "--max-cost-usd",
8275
+ "--input-cost-per-million",
8276
+ "--output-cost-per-million",
8277
+ "--allow-check",
8278
+ "--require-capability",
8279
+ "--subagent",
8280
+ "--reviewer",
8281
+ "--yes",
8282
+ "--approve",
8283
+ "--deny",
8284
+ "--json",
8285
+ "--jsonl",
8286
+ "--session",
8287
+ "--continue",
8288
+ "--status",
8289
+ "--limit",
8290
+ "--cursor",
8291
+ "--before",
8292
+ "--reason",
8293
+ "--cascade",
8294
+ "--final",
8295
+ "--apply",
8296
+ "--help",
8297
+ "--version"
8298
+ ];
8299
+ var CLI_OPTION_DEFINITIONS = Object.fromEntries(CLI_OPTION_NAMES.map((name) => [name, {
8300
+ repeatable: repeatableOptions.has(name),
8301
+ conflictsWith: conflicts[name] ?? []
8302
+ }]));
8303
+ var locator = ["--workspace", "--state-dir", "--store", "--tenant", "--user", "--namespace"];
8304
+ var provider = ["--provider", "--model"];
8305
+ var project = ["--mcp-config", "--context-config", "--no-project-context"];
8306
+ var execution = [
8307
+ "--execution",
8308
+ "--oci-runtime",
8309
+ "--oci-image",
8310
+ "--oci-allow-command",
8311
+ "--oci-shell",
8312
+ "--oci-max-process-runtime-ms",
8313
+ "--oci-max-process-output-bytes",
8314
+ "--oci-max-memory-mb",
8315
+ "--oci-max-pids",
8316
+ "--oci-max-cpus",
8317
+ "--oci-max-workspace-bytes",
8318
+ "--oci-max-file-write-bytes",
8319
+ "--oci-tmpfs-mb"
8320
+ ];
8321
+ var budgets = [
8322
+ "--max-steps",
8323
+ "--timeout-ms",
8324
+ "--max-tool-calls",
8325
+ "--max-tool-errors",
8326
+ "--max-input-tokens",
8327
+ "--max-output-tokens",
8328
+ "--max-total-tokens",
8329
+ "--max-cost-usd",
8330
+ "--input-cost-per-million",
8331
+ "--output-cost-per-million",
8332
+ "--subagent-max-steps",
8333
+ "--subagent-max-tool-calls",
8334
+ "--subagent-max-tool-errors",
8335
+ "--subagent-max-input-tokens",
8336
+ "--subagent-max-output-tokens",
8337
+ "--subagent-max-total-tokens",
8338
+ "--subagent-timeout-ms"
8339
+ ];
8340
+ var childBudgets = [
8341
+ "--subagent-max-steps",
8342
+ "--subagent-max-tool-calls",
8343
+ "--subagent-max-tool-errors",
8344
+ "--subagent-max-input-tokens",
8345
+ "--subagent-max-output-tokens",
8346
+ "--subagent-max-total-tokens",
8347
+ "--subagent-timeout-ms"
8348
+ ];
8349
+ var agent = [
8350
+ ...provider,
8351
+ "--route",
8352
+ ...locator,
8353
+ ...project,
8354
+ ...execution,
8355
+ ...budgets,
8356
+ "--allow-check",
8357
+ "--require-capability",
8358
+ "--subagent"
8359
+ ];
8360
+ var contract = (allowed, required = []) => {
8361
+ const allowedSet = new Set(allowed);
8362
+ return {
8363
+ allowed,
8364
+ required,
8365
+ repeatable: allowed.filter((name) => repeatableOptions.has(name)),
8366
+ conflicts: Object.fromEntries(allowed.flatMap((name) => {
8367
+ const relevant = conflicts[name]?.filter((other) => allowedSet.has(other)) ?? [];
8368
+ return relevant.length > 0 ? [[name, relevant]] : [];
8369
+ }))
8370
+ };
8371
+ };
8372
+ var CLI_COMMAND_OPTION_CONTRACTS = {
8373
+ run: contract([...agent, "--idempotency-key", "--yes", "--json", "--jsonl"]),
8374
+ review: contract([
8375
+ ...provider,
8376
+ "--route",
8377
+ ...locator,
8378
+ "--context-config",
8379
+ "--no-project-context",
8380
+ ...childBudgets,
8381
+ "--max-parallel-reviews",
8382
+ "--require-capability",
8383
+ "--reviewer",
8384
+ "--json"
8385
+ ]),
8386
+ chat: contract([...agent, "--yes", "--session", "--continue"]),
8387
+ providers: contract(["--json"]),
8388
+ doctor: contract([...provider, ...locator, ...project, ...execution, ...budgets, "--allow-check", "--require-capability", "--subagent", "--json"]),
8389
+ resume: contract([...locator, "--approve", "--deny", "--json", "--jsonl"], [["--approve", "--deny"]]),
8390
+ "runs:list": contract([...locator, "--status", "--limit", "--cursor", "--json"]),
8391
+ "runs:inspect": contract([...locator, "--json"]),
8392
+ "runs:cancel": contract([...locator, "--reason", "--cascade", "--final", "--json"]),
8393
+ "runs:cleanup": contract([...locator, "--before", "--status", "--limit", "--json"], ["--before"]),
8394
+ "runs:export": contract([...locator, "--json"]),
8395
+ "sessions:list": contract([...locator, "--limit", "--json"]),
8396
+ "sessions:inspect": contract([...locator, "--json"]),
8397
+ "sessions:rename": contract([...locator, "--json"]),
8398
+ "sessions:fork": contract([...locator, "--json"]),
8399
+ "sessions:archive": contract([...locator, "--json"]),
8400
+ "changes:create": contract(["--patch"], ["--patch"]),
8401
+ "changes:verify": contract(["--patch", "--preconditions", "--now"], ["--patch"]),
8402
+ "state:status": contract([...locator, "--json"]),
8403
+ "state:export": contract([...locator, "--json"]),
8404
+ "state:import": contract([...locator, "--apply", "--json"]),
8405
+ help: contract(["--help"]),
8406
+ version: contract(["--version"])
8407
+ };
8408
+ var validateCliCommandOptions = (commandKey, counts) => {
8409
+ const commandContract = CLI_COMMAND_OPTION_CONTRACTS[commandKey];
8410
+ const allowed = new Set(commandContract.allowed);
8411
+ for (const [name, count] of counts) {
8412
+ if (!allowed.has(name)) {
8413
+ throw new Error(`${name} is not supported by ${commandKey.replace(":", " ")}.`);
8414
+ }
8415
+ if (count > 1 && !commandContract.repeatable.includes(name)) {
8416
+ throw new Error(`${name} cannot be repeated for ${commandKey.replace(":", " ")}.`);
8417
+ }
8418
+ for (const conflicting of commandContract.conflicts[name] ?? []) {
8419
+ if (counts.has(conflicting)) {
8420
+ throw new Error(`${name} cannot be combined with ${conflicting}.`);
8421
+ }
8422
+ }
8423
+ }
8424
+ for (const requirement of commandContract.required) {
8425
+ if (typeof requirement === "string") {
8426
+ if (!counts.has(requirement)) {
8427
+ throw new Error(`${requirement} is required by ${commandKey.replace(":", " ")}.`);
8428
+ }
8429
+ continue;
8430
+ }
8431
+ if (!requirement.some((name) => counts.has(name))) {
8432
+ throw new Error(`${requirement.join(" or ")} is required by ${commandKey.replace(":", " ")}.`);
8433
+ }
8434
+ }
8435
+ };
8436
+
8437
+ // src/state-backup.ts
8438
+ import { createHash as createHash11, randomUUID as randomUUID6 } from "node:crypto";
8439
+ import { constants as fsConstants3 } from "node:fs";
8440
+ import { chmod as chmod4, link as link2, lstat as lstat9, open as open5, realpath as realpath5, unlink as unlink2 } from "node:fs/promises";
8441
+ import path12 from "node:path";
8442
+ import { z as z6 } from "zod";
8443
+ import { normalizeAgentRunState } from "@zhivex-ai/agents";
8444
+ var HARNESS_STATE_BACKUP_SCHEMA_VERSION = 1;
8445
+ var HARNESS_STATE_BACKUP_MAX_BYTES = 64 * 1024 * 1024;
8446
+ var terminalRunStatuses = new Set(["completed", "failed", "cancelled", "timed_out"]);
8447
+ var terminalSessionStatuses = new Set(["completed", "failed", "cancelled", "timed_out"]);
8448
+ var digestSchema = z6.string().regex(/^sha256:[a-f0-9]{64}$/);
8449
+ var bindingKeySchema = z6.string().regex(/^[a-f0-9]{64}$/);
8450
+ var jsonRecordSchema = z6.record(z6.string(), z6.unknown());
8451
+ var durableScopeSchema = z6.object({
8452
+ tenantId: z6.string().min(1),
8453
+ userId: z6.string().min(1).optional(),
8454
+ namespace: z6.string().min(1).optional()
8455
+ }).strict();
8456
+ var journalEntrySchema = z6.object({
8457
+ runId: z6.string().min(1),
8458
+ scope: durableScopeSchema,
8459
+ toolCallId: z6.string().min(1),
8460
+ toolName: z6.string().min(1),
8461
+ status: z6.enum(["pending", "running", "completed", "failed"]),
8462
+ idempotencyKey: z6.string().min(1),
8463
+ revision: z6.number().int().nonnegative(),
8464
+ input: z6.json().optional(),
8465
+ output: z6.json().optional(),
8466
+ error: z6.object({ message: z6.string() }).strict().optional(),
8467
+ startedAt: z6.number().nonnegative().optional(),
8468
+ completedAt: z6.number().nonnegative().optional(),
8469
+ updatedAt: z6.number().nonnegative()
8470
+ }).passthrough();
8471
+ var runRecordSchema = z6.object({
8472
+ key: z6.string().min(1).max(1024),
8473
+ state: jsonRecordSchema,
8474
+ updatedAt: z6.number().int().nonnegative()
8475
+ }).strict();
8476
+ var journalRecordSchema = z6.object({
8477
+ runKey: z6.string().min(1).max(1024),
8478
+ toolCallId: z6.string().min(1).max(1024),
8479
+ entry: journalEntrySchema,
8480
+ revision: z6.number().int().nonnegative(),
8481
+ updatedAt: z6.number().int().nonnegative()
8482
+ }).strict();
8483
+ var idempotencyRecordSchema = z6.object({
8484
+ key: z6.string().min(1).max(1024),
8485
+ runKey: z6.string().min(1).max(1024),
8486
+ updatedAt: z6.number().int().nonnegative()
8487
+ }).strict();
8488
+ var parentRecordSchema = z6.object({
8489
+ runKey: z6.string().min(1).max(1024),
8490
+ parentRunKey: z6.string().min(1).max(1024),
8491
+ updatedAt: z6.number().int().nonnegative()
8492
+ }).strict();
8493
+ var memoryRecordSchema = z6.object({
8494
+ key: z6.string().min(1).max(1024),
8495
+ messages: z6.array(z6.unknown()),
8496
+ updatedAt: z6.number().int().nonnegative()
8497
+ }).strict();
8498
+ var sessionRecordSchema = z6.object({
8499
+ sessionId: z6.string().min(1).max(260),
8500
+ workspaceKey: bindingKeySchema,
8501
+ scopeKey: bindingKeySchema,
8502
+ title: z6.string().nullable(),
8503
+ parentSessionId: z6.string().nullable(),
8504
+ forkedFromTurnId: z6.string().nullable(),
8505
+ revision: z6.number().int().nonnegative(),
8506
+ activitySequence: z6.number().int().nonnegative(),
8507
+ createdAt: z6.number().int().nonnegative(),
8508
+ updatedAt: z6.number().int().nonnegative(),
8509
+ archivedAt: z6.number().int().nonnegative().nullable(),
8510
+ deletedAt: z6.number().int().nonnegative().nullable(),
8511
+ metadataBytes: z6.number().int().nonnegative()
8512
+ }).strict();
8513
+ var sessionRunRecordSchema = z6.object({
8514
+ turnId: z6.string().min(1).max(260),
8515
+ sourceTurnId: z6.string().nullable(),
8516
+ sessionId: z6.string().min(1).max(260),
8517
+ ordinal: z6.number().int().nonnegative(),
8518
+ runId: z6.string().min(1).max(260),
8519
+ provider: z6.string().min(1).max(260),
8520
+ model: z6.string().min(1).max(260),
8521
+ role: z6.string().nullable(),
8522
+ status: z6.string().min(1),
8523
+ createdAt: z6.number().int().nonnegative(),
8524
+ updatedAt: z6.number().int().nonnegative(),
8525
+ completedAt: z6.number().int().nonnegative().nullable(),
8526
+ metadataBytes: z6.number().int().nonnegative()
8527
+ }).strict();
8528
+ var stateBackupPayloadSchema = z6.object({
8529
+ schemaVersion: z6.literal(HARNESS_STATE_BACKUP_SCHEMA_VERSION),
8530
+ kind: z6.literal("state-backup"),
8531
+ createdAt: z6.iso.datetime({ precision: 3 }),
8532
+ binding: z6.object({
8533
+ workspaceKey: bindingKeySchema,
8534
+ scopeKey: bindingKeySchema,
8535
+ scopePrefix: z6.string().min(1).max(1024)
8536
+ }).strict(),
8537
+ schemas: z6.object({
8538
+ operations: z6.literal(HARNESS_OPERATIONS_SCHEMA_VERSION),
8539
+ sessions: z6.literal(HARNESS_SESSION_SCHEMA_VERSION)
8540
+ }).strict(),
8541
+ records: z6.object({
8542
+ runs: z6.array(runRecordSchema),
8543
+ toolJournal: z6.array(journalRecordSchema),
8544
+ idempotency: z6.array(idempotencyRecordSchema),
8545
+ parents: z6.array(parentRecordSchema),
8546
+ memory: z6.array(memoryRecordSchema),
8547
+ sessions: z6.array(sessionRecordSchema),
8548
+ sessionRuns: z6.array(sessionRunRecordSchema)
8549
+ }).strict()
8550
+ }).strict();
8551
+ var stateBackupBundleSchema = stateBackupPayloadSchema.extend({ checksum: digestSchema }).strict();
8552
+ var canonicalJson4 = (value) => {
8553
+ if (value === null || typeof value !== "object")
8554
+ return JSON.stringify(value);
8555
+ if (Array.isArray(value))
8556
+ return `[${value.map(canonicalJson4).join(",")}]`;
8557
+ return `{${Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson4(entry)}`).join(",")}}`;
8558
+ };
8559
+ var checksumPayload = (payload) => `sha256:${createHash11("sha256").update(canonicalJson4(payload)).digest("hex")}`;
8560
+ var stableKey2 = (kind, value) => createHash11("sha256").update(kind).update("\x00").update(value).digest("hex");
8561
+ var scopeValue2 = (config) => `${config.scope.tenantId}\x00${config.scope.userId ?? ""}\x00${config.scope.namespace ?? ""}`;
8562
+ var scopePrefix = (config) => `${encodeURIComponent(config.scope.namespace ?? "default")}:${encodeURIComponent(config.scope.tenantId)}:${encodeURIComponent(config.scope.userId ?? "*")}:`;
8563
+ var stateMatchesScope = (config, state) => {
8564
+ if (!state || typeof state !== "object" || Array.isArray(state))
8565
+ return false;
8566
+ const candidate = state;
8567
+ if (!candidate.scope || typeof candidate.scope !== "object" || Array.isArray(candidate.scope))
8568
+ return false;
8569
+ const scope = candidate.scope;
8570
+ return scope.tenantId === config.scope.tenantId && (scope.userId ?? undefined) === (config.scope.userId ?? undefined) && (scope.namespace ?? undefined) === (config.scope.namespace ?? undefined);
8571
+ };
8572
+ var bindingForConfig = async (config) => ({
8573
+ workspaceKey: stableKey2("workspace", await realpath5(path12.resolve(config.workspace))),
8574
+ scopeKey: stableKey2("scope", scopeValue2(config)),
8575
+ scopePrefix: scopePrefix(config)
8576
+ });
8577
+ var parseJsonRecord = (value, label) => {
8578
+ let parsed;
8579
+ try {
8580
+ parsed = JSON.parse(value);
8581
+ } catch (error) {
8582
+ throw new HarnessStateConflictError(`${label} contains invalid JSON.`, { cause: error });
8583
+ }
8584
+ return jsonRecordSchema.parse(parsed);
8585
+ };
8586
+ var prepareDatabase = async (config) => {
8587
+ if (config.storeBackend !== "sqlite") {
8588
+ throw new HarnessStateConflictError("State backup requires the sqlite store backend.");
8589
+ }
8590
+ const persistence = await openHarnessPersistence(config, { migrateLegacyFileStore: false });
8591
+ persistence.close();
8592
+ const sessions = await openCliSessionStore({
8593
+ workspace: config.workspace,
8594
+ stateDirectory: config.stateDirectory,
8595
+ scope: config.scope
8596
+ });
8597
+ sessions.close();
8598
+ return path12.join(await realpath5(config.stateDirectory), HARNESS_SQLITE_FILE);
8599
+ };
8600
+ var locateExistingDatabase = async (config) => {
8601
+ if (config.storeBackend !== "sqlite") {
8602
+ throw new HarnessStateConflictError("State backup requires the sqlite store backend.");
8603
+ }
8604
+ await validateStateDirectory(config.workspace, config.stateDirectory);
8605
+ let canonicalStateDirectory2;
8606
+ try {
8607
+ canonicalStateDirectory2 = await realpath5(config.stateDirectory);
8608
+ } catch (error) {
8609
+ if (error.code === "ENOENT")
8610
+ return;
8611
+ throw error;
8612
+ }
8613
+ const databasePath = path12.join(canonicalStateDirectory2, HARNESS_SQLITE_FILE);
8614
+ try {
8615
+ const entry = await lstat9(databasePath);
8616
+ if (entry.isSymbolicLink() || !entry.isFile()) {
8617
+ throw new HarnessWorkspaceError(`The SQLite state path must be a real file: ${databasePath}.`);
8618
+ }
8619
+ return databasePath;
8620
+ } catch (error) {
8621
+ if (error.code === "ENOENT")
8622
+ return;
8623
+ throw error;
8624
+ }
8625
+ };
8626
+ var assertTerminalState = (state, label) => {
8627
+ if (!state || typeof state !== "object" || Array.isArray(state)) {
8628
+ throw new HarnessStateConflictError(`${label} is not a terminal run.`);
8629
+ }
8630
+ const candidate = state;
8631
+ if (typeof candidate.runId !== "string" || !terminalRunStatuses.has(String(candidate.status))) {
8632
+ throw new HarnessStateConflictError(`${label} is not a terminal run.`);
8633
+ }
8634
+ if (Array.isArray(candidate.pendingApprovals) && candidate.pendingApprovals.length > 0) {
8635
+ throw new HarnessStateConflictError(`${label} retains approval authority and cannot be backed up.`);
8636
+ }
8637
+ };
8638
+ var validatedRunState = (value, label) => {
8639
+ try {
8640
+ return normalizeAgentRunState(value);
8641
+ } catch (error) {
8642
+ throw new HarnessStateConflictError(`${label} is not a valid AgentRunState.`, { cause: error });
8643
+ }
8644
+ };
8645
+ var readPayload = async (config) => {
8646
+ const databasePath = await prepareDatabase(config);
8647
+ const binding = await bindingForConfig(config);
8648
+ const database = new SqliteDatabase(databasePath, { create: false, strict: true });
8649
+ database.exec("PRAGMA busy_timeout = 5000");
8650
+ database.exec("PRAGMA foreign_keys = ON");
8651
+ database.exec("BEGIN IMMEDIATE");
8652
+ try {
8653
+ const runRows = database.query("SELECT run_id, state_json, updated_at_ms FROM zhivex_agent_runs ORDER BY run_id").all().flatMap((row) => {
8654
+ const state = validatedRunState(parseJsonRecord(row.state_json, `Run ${row.run_id}`), `Run ${row.run_id}`);
8655
+ return stateMatchesScope(config, state) ? [{ row, state }] : [];
8656
+ });
8657
+ const runs = runRows.map(({ row, state }) => {
8658
+ assertTerminalState(state, `Run ${row.run_id}`);
8659
+ return { key: row.run_id, state, updatedAt: row.updated_at_ms };
8660
+ });
8661
+ const runKeys = new Set(runs.map((run) => run.key));
8662
+ const activeLeases = database.query("SELECT run_key, expires_at_ms FROM zhivex_agent_runs_leases").all().filter((row) => runKeys.has(row.run_key) && row.expires_at_ms > Date.now()).length;
8663
+ if (activeLeases > 0) {
8664
+ throw new HarnessStateConflictError("State export refuses to capture active run leases.", { retryable: true });
8665
+ }
8666
+ const journal = database.query("SELECT run_key, tool_call_id, entry_json, revision, updated_at_ms FROM zhivex_agent_runs_tool_journal ORDER BY run_key, tool_call_id").all().filter((row) => runKeys.has(row.run_key)).map((row) => {
8667
+ let entry;
8668
+ try {
8669
+ entry = journalEntrySchema.parse(parseJsonRecord(row.entry_json, `Tool journal ${row.tool_call_id}`));
8670
+ } catch (error) {
8671
+ throw new HarnessStateConflictError(`Tool journal ${row.tool_call_id} is invalid.`, { cause: error });
8672
+ }
8673
+ if (!stateMatchesScope(config, entry)) {
8674
+ throw new HarnessStateConflictError(`Tool journal ${row.tool_call_id} is bound to another durable scope.`);
8675
+ }
8676
+ return {
8677
+ runKey: row.run_key,
8678
+ toolCallId: row.tool_call_id,
8679
+ entry,
8680
+ revision: row.revision,
8681
+ updatedAt: row.updated_at_ms
8682
+ };
8683
+ });
8684
+ const idempotency = database.query("SELECT idempotency_key, run_id, updated_at_ms FROM zhivex_agent_runs_idempotency ORDER BY idempotency_key").all().filter((row) => runKeys.has(row.run_id)).map((row) => ({
8685
+ key: row.idempotency_key,
8686
+ runKey: row.run_id,
8687
+ updatedAt: row.updated_at_ms
8688
+ }));
8689
+ const parents = database.query("SELECT run_id, parent_run_id, updated_at_ms FROM zhivex_agent_runs_parents ORDER BY run_id").all().filter((row) => runKeys.has(row.run_id) && runKeys.has(row.parent_run_id)).map((row) => ({
8690
+ runKey: row.run_id,
8691
+ parentRunKey: row.parent_run_id,
8692
+ updatedAt: row.updated_at_ms
8693
+ }));
8694
+ const memoryKeys = new Set(runs.map((run) => `${binding.scopePrefix}${String(run.state.runId)}`));
8695
+ const memory = database.query("SELECT memory_key, messages_json, updated_at_ms FROM zhivex_agent_memory ORDER BY memory_key").all().filter((row) => memoryKeys.has(row.memory_key)).map((row) => ({
8696
+ key: row.memory_key,
8697
+ messages: z6.array(z6.unknown()).parse(JSON.parse(row.messages_json)),
8698
+ updatedAt: row.updated_at_ms
8699
+ }));
8700
+ const sessionRows = database.query("SELECT * FROM zhivex_cli_sessions ORDER BY session_id").all().filter((row) => row.workspace_key === binding.workspaceKey && row.scope_key === binding.scopeKey);
8701
+ const selectedSessionIds = new Set(sessionRows.map((row) => row.session_id));
8702
+ const sessionRunRows = database.query("SELECT * FROM zhivex_cli_session_runs ORDER BY session_id, ordinal").all().filter((row) => selectedSessionIds.has(row.session_id));
8703
+ for (const row of sessionRunRows) {
8704
+ if (!terminalSessionStatuses.has(row.status) || !runs.some((run) => run.state.runId === row.run_id)) {
8705
+ throw new HarnessStateConflictError(`Session run ${row.run_id} is active or has no terminal run state.`);
8706
+ }
8707
+ }
8708
+ const sessions = sessionRows.map((row) => ({
8709
+ sessionId: row.session_id,
8710
+ workspaceKey: row.workspace_key,
8711
+ scopeKey: row.scope_key,
8712
+ title: row.title,
8713
+ parentSessionId: row.parent_session_id,
8714
+ forkedFromTurnId: row.forked_from_turn_id,
8715
+ revision: row.revision,
8716
+ activitySequence: row.activity_seq,
8717
+ createdAt: row.created_at,
8718
+ updatedAt: row.updated_at,
8719
+ archivedAt: row.archived_at,
8720
+ deletedAt: row.deleted_at,
8721
+ metadataBytes: row.metadata_bytes
8722
+ }));
8723
+ const sessionRuns = sessionRunRows.map((row) => ({
8724
+ turnId: row.turn_id,
8725
+ sourceTurnId: row.source_turn_id,
8726
+ sessionId: row.session_id,
8727
+ ordinal: row.ordinal,
8728
+ runId: row.run_id,
8729
+ provider: row.provider,
8730
+ model: row.model,
8731
+ role: row.role,
8732
+ status: row.status,
8733
+ createdAt: row.created_at,
8734
+ updatedAt: row.updated_at,
8735
+ completedAt: row.completed_at,
8736
+ metadataBytes: row.metadata_bytes
8737
+ }));
8738
+ const payload = stateBackupPayloadSchema.parse({
8739
+ schemaVersion: HARNESS_STATE_BACKUP_SCHEMA_VERSION,
8740
+ kind: "state-backup",
8741
+ createdAt: new Date().toISOString(),
8742
+ binding,
8743
+ schemas: { operations: HARNESS_OPERATIONS_SCHEMA_VERSION, sessions: HARNESS_SESSION_SCHEMA_VERSION },
8744
+ records: { runs, toolJournal: journal, idempotency, parents, memory, sessions, sessionRuns }
8745
+ });
8746
+ database.exec("COMMIT");
8747
+ return payload;
8748
+ } catch (error) {
8749
+ database.exec("ROLLBACK");
8750
+ throw error;
8751
+ } finally {
8752
+ database.close(false);
8753
+ }
8754
+ };
8755
+ var createHarnessStateBackup = async (config) => {
8756
+ const payload = await readPayload(config);
8757
+ return stateBackupBundleSchema.parse({ ...payload, checksum: checksumPayload(payload) });
8758
+ };
8759
+ var writePrivateBackup = async (target, contents) => {
8760
+ const requested = path12.resolve(target);
8761
+ const parent = path12.dirname(requested);
8762
+ let parentHandle;
8763
+ try {
8764
+ parentHandle = await open5(parent, fsConstants3.O_RDONLY | fsConstants3.O_NOFOLLOW);
8765
+ if (!(await parentHandle.stat()).isDirectory()) {
8766
+ throw new Error("Backup parent is not a directory.");
8767
+ }
8768
+ } catch (error) {
8769
+ await parentHandle?.close();
8770
+ throw new HarnessWorkspaceError(`Backup parent must be a real non-symlink directory: ${parent}.`, {
8771
+ cause: error
8772
+ });
8773
+ }
8774
+ const staged = path12.join(parent, `.zhivex-state-backup-${randomUUID6()}.tmp`);
8775
+ let handle;
8776
+ let published = false;
8777
+ let stagedExists = false;
8778
+ try {
8779
+ handle = await open5(staged, fsConstants3.O_WRONLY | fsConstants3.O_CREAT | fsConstants3.O_EXCL | fsConstants3.O_NOFOLLOW, 384);
8780
+ stagedExists = true;
8781
+ await handle.writeFile(contents, "utf8");
8782
+ await handle.sync();
8783
+ await chmod4(staged, 384);
8784
+ await handle.close();
8785
+ handle = undefined;
8786
+ await link2(staged, requested);
8787
+ published = true;
8788
+ await unlink2(staged);
8789
+ stagedExists = false;
8790
+ await parentHandle.sync();
8791
+ } catch (error) {
8792
+ if (published)
8793
+ await unlink2(requested).catch(() => {
8794
+ return;
8795
+ });
8796
+ throw error;
8797
+ } finally {
8798
+ await handle?.close();
8799
+ if (stagedExists)
8800
+ await unlink2(staged).catch(() => {
8801
+ return;
8802
+ });
8803
+ await parentHandle.close();
8804
+ }
8805
+ };
8806
+ var exportHarnessStateBackup = async (config, target) => {
8807
+ const bundle = await createHarnessStateBackup(config);
8808
+ const serialized = `${JSON.stringify(bundle, null, 2)}
8809
+ `;
8810
+ if (Buffer.byteLength(serialized) > HARNESS_STATE_BACKUP_MAX_BYTES) {
8811
+ throw new HarnessStateConflictError("State backup exceeds the supported size limit.");
8812
+ }
8813
+ await writePrivateBackup(target, serialized);
8814
+ return {
8815
+ schemaVersion: HARNESS_STATE_BACKUP_SCHEMA_VERSION,
8816
+ kind: "state-export",
8817
+ path: path12.resolve(target),
8818
+ checksum: bundle.checksum,
8819
+ counts: Object.fromEntries(Object.entries(bundle.records).map(([name, rows]) => [name, rows.length]))
8820
+ };
8821
+ };
8822
+ var readHarnessStateBackup = async (source) => {
8823
+ const { contents, stat: stat4 } = await readRegularFileNoFollow(path12.resolve(source), {
8824
+ label: "Harness state backup",
8825
+ maxBytes: HARNESS_STATE_BACKUP_MAX_BYTES,
8826
+ requireSingleLink: true
8827
+ });
8828
+ if ((stat4.mode & 63) !== 0) {
8829
+ throw new HarnessWorkspaceError("Harness state backup permissions must not grant group or other access.");
8830
+ }
8831
+ let input;
8832
+ try {
8833
+ input = JSON.parse(contents.toString("utf8"));
8834
+ } catch (error) {
8835
+ throw new HarnessStateConflictError("Harness state backup is not valid JSON.", { cause: error });
8836
+ }
8837
+ return validateStateBackupBundle(input);
8838
+ };
8839
+ var validateStateBackupBundle = (input) => {
8840
+ let bundle;
8841
+ try {
8842
+ bundle = stateBackupBundleSchema.parse(input);
8843
+ } catch (error) {
8844
+ throw new HarnessStateConflictError("Harness state backup schema is invalid or unsupported.", { cause: error });
8845
+ }
8846
+ const { checksum, ...payload } = bundle;
8847
+ if (checksumPayload(payload) !== checksum) {
8848
+ throw new HarnessStateConflictError("Harness state backup checksum does not match its payload.");
8849
+ }
8850
+ return bundle;
8851
+ };
8852
+ var validateBundleBinding = async (config, bundle) => {
8853
+ const expected = await bindingForConfig(config);
8854
+ if (canonicalJson4(expected) !== canonicalJson4(bundle.binding)) {
8855
+ throw new HarnessStateConflictError("Harness state backup cannot be rebound to a different workspace or scope.");
8856
+ }
8857
+ const runKeys = new Set(bundle.records.runs.map((run) => run.key));
8858
+ if (runKeys.size !== bundle.records.runs.length) {
8859
+ throw new HarnessStateConflictError("Harness state backup contains duplicate run keys.");
8860
+ }
8861
+ const runIds = new Set;
8862
+ for (const run of bundle.records.runs) {
8863
+ const state = validatedRunState(run.state, `Run ${run.key}`);
8864
+ assertTerminalState(state, `Run ${run.key}`);
8865
+ if (!stateMatchesScope(config, state)) {
8866
+ throw new HarnessStateConflictError(`Run ${run.key} is bound to another durable scope.`);
8867
+ }
8868
+ runIds.add(state.runId);
8869
+ if (run.key !== `${expected.scopePrefix}${state.runId}`) {
8870
+ throw new HarnessStateConflictError(`Run ${run.key} does not match its bound scope and runId.`);
8871
+ }
8872
+ }
8873
+ const journalKeys = new Set;
8874
+ for (const entry of bundle.records.toolJournal) {
8875
+ const journalKey = `${entry.runKey}\x00${entry.toolCallId}`;
8876
+ if (journalKeys.has(journalKey) || !runKeys.has(entry.runKey) || !stateMatchesScope(config, entry.entry) || entry.entry.runId !== entry.runKey.slice(expected.scopePrefix.length)) {
8877
+ throw new HarnessStateConflictError(`Tool journal ${entry.toolCallId} is not bound to an imported run.`);
8878
+ }
8879
+ journalKeys.add(journalKey);
8880
+ }
8881
+ const idempotencyKeys = new Set;
8882
+ for (const entry of bundle.records.idempotency) {
8883
+ if (idempotencyKeys.has(entry.key) || !runKeys.has(entry.runKey)) {
8884
+ throw new HarnessStateConflictError("Idempotency record is duplicated or targets a missing run.");
8885
+ }
8886
+ idempotencyKeys.add(entry.key);
8887
+ const state = bundle.records.runs.find((run) => run.key === entry.runKey).state;
8888
+ if (typeof state.idempotencyKey !== "string" || entry.key !== `${expected.scopePrefix}${state.idempotencyKey}`) {
8889
+ throw new HarnessStateConflictError("Idempotency record does not match its bound run state.");
8890
+ }
8891
+ }
8892
+ const parentKeys = new Set;
8893
+ for (const entry of bundle.records.parents) {
8894
+ if (parentKeys.has(entry.runKey) || !runKeys.has(entry.runKey) || !runKeys.has(entry.parentRunKey)) {
8895
+ throw new HarnessStateConflictError("Parent record targets a missing run.");
8896
+ }
8897
+ parentKeys.add(entry.runKey);
8898
+ }
8899
+ const memoryKeys = new Set;
8900
+ for (const entry of bundle.records.memory) {
8901
+ const memoryRunId = entry.key.startsWith(expected.scopePrefix) ? entry.key.slice(expected.scopePrefix.length) : "";
8902
+ if (memoryKeys.has(entry.key) || !runIds.has(memoryRunId)) {
8903
+ throw new HarnessStateConflictError(`Memory record ${entry.key} is not bound to an imported run.`);
8904
+ }
8905
+ memoryKeys.add(entry.key);
8906
+ }
8907
+ for (const session of bundle.records.sessions) {
8908
+ if (session.workspaceKey !== expected.workspaceKey || session.scopeKey !== expected.scopeKey) {
8909
+ throw new HarnessStateConflictError(`Session ${session.sessionId} is bound to another workspace or scope.`);
8910
+ }
8911
+ }
8912
+ const sessionIds = new Set(bundle.records.sessions.map((session) => session.sessionId));
8913
+ if (sessionIds.size !== bundle.records.sessions.length) {
8914
+ throw new HarnessStateConflictError("Harness state backup contains duplicate session IDs.");
8915
+ }
8916
+ for (const session of bundle.records.sessions) {
8917
+ if (session.parentSessionId && !sessionIds.has(session.parentSessionId)) {
8918
+ throw new HarnessStateConflictError(`Session ${session.sessionId} targets a missing parent session.`);
8919
+ }
8920
+ }
8921
+ const turnIds = new Set;
8922
+ const sessionOrdinals = new Set;
8923
+ const sessionRunIds = new Set;
8924
+ for (const run of bundle.records.sessionRuns) {
8925
+ const ordinalKey = `${run.sessionId}\x00${run.ordinal}`;
8926
+ const sessionRunKey = `${run.sessionId}\x00${run.runId}`;
8927
+ if (turnIds.has(run.turnId) || sessionOrdinals.has(ordinalKey) || sessionRunIds.has(sessionRunKey) || !sessionIds.has(run.sessionId) || !runIds.has(run.runId) || !terminalSessionStatuses.has(run.status)) {
8928
+ throw new HarnessStateConflictError(`Session run ${run.runId} is active or targets a missing session.`);
8929
+ }
8930
+ turnIds.add(run.turnId);
8931
+ sessionOrdinals.add(ordinalKey);
8932
+ sessionRunIds.add(sessionRunKey);
8933
+ }
8934
+ for (const run of bundle.records.sessionRuns) {
8935
+ if (run.sourceTurnId && !turnIds.has(run.sourceTurnId)) {
8936
+ throw new HarnessStateConflictError(`Session run ${run.runId} targets a missing source turn.`);
8937
+ }
8938
+ }
8939
+ };
8940
+ var rowJson = (value) => canonicalJson4(value);
8941
+ var setEquals = (left, right) => left.size === right.size && [...left].every((value) => right.has(value));
8942
+ var importHarnessStateBackup = async (config, bundle, options = {}) => {
8943
+ bundle = validateStateBackupBundle(bundle);
8944
+ await validateBundleBinding(config, bundle);
8945
+ const databasePath = options.dryRun ? await locateExistingDatabase(config) : await prepareDatabase(config);
8946
+ if (!databasePath) {
8947
+ return {
8948
+ schemaVersion: HARNESS_STATE_BACKUP_SCHEMA_VERSION,
8949
+ kind: "state-import",
8950
+ dryRun: true,
8951
+ checksum: bundle.checksum,
8952
+ inserted: {},
8953
+ identical: 0
8954
+ };
8955
+ }
8956
+ const database = new SqliteDatabase(databasePath, {
8957
+ create: false,
8958
+ strict: true,
8959
+ ...options.dryRun ? { readonly: true } : {}
8960
+ });
8961
+ database.exec("PRAGMA busy_timeout = 5000");
8962
+ database.exec("PRAGMA foreign_keys = ON");
8963
+ database.exec(options.dryRun ? "BEGIN" : "BEGIN IMMEDIATE");
8964
+ const availableTables = new Set(database.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
8965
+ let writes = 0;
8966
+ let identical = 0;
8967
+ const inserted = {};
8968
+ const checkFailure = () => {
8969
+ if (options.failAfterWrites !== undefined && writes >= options.failAfterWrites) {
8970
+ throw new Error("Injected state import failure.");
8971
+ }
8972
+ };
8973
+ const insertOrCompare = (table, keyWhere, keyBindings, selectColumns, expected, insertSql, insertBindings) => {
8974
+ if (!availableTables.has(table)) {
8975
+ if (options.dryRun)
8976
+ return;
8977
+ throw new HarnessStateConflictError(`Required state table ${table} is unavailable.`);
8978
+ }
8979
+ const existing = database.query(`SELECT ${selectColumns} FROM ${table} WHERE ${keyWhere}`).get(...keyBindings);
8980
+ if (existing) {
8981
+ const actual = Object.values(existing).map((value) => typeof value === "string" && (value.startsWith("{") || value.startsWith("[")) ? rowJson(JSON.parse(value)) : value);
8982
+ const normalizedExpected = expected.map((value) => typeof value === "string" && (value.startsWith("{") || value.startsWith("[")) ? rowJson(JSON.parse(value)) : value);
8983
+ if (rowJson(actual) !== rowJson(normalizedExpected)) {
8984
+ throw new HarnessStateConflictError(`Conflicting state already exists in ${table}.`);
8985
+ }
8986
+ identical += 1;
8987
+ return;
8988
+ }
8989
+ if (options.dryRun)
8990
+ return;
8991
+ checkFailure();
8992
+ database.query(insertSql).run(...insertBindings);
8993
+ writes += 1;
8994
+ inserted[table] = (inserted[table] ?? 0) + 1;
8995
+ };
8996
+ try {
8997
+ const expectedKeys = {
8998
+ runs: new Set(bundle.records.runs.map((row) => row.key)),
8999
+ toolJournal: new Set(bundle.records.toolJournal.map((row) => `${row.runKey}\x00${row.toolCallId}`)),
9000
+ idempotency: new Set(bundle.records.idempotency.map((row) => row.key)),
9001
+ parents: new Set(bundle.records.parents.map((row) => row.runKey)),
9002
+ memory: new Set(bundle.records.memory.map((row) => row.key)),
9003
+ sessions: new Set(bundle.records.sessions.map((row) => row.sessionId)),
9004
+ sessionRuns: new Set(bundle.records.sessionRuns.map((row) => row.turnId))
9005
+ };
9006
+ const destinationRunRows = availableTables.has("zhivex_agent_runs") ? database.query("SELECT run_id, state_json, updated_at_ms FROM zhivex_agent_runs ORDER BY run_id").all().filter((row) => stateMatchesScope(config, parseJsonRecord(row.state_json, `Run ${row.run_id}`))) : [];
9007
+ const destinationRunKeys = new Set(destinationRunRows.map((row) => row.run_id));
9008
+ const destinationSessionRows = availableTables.has("zhivex_cli_sessions") ? database.query("SELECT * FROM zhivex_cli_sessions ORDER BY session_id").all().filter((row) => row.workspace_key === bundle.binding.workspaceKey && row.scope_key === bundle.binding.scopeKey) : [];
9009
+ const destinationSessionIds = new Set(destinationSessionRows.map((row) => row.session_id));
9010
+ const destinationKeys = {
9011
+ runs: destinationRunKeys,
9012
+ toolJournal: new Set(availableTables.has("zhivex_agent_runs_tool_journal") ? database.query("SELECT run_key, tool_call_id, entry_json, revision, updated_at_ms FROM zhivex_agent_runs_tool_journal").all().filter((row) => destinationRunKeys.has(row.run_key)).map((row) => `${row.run_key}\x00${row.tool_call_id}`) : []),
9013
+ idempotency: new Set(availableTables.has("zhivex_agent_runs_idempotency") ? database.query("SELECT idempotency_key, run_id, updated_at_ms FROM zhivex_agent_runs_idempotency").all().filter((row) => destinationRunKeys.has(row.run_id)).map((row) => row.idempotency_key) : []),
9014
+ parents: new Set(availableTables.has("zhivex_agent_runs_parents") ? database.query("SELECT run_id, parent_run_id, updated_at_ms FROM zhivex_agent_runs_parents").all().filter((row) => destinationRunKeys.has(row.run_id)).map((row) => row.run_id) : []),
9015
+ memory: new Set(availableTables.has("zhivex_agent_memory") ? database.query("SELECT memory_key, messages_json, updated_at_ms FROM zhivex_agent_memory").all().filter((row) => destinationRunRows.some((run) => {
9016
+ const state = JSON.parse(run.state_json);
9017
+ return row.memory_key === `${bundle.binding.scopePrefix}${String(state.runId)}`;
9018
+ })).map((row) => row.memory_key) : []),
9019
+ sessions: destinationSessionIds,
9020
+ sessionRuns: new Set(availableTables.has("zhivex_cli_session_runs") ? database.query("SELECT * FROM zhivex_cli_session_runs ORDER BY session_id, ordinal").all().filter((row) => destinationSessionIds.has(row.session_id)).map((row) => row.turn_id) : [])
9021
+ };
9022
+ if (availableTables.has("zhivex_agent_runs_leases")) {
9023
+ const activeLease = database.query("SELECT run_key, expires_at_ms FROM zhivex_agent_runs_leases").all().some((row) => (destinationRunKeys.has(row.run_key) || expectedKeys.runs.has(row.run_key)) && row.expires_at_ms > Date.now());
9024
+ if (activeLease) {
9025
+ throw new HarnessStateConflictError("State import refuses a destination with active run leases.", {
9026
+ retryable: true
9027
+ });
9028
+ }
9029
+ }
9030
+ const destinationHasState = Object.values(destinationKeys).some((keys) => keys.size > 0);
9031
+ if (destinationHasState && Object.keys(expectedKeys).some((name) => !setEquals(destinationKeys[name], expectedKeys[name]))) {
9032
+ throw new HarnessStateConflictError("State import requires an empty destination or an exactly identical prior import.");
9033
+ }
9034
+ for (const run of bundle.records.runs)
9035
+ insertOrCompare("zhivex_agent_runs", "run_id = ?", [run.key], "state_json, updated_at_ms", [JSON.stringify(run.state), run.updatedAt], "INSERT INTO zhivex_agent_runs (run_id, state_json, updated_at_ms) VALUES (?, ?, ?)", [run.key, JSON.stringify(run.state), run.updatedAt]);
9036
+ for (const entry of bundle.records.idempotency)
9037
+ insertOrCompare("zhivex_agent_runs_idempotency", "idempotency_key = ?", [entry.key], "run_id, updated_at_ms", [entry.runKey, entry.updatedAt], "INSERT INTO zhivex_agent_runs_idempotency (idempotency_key, run_id, updated_at_ms) VALUES (?, ?, ?)", [entry.key, entry.runKey, entry.updatedAt]);
9038
+ for (const entry of bundle.records.parents)
9039
+ insertOrCompare("zhivex_agent_runs_parents", "run_id = ?", [entry.runKey], "parent_run_id, updated_at_ms", [entry.parentRunKey, entry.updatedAt], "INSERT INTO zhivex_agent_runs_parents (run_id, parent_run_id, updated_at_ms) VALUES (?, ?, ?)", [entry.runKey, entry.parentRunKey, entry.updatedAt]);
9040
+ for (const entry of bundle.records.toolJournal)
9041
+ insertOrCompare("zhivex_agent_runs_tool_journal", "run_key = ? AND tool_call_id = ?", [entry.runKey, entry.toolCallId], "entry_json, revision, updated_at_ms", [JSON.stringify(entry.entry), entry.revision, entry.updatedAt], "INSERT INTO zhivex_agent_runs_tool_journal (run_key, tool_call_id, entry_json, revision, updated_at_ms) VALUES (?, ?, ?, ?, ?)", [entry.runKey, entry.toolCallId, JSON.stringify(entry.entry), entry.revision, entry.updatedAt]);
9042
+ for (const entry of bundle.records.memory)
9043
+ insertOrCompare("zhivex_agent_memory", "memory_key = ?", [entry.key], "messages_json, updated_at_ms", [JSON.stringify(entry.messages), entry.updatedAt], "INSERT INTO zhivex_agent_memory (memory_key, messages_json, updated_at_ms) VALUES (?, ?, ?)", [entry.key, JSON.stringify(entry.messages), entry.updatedAt]);
9044
+ for (const session of bundle.records.sessions)
9045
+ insertOrCompare("zhivex_cli_sessions", "session_id = ?", [session.sessionId], "workspace_key, scope_key, title, parent_session_id, forked_from_turn_id, revision, activity_seq, created_at, updated_at, archived_at, deleted_at, metadata_bytes", [
9046
+ session.workspaceKey,
9047
+ session.scopeKey,
9048
+ session.title,
9049
+ session.parentSessionId,
9050
+ session.forkedFromTurnId,
9051
+ session.revision,
9052
+ session.activitySequence,
9053
+ session.createdAt,
9054
+ session.updatedAt,
9055
+ session.archivedAt,
9056
+ session.deletedAt,
9057
+ session.metadataBytes
9058
+ ], "INSERT INTO zhivex_cli_sessions (session_id, workspace_key, scope_key, title, parent_session_id, forked_from_turn_id, revision, activity_seq, created_at, updated_at, archived_at, deleted_at, metadata_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [
9059
+ session.sessionId,
9060
+ session.workspaceKey,
9061
+ session.scopeKey,
9062
+ session.title,
9063
+ session.parentSessionId,
9064
+ session.forkedFromTurnId,
9065
+ session.revision,
9066
+ session.activitySequence,
9067
+ session.createdAt,
9068
+ session.updatedAt,
9069
+ session.archivedAt,
9070
+ session.deletedAt,
9071
+ session.metadataBytes
9072
+ ]);
9073
+ for (const run of bundle.records.sessionRuns)
9074
+ insertOrCompare("zhivex_cli_session_runs", "turn_id = ?", [run.turnId], "source_turn_id, session_id, ordinal, run_id, provider, model, role, status, created_at, updated_at, completed_at, metadata_bytes", [
9075
+ run.sourceTurnId,
9076
+ run.sessionId,
9077
+ run.ordinal,
9078
+ run.runId,
9079
+ run.provider,
9080
+ run.model,
9081
+ run.role,
9082
+ run.status,
9083
+ run.createdAt,
9084
+ run.updatedAt,
9085
+ run.completedAt,
9086
+ run.metadataBytes
9087
+ ], "INSERT INTO zhivex_cli_session_runs (turn_id, source_turn_id, session_id, ordinal, run_id, provider, model, role, status, created_at, updated_at, completed_at, metadata_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [
9088
+ run.turnId,
9089
+ run.sourceTurnId,
9090
+ run.sessionId,
9091
+ run.ordinal,
9092
+ run.runId,
9093
+ run.provider,
9094
+ run.model,
9095
+ run.role,
9096
+ run.status,
9097
+ run.createdAt,
9098
+ run.updatedAt,
9099
+ run.completedAt,
9100
+ run.metadataBytes
9101
+ ]);
9102
+ if (options.dryRun)
9103
+ database.exec("ROLLBACK");
9104
+ else
9105
+ database.exec("COMMIT");
9106
+ return {
9107
+ schemaVersion: HARNESS_STATE_BACKUP_SCHEMA_VERSION,
9108
+ kind: "state-import",
9109
+ dryRun: options.dryRun ?? false,
9110
+ checksum: bundle.checksum,
9111
+ inserted,
9112
+ identical
9113
+ };
9114
+ } catch (error) {
9115
+ database.exec("ROLLBACK");
9116
+ throw error;
9117
+ } finally {
9118
+ database.close(false);
9119
+ }
9120
+ };
9121
+ var importHarnessStateBackupFile = async (config, source, options = {}) => importHarnessStateBackup(config, await readHarnessStateBackup(source), options);
9122
+ var inspectHarnessState = async (config) => {
9123
+ const payload = await readPayload(config);
9124
+ return {
9125
+ schemaVersion: HARNESS_STATE_BACKUP_SCHEMA_VERSION,
9126
+ kind: "state-status",
9127
+ compatible: true,
9128
+ schemas: payload.schemas,
9129
+ counts: Object.fromEntries(Object.entries(payload.records).map(([name, rows]) => [name, rows.length]))
9130
+ };
9131
+ };
9132
+
7687
9133
  // src/cli.ts
7688
9134
  var HARNESS_RESUME_METADATA_KEY = "zhivexHarnessResume";
7689
9135
  var HARNESS_RESUME_METADATA_SCHEMA_VERSION = 1;
@@ -7693,11 +9139,30 @@ var CLI_EXIT_CODES = {
7693
9139
  usageError: 2,
7694
9140
  doctorFailed: 3
7695
9141
  };
7696
- var COMMANDS = new Set(["run", "review", "chat", "providers", "doctor", "resume", "runs", "sessions", "changes", "help", "version"]);
7697
- var RUNS_COMMANDS = new Set(["list", "inspect", "cancel", "cleanup", "export"]);
7698
- var SESSIONS_COMMANDS = new Set(["list", "inspect", "rename", "fork", "archive"]);
7699
- var CHANGES_COMMANDS = new Set(["create", "verify"]);
7700
- var CLI_TIMESTAMP_SCHEMA = z6.iso.datetime({ precision: 3 });
9142
+ var CLI_STREAM_ERROR_SEQUENCE = Symbol("cliStreamErrorSequence");
9143
+ var terminalErrorRedaction = createRedactionPolicy4({ includeEmails: true });
9144
+ var annotateCliStreamError = (error, lastSequence) => {
9145
+ const normalized = error instanceof Error ? error : normalizeHarnessError(error);
9146
+ Object.defineProperty(normalized, CLI_STREAM_ERROR_SEQUENCE, {
9147
+ configurable: true,
9148
+ enumerable: false,
9149
+ value: (lastSequence ?? 0) + 1
9150
+ });
9151
+ return normalized;
9152
+ };
9153
+ var cliStreamErrorSequence = (error) => error && typeof error === "object" && Number.isSafeInteger(error[CLI_STREAM_ERROR_SEQUENCE]) ? error[CLI_STREAM_ERROR_SEQUENCE] : 1;
9154
+ var terminalErrorMessage = (error) => terminalErrorRedaction.redactText(error instanceof Error ? error.message : String(error));
9155
+ var CLI_COMMANDS = ["run", "review", "chat", "providers", "doctor", "resume", "runs", "sessions", "changes", "state", "help", "version"];
9156
+ var CLI_RUNS_COMMANDS = ["list", "inspect", "cancel", "cleanup", "export"];
9157
+ var CLI_SESSIONS_COMMANDS = ["list", "inspect", "rename", "fork", "archive"];
9158
+ var CLI_CHANGES_COMMANDS = ["create", "verify"];
9159
+ var CLI_STATE_COMMANDS = ["status", "export", "import"];
9160
+ var COMMANDS = new Set(CLI_COMMANDS);
9161
+ var RUNS_COMMANDS = new Set(CLI_RUNS_COMMANDS);
9162
+ var SESSIONS_COMMANDS = new Set(CLI_SESSIONS_COMMANDS);
9163
+ var CHANGES_COMMANDS = new Set(CLI_CHANGES_COMMANDS);
9164
+ var STATE_COMMANDS = new Set(CLI_STATE_COMMANDS);
9165
+ var CLI_TIMESTAMP_SCHEMA = z7.iso.datetime({ precision: 3 });
7701
9166
  var RUN_STATUSES = new Set([
7702
9167
  "queued",
7703
9168
  "running",
@@ -7710,9 +9175,9 @@ var RUN_STATUSES = new Set([
7710
9175
  "timed_out"
7711
9176
  ]);
7712
9177
 
7713
- class CliUsageError extends Error {
9178
+ class CliUsageError extends HarnessError {
7714
9179
  constructor(message) {
7715
- super(message);
9180
+ super(message, { code: "CLI_USAGE_INVALID", category: "usage" });
7716
9181
  this.name = "CliUsageError";
7717
9182
  }
7718
9183
  }
@@ -7861,6 +9326,7 @@ var parseCliArgs = (argv) => {
7861
9326
  command,
7862
9327
  cascade: false,
7863
9328
  final: false,
9329
+ apply: false,
7864
9330
  yes: false,
7865
9331
  json: false,
7866
9332
  jsonl: false,
@@ -7868,6 +9334,7 @@ var parseCliArgs = (argv) => {
7868
9334
  implicitCommand: true
7869
9335
  };
7870
9336
  let positionalOnly = false;
9337
+ const optionCounts = new Map;
7871
9338
  for (let index = 0;index < argv.length; index += 1) {
7872
9339
  const argument = argv[index];
7873
9340
  if (!argument) {
@@ -7881,6 +9348,10 @@ var parseCliArgs = (argv) => {
7881
9348
  positionalOnly = true;
7882
9349
  continue;
7883
9350
  }
9351
+ const canonicalOption = argument === "-h" ? "--help" : argument === "-v" ? "--version" : argument;
9352
+ if (canonicalOption in CLI_OPTION_DEFINITIONS) {
9353
+ optionCounts.set(canonicalOption, (optionCounts.get(canonicalOption) ?? 0) + 1);
9354
+ }
7884
9355
  if (!commandWasExplicit && COMMANDS.has(argument)) {
7885
9356
  command = argument;
7886
9357
  options.command = command;
@@ -8225,6 +9696,9 @@ var parseCliArgs = (argv) => {
8225
9696
  case "--final":
8226
9697
  options.final = true;
8227
9698
  break;
9699
+ case "--apply":
9700
+ options.apply = true;
9701
+ break;
8228
9702
  case "--help":
8229
9703
  case "-h":
8230
9704
  options.command = "help";
@@ -8274,9 +9748,6 @@ var parseCliArgs = (argv) => {
8274
9748
  }
8275
9749
  options.runId = runId;
8276
9750
  }
8277
- if (runsCommand === "cleanup" && options.before === undefined) {
8278
- throw new CliUsageError("runs cleanup requires --before.");
8279
- }
8280
9751
  if (positional.length > 0) {
8281
9752
  throw new CliUsageError(`runs ${runsCommand} received unexpected positional arguments.`);
8282
9753
  }
@@ -8313,15 +9784,27 @@ var parseCliArgs = (argv) => {
8313
9784
  throw new CliUsageError(`changes ${changesCommand} requires an input JSON file.`);
8314
9785
  }
8315
9786
  options.artifactPath = artifactPath;
8316
- if (!options.patchPath) {
8317
- throw new CliUsageError(`changes ${changesCommand} requires --patch <file>.`);
8318
- }
8319
9787
  if (changesCommand === "create" && (options.preconditionsPath || options.verificationTime)) {
8320
9788
  throw new CliUsageError("--preconditions and --now are only supported by changes verify.");
8321
9789
  }
8322
9790
  if (positional.length > 0) {
8323
9791
  throw new CliUsageError(`changes ${changesCommand} received unexpected positional arguments.`);
8324
9792
  }
9793
+ } else if (options.command === "state") {
9794
+ const stateCommand = positional.shift();
9795
+ if (!stateCommand || !STATE_COMMANDS.has(stateCommand)) {
9796
+ throw new CliUsageError("state requires one of: status, export, import.");
9797
+ }
9798
+ options.stateCommand = stateCommand;
9799
+ if (stateCommand !== "status") {
9800
+ const backupPath = positional.shift();
9801
+ if (!backupPath)
9802
+ throw new CliUsageError(`state ${stateCommand} requires a backup JSON path.`);
9803
+ options.backupPath = backupPath;
9804
+ }
9805
+ if (positional.length > 0) {
9806
+ throw new CliUsageError(`state ${stateCommand} received unexpected positional arguments.`);
9807
+ }
8325
9808
  } else if (options.command === "run" || options.command === "review") {
8326
9809
  const prompt = positional.join(" ").trim();
8327
9810
  if (prompt) {
@@ -8330,9 +9813,21 @@ var parseCliArgs = (argv) => {
8330
9813
  } else if (positional.length > 0) {
8331
9814
  throw new CliUsageError(`${options.command} does not accept positional arguments.`);
8332
9815
  }
9816
+ const commandKey = options.command === "runs" ? `runs:${options.runsCommand}` : options.command === "sessions" ? `sessions:${options.sessionsCommand}` : options.command === "changes" ? `changes:${options.changesCommand}` : options.command === "state" ? `state:${options.stateCommand}` : options.command;
9817
+ try {
9818
+ validateCliCommandOptions(commandKey, optionCounts);
9819
+ } catch (error) {
9820
+ throw new CliUsageError(error instanceof Error ? error.message : String(error));
9821
+ }
9822
+ if (options.command === "review") {
9823
+ const invalidRoute = options.routes?.map((route) => parseHarnessModelRoute(route)).find((route) => route.profile !== "explorer" && route.profile !== "reviewer");
9824
+ if (invalidRoute) {
9825
+ throw new CliUsageError(`review cannot route the unused ${invalidRoute.profile} profile; use explorer or reviewer.`);
9826
+ }
9827
+ }
8333
9828
  return options;
8334
9829
  };
8335
- var help = `Zhivex Harness v${HARNESS_VERSION}
9830
+ var CLI_HELP_TEXT = `Zhivex Harness v${HARNESS_VERSION}
8336
9831
 
8337
9832
  Usage:
8338
9833
  zhx Start the interactive console
@@ -8346,6 +9841,9 @@ Usage:
8346
9841
  zhx sessions list|inspect|rename|fork|archive
8347
9842
  zhx changes create <input.json> --patch <artifact>
8348
9843
  zhx changes verify <envelope.json> --patch <artifact> [--preconditions <file>]
9844
+ zhx state status
9845
+ zhx state export <backup.json>
9846
+ zhx state import <backup.json> [--apply]
8349
9847
 
8350
9848
  The long command zhivex-harness remains supported for compatibility.
8351
9849
 
@@ -8396,6 +9894,9 @@ Options:
8396
9894
  --subagent <profile> Enable explorer, implementer, tester, or reviewer; repeatable
8397
9895
  --subagent-max-steps <n> Independent child step budget (default: 8)
8398
9896
  --subagent-max-tool-calls <n> Independent child tool budget (default: 16)
9897
+ --subagent-max-tool-errors <n> Independent child failed-tool budget (default: 3)
9898
+ --subagent-max-input-tokens <n> Independent child input-token budget (default: 30000)
9899
+ --subagent-max-output-tokens <n> Independent child output-token budget (default: 8000)
8399
9900
  --subagent-max-total-tokens <n> Independent child token budget (default: 36000)
8400
9901
  --subagent-timeout-ms <n> Independent child timeout (default: 300000)
8401
9902
  --reviewer <profile> Read-only review group member; repeatable
@@ -8403,6 +9904,12 @@ Options:
8403
9904
  --yes Automatically approve writes and checks
8404
9905
  --json Emit structured final output
8405
9906
  --jsonl Stream redacted JSON Lines, then the final result
9907
+ --cursor <cursor> Continue a paginated run listing
9908
+ --before <date|timestamp> Explicit retention cutoff for runs cleanup
9909
+ --reason <text> Bounded operator cancellation reason
9910
+ --cascade Cancel a run and its known child runs
9911
+ --final Record terminal cancellation immediately
9912
+ --apply Apply a validated state import (default: dry-run)
8406
9913
  -h, --help Show this help
8407
9914
  -v, --version Show the version
8408
9915
 
@@ -8613,8 +10120,9 @@ var runOnce = async (options) => {
8613
10120
  throw new CliUsageError('Missing task. Example: zhivex-harness run "fix the tests".');
8614
10121
  }
8615
10122
  const { harness, routes } = await createConfiguredHarness(options);
10123
+ const tracker = { streamedText: false };
10124
+ let closeAttempted = false;
8616
10125
  try {
8617
- const tracker = { streamedText: false };
8618
10126
  const result = await runHarness(harness, {
8619
10127
  prompt: options.prompt,
8620
10128
  scope: harness.config.scope,
@@ -8624,12 +10132,20 @@ var runOnce = async (options) => {
8624
10132
  onEvent: streamSink(options, tracker),
8625
10133
  resolveApprovals: terminalApprovalResolver(options.yes)
8626
10134
  });
10135
+ closeAttempted = true;
10136
+ await harness.close();
8627
10137
  printTerminalResult(result, harness, options, tracker);
8628
10138
  if (result.status === "failed" || result.status === "timed_out") {
8629
10139
  process.exitCode = CLI_EXIT_CODES.runtimeError;
8630
10140
  }
8631
- } finally {
8632
- await harness.close();
10141
+ } catch (error) {
10142
+ if (!closeAttempted) {
10143
+ closeAttempted = true;
10144
+ await harness.close().catch(() => {
10145
+ return;
10146
+ });
10147
+ }
10148
+ throw options.jsonl ? annotateCliStreamError(error, tracker.sequence) : error;
8633
10149
  }
8634
10150
  };
8635
10151
  var reviewOnce = async (options) => {
@@ -8661,23 +10177,25 @@ var reviewOnce = async (options) => {
8661
10177
  steps: member.output.steps.length,
8662
10178
  usage: member.output.usage
8663
10179
  } : {},
8664
- ...member.error ? { error: member.error } : {}
10180
+ ...member.error ? { error: harnessErrorDocument(member.error).error } : {}
8665
10181
  }))
8666
10182
  };
8667
10183
  if (options.json) {
8668
10184
  process.stdout.write(`${JSON.stringify(document, null, 2)}
8669
10185
  `);
8670
10186
  } else {
8671
- for (const output of document.outputs) {
10187
+ for (const [index, output] of document.outputs.entries()) {
8672
10188
  process.stdout.write(`
8673
10189
  [${output.name ?? output.agentId ?? "reviewer"}] ${output.status}
8674
10190
  `);
8675
10191
  if ("output" in output && output.output)
8676
10192
  process.stdout.write(`${output.output}
8677
10193
  `);
8678
- if (output.error)
8679
- process.stdout.write(`Error: ${output.error.message}
10194
+ const memberError = result.outputs[index]?.error;
10195
+ if (memberError) {
10196
+ process.stdout.write(`Error [${output.error?.code ?? "EXECUTION_FAILED"}]: ${terminalErrorMessage(memberError)}
8680
10197
  `);
10198
+ }
8681
10199
  }
8682
10200
  }
8683
10201
  if (result.status === "failed") {
@@ -8697,13 +10215,20 @@ var resumeRun = async (options) => {
8697
10215
  const initialConfig = resolveHarnessConfig(options);
8698
10216
  await validateStateDirectory(initialConfig.workspace, initialConfig.stateDirectory);
8699
10217
  const persistence = await openHarnessPersistence(initialConfig);
10218
+ let persistenceClosed = false;
10219
+ const closePersistence = () => {
10220
+ if (persistenceClosed)
10221
+ return;
10222
+ persistenceClosed = true;
10223
+ persistence.close();
10224
+ };
8700
10225
  try {
8701
10226
  const state = await persistence.store.load(options.runId, initialConfig.scope);
8702
10227
  if (!state) {
8703
- throw new Error(`Run ${options.runId} was not found in ${initialConfig.stateDirectory}.`);
10228
+ throw new HarnessStateConflictError(`Run ${options.runId} was not found in ${initialConfig.stateDirectory}.`);
8704
10229
  }
8705
10230
  if (state.status !== "waiting_approval" || state.pendingApprovals.length === 0) {
8706
- throw new Error(`Run ${options.runId} is not waiting for approval (status: ${state.status}).`);
10231
+ throw new HarnessStateConflictError(`Run ${options.runId} is not waiting for approval (status: ${state.status}).`);
8707
10232
  }
8708
10233
  for (const approval of state.pendingApprovals) {
8709
10234
  process.stderr.write(`
@@ -8718,7 +10243,7 @@ ${summarizeApproval(approval)}
8718
10243
  if (persistedResumeInput) {
8719
10244
  const persistedConfig = resolveHarnessConfig(persistedResumeInput);
8720
10245
  if (persistedConfig.workspace !== initialConfig.workspace || persistedConfig.stateDirectory !== initialConfig.stateDirectory || persistedConfig.storeBackend !== initialConfig.storeBackend || JSON.stringify(persistedConfig.scope) !== JSON.stringify(initialConfig.scope)) {
8721
- throw new Error("Resume locator options do not match the persisted workspace, state directory, store, or scope.");
10246
+ throw new HarnessStateConflictError("Resume locator options do not match the persisted workspace, state directory, store, or scope.");
8722
10247
  }
8723
10248
  persistedResumeOptions = harnessConfigInput(persistedConfig);
8724
10249
  resumeCostBudget = persistedConfig.costBudget;
@@ -8740,20 +10265,37 @@ ${summarizeApproval(approval)}
8740
10265
  });
8741
10266
  const approve = options.approve;
8742
10267
  const tracker = { streamedText: false };
8743
- const result = await runHarness(harness, {
8744
- state,
8745
- approvals: approvalResponses(state.pendingApprovals, approve, approve ? "Approved by resume --approve." : "Denied by resume --deny.")
8746
- }, {
8747
- onEvent: streamSink(options, tracker),
8748
- resolveApprovals: async (approvals) => approvalResponses(approvals, approve, approve ? "Approved by resume --approve." : "Denied by resume --deny.")
8749
- });
8750
- await updateIndexedSessionRun(harness.config, result.state.runId, result.status);
8751
- printTerminalResult(result, harness, options, tracker);
8752
- if (result.status === "failed" || result.status === "timed_out") {
8753
- process.exitCode = CLI_EXIT_CODES.runtimeError;
10268
+ let harnessCloseAttempted = false;
10269
+ try {
10270
+ const result = await runHarness(harness, {
10271
+ state,
10272
+ approvals: approvalResponses(state.pendingApprovals, approve, approve ? "Approved by resume --approve." : "Denied by resume --deny.")
10273
+ }, {
10274
+ onEvent: streamSink(options, tracker),
10275
+ resolveApprovals: async (approvals) => approvalResponses(approvals, approve, approve ? "Approved by resume --approve." : "Denied by resume --deny.")
10276
+ });
10277
+ await updateIndexedSessionRun(harness.config, result.state.runId, result.status);
10278
+ harnessCloseAttempted = true;
10279
+ await harness.close();
10280
+ closePersistence();
10281
+ printTerminalResult(result, harness, options, tracker);
10282
+ if (result.status === "failed" || result.status === "timed_out") {
10283
+ process.exitCode = CLI_EXIT_CODES.runtimeError;
10284
+ }
10285
+ } catch (error) {
10286
+ if (!harnessCloseAttempted) {
10287
+ harnessCloseAttempted = true;
10288
+ await harness.close().catch(() => {
10289
+ return;
10290
+ });
10291
+ }
10292
+ try {
10293
+ closePersistence();
10294
+ } catch {}
10295
+ throw options.jsonl ? annotateCliStreamError(error, tracker.sequence) : error;
8754
10296
  }
8755
10297
  } finally {
8756
- persistence.close();
10298
+ closePersistence();
8757
10299
  }
8758
10300
  };
8759
10301
  var chat = async (options) => {
@@ -8769,7 +10311,7 @@ var chat = async (options) => {
8769
10311
  if (options.sessionId && !selectedSession) {
8770
10312
  sessionStore.close();
8771
10313
  readline.close();
8772
- throw new Error(`Session ${options.sessionId} was not found.`);
10314
+ throw new HarnessStateConflictError(`Session ${options.sessionId} was not found.`);
8773
10315
  }
8774
10316
  let session = selectedSession ?? await sessionStore.create();
8775
10317
  let messages = [];
@@ -8781,7 +10323,7 @@ var chat = async (options) => {
8781
10323
  try {
8782
10324
  const state = await persistence.store.load(latest.runId, baseConfig.scope);
8783
10325
  if (!state)
8784
- throw new Error(`Run ${latest.runId} referenced by session ${selected.sessionId} was not found.`);
10326
+ throw new HarnessStateConflictError(`Run ${latest.runId} referenced by session ${selected.sessionId} was not found.`);
8785
10327
  return state;
8786
10328
  } finally {
8787
10329
  persistence.close();
@@ -8810,7 +10352,7 @@ var chat = async (options) => {
8810
10352
  const refreshSession = async () => {
8811
10353
  const refreshed = await sessionStore.get(session.sessionId);
8812
10354
  if (!refreshed)
8813
- throw new Error(`Session ${session.sessionId} was not found.`);
10355
+ throw new HarnessStateConflictError(`Session ${session.sessionId} was not found.`);
8814
10356
  session = refreshed;
8815
10357
  return session;
8816
10358
  };
@@ -8971,7 +10513,7 @@ ${summarizeApproval(approval)}
8971
10513
  if (prompt === "/provider" || prompt.startsWith("/provider ")) {
8972
10514
  const value = prompt.slice("/provider".length).trim();
8973
10515
  if (!value) {
8974
- process.stderr.write(`${providerAvailability().map((provider2) => `${provider2.id}${provider2.id === harness.config.provider ? "*" : ""}`).join(" ")}
10516
+ process.stderr.write(`${providerAvailability().map((provider3) => `${provider3.id}${provider3.id === harness.config.provider ? "*" : ""}`).join(" ")}
8975
10517
  `);
8976
10518
  continue;
8977
10519
  }
@@ -8981,12 +10523,12 @@ ${summarizeApproval(approval)}
8981
10523
  `);
8982
10524
  continue;
8983
10525
  }
8984
- const provider = parseProvider(value);
8985
- const model = DEFAULT_PROVIDER_REGISTRY.descriptor(provider).defaultModel;
10526
+ const provider2 = parseProvider(value);
10527
+ const model = DEFAULT_PROVIDER_REGISTRY.descriptor(provider2).defaultModel;
8986
10528
  const portableMessages = compactHarnessMessages(messages);
8987
- await replaceHarness({ ...runtimeOptions, provider, model }, routes);
10529
+ await replaceHarness({ ...runtimeOptions, provider: provider2, model }, routes);
8988
10530
  messages = portableMessages;
8989
- process.stderr.write(`Next turn: ${provider}/${model}; context was compacted for a safe handoff.
10531
+ process.stderr.write(`Next turn: ${provider2}/${model}; context was compacted for a safe handoff.
8990
10532
  `);
8991
10533
  continue;
8992
10534
  }
@@ -9114,7 +10656,7 @@ ${summarizeApproval(approval)}
9114
10656
  `);
9115
10657
  continue;
9116
10658
  }
9117
- const runId = `run_${randomUUID6()}`;
10659
+ const runId = `run_${randomUUID7()}`;
9118
10660
  session = await sessionStore.appendRun(session.sessionId, {
9119
10661
  runId,
9120
10662
  provider: harness.config.provider,
@@ -9198,8 +10740,8 @@ var listProviders = (json) => {
9198
10740
  `);
9199
10741
  return;
9200
10742
  }
9201
- for (const provider of document.providers) {
9202
- process.stdout.write(`${provider.id.padEnd(7)} ${provider.defaultModel.padEnd(22)} ${provider.support.padEnd(11)} ${provider.configured ? "configured" : `missing ${provider.credentialNames.join("/")}`}
10743
+ for (const provider2 of document.providers) {
10744
+ process.stdout.write(`${provider2.id.padEnd(7)} ${provider2.defaultModel.padEnd(22)} ${provider2.support.padEnd(11)} ${provider2.configured ? "configured" : `missing ${provider2.credentialNames.join("/")}`}
9203
10745
  `);
9204
10746
  }
9205
10747
  };
@@ -9242,7 +10784,7 @@ var inspectWorkspace = async (workspace) => {
9242
10784
  if (!workspaceStat.isDirectory()) {
9243
10785
  return diagnostic("workspace", "fail", "Workspace is not a directory.", { path: workspace });
9244
10786
  }
9245
- await access(workspace, fsConstants3.R_OK);
10787
+ await access(workspace, fsConstants4.R_OK);
9246
10788
  return diagnostic("workspace", "pass", "Workspace exists and is readable.", { path: workspace });
9247
10789
  } catch (error) {
9248
10790
  const code = error.code ?? "UNKNOWN";
@@ -9272,16 +10814,13 @@ var inspectGit = async (workspace) => {
9272
10814
  }
9273
10815
  };
9274
10816
  var inspectScripts = async (workspace, allowedChecks) => {
9275
- const packagePath = path12.join(workspace, "package.json");
10817
+ const packagePath = path13.join(workspace, "package.json");
9276
10818
  try {
9277
- const packageStat = await stat4(packagePath);
9278
- if (!packageStat.isFile() || packageStat.size > 1024 * 1024) {
9279
- return diagnostic("scripts", "warn", "package.json is not a readable regular file.", {
9280
- packageJson: false,
9281
- available: []
9282
- });
9283
- }
9284
- const packageJson = JSON.parse(await readFile4(packagePath, "utf8"));
10819
+ const packageFile = await readRegularFileNoFollow(packagePath, {
10820
+ label: "package.json",
10821
+ maxBytes: 1024 * 1024
10822
+ });
10823
+ const packageJson = JSON.parse(packageFile.contents.toString("utf8"));
9285
10824
  const scripts = packageJson.scripts && typeof packageJson.scripts === "object" ? packageJson.scripts : {};
9286
10825
  const available = allowedChecks.filter((name) => typeof scripts[name] === "string");
9287
10826
  const missing = allowedChecks.filter((name) => typeof scripts[name] !== "string");
@@ -9304,17 +10843,17 @@ var inspectScripts = async (workspace, allowedChecks) => {
9304
10843
  }
9305
10844
  };
9306
10845
  var isInsidePath2 = (root, candidate) => {
9307
- const relative = path12.relative(root, candidate);
9308
- return relative === "" || !relative.startsWith(`..${path12.sep}`) && relative !== ".." && !path12.isAbsolute(relative);
10846
+ const relative = path13.relative(root, candidate);
10847
+ return relative === "" || !relative.startsWith(`..${path13.sep}`) && relative !== ".." && !path13.isAbsolute(relative);
9309
10848
  };
9310
10849
  var containsSymlink = async (candidate, trustedPrefix) => {
9311
- const parsed = path12.parse(candidate);
9312
- const parts = trustedPrefix ? path12.relative(trustedPrefix, candidate).split(path12.sep).filter(Boolean) : candidate.slice(parsed.root.length).split(path12.sep).filter(Boolean).slice(1);
9313
- let current = trustedPrefix ?? path12.join(parsed.root, candidate.slice(parsed.root.length).split(path12.sep).filter(Boolean)[0] ?? "");
10850
+ const parsed = path13.parse(candidate);
10851
+ const parts = trustedPrefix ? path13.relative(trustedPrefix, candidate).split(path13.sep).filter(Boolean) : candidate.slice(parsed.root.length).split(path13.sep).filter(Boolean).slice(1);
10852
+ let current = trustedPrefix ?? path13.join(parsed.root, candidate.slice(parsed.root.length).split(path13.sep).filter(Boolean)[0] ?? "");
9314
10853
  for (const part of parts) {
9315
- current = path12.join(current, part);
10854
+ current = path13.join(current, part);
9316
10855
  try {
9317
- if ((await lstat9(current)).isSymbolicLink()) {
10856
+ if ((await lstat10(current)).isSymbolicLink()) {
9318
10857
  return true;
9319
10858
  }
9320
10859
  } catch (error) {
@@ -9335,7 +10874,7 @@ var nearestExistingPath = async (candidate) => {
9335
10874
  if (error.code !== "ENOENT") {
9336
10875
  throw error;
9337
10876
  }
9338
- const parent = path12.dirname(current);
10877
+ const parent = path13.dirname(current);
9339
10878
  if (parent === current) {
9340
10879
  throw error;
9341
10880
  }
@@ -9351,7 +10890,7 @@ var inspectStateDirectory = async (workspace, stateDirectory) => {
9351
10890
  });
9352
10891
  }
9353
10892
  if (isInsidePath2(workspace, stateDirectory)) {
9354
- const segments = path12.relative(workspace, stateDirectory).split(path12.sep).filter(Boolean);
10893
+ const segments = path13.relative(workspace, stateDirectory).split(path13.sep).filter(Boolean);
9355
10894
  const sensitiveSegment = segments.find(isSensitiveStateSegment);
9356
10895
  if (sensitiveSegment) {
9357
10896
  return diagnostic("state-directory", "fail", "State directory is inside a sensitive workspace path.", {
@@ -9376,7 +10915,7 @@ var inspectStateDirectory = async (workspace, stateDirectory) => {
9376
10915
  writable: false
9377
10916
  });
9378
10917
  }
9379
- await access(existing.path, fsConstants3.R_OK | fsConstants3.W_OK);
10918
+ await access(existing.path, fsConstants4.R_OK | fsConstants4.W_OK);
9380
10919
  return diagnostic("state-directory", "pass", "State directory is safe and writable.", {
9381
10920
  path: stateDirectory,
9382
10921
  exists: existing.path === stateDirectory,
@@ -9398,9 +10937,9 @@ var inspectOperationsStore = async (stateDirectory, storeBackend) => {
9398
10937
  migrationAvailable: true
9399
10938
  });
9400
10939
  }
9401
- const databasePath = path12.join(stateDirectory, "operations.sqlite");
10940
+ const databasePath = path13.join(stateDirectory, "operations.sqlite");
9402
10941
  try {
9403
- const entry = await lstat9(databasePath);
10942
+ const entry = await lstat10(databasePath);
9404
10943
  if (entry.isSymbolicLink() || !entry.isFile()) {
9405
10944
  return diagnostic("operations-store", "fail", "SQLite state path is not a regular file.", {
9406
10945
  backend: storeBackend,
@@ -9408,11 +10947,34 @@ var inspectOperationsStore = async (stateDirectory, storeBackend) => {
9408
10947
  safe: false
9409
10948
  });
9410
10949
  }
9411
- return diagnostic("operations-store", "pass", "SQLite durable operations store is available.", {
9412
- backend: storeBackend,
9413
- databasePath,
9414
- safe: true
9415
- });
10950
+ const database = new SqliteDatabase(databasePath, { create: false, readonly: true, strict: true });
10951
+ try {
10952
+ const integrity = database.query("PRAGMA quick_check").get()?.quick_check;
10953
+ const tables = new Set(database.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
10954
+ const requiredOperationsTables = [
10955
+ "zhivex_agent_runs",
10956
+ "zhivex_agent_runs_idempotency",
10957
+ "zhivex_agent_runs_parents",
10958
+ "zhivex_agent_runs_leases",
10959
+ "zhivex_agent_runs_tool_journal",
10960
+ "zhivex_agent_memory"
10961
+ ];
10962
+ const operationsCompatible = requiredOperationsTables.every((table) => tables.has(table));
10963
+ const sessionVersion = tables.has("zhivex_cli_session_schema") ? database.query("SELECT version FROM zhivex_cli_session_schema WHERE singleton = 1").get()?.version : undefined;
10964
+ const sessionCompatible = sessionVersion === undefined || sessionVersion === 1;
10965
+ const compatible = integrity === "ok" && operationsCompatible && sessionCompatible;
10966
+ return diagnostic("operations-store", compatible ? "pass" : "fail", compatible ? "SQLite durable operations store is integral and schema-compatible." : "SQLite durable operations store failed integrity or schema compatibility checks.", {
10967
+ backend: storeBackend,
10968
+ databasePath,
10969
+ safe: true,
10970
+ integrity: integrity === "ok",
10971
+ operationsSchema: operationsCompatible ? 1 : "unsupported",
10972
+ sessionSchema: sessionVersion ?? "not-initialized",
10973
+ compatible
10974
+ });
10975
+ } finally {
10976
+ database.close(false);
10977
+ }
9416
10978
  } catch (error) {
9417
10979
  if (error.code === "ENOENT") {
9418
10980
  return diagnostic("operations-store", "pass", "SQLite durable operations store will be created on first use.", {
@@ -9451,16 +11013,16 @@ var inspectMcpConfiguration = async (workspace, configPath) => {
9451
11013
  });
9452
11014
  }
9453
11015
  };
9454
- var inspectExecutionEnvironment = async (execution, runtimeOverride) => {
9455
- if (execution.backend === "none") {
11016
+ var inspectExecutionEnvironment = async (execution2, runtimeOverride) => {
11017
+ if (execution2.backend === "none") {
9456
11018
  return diagnostic("execution-environment", "pass", "Enforced OCI execution is disabled; shell-class tools remain unavailable.", {
9457
11019
  backend: "none",
9458
11020
  shellAvailable: false
9459
11021
  });
9460
11022
  }
9461
11023
  try {
9462
- const runtime = runtimeOverride ?? new CliOciRuntimeAdapter(execution.runtime);
9463
- const image = await runtime.inspectImage(execution.image);
11024
+ const runtime = runtimeOverride ?? new CliOciRuntimeAdapter(execution2.runtime);
11025
+ const image = await runtime.inspectImage(execution2.image);
9464
11026
  return diagnostic("execution-environment", "pass", "OCI runtime and preloaded image are available.", {
9465
11027
  backend: "oci",
9466
11028
  runtime: image.runtime,
@@ -9473,8 +11035,8 @@ var inspectExecutionEnvironment = async (execution, runtimeOverride) => {
9473
11035
  } catch (error) {
9474
11036
  return diagnostic("execution-environment", "fail", "OCI execution was requested, but the runtime or preloaded image is unavailable.", {
9475
11037
  backend: "oci",
9476
- runtime: execution.runtime,
9477
- imageReference: execution.image,
11038
+ runtime: execution2.runtime,
11039
+ imageReference: execution2.image,
9478
11040
  error: error instanceof Error ? error.message : String(error),
9479
11041
  shellAvailable: false
9480
11042
  });
@@ -9490,7 +11052,7 @@ var inspectProjectContext = async (config) => {
9490
11052
  }
9491
11053
  try {
9492
11054
  const workspace = await Workspace.open(config.workspace);
9493
- const manifestPath = path12.relative(config.workspace, config.context.configPath).split(path12.sep).join("/");
11055
+ const manifestPath = path13.relative(config.workspace, config.context.configPath).split(path13.sep).join("/");
9494
11056
  const bundle = await loadHarnessProjectContext(workspace, {
9495
11057
  manifestPath,
9496
11058
  requireManifest: manifestPath !== DEFAULT_HARNESS_CONTEXT_MANIFEST
@@ -9561,7 +11123,7 @@ var createDoctorReport = async (options = {}, context = {}) => {
9561
11123
  });
9562
11124
  const runtime = context.nodeVersion ? { name: "node", version: context.nodeVersion, required: NODE_ENGINE_RANGE } : context.bunVersion ? { name: "bun", version: context.bunVersion, required: BUN_ENGINE_RANGE } : process.versions.bun ? { name: "bun", version: process.versions.bun, required: BUN_ENGINE_RANGE } : { name: "node", version: process.versions.node, required: NODE_ENGINE_RANGE };
9563
11125
  const providers = providerAvailability(env);
9564
- const selectedProvider = providers.find((provider) => provider.id === config.provider);
11126
+ const selectedProvider = providers.find((provider2) => provider2.id === config.provider);
9565
11127
  const checks = [];
9566
11128
  checks.push(diagnostic(runtime.name, satisfiesEngine(runtime.version, runtime.required) ? "pass" : "fail", satisfiesEngine(runtime.version, runtime.required) ? `${runtime.name === "node" ? "Node.js" : "Bun"} satisfies the package engine requirement.` : `${runtime.name === "node" ? "Node.js" : "Bun"} does not satisfy the package engine requirement.`, { version: runtime.version, required: runtime.required, primary: runtime.name === "node" }));
9567
11129
  checks.push(await inspectWorkspace(config.workspace));
@@ -9572,26 +11134,26 @@ var createDoctorReport = async (options = {}, context = {}) => {
9572
11134
  checks.push(await inspectProjectContext(config));
9573
11135
  checks.push(await inspectMcpConfiguration(config.workspace, config.mcpConfigPath));
9574
11136
  checks.push(await inspectExecutionEnvironment(config.execution, context.ociRuntimeAdapter));
9575
- for (const provider of providers) {
9576
- const invalidRegion = provider.id === "qwen" && provider.configuration.regionValid === false;
9577
- const invalidEndpoint = !provider.configuration.endpointValid;
9578
- const selected = provider.id === selectedProvider?.id;
9579
- const status = invalidRegion || invalidEndpoint || !provider.configured ? selected ? "fail" : "warn" : provider.support === "provisional" ? "warn" : "pass";
9580
- const message = invalidEndpoint ? `${provider.name} custom endpoint configuration is invalid.` : invalidRegion ? "Qwen region configuration is invalid." : provider.configured ? provider.support === "provisional" ? `${provider.name} credentials are present, but live support is provisional.` : `${provider.name} credentials are present.` : `${provider.name} credentials are missing.`;
9581
- checks.push(diagnostic(`provider:${provider.id}`, status, message, {
9582
- provider: provider.id,
11137
+ for (const provider2 of providers) {
11138
+ const invalidRegion = provider2.id === "qwen" && provider2.configuration.regionValid === false;
11139
+ const invalidEndpoint = !provider2.configuration.endpointValid;
11140
+ const selected = provider2.id === selectedProvider?.id;
11141
+ const status = invalidRegion || invalidEndpoint || !provider2.configured ? selected ? "fail" : "warn" : provider2.support === "provisional" ? "warn" : "pass";
11142
+ const message = invalidEndpoint ? `${provider2.name} custom endpoint configuration is invalid.` : invalidRegion ? "Qwen region configuration is invalid." : provider2.configured ? provider2.support === "provisional" ? `${provider2.name} credentials are present, but live support is provisional.` : `${provider2.name} credentials are present.` : `${provider2.name} credentials are missing.`;
11143
+ checks.push(diagnostic(`provider:${provider2.id}`, status, message, {
11144
+ provider: provider2.id,
9583
11145
  selected,
9584
- configured: provider.configured,
9585
- support: provider.support,
9586
- credentialNames: provider.credentialNames,
9587
- capabilities: provider.capabilities,
9588
- customEndpoint: provider.configuration.customEndpoint,
9589
- endpointValid: provider.configuration.endpointValid,
9590
- endpointSecure: provider.configuration.endpointSecure,
9591
- ...provider.id === "qwen" ? {
9592
- regionConfigured: provider.configuration.regionConfigured,
9593
- regionValid: provider.configuration.regionValid,
9594
- workspaceIdConfigured: provider.configuration.workspaceIdConfigured
11146
+ configured: provider2.configured,
11147
+ support: provider2.support,
11148
+ credentialNames: provider2.credentialNames,
11149
+ capabilities: provider2.capabilities,
11150
+ customEndpoint: provider2.configuration.customEndpoint,
11151
+ endpointValid: provider2.configuration.endpointValid,
11152
+ endpointSecure: provider2.configuration.endpointSecure,
11153
+ ...provider2.id === "qwen" ? {
11154
+ regionConfigured: provider2.configuration.regionConfigured,
11155
+ regionValid: provider2.configuration.regionValid,
11156
+ workspaceIdConfigured: provider2.configuration.workspaceIdConfigured
9595
11157
  } : {}
9596
11158
  }));
9597
11159
  }
@@ -9766,7 +11328,7 @@ var manageSessions = async (options) => {
9766
11328
  case "inspect":
9767
11329
  session = await store.get(options.sessionId);
9768
11330
  if (!session)
9769
- throw new Error(`Session ${options.sessionId} was not found.`);
11331
+ throw new HarnessStateConflictError(`Session ${options.sessionId} was not found.`);
9770
11332
  document = { schemaVersion: CLI_JSON_SCHEMA_VERSION, kind: "session", session };
9771
11333
  break;
9772
11334
  case "rename":
@@ -9810,28 +11372,28 @@ var updateIndexedSessionRun = async (config, runId, status) => {
9810
11372
  store.close();
9811
11373
  }
9812
11374
  };
9813
- var cliExitCodeForError = (error) => error instanceof CliUsageError ? CLI_EXIT_CODES.usageError : CLI_EXIT_CODES.runtimeError;
11375
+ var cliExitCodeForError = (error) => error instanceof CliUsageError || error instanceof HarnessConfigError ? CLI_EXIT_CODES.usageError : CLI_EXIT_CODES.runtimeError;
9814
11376
  var MAX_CHANGE_ENVELOPE_JSON_BYTES = 4 * 1024 * 1024;
9815
11377
  var MAX_CHANGE_ARTIFACT_BYTES = 64 * 1024 * 1024;
9816
11378
  var readStableCliArtifact = async (filePath, maxBytes) => {
9817
- const absolute = path12.resolve(process.cwd(), filePath);
11379
+ const absolute = path13.resolve(process.cwd(), filePath);
9818
11380
  try {
9819
- const before = await lstat9(absolute);
9820
- if (before.isSymbolicLink() || !before.isFile()) {
11381
+ return (await readRegularFileNoFollow(absolute, {
11382
+ label: `Change artifact ${filePath}`,
11383
+ maxBytes
11384
+ })).contents;
11385
+ } catch (error) {
11386
+ if (error instanceof CliUsageError)
11387
+ throw error;
11388
+ if (error instanceof UnsafeFileTypeError) {
9821
11389
  throw new CliUsageError(`Change artifact must be a regular non-symlink file: ${filePath}`);
9822
11390
  }
9823
- if (before.size > maxBytes) {
11391
+ if (error instanceof FileSizeLimitError) {
9824
11392
  throw new CliUsageError(`Change artifact exceeds the ${maxBytes}-byte limit: ${filePath}`);
9825
11393
  }
9826
- const contents = await readFile4(absolute);
9827
- const after = await lstat9(absolute);
9828
- if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
11394
+ if (error instanceof FileChangedWhileReadingError) {
9829
11395
  throw new CliUsageError(`Change artifact changed while it was being read: ${filePath}`);
9830
11396
  }
9831
- return contents;
9832
- } catch (error) {
9833
- if (error instanceof CliUsageError)
9834
- throw error;
9835
11397
  const code = error && typeof error === "object" && "code" in error ? error.code : undefined;
9836
11398
  if (typeof code === "string") {
9837
11399
  throw new CliUsageError(`Change artifact cannot be read (${code}): ${filePath}`);
@@ -9895,11 +11457,32 @@ var manageChanges = async (options) => {
9895
11457
  if (!result.valid)
9896
11458
  process.exitCode = CLI_EXIT_CODES.runtimeError;
9897
11459
  };
11460
+ var manageState = async (options) => {
11461
+ const config = resolveHarnessConfig(options);
11462
+ let document;
11463
+ switch (options.stateCommand) {
11464
+ case "status":
11465
+ document = await inspectHarnessState(config);
11466
+ break;
11467
+ case "export":
11468
+ document = await exportHarnessStateBackup(config, options.backupPath);
11469
+ break;
11470
+ case "import":
11471
+ document = await importHarnessStateBackupFile(config, options.backupPath, {
11472
+ dryRun: !options.apply
11473
+ });
11474
+ break;
11475
+ default:
11476
+ throw new CliUsageError("state requires one of: status, export, import.");
11477
+ }
11478
+ process.stdout.write(`${JSON.stringify(document, null, 2)}
11479
+ `);
11480
+ };
9898
11481
  var main = async (argv = process.argv.slice(2)) => {
9899
11482
  const options = parseCliArgs(argv);
9900
11483
  switch (options.command) {
9901
11484
  case "help":
9902
- process.stdout.write(`${help}
11485
+ process.stdout.write(`${CLI_HELP_TEXT}
9903
11486
  `);
9904
11487
  return;
9905
11488
  case "version":
@@ -9927,6 +11510,9 @@ var main = async (argv = process.argv.slice(2)) => {
9927
11510
  case "changes":
9928
11511
  await manageChanges(options);
9929
11512
  return;
11513
+ case "state":
11514
+ await manageState(options);
11515
+ return;
9930
11516
  case "run":
9931
11517
  if (options.implicitCommand && !options.prompt && process.stdin.isTTY && process.stdout.isTTY) {
9932
11518
  await chat(options);
@@ -9949,19 +11535,39 @@ var isMainModule = (() => {
9949
11535
  })();
9950
11536
  if (isMainModule) {
9951
11537
  main().catch((error) => {
9952
- const message = error instanceof Error ? error.message : String(error);
9953
- process.stderr.write(`Error: ${message}
11538
+ const document = harnessErrorDocument(error);
11539
+ if (process.argv.includes("--jsonl")) {
11540
+ process.stdout.write(`${JSON.stringify({
11541
+ ...document,
11542
+ kind: "run-stream-error",
11543
+ sequence: cliStreamErrorSequence(error)
11544
+ })}
9954
11545
  `);
11546
+ } else if (process.argv.includes("--json")) {
11547
+ process.stderr.write(`${JSON.stringify(document)}
11548
+ `);
11549
+ } else {
11550
+ process.stderr.write(`Error: ${terminalErrorMessage(error)}
11551
+ `);
11552
+ }
9955
11553
  process.exitCode = cliExitCodeForError(error);
9956
11554
  });
9957
11555
  }
9958
11556
  export {
11557
+ CLI_CHANGES_COMMANDS,
11558
+ CLI_COMMANDS,
9959
11559
  CLI_EXIT_CODES,
11560
+ CLI_HELP_TEXT,
9960
11561
  CLI_JSON_SCHEMA_VERSION,
11562
+ CLI_RUNS_COMMANDS,
11563
+ CLI_SESSIONS_COMMANDS,
11564
+ CLI_STATE_COMMANDS,
9961
11565
  CliUsageError,
9962
11566
  HARNESS_RESUME_METADATA_KEY,
9963
11567
  HARNESS_RESUME_METADATA_SCHEMA_VERSION,
11568
+ annotateCliStreamError,
9964
11569
  cliExitCodeForError,
11570
+ cliStreamErrorSequence,
9965
11571
  createDoctorReport,
9966
11572
  createHarnessResumeMetadata,
9967
11573
  formatDoctorReport,
@@ -9973,5 +11579,6 @@ export {
9973
11579
  resumeCommand,
9974
11580
  runResultDocument,
9975
11581
  summarizeApproval,
11582
+ terminalErrorMessage,
9976
11583
  withTemporaryHarnessProfiles
9977
11584
  };