@holmes-lab/holmes-kit 0.39.0 → 0.40.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +578 -6
- package/README.md +120 -41
- package/dist/.build-id +1 -1
- package/dist/holmes/admission/core/admission-policy.d.ts +37 -0
- package/dist/holmes/admission/core/admission-policy.js +147 -0
- package/dist/holmes/admission/core/bounded-reader.d.ts +56 -0
- package/dist/holmes/admission/core/bounded-reader.js +135 -0
- package/dist/holmes/admission/core/change-classifier.d.ts +34 -0
- package/dist/holmes/admission/core/change-classifier.js +278 -0
- package/dist/holmes/admission/core/config-loader.d.ts +30 -0
- package/dist/holmes/admission/core/config-loader.js +145 -0
- package/dist/holmes/admission/core/event-judgement.d.ts +37 -0
- package/dist/holmes/admission/core/event-judgement.js +251 -0
- package/dist/holmes/admission/core/path-rules.d.ts +35 -0
- package/dist/holmes/admission/core/path-rules.js +88 -0
- package/dist/holmes/admission/core/pin.d.ts +7 -0
- package/dist/holmes/admission/core/pin.js +29 -0
- package/dist/holmes/admission/core/ports.d.ts +48 -0
- package/dist/holmes/admission/core/ports.js +11 -0
- package/dist/holmes/admission/core/range-resolver.d.ts +32 -0
- package/dist/holmes/admission/core/range-resolver.js +51 -0
- package/dist/holmes/admission/core/self-containment.d.ts +1 -0
- package/dist/holmes/admission/core/self-containment.js +125 -0
- package/dist/holmes/admission/core/signature-source.d.ts +9 -0
- package/dist/holmes/admission/core/signature-source.js +4 -0
- package/dist/holmes/admission/core/transition-planner.d.ts +15 -0
- package/dist/holmes/admission/core/transition-planner.js +14 -0
- package/dist/holmes/admission/core/verdict.d.ts +38 -0
- package/dist/holmes/admission/core/verdict.js +17 -0
- package/dist/holmes/admission/core/wiring.d.ts +44 -0
- package/dist/holmes/admission/core/wiring.js +618 -0
- package/dist/holmes/admission/forge/git-object-port.d.ts +4 -0
- package/dist/holmes/admission/forge/git-object-port.js +132 -0
- package/dist/holmes/assoc/assoc-arm.d.ts +1 -1
- package/dist/holmes/assoc/assoc-arm.js +1 -1
- package/dist/holmes/cli/agents.d.ts +8 -0
- package/dist/holmes/cli/agents.js +9 -5
- package/dist/holmes/cli/approve-cli.d.ts +2 -0
- package/dist/holmes/cli/approve-cli.js +392 -0
- package/dist/holmes/cli/approve-ref.d.ts +13 -7
- package/dist/holmes/cli/approve-ref.js +30 -10
- package/dist/holmes/cli/approve-status.d.ts +26 -2
- package/dist/holmes/cli/approve-status.js +98 -18
- package/dist/holmes/cli/approve-watch.d.ts +5 -0
- package/dist/holmes/cli/approve-watch.js +10 -5
- package/dist/holmes/cli/approve.d.ts +49 -13
- package/dist/holmes/cli/approve.js +249 -67
- package/dist/holmes/cli/attest.js +2 -1
- package/dist/holmes/cli/autonomy.d.ts +4 -1
- package/dist/holmes/cli/autonomy.js +17 -10
- package/dist/holmes/cli/codex-oracle.d.ts +11 -0
- package/dist/holmes/cli/codex-oracle.js +5 -1
- package/dist/holmes/cli/codex-toml.d.ts +10 -0
- package/dist/holmes/cli/codex-toml.js +36 -2
- package/dist/holmes/cli/doctor-boundary.d.ts +76 -0
- package/dist/holmes/cli/doctor-boundary.js +308 -0
- package/dist/holmes/cli/doctor-locks.d.ts +15 -0
- package/dist/holmes/cli/doctor-locks.js +119 -0
- package/dist/holmes/cli/doctor.d.ts +2 -0
- package/dist/holmes/cli/doctor.js +34 -5
- package/dist/holmes/cli/flags.d.ts +23 -0
- package/dist/holmes/cli/flags.js +89 -0
- package/dist/holmes/cli/index.d.ts +5 -1
- package/dist/holmes/cli/index.js +226 -442
- package/dist/holmes/cli/init.js +33 -0
- package/dist/holmes/cli/interactive-prompt.d.ts +39 -2
- package/dist/holmes/cli/interactive-prompt.js +98 -16
- package/dist/holmes/cli/lock-recover.d.ts +5 -0
- package/dist/holmes/cli/lock-recover.js +126 -0
- package/dist/holmes/cli/mcp-processes.js +1 -1
- package/dist/holmes/cli/release-docs.js +1 -1
- package/dist/holmes/cli/run-exec.d.ts +141 -0
- package/dist/holmes/cli/run-exec.js +1435 -0
- package/dist/holmes/cli/run-provision.d.ts +3 -1
- package/dist/holmes/cli/run-provision.js +255 -44
- package/dist/holmes/cli/run-wiring.d.ts +69 -0
- package/dist/holmes/cli/run-wiring.js +270 -0
- package/dist/holmes/cli/run.d.ts +21 -0
- package/dist/holmes/cli/run.js +341 -92
- package/dist/holmes/cli/runtime-binding-approval.js +32 -19
- package/dist/holmes/cli/screen-safe.d.ts +3 -92
- package/dist/holmes/cli/screen-safe.js +18 -756
- package/dist/holmes/config/config.d.ts +19 -0
- package/dist/holmes/config/config.js +18 -3
- package/dist/holmes/cpg/foundation/language-matrix.js +2 -2
- package/dist/holmes/cpg/import-resolver.js +1 -1
- package/dist/holmes/governance/approval-decisions.d.ts +47 -0
- package/dist/holmes/governance/approval-decisions.js +29 -0
- package/dist/holmes/governance/approval-grants.d.ts +220 -1
- package/dist/holmes/governance/approval-grants.js +612 -33
- package/dist/holmes/governance/approval-queue.d.ts +26 -0
- package/dist/holmes/governance/approval-queue.js +109 -11
- package/dist/holmes/governance/approval-spend.d.ts +95 -0
- package/dist/holmes/governance/approval-spend.js +191 -0
- package/dist/holmes/governance/autonomous-shell.d.ts +61 -0
- package/dist/holmes/governance/autonomous-shell.js +332 -0
- package/dist/holmes/governance/autonomy.d.ts +12 -0
- package/dist/holmes/governance/autonomy.js +51 -15
- package/dist/holmes/governance/constitution.d.ts +5 -0
- package/dist/holmes/governance/constitution.js +32 -12
- package/dist/holmes/governance/full-autonomy.d.ts +10 -0
- package/dist/holmes/governance/full-autonomy.js +103 -7
- package/dist/holmes/governance/harness-catalog.d.ts +103 -0
- package/dist/holmes/governance/harness-catalog.js +348 -0
- package/dist/holmes/governance/human-channel.d.ts +38 -0
- package/dist/holmes/governance/human-channel.js +49 -0
- package/dist/holmes/governance/install-manifest.d.ts +22 -0
- package/dist/holmes/governance/install-manifest.js +160 -0
- package/dist/holmes/governance/ledger-rechain.js +2 -0
- package/dist/holmes/governance/ledger-store.conformance.d.ts +7 -1
- package/dist/holmes/governance/ledger-store.conformance.js +66 -0
- package/dist/holmes/governance/ledger-store.d.ts +88 -11
- package/dist/holmes/governance/ledger-store.js +186 -8
- package/dist/holmes/governance/provenance-chain.d.ts +16 -4
- package/dist/holmes/governance/provenance-chain.js +19 -4
- package/dist/holmes/governance/provenance-ledger.d.ts +6 -3
- package/dist/holmes/governance/provenance-ledger.js +53 -18
- package/dist/holmes/governance/push-gate-runner.d.ts +2 -0
- package/dist/holmes/governance/push-gate-runner.js +50 -9
- package/dist/holmes/governance/push-gate.d.ts +13 -2
- package/dist/holmes/governance/push-gate.js +106 -14
- package/dist/holmes/governance/recorded-pairs.d.ts +96 -0
- package/dist/holmes/governance/recorded-pairs.js +522 -0
- package/dist/holmes/governance/replica-id.d.ts +1 -1
- package/dist/holmes/governance/replica-id.js +1 -1
- package/dist/holmes/governance/spec-seam.d.ts +59 -0
- package/dist/holmes/governance/spec-seam.js +587 -0
- package/dist/holmes/governance/spend-kinds.d.ts +16 -0
- package/dist/holmes/governance/spend-kinds.js +18 -0
- package/dist/holmes/guardrail/advisory-line.d.ts +102 -0
- package/dist/holmes/guardrail/advisory-line.js +718 -0
- package/dist/holmes/guardrail/decision-ledger.d.ts +2 -1
- package/dist/holmes/guardrail/decision-ledger.js +2 -1
- package/dist/holmes/guardrail/impact-gate.d.ts +7 -0
- package/dist/holmes/guardrail/impact-gate.js +33 -6
- package/dist/holmes/guardrail/line-continuation.d.ts +8 -0
- package/dist/holmes/guardrail/line-continuation.js +39 -0
- package/dist/holmes/guardrail/operator-person.d.ts +28 -4
- package/dist/holmes/guardrail/operator-person.js +57 -11
- package/dist/holmes/guardrail/refusal-codes.d.ts +8 -3
- package/dist/holmes/guardrail/refusal-codes.js +64 -10
- package/dist/holmes/guardrail/risk-classifier.d.ts +15 -9
- package/dist/holmes/guardrail/risk-classifier.js +228 -16
- package/dist/holmes/guardrail/risk-gate.d.ts +2 -8
- package/dist/holmes/guardrail/risk-gate.js +7 -34
- package/dist/holmes/guardrail/risk-types.d.ts +10 -0
- package/dist/holmes/guardrail/run-plan-scope.js +3 -1
- package/dist/holmes/guardrail/run-refusals.js +24 -8
- package/dist/holmes/guardrail/run-stages.d.ts +5 -0
- package/dist/holmes/guardrail/run-stages.js +25 -5
- package/dist/holmes/guardrail/scope-judgment.js +1 -1
- package/dist/holmes/guardrail/shell-words.js +24 -3
- package/dist/holmes/guardrail/unresolved-write.d.ts +40 -0
- package/dist/holmes/guardrail/unresolved-write.js +556 -0
- package/dist/holmes/guardrail/write-target.d.ts +3 -0
- package/dist/holmes/guardrail/write-target.js +26 -5
- package/dist/holmes/hooks/pre-tool-use.d.ts +116 -1
- package/dist/holmes/hooks/pre-tool-use.js +1176 -170
- package/dist/holmes/hooks/rtm-refresh-child.d.ts +1 -1
- package/dist/holmes/hooks/rtm-refresh-child.js +1 -1
- package/dist/holmes/hooks/session-start.js +17 -1
- package/dist/holmes/hooks/stop.d.ts +23 -0
- package/dist/holmes/hooks/stop.js +86 -33
- package/dist/holmes/mcp/approval-adapters.js +3 -1
- package/dist/holmes/mcp/approval-commit.js +3 -2
- package/dist/holmes/mcp/approval-policy.d.ts +2 -1
- package/dist/holmes/mcp/approval-policy.js +3 -1
- package/dist/holmes/mcp/handlers/adoption.d.ts +1 -1
- package/dist/holmes/mcp/handlers/approval-ask.d.ts +3 -0
- package/dist/holmes/mcp/handlers/approval-ask.js +18 -7
- package/dist/holmes/mcp/handlers/entity-integration.d.ts +3 -3
- package/dist/holmes/mcp/handlers/entity-integration.js +29 -11
- package/dist/holmes/mcp/handlers/entity-renumber.d.ts +4 -4
- package/dist/holmes/mcp/handlers/entity-renumber.js +29 -11
- package/dist/holmes/mcp/handlers/entity-store.d.ts +2 -2
- package/dist/holmes/mcp/handlers/entity-store.js +133 -59
- package/dist/holmes/mcp/handlers/maintenance-analysis.d.ts +13 -0
- package/dist/holmes/mcp/handlers/maintenance-analysis.js +59 -2
- package/dist/holmes/mcp/handlers/operator-inspection.d.ts +9 -5
- package/dist/holmes/mcp/handlers/operator-inspection.js +79 -16
- package/dist/holmes/mcp/handlers/phase-queries.d.ts +1 -1
- package/dist/holmes/mcp/handlers/requirement-triage.d.ts +4 -4
- package/dist/holmes/mcp/handlers/review-evidence.d.ts +2 -2
- package/dist/holmes/mcp/handlers/review-evidence.js +35 -11
- package/dist/holmes/mcp/handlers/review-queries.d.ts +5 -0
- package/dist/holmes/mcp/handlers/review-queries.js +8 -1
- package/dist/holmes/mcp/handlers/review-verdict.d.ts +3 -0
- package/dist/holmes/mcp/handlers/review-verdict.js +10 -3
- package/dist/holmes/mcp/handlers/risk-assessment.d.ts +7 -2
- package/dist/holmes/mcp/handlers/risk-assessment.js +34 -12
- package/dist/holmes/mcp/handlers/runtime-binding-tool.d.ts +2 -2
- package/dist/holmes/mcp/handlers/slice-orchestration.d.ts +6 -1
- package/dist/holmes/mcp/handlers/slice-orchestration.js +14 -1
- package/dist/holmes/mcp/handlers/spec-approval.d.ts +15 -3
- package/dist/holmes/mcp/handlers/spec-approval.js +32 -5
- package/dist/holmes/mcp/handlers/spec-authoring.d.ts +2 -2
- package/dist/holmes/mcp/handlers/spec-authoring.js +19 -2
- package/dist/holmes/mcp/handlers/spec-lifecycle.d.ts +11 -38
- package/dist/holmes/mcp/handlers/spec-lifecycle.js +441 -94
- package/dist/holmes/mcp/handlers/spec-queries.d.ts +2 -2
- package/dist/holmes/mcp/handlers/taint-screening.d.ts +1 -1
- package/dist/holmes/mcp/handlers/taint-screening.js +2 -2
- package/dist/holmes/mcp/handlers/test-execution.d.ts +471 -4
- package/dist/holmes/mcp/handlers/test-execution.js +199 -21
- package/dist/holmes/mcp/handlers/workspace-queries.d.ts +2 -2
- package/dist/holmes/mcp/handlers.d.ts +557 -82
- package/dist/holmes/mcp/handlers.js +74 -23
- package/dist/holmes/mcp/harness-attestation.d.ts +78 -5
- package/dist/holmes/mcp/harness-attestation.js +325 -53
- package/dist/holmes/mcp/maintenance-analyze.d.ts +6 -1
- package/dist/holmes/mcp/maintenance-analyze.js +13 -11
- package/dist/holmes/mcp/maintenance-evidence.d.ts +9 -0
- package/dist/holmes/mcp/maintenance-evidence.js +35 -3
- package/dist/holmes/mcp/requirement-triage-evidence.js +22 -13
- package/dist/holmes/mcp/server-staleness.js +1 -1
- package/dist/holmes/mcp/server.js +9 -8
- package/dist/holmes/mcp/spec-id-guard.js +1 -1
- package/dist/holmes/mcp/tool-schemas.d.ts +13 -0
- package/dist/holmes/mcp/tool-schemas.js +42 -9
- package/dist/holmes/project/act-root.d.ts +19 -0
- package/dist/holmes/project/act-root.js +100 -0
- package/dist/holmes/project/baseline.d.ts +15 -2
- package/dist/holmes/project/baseline.js +14 -8
- package/dist/holmes/project/bounded-group.d.ts +47 -0
- package/dist/holmes/project/bounded-group.js +140 -0
- package/dist/holmes/project/bounded-io.d.ts +51 -2
- package/dist/holmes/project/bounded-io.js +140 -6
- package/dist/holmes/project/change-source.d.ts +4 -0
- package/dist/holmes/project/change-source.js +14 -6
- package/dist/holmes/project/instance-id.d.ts +10 -0
- package/dist/holmes/project/instance-id.js +233 -0
- package/dist/holmes/project/machine-identity.d.ts +25 -0
- package/dist/holmes/project/machine-identity.js +133 -0
- package/dist/holmes/project/owned-lock.d.ts +84 -0
- package/dist/holmes/project/owned-lock.js +263 -0
- package/dist/holmes/project/plain-lock-fs.d.ts +2 -0
- package/dist/holmes/project/plain-lock-fs.js +126 -0
- package/dist/holmes/project/request-lock.d.ts +85 -0
- package/dist/holmes/project/request-lock.js +459 -0
- package/dist/holmes/project/root.d.ts +12 -4
- package/dist/holmes/project/root.js +29 -8
- package/dist/holmes/project/run-records.d.ts +19 -0
- package/dist/holmes/project/run-records.js +94 -12
- package/dist/holmes/project/screen-text.d.ts +94 -0
- package/dist/holmes/project/screen-text.js +763 -0
- package/dist/holmes/project/spend-lock.d.ts +82 -0
- package/dist/holmes/project/spend-lock.js +413 -0
- package/dist/holmes/refresh/freshness-coordinator.d.ts +1 -1
- package/dist/holmes/refresh/freshness-coordinator.js +1 -1
- package/dist/holmes/review/condition-hunk-replay.js +4 -2
- package/dist/holmes/review/confidence-calibration.d.ts +1 -1
- package/dist/holmes/review/confidence-calibration.js +1 -1
- package/dist/holmes/review/content-verify.js +1 -1
- package/dist/holmes/review/evidence-mode.d.ts +21 -0
- package/dist/holmes/review/evidence-mode.js +33 -0
- package/dist/holmes/review/head-worktree.d.ts +55 -0
- package/dist/holmes/review/head-worktree.js +329 -0
- package/dist/holmes/review/hop-ablation.d.ts +4 -4
- package/dist/holmes/review/hop-ablation.js +5 -5
- package/dist/holmes/review/mrp.js +13 -3
- package/dist/holmes/review/point-in-time-replay.js +12 -3
- package/dist/holmes/review/rank-diagnosis.d.ts +2 -2
- package/dist/holmes/review/rank-diagnosis.js +1 -1
- package/dist/holmes/review/replay-corpus.d.ts +10 -4
- package/dist/holmes/review/replay-corpus.js +25 -9
- package/dist/holmes/review/requirement-triage.js +2 -2
- package/dist/holmes/review/run-provenance.d.ts +45 -0
- package/dist/holmes/review/run-provenance.js +314 -0
- package/dist/holmes/review/semantic-arm.d.ts +3 -3
- package/dist/holmes/review/semantic-arm.js +3 -3
- package/dist/holmes/review/test-evidence.d.ts +174 -0
- package/dist/holmes/review/test-evidence.js +330 -2
- package/dist/holmes/review/test-outcomes.js +3 -1
- package/dist/holmes/review/test-reports.d.ts +94 -0
- package/dist/holmes/review/test-reports.js +382 -0
- package/dist/holmes/review/test-runner.d.ts +180 -58
- package/dist/holmes/review/test-runner.js +560 -324
- package/dist/holmes/review/test-selection-breadth.js +2 -2
- package/dist/holmes/review/test-units.d.ts +159 -0
- package/dist/holmes/review/test-units.js +814 -0
- package/dist/holmes/review/verdicts.d.ts +105 -8
- package/dist/holmes/review/verdicts.js +640 -36
- package/dist/holmes/rtm/anchor-census.d.ts +9 -0
- package/dist/holmes/rtm/anchor-census.js +151 -0
- package/dist/holmes/rtm/anchor-ids.d.ts +25 -1
- package/dist/holmes/rtm/anchor-ids.js +45 -2
- package/dist/holmes/rtm/comment-ranges.d.ts +2 -0
- package/dist/holmes/rtm/comment-ranges.js +104 -0
- package/dist/holmes/rtm/counted-tests.d.ts +1 -0
- package/dist/holmes/rtm/counted-tests.js +63 -0
- package/dist/holmes/rtm/impact-advisory.d.ts +1 -1
- package/dist/holmes/rtm/known-defects.js +1 -1
- package/dist/holmes/rtm/localize.js +1 -1
- package/dist/holmes/rtm/taint-benchmark.d.ts +1 -1
- package/dist/holmes/rtm/taint-vocabulary.d.ts +1 -1
- package/dist/holmes/rtm/test-scope.d.ts +31 -0
- package/dist/holmes/rtm/test-scope.js +166 -5
- package/dist/holmes/rtm/trace-gaps.js +1 -1
- package/dist/holmes/runtime/dispatch.d.ts +10 -0
- package/dist/holmes/runtime/dispatch.js +12 -1
- package/dist/holmes/semantic/cloud-usage.d.ts +1 -1
- package/dist/holmes/semantic/cloud-usage.js +1 -1
- package/dist/holmes/semantic/unreadable-paths.d.ts +1 -1
- package/dist/holmes/semantic/unreadable-paths.js +1 -1
- package/dist/holmes/spec/approval-blockers.js +1 -1
- package/dist/holmes/spec/entity-store.d.ts +6 -1
- package/dist/holmes/spec/entity-store.js +16 -2
- package/dist/holmes/spec/entity-transaction.d.ts +7 -2
- package/dist/holmes/spec/entity-transaction.js +87 -170
- package/dist/holmes/spec/spec-store.d.ts +12 -6
- package/dist/holmes/spec/spec-store.js +4 -2
- package/dist/holmes/spec/spec-types.js +1 -1
- package/dist/holmes/spec/succession-guard.d.ts +56 -0
- package/dist/holmes/spec/succession-guard.js +187 -0
- package/dist/holmes/spec/succession.d.ts +70 -0
- package/dist/holmes/spec/succession.js +171 -0
- package/dist/holmes/spec/transition-policy.d.ts +2 -2
- package/docs/install-guide.md +9 -3
- package/docs/language-support.md +78 -0
- package/package.json +4 -3
- package/playbooks/author-slice/PLAYBOOK.md +1 -1
- package/playbooks/promote-slice/PLAYBOOK.md +5 -1
- package/playbooks/publish/PLAYBOOK.md +47 -34
- package/dist/holmes/review/manual-baseline.d.ts +0 -209
- package/dist/holmes/review/manual-baseline.js +0 -2847
|
@@ -0,0 +1,1435 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.claudeTmpName = void 0;
|
|
37
|
+
exports.canonicalOrRefuse = canonicalOrRefuse;
|
|
38
|
+
exports.sandboxProfile = sandboxProfile;
|
|
39
|
+
exports.sandboxEnv = sandboxEnv;
|
|
40
|
+
exports.makeCanary = makeCanary;
|
|
41
|
+
exports.canaryProblem = canaryProblem;
|
|
42
|
+
exports.sandboxDetect = sandboxDetect;
|
|
43
|
+
exports.sweepVerdict = sweepVerdict;
|
|
44
|
+
exports.sandboxSweep = sandboxSweep;
|
|
45
|
+
exports.removeRunTmp = removeRunTmp;
|
|
46
|
+
exports.liveExecEntries = liveExecEntries;
|
|
47
|
+
exports.sweepOrphanExecs = sweepOrphanExecs;
|
|
48
|
+
exports.runExec = runExec;
|
|
49
|
+
// @implements A-SPEC-774.34, A-SPEC-774.35, A-SPEC-774.36
|
|
50
|
+
/**
|
|
51
|
+
* `holmes-kit run exec --id <run> -- <command>`: run a run's engine inside a write sandbox (D14).
|
|
52
|
+
*
|
|
53
|
+
* An orchestrator measured three writes an engine with a shell makes today: (a) the worktree's `.git` pointer rewritten to the
|
|
54
|
+
* root, (b) `core.fsmonitor` or hooks planted in the common dir, which the orchestrator's next git call runs, and (c)
|
|
55
|
+
* the root's tree written through `../../`. Holmes detected some of it afterwards; only the run layer can refuse the
|
|
56
|
+
* write. On macOS the command runs under `sandbox-exec` with a profile generated from the run record (measured on this
|
|
57
|
+
* machine before writing it: a commit passes; the `.git` file, the common config and hooks, the main checkout and any
|
|
58
|
+
* outside path are refused). Linux and Windows are named gaps until measured there.
|
|
59
|
+
*
|
|
60
|
+
* Nothing the command starts outlives it: it runs in its own process group, which is killed when it exits, and then
|
|
61
|
+
* every process whose environment carries this run's random marker is killed too — the setsid and double-fork escapes
|
|
62
|
+
* a process group does not hold. A process that clears its own environment is the gap that remains (named in the spec).
|
|
63
|
+
*/
|
|
64
|
+
const node_child_process_1 = require("node:child_process");
|
|
65
|
+
const crypto = __importStar(require("node:crypto"));
|
|
66
|
+
const fs = __importStar(require("node:fs"));
|
|
67
|
+
const os = __importStar(require("node:os"));
|
|
68
|
+
const path = __importStar(require("node:path"));
|
|
69
|
+
const run_records_1 = require("../project/run-records");
|
|
70
|
+
const bounded_io_1 = require("../project/bounded-io");
|
|
71
|
+
/**
|
|
72
|
+
* @implements A-SPEC-774.35 — the name Claude Code gives a working directory under `/tmp/claude-<uid>`: its real path
|
|
73
|
+
* with every character outside [A-Za-z0-9] replaced by `-` (the naming measured in `~/.claude/projects`).
|
|
74
|
+
*/
|
|
75
|
+
const claudeTmpName = (p) => p.replace(/[^A-Za-z0-9]/g, '-');
|
|
76
|
+
exports.claudeTmpName = claudeTmpName;
|
|
77
|
+
const SANDBOX_EXEC = '/usr/bin/sandbox-exec';
|
|
78
|
+
const sbplString = (p) => {
|
|
79
|
+
if (/["\\\n\r]/.test(p))
|
|
80
|
+
throw new Error(`a path the sandbox profile cannot quote: ${JSON.stringify(p)}`);
|
|
81
|
+
return `"${p}"`;
|
|
82
|
+
};
|
|
83
|
+
/** The git dirs of a linked worktree, and its branch when one is checked out; inherited GIT_* variables dropped. */
|
|
84
|
+
/** Spellings that reach a file without being its path: the no-follow, resolve and volume-id namespaces and the data volume. */
|
|
85
|
+
const VIRTUAL_PREFIXES = ['/.nofollow', '/.resolve', '/.vol', '/system/volumes/data'];
|
|
86
|
+
const realFs = { realpath: (p) => fs.realpathSync.native(p), lstat: (p) => fs.lstatSync(p), stat: (p) => fs.statSync(p) };
|
|
87
|
+
/**
|
|
88
|
+
* @implements A-SPEC-774.82 — the one input seam (owner decision 2026-10-25: accept only canonical spellings). Seatbelt
|
|
89
|
+
* judges an access by its real path and a rule as written, so a rule in any other spelling is dead; four rounds of
|
|
90
|
+
* folding spellings (H1.4–H1.7) each left the next one open (/.nofollow, /.vol, /home, lower-case Data). A path is
|
|
91
|
+
* admitted only when it is absolute, carries no virtual prefix, is its own realpath.native, and stats to that file.
|
|
92
|
+
*/
|
|
93
|
+
function canonicalOrRefuse(p, fsx = realFs) {
|
|
94
|
+
if (!path.isAbsolute(p))
|
|
95
|
+
return { refused: `${p} is not an absolute path` };
|
|
96
|
+
const lower = p.toLowerCase();
|
|
97
|
+
if (VIRTUAL_PREFIXES.some((v) => lower === v || lower.startsWith(`${v}/`)))
|
|
98
|
+
return { refused: `${p} is a virtual spelling (${p.split('/').slice(0, 2).join('/')}…), not a path` };
|
|
99
|
+
let real;
|
|
100
|
+
try {
|
|
101
|
+
real = fsx.realpath(p);
|
|
102
|
+
}
|
|
103
|
+
catch (e) {
|
|
104
|
+
return { refused: `${p} cannot be resolved (${e instanceof Error ? e.message.split('\n')[0] : String(e)})` };
|
|
105
|
+
}
|
|
106
|
+
if (real !== p)
|
|
107
|
+
return { refused: `${p} is not canonical; its canonical spelling is ${real}` };
|
|
108
|
+
try {
|
|
109
|
+
const a = fsx.lstat(p);
|
|
110
|
+
const b = fsx.stat(real);
|
|
111
|
+
if (a.dev !== b.dev || a.ino !== b.ino)
|
|
112
|
+
return { refused: `${p} does not stat to the file its path names` };
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
return { refused: `${p} cannot be stat'ed (${e instanceof Error ? e.message.split('\n')[0] : String(e)})` };
|
|
116
|
+
}
|
|
117
|
+
return { path: p };
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* @implements A-SPEC-774.82 — a second LOCATION, not a second spelling: a home dotfile or secret path that is a link,
|
|
121
|
+
* at its target, when that target is itself canonical.
|
|
122
|
+
*/
|
|
123
|
+
function linkTarget(p) {
|
|
124
|
+
try {
|
|
125
|
+
if (!fs.lstatSync(p).isSymbolicLink())
|
|
126
|
+
return null;
|
|
127
|
+
const t = canonicalOrRefuse(fs.realpathSync.native(p));
|
|
128
|
+
return 'path' in t ? t.path : null;
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* @implements A-SPEC-774.87 — where a path really lies when one of its ANCESTORS is a link: the longest existing prefix
|
|
136
|
+
* resolved, the rest of the name appended (H1.9-a: `~/.config` linked out of home left `<home>/.config/gh` a rule that
|
|
137
|
+
* names nothing). Null when the path lies where it is spelled, or nothing of it exists. For deny rules only.
|
|
138
|
+
*/
|
|
139
|
+
function realLocation(p) {
|
|
140
|
+
let head = p;
|
|
141
|
+
const rest = [];
|
|
142
|
+
while (!fs.existsSync(head)) {
|
|
143
|
+
// @implements A-SPEC-222.8 — L-c: a dangling link is a location already: its target (made later, it holds the secret)
|
|
144
|
+
try {
|
|
145
|
+
if (fs.lstatSync(head).isSymbolicLink()) {
|
|
146
|
+
const target = path.resolve(path.dirname(head), fs.readlinkSync(head));
|
|
147
|
+
const at = path.join(target === head ? head : realLocation(target) ?? target, ...rest);
|
|
148
|
+
return at === p ? null : at;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
catch { /* nothing at this spelling: go up */ }
|
|
152
|
+
const up = path.dirname(head);
|
|
153
|
+
if (up === head)
|
|
154
|
+
return null;
|
|
155
|
+
rest.unshift(path.basename(head));
|
|
156
|
+
head = up;
|
|
157
|
+
}
|
|
158
|
+
let real;
|
|
159
|
+
try {
|
|
160
|
+
real = fs.realpathSync.native(head);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
const at = path.join(real, ...rest);
|
|
166
|
+
return at === p ? null : at;
|
|
167
|
+
}
|
|
168
|
+
function gitLayout(worktree) {
|
|
169
|
+
// @implements A-SPEC-774.79 — the judgments' git environment from its own module, not through run.ts (no cycle)
|
|
170
|
+
const { judgmentGitEnv } = require('../review/verdicts');
|
|
171
|
+
const out = (args) => (0, node_child_process_1.execFileSync)('git', args, { cwd: worktree, encoding: 'utf8', env: judgmentGitEnv(process.env), stdio: ['ignore', 'pipe', 'ignore'], timeout: bounded_io_1.GIT_TIMEOUT_MS, maxBuffer: bounded_io_1.GIT_MAX_BUFFER }).trim();
|
|
172
|
+
const [gitDir, common] = out(['rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir']).split('\n');
|
|
173
|
+
let branch = null;
|
|
174
|
+
try {
|
|
175
|
+
branch = out(['symbolic-ref', '--quiet', 'HEAD']) || null;
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
branch = null;
|
|
179
|
+
} // detached: no branch ref
|
|
180
|
+
return { gitDir, common, branch }; // A-SPEC-774.82 — judged by the caller's seam, not folded here
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* @implements A-SPEC-774.34, A-SPEC-774.35, A-SPEC-774.36 — the profile: deny every write, then allow exactly what the
|
|
184
|
+
* run's engine needs. Its engine state lives in its own home inside the run temp dir (774.36: nothing reaches the
|
|
185
|
+
* owner's ~/.claude* or ~/.codex); a claude run also gets Claude Code's temp directory for its worktree (774.35).
|
|
186
|
+
*/
|
|
187
|
+
function sandboxProfile(p) {
|
|
188
|
+
const uid = typeof process.getuid === 'function' ? process.getuid() : 0;
|
|
189
|
+
const claudeShared = `/private/tmp/claude-${uid}`;
|
|
190
|
+
const allow = [
|
|
191
|
+
`(subpath ${sbplString(p.worktree)})`, `(subpath ${sbplString(p.gitDir)})`, `(subpath ${sbplString(path.join(p.common, 'objects'))})`,
|
|
192
|
+
...(p.branch ? [path.join(p.common, p.branch), `${path.join(p.common, p.branch)}.lock`, path.join(p.common, 'logs', p.branch)].map((f) => `(literal ${sbplString(f)})`) : []),
|
|
193
|
+
`(subpath ${sbplString(p.tmp)})`,
|
|
194
|
+
...(p.engineHome ? [`(subpath ${sbplString(p.engineHome)})`] : []),
|
|
195
|
+
...(p.engine === 'claude' ? [`(literal ${sbplString(claudeShared)})`, `(subpath ${sbplString(path.join(claudeShared, (0, exports.claudeTmpName)(p.worktree)))})`] : []),
|
|
196
|
+
'(literal "/dev/null")', '(literal "/dev/tty")', '(regex #"^/dev/fd/")', '(regex #"^/dev/ttys")',
|
|
197
|
+
];
|
|
198
|
+
// @implements A-SPEC-774.39, A-SPEC-774.43 — and the git dir's own pointers: the engine stays in its repository. HEAD
|
|
199
|
+
// is its own to move (detached worktrees commit); authorship never reads it (A-SPEC-102.19/102.20).
|
|
200
|
+
// @implements A-SPEC-774.58 — and the run temp dir itself: its contents are the run's, the dir is not (a run that
|
|
201
|
+
// moved it away and left a link took its canaries out of the teardown's view).
|
|
202
|
+
// @implements A-SPEC-102.25 — and the object store's own shape: no alternates added, written or renamed into place
|
|
203
|
+
const objects = path.join(p.common, 'objects');
|
|
204
|
+
const deny = [path.join(p.worktree, '.git'), ...['commondir', 'gitdir'].map((n) => path.join(p.gitDir, n)), p.tmp,
|
|
205
|
+
objects, path.join(objects, 'info'), path.join(objects, 'info', 'alternates'), path.join(objects, 'info', 'http-alternates')]
|
|
206
|
+
.map((f) => `(literal ${sbplString(f)})`);
|
|
207
|
+
// @implements A-SPEC-774.52 — nothing in the run reads a credential store or the owner's engine homes; the run has its
|
|
208
|
+
// own engine home (774.36), copied in by run exec outside the sandbox.
|
|
209
|
+
const homes = [p.home]; // @implements A-SPEC-774.82 — one canonical spelling; the caller's seam admitted it
|
|
210
|
+
const secret = [...new Set([
|
|
211
|
+
...homes.flatMap((h) => ['.ssh', '.aws', path.join('.config', 'gcloud'), '.gnupg', '.kube', '.azure', '.docker', '.codex', '.claude'].map((d) => `(subpath ${sbplString(path.join(h, d))})`)),
|
|
212
|
+
...homes.flatMap((h) => ['.netrc', '.claude.json'].map((f) => `(literal ${sbplString(path.join(h, f))})`)),
|
|
213
|
+
...(p.ownerCodexHome ? [`(subpath ${sbplString(p.ownerCodexHome)})`] : []),
|
|
214
|
+
// @implements A-SPEC-774.59 — and every credential an allowed directory could hold
|
|
215
|
+
...homes.flatMap((h) => [path.join('.config', 'gh'), path.join('Library', 'Keychains')].map((d) => `(subpath ${sbplString(path.join(h, d))})`)),
|
|
216
|
+
...homes.flatMap((h) => ['.npmrc', '.git-credentials', '.pypirc', path.join('.gem', 'credentials'), path.join('.cargo', 'credentials'), path.join('.cargo', 'credentials.toml')]
|
|
217
|
+
.map((f) => `(literal ${sbplString(path.join(h, f))})`)),
|
|
218
|
+
// @implements A-SPEC-774.62 — Holmes's own key file and every name it starts (a paused or backup copy)
|
|
219
|
+
...homes.map((h) => `(regex #"^${sbplString(path.join(h, '.holmes', 'credentials.json')).slice(1, -1).replace(/[.^$*+?()[\]{}|]/g, '\\$&')}")`),
|
|
220
|
+
// @implements A-SPEC-774.63 — the conventional credential files of git, build tools, password and token stores and
|
|
221
|
+
// database and cloud clients, and the main checkout's untracked files unless the orchestrator opened them
|
|
222
|
+
...homes.flatMap((h) => [path.join('.local', 'share', 'keyrings'), '.password-store', path.join('.config', 'hub'), path.join('.config', 'op'), path.join('.config', 'rclone')]
|
|
223
|
+
.map((d) => `(subpath ${sbplString(path.join(h, d))})`)),
|
|
224
|
+
...homes.flatMap((h) => [path.join('.config', 'git', 'credentials'), path.join('.m2', 'settings.xml'), path.join('.m2', 'settings-security.xml'),
|
|
225
|
+
path.join('.gradle', 'gradle.properties'), '.vault-token', path.join('.terraform.d', 'credentials.tfrc.json'), '.pgpass', '.my.cnf', '.boto', '.s3cfg']
|
|
226
|
+
.map((f) => `(literal ${sbplString(path.join(h, f))})`)),
|
|
227
|
+
// @implements A-SPEC-774.66 — and a token cached by a client in ~/.cache
|
|
228
|
+
...homes.flatMap((h) => ['token', 'stored_tokens'].map((f) => `(literal ${sbplString(path.join(h, '.cache', 'huggingface', f))})`)),
|
|
229
|
+
])];
|
|
230
|
+
// @implements A-SPEC-774.82 — a secret path that is a link is denied at its target too (H1.8-b: ~/.aws linked outside
|
|
231
|
+
// home was read there); the target is a second location, so it is added only when canonical
|
|
232
|
+
// @implements A-SPEC-774.87 — and at its real location when an ANCESTOR is the link (H1.9-a: ~/.config out of home)
|
|
233
|
+
const secretTargets = secret.flatMap((r) => {
|
|
234
|
+
const m = /^\((subpath|literal) "([^"]+)"\)$/.exec(r);
|
|
235
|
+
const t = m ? linkTarget(m[2]) ?? realLocation(m[2]) : null;
|
|
236
|
+
return m && t ? [`(${m[1]} ${sbplString(t)})`] : [];
|
|
237
|
+
});
|
|
238
|
+
secret.push(...secretTargets.filter((r) => !secret.includes(r)));
|
|
239
|
+
for (const h of homes) {
|
|
240
|
+
const key = realLocation(path.join(h, '.holmes', 'credentials.json'));
|
|
241
|
+
if (key)
|
|
242
|
+
secret.push(`(regex #"^${sbplString(key).slice(1, -1).replace(/[.^$*+?()[\]{}|]/g, '\\$&')}")`);
|
|
243
|
+
}
|
|
244
|
+
// @implements A-SPEC-774.66 — an untracked file by literal, an ignored directory by subpath; a name the profile
|
|
245
|
+
// cannot quote by an escaped pattern (its unquotable characters as any character) instead of refusing the run
|
|
246
|
+
// @implements A-SPEC-774.70 — kept apart from the secrets: the orchestrator's named paths outrank these, not those
|
|
247
|
+
const untrackedRule = (e) => {
|
|
248
|
+
if (!/["\\\n\r]/.test(e.path))
|
|
249
|
+
return `(${e.dir ? 'subpath' : 'literal'} ${sbplString(e.path)})`;
|
|
250
|
+
const re = e.path.split(/["\\\n\r]/).map((s) => s.replace(/[.^$*+?()[\]{}|]/g, '\\$&')).join('.');
|
|
251
|
+
return `(regex #"^${re}${e.dir ? '(/|$)' : '$'}")`;
|
|
252
|
+
};
|
|
253
|
+
// @implements A-SPEC-774.59 — home contents are an allowlist: the repository, the Holmes package, toolchains, git and
|
|
254
|
+
// shell startup files, ~/.holmes and the orchestrator's named paths (measured: node, npm, git, zsh -l, python3 work).
|
|
255
|
+
// @implements A-SPEC-774.82 — every path here passed the seam; no second spelling is written (774.73's `.native`
|
|
256
|
+
// twin and 774.77's firmlink fold are gone with the inputs that needed them)
|
|
257
|
+
const homeDirs = ['.nvm', '.npm', '.node-gyp', '.rustup', '.pyenv', '.rbenv', '.volta', '.bun', '.deno', 'go',
|
|
258
|
+
'.cache', '.yarn', '.pnpm-store', path.join('Library', 'Caches'), path.join('Library', 'pnpm'), path.join('.config', 'git'),
|
|
259
|
+
// @implements A-SPEC-774.63 — of a build tool's home, only the subpaths its caches and installs live in
|
|
260
|
+
...[['.m2', 'repository'], ['.m2', 'wrapper'], ['.gradle', 'caches'], ['.gradle', 'wrapper'], ['.gradle', 'native'],
|
|
261
|
+
['.cargo', 'bin'], ['.cargo', 'registry'], ['.cargo', 'git'], ['.local', 'bin'], ['.local', 'lib'], ['.local', 'pipx'],
|
|
262
|
+
['.local', 'share', 'uv']].map((s) => path.join(...s)), // @implements A-SPEC-774.66 — uv's tools and pythons
|
|
263
|
+
// @implements A-SPEC-774.62 — of ~/.holmes, only what a run reads: the model cache, the runtime bindings, codex's hooks
|
|
264
|
+
...['models', 'runtime', 'codex-plugin'].map((d) => path.join('.holmes', d))];
|
|
265
|
+
const homeFiles = ['.gitconfig', '.gitignore_global',
|
|
266
|
+
// @implements A-SPEC-774.63 — shell startup files hold token exports: read only when the orchestrator says so
|
|
267
|
+
...(p.shellStartup ? ['.zshrc', '.zprofile', '.zshenv', '.zlogin', '.profile', '.bashrc', '.bash_profile'] : []),
|
|
268
|
+
...['full-autonomy.json', 'update-check.json', 'workspaces.json'].map((f) => path.join('.holmes', f))];
|
|
269
|
+
const readable = [...new Set([
|
|
270
|
+
...[p.worktree, ...(p.readAllow ?? [])].map((d) => `(subpath ${sbplString(d)})`),
|
|
271
|
+
...homes.flatMap((h) => homeDirs.map((d) => `(subpath ${sbplString(path.join(h, d))})`)),
|
|
272
|
+
// @implements A-SPEC-774.66 — and a home file that is a link (dotfiles) by its target too (A-SPEC-774.82: a canonical one)
|
|
273
|
+
...homes.flatMap((h) => homeFiles.flatMap((f) => [path.join(h, f), linkTarget(path.join(h, f))]))
|
|
274
|
+
.filter((f) => f !== null).map((f) => `(literal ${sbplString(f)})`),
|
|
275
|
+
])];
|
|
276
|
+
// @implements A-SPEC-774.82 — the named paths as admitted by the seam: no `..` fold, no second spelling
|
|
277
|
+
const namedPaths = [...new Set(p.readAllowNamed ?? [])];
|
|
278
|
+
// @implements A-SPEC-774.74 — untracked denials and named allowances in ascending path depth (a deny before an allow
|
|
279
|
+
// at equal depth): every rule that governs a file lies on its ancestor chain, so the deepest one decides, at any
|
|
280
|
+
// nesting. The 774.71/774.73 ancestry re-denial computed ancestry from spellings and, re-allowing a named descendant,
|
|
281
|
+
// covered entries nested under it (H1.6-a); ordering needs no ancestry at all.
|
|
282
|
+
const depth = (s) => s.split(path.sep).filter(Boolean).length;
|
|
283
|
+
const ordered = [
|
|
284
|
+
...(p.denyRead ?? []).map((e) => ({ d: depth(e.path), kind: 'deny', rule: untrackedRule(e) })),
|
|
285
|
+
...namedPaths.map((n) => ({ d: depth(n), kind: 'allow', rule: `(subpath ${sbplString(n)})` })),
|
|
286
|
+
].sort((x, y) => x.d - y.d || (x.kind === y.kind ? 0 : x.kind === 'deny' ? -1 : 1));
|
|
287
|
+
const depthOrdered = [];
|
|
288
|
+
for (let i = 0; i < ordered.length;) {
|
|
289
|
+
let j = i;
|
|
290
|
+
while (j < ordered.length && ordered[j].kind === ordered[i].kind)
|
|
291
|
+
j++;
|
|
292
|
+
const rules = [...new Set(ordered.slice(i, j).map((o) => o.rule))].join(' ');
|
|
293
|
+
depthOrdered.push(`(${ordered[i].kind} file-read* ${rules})`, `(${ordered[i].kind} file-read-data ${rules})`);
|
|
294
|
+
i = j;
|
|
295
|
+
}
|
|
296
|
+
// @implements A-SPEC-774.71 — another run's temp dir (an engine-home copy holds its auth) is not this run's to read
|
|
297
|
+
// @implements A-SPEC-774.87 — under every temp root this checkout's exec registry records, not only this run's (H1.9-b)
|
|
298
|
+
const tmpRoots = [...new Set([path.dirname(p.tmp), ...(p.tmpRoots ?? [])])];
|
|
299
|
+
const otherRuns = tmpRoots.map((r) => `(regex #"^${sbplString(path.join(r, 'holmes-run-')).slice(1, -1).replace(/[.^$*+?()[\]{}|]/g, '\\$&')}")`).join(' ');
|
|
300
|
+
return ['(version 1)', '(allow default)',
|
|
301
|
+
`(deny file-read-data ${homes.map((h) => `(subpath ${sbplString(h)})`).join(' ')})`, `(allow file-read-data ${readable.join(' ')})`,
|
|
302
|
+
// @implements A-SPEC-774.70, A-SPEC-774.71, A-SPEC-774.73, A-SPEC-774.74 — the untracked denials and the
|
|
303
|
+
// orchestrator's named paths, most specific last, then the secrets (same operation: the later rule wins; each is
|
|
304
|
+
// written for file-read* and file-read-data, so neither outranks by kind)
|
|
305
|
+
...depthOrdered,
|
|
306
|
+
// @implements A-SPEC-774.62, A-SPEC-774.66 — file-read-data as well: a file-read* denial does not override a
|
|
307
|
+
// file-read-data allowance, wherever it stands; the more specific operation decides (measured), so a secret inside
|
|
308
|
+
// an allowed directory was readable
|
|
309
|
+
`(deny file-read* ${secret.join(' ')})`, `(deny file-read-data ${secret.join(' ')})`,
|
|
310
|
+
// @implements A-SPEC-774.71 — other runs' temp dirs, then this run's own again
|
|
311
|
+
`(deny file-read* ${otherRuns})`, `(deny file-read-data ${otherRuns})`,
|
|
312
|
+
`(allow file-read* (subpath ${sbplString(p.tmp)}))`, `(allow file-read-data (subpath ${sbplString(p.tmp)}))`,
|
|
313
|
+
// @implements A-SPEC-774.60 — the network reaches only run exec's own proxy (nothing local, nothing remote)
|
|
314
|
+
...(p.proxyPort !== undefined ? ['(deny network-outbound)', `(allow network-outbound (remote ip "localhost:${p.proxyPort}"))`] : []),
|
|
315
|
+
'(deny file-write*)', `(allow file-write* ${allow.join(' ')})`, `(deny file-write* ${deny.join(' ')})`,
|
|
316
|
+
// @implements A-SPEC-774.53 — the canaries' guard dir: only the allow-canary's data is writable, nothing is replaceable.
|
|
317
|
+
...(p.guard ? [`(deny file-write* (subpath ${sbplString(p.guard)}))`, `(allow file-write-data (literal ${sbplString(path.join(p.guard, 'allow'))}))`] : []),
|
|
318
|
+
// @implements A-SPEC-774.45 — no signal leaves the sandbox (run exec, its watchdog, the orchestrator); its own children
|
|
319
|
+
// stay killable.
|
|
320
|
+
'(deny signal)', '(allow signal (target same-sandbox))', ''].join('\n');
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* @implements A-SPEC-774.36 — a codex run's own CODEX_HOME: a 0600 copy of the owner's auth file, the owner's Holmes
|
|
324
|
+
* hook groups, and their trust carried over only for the byte-identical definitions the owner already trusted. Trust is
|
|
325
|
+
* never minted; a gate that cannot be carried over refuses rather than running the engine ungoverned.
|
|
326
|
+
*/
|
|
327
|
+
function codexRunHome(engineHome, ownerHome, trustDirs) {
|
|
328
|
+
const { parseCodexConfig, tomlStr } = require('./codex-toml');
|
|
329
|
+
const { isHolmesPreToolCommand } = require('./codex-oracle');
|
|
330
|
+
const { codexTrusts } = require('./run-wiring');
|
|
331
|
+
const read = (f) => { try {
|
|
332
|
+
return fs.readFileSync(f, 'utf8');
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
return null;
|
|
336
|
+
} };
|
|
337
|
+
if (!fs.existsSync(path.join(ownerHome, 'auth.json')))
|
|
338
|
+
return `the owner's ${path.join(ownerHome, 'auth.json')} is absent — codex cannot authenticate`;
|
|
339
|
+
const ownerHooksPath = path.join(ownerHome, 'hooks.json');
|
|
340
|
+
const configText = read(path.join(ownerHome, 'config.toml'));
|
|
341
|
+
const parsed = configText === null ? null : parseCodexConfig(configText);
|
|
342
|
+
const doc = parsed && parsed.ok ? parsed.doc : {};
|
|
343
|
+
const state = (doc.hooks?.state ?? {});
|
|
344
|
+
const ownerKeys = (() => { const s = new Set([ownerHooksPath]); try {
|
|
345
|
+
s.add(fs.realpathSync(ownerHooksPath));
|
|
346
|
+
}
|
|
347
|
+
catch { /* as given */ } return [...s]; })();
|
|
348
|
+
let hooksDoc;
|
|
349
|
+
try {
|
|
350
|
+
hooksDoc = JSON.parse(read(ownerHooksPath) ?? '{}');
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
return `the owner's ${ownerHooksPath} cannot be read`;
|
|
354
|
+
}
|
|
355
|
+
const events = [
|
|
356
|
+
{ event: 'PreToolUse', key: 'pre_tool_use', isHolmes: (c) => isHolmesPreToolCommand(c) },
|
|
357
|
+
{ event: 'Stop', key: 'stop', isHolmes: (c) => /[\\/]dist[\\/]holmes[\\/]hooks[\\/]stop\.js\b/.test(c) },
|
|
358
|
+
];
|
|
359
|
+
const runHooks = {};
|
|
360
|
+
const runState = [];
|
|
361
|
+
const runHooksPath = path.join(engineHome, 'hooks.json');
|
|
362
|
+
for (const e of events) {
|
|
363
|
+
let carried = false;
|
|
364
|
+
(hooksDoc.hooks?.[e.event] ?? []).forEach((g, gi) => (g?.hooks ?? []).forEach((h, hi) => {
|
|
365
|
+
if (carried || typeof h?.command !== 'string' || !e.isHolmes(h.command))
|
|
366
|
+
return;
|
|
367
|
+
const entry = ownerKeys.map((k) => state[`${k}:${e.key}:${gi}:${hi}`]).find((s) => s && typeof s.trusted_hash === 'string');
|
|
368
|
+
if (!entry || entry.enabled === false)
|
|
369
|
+
return;
|
|
370
|
+
const { hooks: _drop, ...groupFields } = g;
|
|
371
|
+
runHooks[e.event] = [{ ...groupFields, hooks: [h] }];
|
|
372
|
+
runState.push(`[hooks.state.${tomlStr(`${runHooksPath}:${e.key}:0:0`)}]`, `trusted_hash = ${tomlStr(String(entry.trusted_hash))}`, 'enabled = true', '');
|
|
373
|
+
carried = true;
|
|
374
|
+
}));
|
|
375
|
+
if (!carried)
|
|
376
|
+
return `the owner's ${ownerHooksPath} holds no ${e.event} Holmes hook the owner trusted — the gate cannot be carried into the run's CODEX_HOME`;
|
|
377
|
+
}
|
|
378
|
+
const features = doc.features && typeof doc.features === 'object' ? doc.features : {};
|
|
379
|
+
const featureLines = Object.entries(features).filter(([, v]) => typeof v === 'boolean' || typeof v === 'string' || typeof v === 'number')
|
|
380
|
+
.map(([k, v]) => `${/^[A-Za-z0-9_-]+$/.test(k) ? k : tomlStr(k)} = ${typeof v === 'string' ? tomlStr(v) : String(v)}`);
|
|
381
|
+
const trustLines = trustDirs.filter((d) => codexTrusts(configText, [d])).flatMap((d) => [`[projects.${tomlStr(d)}]`, 'trust_level = "trusted"', '']);
|
|
382
|
+
// @implements A-SPEC-774.56 — the owner's holmes-kit MCP table, as run start judged it in the user layer: the run reads
|
|
383
|
+
// this home, not the owner's. Scalars and arrays of scalars only; a nested table (env) keeps its own header.
|
|
384
|
+
const key = (k) => (/^[A-Za-z0-9_-]+$/.test(k) ? k : tomlStr(k));
|
|
385
|
+
const scalar = (v) => (typeof v === 'string' ? tomlStr(v) : typeof v === 'boolean' || typeof v === 'number' ? String(v) : null);
|
|
386
|
+
const value = (v) => (Array.isArray(v) ? (v.every((x) => scalar(x) !== null) ? `[${v.map((x) => scalar(x)).join(', ')}]` : null) : scalar(v));
|
|
387
|
+
const tableLines = (header, t) => {
|
|
388
|
+
const own = Object.entries(t).flatMap(([k, v]) => { const s = value(v); return s === null ? [] : [`${key(k)} = ${s}`]; });
|
|
389
|
+
const nested = Object.entries(t).filter(([, v]) => v !== null && typeof v === 'object' && !Array.isArray(v))
|
|
390
|
+
.flatMap(([k, v]) => tableLines(`${header}.${key(k)}`, v));
|
|
391
|
+
return [`[${header}]`, ...own, '', ...nested];
|
|
392
|
+
};
|
|
393
|
+
const holmesTable = doc.mcp_servers?.['holmes-kit'];
|
|
394
|
+
const mcpLines = holmesTable && typeof holmesTable === 'object' ? tableLines('mcp_servers.holmes-kit', holmesTable) : [];
|
|
395
|
+
fs.mkdirSync(engineHome, { recursive: true, mode: 0o700 });
|
|
396
|
+
const authCopy = path.join(engineHome, 'auth.json');
|
|
397
|
+
fs.copyFileSync(path.join(ownerHome, 'auth.json'), authCopy);
|
|
398
|
+
fs.chmodSync(authCopy, 0o600);
|
|
399
|
+
fs.writeFileSync(runHooksPath, `${JSON.stringify({ hooks: runHooks }, null, 2)}\n`);
|
|
400
|
+
fs.writeFileSync(path.join(engineHome, 'config.toml'), ['[features]', ...featureLines, '', ...trustLines, ...mcpLines, '[hooks.state]', '', ...runState].join('\n'));
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
403
|
+
/** @implements A-SPEC-774.34 — git runs no hook and no fsmonitor, reads no system config, and never gcs into the common dir. */
|
|
404
|
+
function sandboxEnv(base, run) {
|
|
405
|
+
const { judgmentGitEnv } = require('../review/verdicts'); // A-SPEC-774.79
|
|
406
|
+
const env = judgmentGitEnv(base);
|
|
407
|
+
delete env.GIT_NO_REPLACE_OBJECTS; // the engine's own git keeps its ordinary behaviour
|
|
408
|
+
delete env.GIT_GRAFT_FILE; // @implements A-SPEC-102.22 — likewise (the sandbox denies writing the grafts file)
|
|
409
|
+
const config = [['core.fsmonitor', 'false'], ['core.hooksPath', '/dev/null'], ['gc.auto', '0'], ['maintenance.auto', 'false']];
|
|
410
|
+
return {
|
|
411
|
+
...env, HOLMES_RUN_ID: run.id, TMPDIR: run.tmp, HOLMES_RUN_SANDBOX: run.marker, GIT_CONFIG_NOSYSTEM: '1',
|
|
412
|
+
GIT_CONFIG_COUNT: String(config.length),
|
|
413
|
+
...Object.fromEntries(config.flatMap(([k, v], i) => [[`GIT_CONFIG_KEY_${i}`, k], [`GIT_CONFIG_VALUE_${i}`, v]])),
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
/** Every process: parent, group and start second (C-locale `lstart`). */
|
|
417
|
+
function procTable() {
|
|
418
|
+
const cp = require('child_process');
|
|
419
|
+
const rows = {};
|
|
420
|
+
let text = '';
|
|
421
|
+
try {
|
|
422
|
+
text = cp.execFileSync('ps', ['-A', '-o', 'pid=,ppid=,pgid=,uid=,lstart='], { encoding: 'utf8', env: { ...process.env, LC_ALL: 'C', LANG: 'C' }, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 });
|
|
423
|
+
}
|
|
424
|
+
catch {
|
|
425
|
+
return rows;
|
|
426
|
+
}
|
|
427
|
+
for (const line of text.split('\n')) {
|
|
428
|
+
const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line);
|
|
429
|
+
const start = m ? Math.floor(Date.parse(m[5]) / 1000) : NaN;
|
|
430
|
+
if (m && Number.isFinite(start))
|
|
431
|
+
rows[m[1]] = { ppid: Number(m[2]), pgid: Number(m[3]), uid: Number(m[4]), start };
|
|
432
|
+
}
|
|
433
|
+
return rows;
|
|
434
|
+
}
|
|
435
|
+
/** Adds to `tracked` (pid → start) every process started since `since` in the engine group or under a tracked parent. */
|
|
436
|
+
function growLineage(table, tracked, pgid, since, pgidStart) {
|
|
437
|
+
// @implements A-SPEC-774.44 — group membership is evidence only while the recorded group leader is still that process.
|
|
438
|
+
const groupOk = pgid > 1 && pgidStart !== undefined && table[String(pgid)] !== undefined && table[String(pgid)].start === pgidStart;
|
|
439
|
+
let grew = false;
|
|
440
|
+
for (let changed = true; changed;) {
|
|
441
|
+
changed = false;
|
|
442
|
+
for (const [pid, p] of Object.entries(table)) {
|
|
443
|
+
if (tracked[pid] !== undefined || p.start < since)
|
|
444
|
+
continue;
|
|
445
|
+
const parent = table[String(p.ppid)];
|
|
446
|
+
if ((groupOk && p.pgid === pgid) || (parent !== undefined && tracked[String(p.ppid)] === parent.start)) {
|
|
447
|
+
tracked[pid] = p.start;
|
|
448
|
+
grew = changed = true;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return grew;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* The pids, among `pids`, whose working directory, or an open file directly in one of `listDirs`, lies under one of
|
|
456
|
+
* `prefixes`. lsof is asked about those pids only (`-a -p`): a scan of every process takes seconds under load.
|
|
457
|
+
*/
|
|
458
|
+
function pathHolders(prefixes, listDirs, pids) {
|
|
459
|
+
if (pids.length === 0)
|
|
460
|
+
return [];
|
|
461
|
+
const only = ['-a', '-p', pids.join(',')];
|
|
462
|
+
const cp = require('child_process');
|
|
463
|
+
const found = new Set();
|
|
464
|
+
const parse = (text) => {
|
|
465
|
+
let pid = 0;
|
|
466
|
+
for (const l of text.split('\n')) {
|
|
467
|
+
if (l.startsWith('p'))
|
|
468
|
+
pid = Number(l.slice(1));
|
|
469
|
+
else if (l.startsWith('n') && prefixes.some((d) => l.slice(1) === d || l.slice(1).startsWith(`${d}/`)))
|
|
470
|
+
found.add(pid);
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
const lsof = (args) => {
|
|
474
|
+
try {
|
|
475
|
+
parse(cp.execFileSync('lsof', ['-w', '-Fpn', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 }));
|
|
476
|
+
}
|
|
477
|
+
catch (e) {
|
|
478
|
+
const out = e.stdout; // lsof exits 1 when it finds nothing
|
|
479
|
+
if (typeof out === 'string')
|
|
480
|
+
parse(out);
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
lsof([...only, '-d', 'cwd']);
|
|
484
|
+
for (const d of listDirs)
|
|
485
|
+
lsof([...only, '+d', d]); // -a ANDs every selection, so one directory per call
|
|
486
|
+
return [...found];
|
|
487
|
+
}
|
|
488
|
+
function makeCanary(tmp) {
|
|
489
|
+
const guard = path.join(tmp, '.holmes-guard');
|
|
490
|
+
const tmpStat = fs.lstatSync(tmp, { bigint: true }); // @implements A-SPEC-774.58 — the temp dir as made
|
|
491
|
+
fs.mkdirSync(guard, { mode: 0o700 });
|
|
492
|
+
const token = crypto.randomBytes(16).toString('hex');
|
|
493
|
+
const allow = path.join(guard, 'allow');
|
|
494
|
+
const deny = path.join(guard, 'deny');
|
|
495
|
+
const ids = [allow, deny].map((f) => {
|
|
496
|
+
fs.writeFileSync(f, token, { mode: 0o600, flag: 'wx' });
|
|
497
|
+
const st = fs.lstatSync(f, { bigint: true });
|
|
498
|
+
return `${st.dev}:${st.ino}`;
|
|
499
|
+
});
|
|
500
|
+
const canary = { guard, allow, deny, token, ids, tmp, tmpId: `${tmpStat.dev}:${tmpStat.ino}` };
|
|
501
|
+
const problem = canaryProblem(canary);
|
|
502
|
+
if (problem !== null)
|
|
503
|
+
throw new Error(problem);
|
|
504
|
+
return canary;
|
|
505
|
+
}
|
|
506
|
+
/** @implements A-SPEC-774.53 — null when both canaries are still the regular files run exec made, holding its token. */
|
|
507
|
+
function canaryProblem(c) {
|
|
508
|
+
const fsm = require('fs');
|
|
509
|
+
// @implements A-SPEC-774.58 — the temp dir is still the one run exec made, and no link sits on the guard's path
|
|
510
|
+
if (c && (typeof c.tmp === 'string' || typeof c.tmpId === 'string')) {
|
|
511
|
+
let st;
|
|
512
|
+
try {
|
|
513
|
+
st = fsm.lstatSync(c.tmp, { bigint: true });
|
|
514
|
+
}
|
|
515
|
+
catch {
|
|
516
|
+
return 'the run\'s temp dir is gone';
|
|
517
|
+
}
|
|
518
|
+
if (!st.isDirectory() || `${st.dev}:${st.ino}` !== c.tmpId)
|
|
519
|
+
return 'the run\'s temp dir is not the one run exec made';
|
|
520
|
+
}
|
|
521
|
+
try {
|
|
522
|
+
if (fsm.realpathSync(c.guard) !== c.guard)
|
|
523
|
+
return 'the run\'s canary guard is reached through a link';
|
|
524
|
+
}
|
|
525
|
+
catch {
|
|
526
|
+
return 'the run\'s canary guard is gone';
|
|
527
|
+
}
|
|
528
|
+
const sides = [['allow', c && c.allow, c && Array.isArray(c.ids) ? c.ids[0] : undefined], ['deny', c && c.deny, c && Array.isArray(c.ids) ? c.ids[1] : undefined]];
|
|
529
|
+
for (const [name, file, id] of sides) {
|
|
530
|
+
if (typeof file !== 'string' || typeof id !== 'string' || typeof c.token !== 'string')
|
|
531
|
+
return `the run's ${name}-canary record is malformed`;
|
|
532
|
+
let fd;
|
|
533
|
+
try {
|
|
534
|
+
fd = fsm.openSync(file, fsm.constants.O_RDONLY | fsm.constants.O_NOFOLLOW);
|
|
535
|
+
}
|
|
536
|
+
catch {
|
|
537
|
+
return `the run's ${name}-canary is gone or a link`;
|
|
538
|
+
}
|
|
539
|
+
try {
|
|
540
|
+
const st = fsm.fstatSync(fd, { bigint: true });
|
|
541
|
+
if (!st.isFile())
|
|
542
|
+
return `the run's ${name}-canary is not a regular file`;
|
|
543
|
+
if (`${st.dev}:${st.ino}` !== id)
|
|
544
|
+
return `the run's ${name}-canary is not the file run exec made`;
|
|
545
|
+
if (fsm.readFileSync(fd, 'utf8') !== c.token)
|
|
546
|
+
return `the run's ${name}-canary holds another token`;
|
|
547
|
+
}
|
|
548
|
+
catch {
|
|
549
|
+
return `the run's ${name}-canary cannot be read`;
|
|
550
|
+
}
|
|
551
|
+
finally {
|
|
552
|
+
try {
|
|
553
|
+
fsm.closeSync(fd);
|
|
554
|
+
}
|
|
555
|
+
catch { /* closed */ }
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
return null;
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* @implements A-SPEC-774.50, A-SPEC-774.53 — the pids, among `pids`, inside THIS run's sandbox: under `uid`, and
|
|
562
|
+
* `sandbox_check` answers 1 (in a sandbox), 0 for writing the allow-canary and 1 for writing the deny-canary — only the
|
|
563
|
+
* run's own profile gives that pair (an allow-default neighbor, or one allowing the temp dir, is allowed both).
|
|
564
|
+
* `/usr/bin/python3 -I` with ctypes (JXA cannot pass the variadic path on arm64, measured), only when the
|
|
565
|
+
* CommandLineTools exist (else the stub opens an install dialog), with a fixed environment and a 3-second timeout.
|
|
566
|
+
* Null when it cannot answer: the caller then taints the run.
|
|
567
|
+
*/
|
|
568
|
+
function sandboxDetect(pids, canary, python, uid, known) {
|
|
569
|
+
if (python !== '/usr/bin/python3')
|
|
570
|
+
return null;
|
|
571
|
+
if (pids.length === 0)
|
|
572
|
+
return [];
|
|
573
|
+
const table = known ?? procTable(); // the caller's table when it has one: a ps less inside the teardown's budget
|
|
574
|
+
const mine = pids.filter((p) => table[String(p)] !== undefined && table[String(p)].uid === uid);
|
|
575
|
+
if (mine.length === 0)
|
|
576
|
+
return [];
|
|
577
|
+
const cp = require('child_process');
|
|
578
|
+
const env = { PATH: '/usr/bin:/bin', LANG: 'C' };
|
|
579
|
+
try {
|
|
580
|
+
cp.execFileSync('/usr/bin/xcode-select', ['-p'], { stdio: 'ignore', timeout: 2000, env });
|
|
581
|
+
}
|
|
582
|
+
catch {
|
|
583
|
+
return null;
|
|
584
|
+
}
|
|
585
|
+
const script = [
|
|
586
|
+
'import ctypes, sys',
|
|
587
|
+
"f = ctypes.CDLL('/usr/lib/libSystem.B.dylib').sandbox_check",
|
|
588
|
+
'f.restype = ctypes.c_int',
|
|
589
|
+
'f.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int]',
|
|
590
|
+
'a = ctypes.c_char_p(sys.argv[1].encode())',
|
|
591
|
+
'd = ctypes.c_char_p(sys.argv[2].encode())',
|
|
592
|
+
'for p in sys.argv[3:]:',
|
|
593
|
+
" print(p, f(int(p), None, 0), f(int(p), b'file-write-data', 1, a), f(int(p), b'file-write-data', 1, d))",
|
|
594
|
+
].join('\n');
|
|
595
|
+
let out;
|
|
596
|
+
try {
|
|
597
|
+
out = cp.execFileSync(python, ['-I', '-c', script, canary.allow, canary.deny, ...mine.map(String)], { encoding: 'utf8', timeout: 3000, env, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 16 * 1024 * 1024 });
|
|
598
|
+
}
|
|
599
|
+
catch {
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
const ours = [];
|
|
603
|
+
for (const line of out.split('\n')) {
|
|
604
|
+
const m = /^(\d+) (-?\d+) (-?\d+) (-?\d+)$/.exec(line.trim());
|
|
605
|
+
if (!m)
|
|
606
|
+
continue;
|
|
607
|
+
if (m[2] === '1' && m[3] === '0' && m[4] === '1')
|
|
608
|
+
ours.push(Number(m[1]));
|
|
609
|
+
}
|
|
610
|
+
return ours;
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* @implements A-SPEC-774.61 — the sandbox is empty only after three consecutive passes with none of the run's and none
|
|
614
|
+
* unjudgeable; past the budget without them the run is tainted; otherwise one more pass.
|
|
615
|
+
*/
|
|
616
|
+
function sweepVerdict(passes, elapsedMs, budgetMs) {
|
|
617
|
+
const last = passes.slice(-3);
|
|
618
|
+
if (last.length === 3 && last.every((p) => p.ours === 0 && p.unjudgeable === 0))
|
|
619
|
+
return 'empty';
|
|
620
|
+
return elapsedMs > budgetMs ? 'taint' : 'again';
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* @implements A-SPEC-774.61 — enumerate, check and kill in one detector process, pass after pass: every pid of
|
|
624
|
+
* `proc_listallpids` under `uid`, started since `since` and not a zombie, is asked `sandbox_check` (boxed, allow- and
|
|
625
|
+
* deny-canary, as A-SPEC-774.53) and SIGKILLed at once when it is the run's; an error answer counts it unjudgeable.
|
|
626
|
+
* The detector stops after three clean passes or past the budget; each pass is printed as "ours unjudgeable elapsedMs".
|
|
627
|
+
* Same preconditions as sandboxDetect. Null when it cannot answer: the caller then taints the run.
|
|
628
|
+
*/
|
|
629
|
+
function sandboxSweep(canary, python, uid, since, budgetMs) {
|
|
630
|
+
if (python !== '/usr/bin/python3')
|
|
631
|
+
return null;
|
|
632
|
+
const cp = require('child_process');
|
|
633
|
+
const env = { PATH: '/usr/bin:/bin', LANG: 'C' };
|
|
634
|
+
try {
|
|
635
|
+
cp.execFileSync('/usr/bin/xcode-select', ['-p'], { stdio: 'ignore', timeout: 2000, env });
|
|
636
|
+
}
|
|
637
|
+
catch {
|
|
638
|
+
return null;
|
|
639
|
+
}
|
|
640
|
+
const script = [
|
|
641
|
+
'import ctypes, os, struct, sys, time',
|
|
642
|
+
"L = ctypes.CDLL('/usr/lib/libSystem.B.dylib')",
|
|
643
|
+
'f = L.sandbox_check',
|
|
644
|
+
'f.restype = ctypes.c_int',
|
|
645
|
+
'f.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int]',
|
|
646
|
+
'L.proc_listallpids.restype = ctypes.c_int',
|
|
647
|
+
'L.proc_listallpids.argtypes = [ctypes.c_void_p, ctypes.c_int]',
|
|
648
|
+
'L.proc_pidinfo.restype = ctypes.c_int',
|
|
649
|
+
'L.proc_pidinfo.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_int]',
|
|
650
|
+
'a = ctypes.c_char_p(sys.argv[1].encode())',
|
|
651
|
+
'd = ctypes.c_char_p(sys.argv[2].encode())',
|
|
652
|
+
'uid, since, budget = int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]) / 1000.0',
|
|
653
|
+
'me, t0, clean = os.getpid(), time.monotonic(), 0',
|
|
654
|
+
'info = ctypes.create_string_buffer(136)',
|
|
655
|
+
'while True:',
|
|
656
|
+
' n = L.proc_listallpids(None, 0)',
|
|
657
|
+
' if n <= 0: sys.exit(2)',
|
|
658
|
+
' pids = (ctypes.c_int * (n + 256))()',
|
|
659
|
+
' n = L.proc_listallpids(pids, ctypes.sizeof(pids))',
|
|
660
|
+
' if n <= 0: sys.exit(2)',
|
|
661
|
+
' ours = unj = 0',
|
|
662
|
+
' for i in range(n):',
|
|
663
|
+
' p = pids[i]',
|
|
664
|
+
' if p <= 1 or p == me: continue',
|
|
665
|
+
' if L.proc_pidinfo(p, 3, 0, info, 136) != 136: continue', // PROC_PIDTBSDINFO, struct proc_bsdinfo
|
|
666
|
+
" status, u = struct.unpack_from('<I', info, 4)[0], struct.unpack_from('<I', info, 20)[0]",
|
|
667
|
+
" if u != uid or status == 5 or struct.unpack_from('<Q', info, 120)[0] < since: continue", // 5: SZOMB
|
|
668
|
+
' b = f(p, None, 0)',
|
|
669
|
+
' if b == 0: continue',
|
|
670
|
+
" x, y = f(p, b'file-write-data', 1, a), f(p, b'file-write-data', 1, d)",
|
|
671
|
+
' if b < 0 or x < 0 or y < 0:',
|
|
672
|
+
' unj += 1',
|
|
673
|
+
' elif b == 1 and x == 0 and y == 1:',
|
|
674
|
+
' try: os.kill(p, 9)',
|
|
675
|
+
' except ProcessLookupError: pass',
|
|
676
|
+
' ours += 1',
|
|
677
|
+
' el = time.monotonic() - t0',
|
|
678
|
+
" print(ours, unj, int(el * 1000), flush=True)",
|
|
679
|
+
' clean = clean + 1 if ours == 0 and unj == 0 else 0',
|
|
680
|
+
' if clean >= 3 or el > budget: break',
|
|
681
|
+
' time.sleep(0.01)',
|
|
682
|
+
].join('\n');
|
|
683
|
+
let out;
|
|
684
|
+
try {
|
|
685
|
+
out = cp.execFileSync(python, ['-I', '-c', script, canary.allow, canary.deny, String(uid), String(since), String(budgetMs)], { encoding: 'utf8', timeout: budgetMs + 1500, env, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
686
|
+
}
|
|
687
|
+
catch {
|
|
688
|
+
return null;
|
|
689
|
+
}
|
|
690
|
+
const passes = [];
|
|
691
|
+
let elapsedMs = 0;
|
|
692
|
+
for (const line of out.split('\n')) {
|
|
693
|
+
const m = /^(\d+) (\d+) (\d+)$/.exec(line.trim());
|
|
694
|
+
if (!m)
|
|
695
|
+
continue;
|
|
696
|
+
passes.push({ ours: Number(m[1]), unjudgeable: Number(m[2]) });
|
|
697
|
+
elapsedMs = Number(m[3]);
|
|
698
|
+
}
|
|
699
|
+
return passes.length === 0 ? null : { passes, elapsedMs };
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Kill, until a pass finds nothing (at most five passes), every process of the run: the engine group, the tracked
|
|
703
|
+
* lineage whose start still matches, and whatever started since the exec with its cwd or an open file in the run's
|
|
704
|
+
* paths. Never this process nor `spare`.
|
|
705
|
+
*/
|
|
706
|
+
function endRunProcesses(r) {
|
|
707
|
+
const nap = () => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
|
|
708
|
+
// Never this process, the spared ones, nor any of their ancestors (the wrapper that called run exec).
|
|
709
|
+
const spareFrom = (table, victims) => {
|
|
710
|
+
for (const root of [process.pid, ...r.spare]) {
|
|
711
|
+
for (let p = root, hops = 0; p > 1 && hops < 4096; hops++) {
|
|
712
|
+
victims.delete(p);
|
|
713
|
+
const row = table[String(p)];
|
|
714
|
+
if (row === undefined)
|
|
715
|
+
break;
|
|
716
|
+
p = row.ppid;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
};
|
|
720
|
+
// The tracked lineage, its start still matching (no lsof: these passes are cheap).
|
|
721
|
+
const lineagePasses = () => {
|
|
722
|
+
for (let round = 0; round < 5; round++) {
|
|
723
|
+
const table = procTable();
|
|
724
|
+
// @implements A-SPEC-774.44 — the group only while its recorded leader is still that process (a pgid can be reused).
|
|
725
|
+
const leader = table[String(r.pgid)];
|
|
726
|
+
const leaderMatches = r.pgid > 1 && r.pgidStart !== undefined && leader !== undefined && leader.start === r.pgidStart;
|
|
727
|
+
// @implements A-SPEC-774.47 — run exec and its watchdog learned the group from the spawn: with the leader gone, a
|
|
728
|
+
// member still carrying that pgid means the group lives (a pgid is not reused while its group has a member).
|
|
729
|
+
const orphanedGroup = r.groupKnown === true && r.pgid > 1 && leader === undefined
|
|
730
|
+
&& Object.values(table).some((p) => p.pgid === r.pgid && p.start >= r.since);
|
|
731
|
+
if (leaderMatches || orphanedGroup) {
|
|
732
|
+
try {
|
|
733
|
+
process.kill(-r.pgid, 'SIGKILL');
|
|
734
|
+
}
|
|
735
|
+
catch { /* gone */ }
|
|
736
|
+
}
|
|
737
|
+
growLineage(table, r.tracked, r.pgid, r.since, r.pgidStart);
|
|
738
|
+
const victims = new Set();
|
|
739
|
+
for (const [pid, start] of Object.entries(r.tracked))
|
|
740
|
+
if (table[pid] !== undefined && table[pid].start === start)
|
|
741
|
+
victims.add(Number(pid));
|
|
742
|
+
spareFrom(table, victims);
|
|
743
|
+
if (victims.size === 0)
|
|
744
|
+
return;
|
|
745
|
+
for (const pid of victims) {
|
|
746
|
+
try {
|
|
747
|
+
process.kill(pid, 'SIGKILL');
|
|
748
|
+
}
|
|
749
|
+
catch { /* exited meanwhile */ }
|
|
750
|
+
}
|
|
751
|
+
nap();
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
lineagePasses();
|
|
755
|
+
// One path pass (lsof is slow under load): a process started since the exec that holds a run-unique path (`dirs`: the
|
|
756
|
+
// run temp dir and engine home — never the worktree, which the owner uses too) joins the lineage, children included.
|
|
757
|
+
const recentOf = (table) => {
|
|
758
|
+
const recent = new Set(Object.entries(table).filter(([, p]) => p.start >= r.since).map(([pid]) => Number(pid)));
|
|
759
|
+
spareFrom(table, recent);
|
|
760
|
+
return [...recent];
|
|
761
|
+
};
|
|
762
|
+
if (r.dirs.length > 0) {
|
|
763
|
+
const table = procTable();
|
|
764
|
+
const holders = pathHolders(r.dirs, r.dirs, recentOf(table)).filter((pid) => table[String(pid)] !== undefined && table[String(pid)].start >= r.since);
|
|
765
|
+
if (holders.length > 0) {
|
|
766
|
+
for (const pid of holders)
|
|
767
|
+
r.tracked[String(pid)] = table[String(pid)].start;
|
|
768
|
+
lineagePasses();
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
// @implements A-SPEC-774.50 — last, whatever is still inside THIS run's sandbox (sandbox_check with its canary): ended,
|
|
772
|
+
// or the run is tainted when that cannot be looked for or does not work.
|
|
773
|
+
if (r.canary === undefined)
|
|
774
|
+
return null;
|
|
775
|
+
// @implements A-SPEC-774.53 — a canary that is not the file run exec made cannot vouch for anything: the run taints
|
|
776
|
+
const uid = typeof process.getuid === 'function' ? process.getuid() : -1;
|
|
777
|
+
const canaryBad = canaryProblem(r.canary);
|
|
778
|
+
if (canaryBad !== null)
|
|
779
|
+
return `${canaryBad}, so its sandbox cannot be checked`;
|
|
780
|
+
// @implements A-SPEC-774.61 — a re-forking chain is killed while alive, pass after pass; silence is never absence
|
|
781
|
+
const budgetMs = 1500;
|
|
782
|
+
const sweep = sandboxSweep(r.canary, r.python ?? null, uid, r.since, budgetMs);
|
|
783
|
+
if (sweep === null)
|
|
784
|
+
return 'the sandbox detector could not run (CommandLineTools python3 with ctypes sandbox_check)';
|
|
785
|
+
const afterBad = canaryProblem(r.canary);
|
|
786
|
+
if (afterBad !== null)
|
|
787
|
+
return `${afterBad}, so its sandbox cannot be checked after the sweep`;
|
|
788
|
+
if (sweepVerdict(sweep.passes, sweep.elapsedMs, budgetMs) === 'empty')
|
|
789
|
+
return null;
|
|
790
|
+
const last = sweep.passes[sweep.passes.length - 1];
|
|
791
|
+
return `the run's sandbox was not seen empty three passes in a row within ${budgetMs} ms (${sweep.passes.length} passes; the last: ${last.ours} of the run's killed, ${last.unjudgeable} unjudgeable)`;
|
|
792
|
+
}
|
|
793
|
+
const ENGINE_EGRESS = {
|
|
794
|
+
claude: ['api.anthropic.com:443', 'statsig.anthropic.com:443'],
|
|
795
|
+
codex: ['chatgpt.com:443', 'api.openai.com:443', 'auth.openai.com:443'],
|
|
796
|
+
};
|
|
797
|
+
async function startEgressProxy(allowed, token) {
|
|
798
|
+
const net = require('net');
|
|
799
|
+
const sockets = new Set();
|
|
800
|
+
// @implements A-SPEC-774.65 — only the run's own engine, which holds the token, tunnels
|
|
801
|
+
const credential = Buffer.from(`holmes:${token}`).toString('base64');
|
|
802
|
+
const authorized = (headerBlock) => headerBlock.split('\r\n').slice(1).some((h) => {
|
|
803
|
+
const i = h.indexOf(':');
|
|
804
|
+
if (i <= 0 || h.slice(0, i).trim().toLowerCase() !== 'proxy-authorization')
|
|
805
|
+
return false;
|
|
806
|
+
const [scheme, value] = h.slice(i + 1).trim().split(/\s+/);
|
|
807
|
+
return scheme?.toLowerCase() === 'basic' && value === credential;
|
|
808
|
+
});
|
|
809
|
+
const handler = (client) => {
|
|
810
|
+
sockets.add(client);
|
|
811
|
+
client.on('close', () => sockets.delete(client));
|
|
812
|
+
client.on('error', () => undefined);
|
|
813
|
+
let head = Buffer.alloc(0);
|
|
814
|
+
const onData = (chunk) => {
|
|
815
|
+
head = Buffer.concat([head, chunk]);
|
|
816
|
+
const end = head.indexOf('\r\n\r\n');
|
|
817
|
+
if (end < 0) {
|
|
818
|
+
if (head.length > 16384)
|
|
819
|
+
client.destroy();
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
client.off('data', onData);
|
|
823
|
+
const line = head.subarray(0, head.indexOf('\r\n')).toString('latin1');
|
|
824
|
+
const m = /^CONNECT ([^\s:/]+):(\d{1,5}) HTTP\/1\.[01]$/i.exec(line);
|
|
825
|
+
if (!m) {
|
|
826
|
+
client.end('HTTP/1.1 405 Method Not Allowed\r\n\r\n');
|
|
827
|
+
return;
|
|
828
|
+
}
|
|
829
|
+
if (!authorized(head.subarray(0, end).toString('latin1'))) {
|
|
830
|
+
client.end('HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm="holmes-run"\r\n\r\n');
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
const host = m[1].toLowerCase();
|
|
834
|
+
const port = Number(m[2]);
|
|
835
|
+
if (!allowed.has(`${host}:${port}`)) {
|
|
836
|
+
client.end('HTTP/1.1 403 Forbidden\r\n\r\n');
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
const rest = head.subarray(end + 4);
|
|
840
|
+
const upstream = net.connect(port, host, () => {
|
|
841
|
+
client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
842
|
+
if (rest.length > 0)
|
|
843
|
+
upstream.write(rest);
|
|
844
|
+
upstream.pipe(client);
|
|
845
|
+
client.pipe(upstream);
|
|
846
|
+
});
|
|
847
|
+
sockets.add(upstream);
|
|
848
|
+
upstream.on('error', () => { if (!client.destroyed)
|
|
849
|
+
client.end('HTTP/1.1 502 Bad Gateway\r\n\r\n'); });
|
|
850
|
+
upstream.on('close', () => { sockets.delete(upstream); client.destroy(); });
|
|
851
|
+
client.on('close', () => upstream.destroy());
|
|
852
|
+
};
|
|
853
|
+
client.on('data', onData);
|
|
854
|
+
};
|
|
855
|
+
const listen = (host, at) => new Promise((resolve, reject) => {
|
|
856
|
+
const server = net.createServer(handler);
|
|
857
|
+
server.once('error', reject);
|
|
858
|
+
server.listen(at, host, () => resolve(server));
|
|
859
|
+
});
|
|
860
|
+
// @implements A-SPEC-774.65 — the sandbox's localhost:<port> also reaches [::1]:<port> (measured): hold it too
|
|
861
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
862
|
+
const v4 = await listen('127.0.0.1', 0);
|
|
863
|
+
const address = v4.address();
|
|
864
|
+
if (address === null || typeof address === 'string') {
|
|
865
|
+
v4.close();
|
|
866
|
+
throw new Error('no port');
|
|
867
|
+
}
|
|
868
|
+
let v6 = null;
|
|
869
|
+
try {
|
|
870
|
+
v6 = await listen('::1', address.port);
|
|
871
|
+
}
|
|
872
|
+
catch (e) {
|
|
873
|
+
const code = e.code;
|
|
874
|
+
if (code === 'EADDRINUSE') {
|
|
875
|
+
v4.close();
|
|
876
|
+
continue;
|
|
877
|
+
}
|
|
878
|
+
if (code !== 'EADDRNOTAVAIL' && code !== 'EAFNOSUPPORT') {
|
|
879
|
+
v4.close();
|
|
880
|
+
throw e;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
const servers = [v4, ...(v6 ? [v6] : [])];
|
|
884
|
+
return { port: address.port, close: () => { for (const s of sockets)
|
|
885
|
+
s.destroy(); for (const s of servers)
|
|
886
|
+
s.close(); } };
|
|
887
|
+
}
|
|
888
|
+
throw new Error('no port free on both 127.0.0.1 and ::1 after 8 tries');
|
|
889
|
+
}
|
|
890
|
+
/** @implements A-SPEC-774.58 — removes the run temp dir; a link found in its place is removed, never followed. */
|
|
891
|
+
function removeRunTmp(p) {
|
|
892
|
+
const fsm = require('fs');
|
|
893
|
+
let st;
|
|
894
|
+
try {
|
|
895
|
+
st = fsm.lstatSync(p);
|
|
896
|
+
}
|
|
897
|
+
catch {
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
if (st.isSymbolicLink()) {
|
|
901
|
+
try {
|
|
902
|
+
fsm.unlinkSync(p);
|
|
903
|
+
}
|
|
904
|
+
catch { /* best effort */ }
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
try {
|
|
908
|
+
fsm.rmSync(p, { recursive: true, force: true });
|
|
909
|
+
}
|
|
910
|
+
catch { /* best effort */ }
|
|
911
|
+
}
|
|
912
|
+
/** @implements A-SPEC-774.50 — a run whose teardown could not prove its sandbox empty: its work waits for a person. */
|
|
913
|
+
function recordTaint(file, reason) {
|
|
914
|
+
const fsm = require('fs');
|
|
915
|
+
try {
|
|
916
|
+
fsm.appendFileSync(file, `${JSON.stringify({ ts: new Date().toISOString(), reason })}\n`, { mode: 0o600 });
|
|
917
|
+
}
|
|
918
|
+
catch { /* best effort: the registry entry stays */ }
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* @implements A-SPEC-774.41 — where a run exec records itself while it runs: the main checkout's run state, which the
|
|
922
|
+
* sandbox cannot write. A run exec or run start that finds an entry whose run exec and watchdog are both gone sweeps it.
|
|
923
|
+
*/
|
|
924
|
+
const execEntryFile = (main, id, pid) => path.join(main, '.ax', 'state', 'runs', `${id}.exec.${pid}`);
|
|
925
|
+
/** @implements A-SPEC-774.50 — the detector's interpreter: /usr/bin/python3 only; any other value can only taint. */
|
|
926
|
+
const detectorPython = (env) => env.HOLMES_RUN_EXEC_PYTHON ?? '/usr/bin/python3';
|
|
927
|
+
const taintFileOf = (entryFile) => entryFile.replace(/\.exec\.\d+$/, '.tainted');
|
|
928
|
+
/** @implements A-SPEC-774.43 — the top-level `*.lock` files an ended engine left in its git dir. */
|
|
929
|
+
function removeGitLocks(gitDir) {
|
|
930
|
+
const fsm = require('fs');
|
|
931
|
+
const pathm = require('path');
|
|
932
|
+
if (!pathm.isAbsolute(gitDir) || !/[\\/]worktrees[\\/][^\\/]+$/.test(gitDir))
|
|
933
|
+
return;
|
|
934
|
+
let names = [];
|
|
935
|
+
try {
|
|
936
|
+
names = fsm.readdirSync(gitDir);
|
|
937
|
+
}
|
|
938
|
+
catch {
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
for (const n of names)
|
|
942
|
+
if (n.endsWith('.lock')) {
|
|
943
|
+
try {
|
|
944
|
+
fsm.rmSync(pathm.join(gitDir, n), { force: true });
|
|
945
|
+
}
|
|
946
|
+
catch { /* best effort */ }
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* @implements A-SPEC-774.54 — the run's exec entries whose run exec or watchdog is alive, after the orphans are swept:
|
|
951
|
+
* while one remains its teardown may still write the run's taint.
|
|
952
|
+
*/
|
|
953
|
+
function liveExecEntries(main, runId) {
|
|
954
|
+
sweepOrphanExecs(main);
|
|
955
|
+
const dir = path.join(main, '.ax', 'state', 'runs');
|
|
956
|
+
let names;
|
|
957
|
+
try {
|
|
958
|
+
names = fs.readdirSync(dir).filter((n) => n.startsWith(`${runId}.exec.`) && /\.exec\.\d+$/.test(n));
|
|
959
|
+
}
|
|
960
|
+
catch {
|
|
961
|
+
return [];
|
|
962
|
+
}
|
|
963
|
+
return names.filter((n) => {
|
|
964
|
+
try {
|
|
965
|
+
const e = JSON.parse(fs.readFileSync(path.join(dir, n), 'utf8'));
|
|
966
|
+
return isAlive(Number(e.pid)) || isAlive(Number(e.watchdog));
|
|
967
|
+
}
|
|
968
|
+
catch {
|
|
969
|
+
return true;
|
|
970
|
+
}
|
|
971
|
+
});
|
|
972
|
+
}
|
|
973
|
+
const isAlive = (pid) => { if (!Number.isInteger(pid) || pid <= 1)
|
|
974
|
+
return false; try {
|
|
975
|
+
process.kill(pid, 0);
|
|
976
|
+
return true;
|
|
977
|
+
}
|
|
978
|
+
catch (e) {
|
|
979
|
+
return e.code === 'EPERM';
|
|
980
|
+
} };
|
|
981
|
+
/** Only a run temp dir this module makes: a direct child of the temp root named holmes-run-*. */
|
|
982
|
+
const isRunTmp = (p) => {
|
|
983
|
+
try {
|
|
984
|
+
return path.dirname(fs.realpathSync(p)) === fs.realpathSync(os.tmpdir()) && path.basename(p).startsWith('holmes-run-');
|
|
985
|
+
}
|
|
986
|
+
catch {
|
|
987
|
+
return false;
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
/**
|
|
991
|
+
* @implements A-SPEC-774.41 — engines and run homes a killed run exec (and its killed watchdog) left: swept by the next
|
|
992
|
+
* run exec or run start for the same main checkout. Returns the entries swept.
|
|
993
|
+
*/
|
|
994
|
+
function sweepOrphanExecs(main) {
|
|
995
|
+
const dir = path.join(main, '.ax', 'state', 'runs');
|
|
996
|
+
let names;
|
|
997
|
+
try {
|
|
998
|
+
names = fs.readdirSync(dir).filter((n) => /\.exec\.\d+$/.test(n));
|
|
999
|
+
}
|
|
1000
|
+
catch {
|
|
1001
|
+
return 0;
|
|
1002
|
+
}
|
|
1003
|
+
let swept = 0;
|
|
1004
|
+
for (const n of names) {
|
|
1005
|
+
const file = path.join(dir, n);
|
|
1006
|
+
let e;
|
|
1007
|
+
try {
|
|
1008
|
+
e = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
1009
|
+
}
|
|
1010
|
+
catch {
|
|
1011
|
+
continue;
|
|
1012
|
+
}
|
|
1013
|
+
if (isAlive(Number(e.pid)) || isAlive(Number(e.watchdog)))
|
|
1014
|
+
continue;
|
|
1015
|
+
// @implements A-SPEC-774.42 — the lineage the watchdog recorded, and the run's paths (dirs are absolute run paths only).
|
|
1016
|
+
// @implements A-SPEC-774.47 — only the entry's own temp dir and paths under it (an old entry may name the worktree)
|
|
1017
|
+
const tmpRoot = typeof e.tmp === 'string' && isRunTmp(e.tmp) ? e.tmp : null;
|
|
1018
|
+
const dirs = tmpRoot === null || !Array.isArray(e.dirs) ? []
|
|
1019
|
+
: e.dirs.filter((d) => typeof d === 'string' && (d === tmpRoot || d.startsWith(`${tmpRoot}/`)));
|
|
1020
|
+
if (typeof e.since === 'number') {
|
|
1021
|
+
// @implements A-SPEC-774.50, A-SPEC-774.53 — the entry's canary only when both files lie in the entry's own guard dir
|
|
1022
|
+
// (the old string form has none); whether they are still the files run exec made, endRunProcesses checks.
|
|
1023
|
+
const guard = tmpRoot === null ? null : path.join(tmpRoot, '.holmes-guard');
|
|
1024
|
+
const c = e.canary;
|
|
1025
|
+
const canary = guard !== null && c && typeof c === 'object' && typeof c.allow === 'string' && typeof c.deny === 'string'
|
|
1026
|
+
&& path.dirname(c.allow) === guard && path.dirname(c.deny) === guard ? c : undefined;
|
|
1027
|
+
const taint = endRunProcesses({ pgid: Number(e.pgid ?? 0), ...(typeof e.pgidStart === 'number' ? { pgidStart: e.pgidStart } : {}),
|
|
1028
|
+
tracked: e.tracked && typeof e.tracked === 'object' ? { ...e.tracked } : {}, dirs, since: e.since, spare: [],
|
|
1029
|
+
...(canary ? { canary, python: detectorPython(process.env) } : {}) });
|
|
1030
|
+
if (taint !== null)
|
|
1031
|
+
recordTaint(taintFileOf(file), `orphan sweep: ${taint}`);
|
|
1032
|
+
// @implements A-SPEC-774.54 — no canary to look with is no proof the run's sandbox is empty
|
|
1033
|
+
else if (canary === undefined)
|
|
1034
|
+
recordTaint(taintFileOf(file), 'orphan sweep: the entry has no canary in its own guard dir, so its sandbox could not be checked');
|
|
1035
|
+
}
|
|
1036
|
+
else {
|
|
1037
|
+
recordTaint(taintFileOf(file), 'orphan sweep: the entry has no start, so the run\'s processes could not be looked for'); // @implements A-SPEC-774.54
|
|
1038
|
+
}
|
|
1039
|
+
if (typeof e.gitDir === 'string')
|
|
1040
|
+
removeGitLocks(e.gitDir);
|
|
1041
|
+
// @implements A-SPEC-774.58 — a link left where the run temp dir was goes too, without being followed
|
|
1042
|
+
const linkInPlace = typeof e.tmp === 'string' && path.basename(e.tmp).startsWith('holmes-run-') && (() => {
|
|
1043
|
+
try {
|
|
1044
|
+
return fs.lstatSync(e.tmp).isSymbolicLink() && fs.realpathSync(path.dirname(e.tmp)) === fs.realpathSync(os.tmpdir());
|
|
1045
|
+
}
|
|
1046
|
+
catch {
|
|
1047
|
+
return false;
|
|
1048
|
+
}
|
|
1049
|
+
})();
|
|
1050
|
+
if (typeof e.tmp === 'string' && (linkInPlace || isRunTmp(e.tmp)))
|
|
1051
|
+
removeRunTmp(e.tmp);
|
|
1052
|
+
try {
|
|
1053
|
+
fs.rmSync(file, { force: true });
|
|
1054
|
+
}
|
|
1055
|
+
catch { /* best effort */ }
|
|
1056
|
+
swept++;
|
|
1057
|
+
}
|
|
1058
|
+
return swept;
|
|
1059
|
+
}
|
|
1060
|
+
/**
|
|
1061
|
+
* @implements A-SPEC-774.41, A-SPEC-774.42 — the watchdog: a detached node process outside the sandbox holding a pipe
|
|
1062
|
+
* from run exec. A "pgid N" line names the engine group; every 100 ms it grows the engine's lineage and records it in the
|
|
1063
|
+
* registry entry; "done" ends it quietly; the pipe closing without "done" (run exec killed) runs the teardown.
|
|
1064
|
+
*/
|
|
1065
|
+
const WATCHDOG = `${procTable.toString()}
|
|
1066
|
+
${growLineage.toString()}
|
|
1067
|
+
${pathHolders.toString()}
|
|
1068
|
+
${endRunProcesses.toString()}
|
|
1069
|
+
${removeGitLocks.toString()}
|
|
1070
|
+
${sandboxSweep.toString()}
|
|
1071
|
+
${sweepVerdict.toString()}
|
|
1072
|
+
${canaryProblem.toString()}
|
|
1073
|
+
${removeRunTmp.toString()}
|
|
1074
|
+
${recordTaint.toString()}
|
|
1075
|
+
const fs = require('fs');
|
|
1076
|
+
const [entry, tmp, sinceText, dirsJson, gitDir, canaryJson, python] = process.argv.slice(1);
|
|
1077
|
+
const canary = JSON.parse(canaryJson);
|
|
1078
|
+
const since = Number(sinceText), dirs = JSON.parse(dirsJson);
|
|
1079
|
+
let pgid = 0, pgidStart, done = false, buf = '';
|
|
1080
|
+
const tracked = {};
|
|
1081
|
+
const record = () => { try { const e = JSON.parse(fs.readFileSync(entry, 'utf8')); e.pgid = pgid; e.pgidStart = pgidStart; e.tracked = tracked; fs.writeFileSync(entry, JSON.stringify(e)); } catch {} };
|
|
1082
|
+
process.stdin.on('data', (b) => { buf += b.toString(); let i;
|
|
1083
|
+
while ((i = buf.indexOf('\\n')) >= 0) { const l = buf.slice(0, i); buf = buf.slice(i + 1);
|
|
1084
|
+
if (l === 'done') done = true;
|
|
1085
|
+
else if (/^pgid \\d+ \\d+$/.test(l)) { const [, g, s] = l.split(' '); pgid = Number(g); if (Number(s) > 0) { pgidStart = Number(s); tracked[g] = pgidStart; } record(); } } });
|
|
1086
|
+
const poll = setInterval(() => {
|
|
1087
|
+
if (pgid <= 1) return;
|
|
1088
|
+
const t = procTable();
|
|
1089
|
+
if (pgidStart === undefined && t[String(pgid)] !== undefined && t[String(pgid)].start >= since) { pgidStart = t[String(pgid)].start; tracked[String(pgid)] = pgidStart; record(); }
|
|
1090
|
+
if (growLineage(t, tracked, pgid, since, pgidStart)) record();
|
|
1091
|
+
}, 100);
|
|
1092
|
+
process.stdin.on('close', () => {
|
|
1093
|
+
clearInterval(poll);
|
|
1094
|
+
if (done) process.exit(0);
|
|
1095
|
+
// run exec named the group over the pipe; a leader started since the exec is its engine, even before the first poll
|
|
1096
|
+
if (pgid > 1 && pgidStart === undefined) { const row = procTable()[String(pgid)]; if (row !== undefined && row.start >= since) { pgidStart = row.start; tracked[String(pgid)] = row.start; } }
|
|
1097
|
+
const taint = endRunProcesses({ pgid, pgidStart, groupKnown: true, tracked, dirs, since, spare: [], canary, python });
|
|
1098
|
+
if (taint !== null) recordTaint(entry.replace(/\\.exec\\.\\d+$/, '.tainted'), 'watchdog: ' + taint);
|
|
1099
|
+
removeGitLocks(gitDir);
|
|
1100
|
+
removeRunTmp(tmp);
|
|
1101
|
+
try { fs.rmSync(entry, { force: true }); } catch {}
|
|
1102
|
+
process.exit(0);
|
|
1103
|
+
});`;
|
|
1104
|
+
async function runExec(opts, io, deps = {}) {
|
|
1105
|
+
if (opts.command.length === 0 || !opts.id) {
|
|
1106
|
+
io.stderr('usage: holmes-kit run exec --id <run_id> [--target <dir>] -- <command> [args...]\n');
|
|
1107
|
+
return 2;
|
|
1108
|
+
}
|
|
1109
|
+
if (process.platform !== 'darwin' || !fs.existsSync(SANDBOX_EXEC)) {
|
|
1110
|
+
io.stderr(`run exec refused: no write sandbox is available on ${process.platform} yet (macOS sandbox-exec only; Linux and Windows are named gaps)\n`);
|
|
1111
|
+
return 3;
|
|
1112
|
+
}
|
|
1113
|
+
// @implements A-SPEC-774.82 — every path a rule is built from passes the one seam, or the run is refused (exit 3)
|
|
1114
|
+
const refuse = (what, r) => {
|
|
1115
|
+
io.stderr(`run exec refused: ${what} — ${r.refused}; give its canonical path (A-SPEC-774.82)\n`);
|
|
1116
|
+
return 3;
|
|
1117
|
+
};
|
|
1118
|
+
const targetGiven = opts.target ?? process.cwd();
|
|
1119
|
+
const targetChecked = canonicalOrRefuse(targetGiven);
|
|
1120
|
+
if ('refused' in targetChecked)
|
|
1121
|
+
return refuse('the target', targetChecked);
|
|
1122
|
+
// A-SPEC-102.32 — non-strict: a forged pointer makes the target its own main, so the run's records go to its `.ax`; a
|
|
1123
|
+
// pointer that cannot be opened throws out of run exec, which then fails
|
|
1124
|
+
const mainChecked = canonicalOrRefuse((0, run_records_1.mainCheckoutOf)(targetChecked.path));
|
|
1125
|
+
if ('refused' in mainChecked)
|
|
1126
|
+
return refuse('the main checkout', mainChecked);
|
|
1127
|
+
const main = mainChecked.path;
|
|
1128
|
+
sweepOrphanExecs(main); // @implements A-SPEC-774.41
|
|
1129
|
+
const rec = (0, run_records_1.listRuns)(main).find((r) => r.run_id === opts.id);
|
|
1130
|
+
if (!rec) {
|
|
1131
|
+
io.stderr(`run exec refused: no run ${opts.id} in ${main}\n`);
|
|
1132
|
+
return 3;
|
|
1133
|
+
}
|
|
1134
|
+
if (rec.engine === 'agy') {
|
|
1135
|
+
io.stderr('run exec refused: agy runs are refused until their wiring is measured (A-SPEC-774.31)\n');
|
|
1136
|
+
return 3;
|
|
1137
|
+
}
|
|
1138
|
+
// @implements A-SPEC-774.52, A-SPEC-774.60 — the engine's own sandbox is off under run exec: its network is open only
|
|
1139
|
+
// when the starter said so on record; otherwise it reaches only run exec's allowlisting proxy.
|
|
1140
|
+
const networkOpen = rec.network === 'open';
|
|
1141
|
+
let worktree;
|
|
1142
|
+
let layout;
|
|
1143
|
+
try {
|
|
1144
|
+
const disk = (p) => { const d = canonicalOrRefuse(p); if ('refused' in d)
|
|
1145
|
+
throw new Error(d.refused); return d.path; }; // A-SPEC-774.82
|
|
1146
|
+
worktree = disk(rec.worktree);
|
|
1147
|
+
const l = gitLayout(worktree);
|
|
1148
|
+
layout = { ...l, gitDir: disk(l.gitDir), common: disk(l.common) };
|
|
1149
|
+
}
|
|
1150
|
+
catch (e) {
|
|
1151
|
+
io.stderr(`run exec refused: the run's worktree cannot be read (${e instanceof Error ? e.message : String(e)})\n`);
|
|
1152
|
+
return 3;
|
|
1153
|
+
}
|
|
1154
|
+
const baseEnv = deps.env ?? process.env;
|
|
1155
|
+
const homeChecked = canonicalOrRefuse(deps.home ?? os.homedir()); // @implements A-SPEC-774.82
|
|
1156
|
+
if ('refused' in homeChecked)
|
|
1157
|
+
return refuse('home', homeChecked);
|
|
1158
|
+
const home = homeChecked.path;
|
|
1159
|
+
const ownerCodexGiven = deps.codexHome ?? baseEnv.CODEX_HOME;
|
|
1160
|
+
const ownerCodexChecked = ownerCodexGiven === undefined ? undefined : canonicalOrRefuse(ownerCodexGiven); // H1.8: was never normalized
|
|
1161
|
+
if (ownerCodexChecked && 'refused' in ownerCodexChecked)
|
|
1162
|
+
return refuse('CODEX_HOME', ownerCodexChecked);
|
|
1163
|
+
const ownerCodexHome = ownerCodexChecked?.path;
|
|
1164
|
+
// @implements A-SPEC-774.36 — a claude run authenticates by the orchestrator's token; Holmes reads no credential store.
|
|
1165
|
+
if (rec.engine === 'claude' && !baseEnv.CLAUDE_CODE_OAUTH_TOKEN) {
|
|
1166
|
+
io.stderr('run exec refused: a claude run needs CLAUDE_CODE_OAUTH_TOKEN in the environment — its engine home is the run\'s own, not the owner\'s ~/.claude\n');
|
|
1167
|
+
return 3;
|
|
1168
|
+
}
|
|
1169
|
+
// @implements A-SPEC-774.82 — the run makes its own temp dir under the canonical temp root (supervisor ruling: the
|
|
1170
|
+
// default /var/folders TMPDIR passes through a symlink, and the TMPDIR spelling itself enters no rule). The root must
|
|
1171
|
+
// pass the seam, be the directory TMPDIR names, and mkdtemp must succeed — else exit 3.
|
|
1172
|
+
const tmpGiven = deps.tmpdir ?? os.tmpdir();
|
|
1173
|
+
let tmp;
|
|
1174
|
+
try {
|
|
1175
|
+
const root = canonicalOrRefuse(fs.realpathSync.native(tmpGiven));
|
|
1176
|
+
if ('refused' in root)
|
|
1177
|
+
return refuse(`the temp root of TMPDIR ${tmpGiven}`, root);
|
|
1178
|
+
const given = fs.statSync(tmpGiven);
|
|
1179
|
+
const at = fs.lstatSync(root.path);
|
|
1180
|
+
if (!at.isDirectory() || given.dev !== at.dev || given.ino !== at.ino)
|
|
1181
|
+
return refuse(`TMPDIR ${tmpGiven}`, { refused: `${root.path} is not the directory TMPDIR names` });
|
|
1182
|
+
// @implements A-SPEC-774.87 — never inside the repository: the run's writes would join the work tree (H1.9-d)
|
|
1183
|
+
// @implements A-SPEC-222.8 — L-d: and every other worktree of the repository (the common dir's worktrees/*/gitdir)
|
|
1184
|
+
const worktrees = [];
|
|
1185
|
+
try {
|
|
1186
|
+
for (const n of fs.readdirSync(path.join(layout.common, 'worktrees'))) {
|
|
1187
|
+
try {
|
|
1188
|
+
worktrees.push(path.dirname(fs.readFileSync(path.join(layout.common, 'worktrees', n, 'gitdir'), 'utf8').trim()));
|
|
1189
|
+
}
|
|
1190
|
+
catch { /* half-made */ }
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
catch { /* no linked worktrees */ }
|
|
1194
|
+
const holder = [targetChecked.path, main, worktree, layout.gitDir, layout.common, ...worktrees].find((d) => root.path === d || root.path.startsWith(d + path.sep));
|
|
1195
|
+
if (holder !== undefined)
|
|
1196
|
+
return refuse(`TMPDIR ${tmpGiven}`, { refused: `${root.path} lies inside ${holder}; the temp root must be outside the repository` });
|
|
1197
|
+
tmp = fs.mkdtempSync(path.join(root.path, `holmes-run-${rec.run_id}-`));
|
|
1198
|
+
}
|
|
1199
|
+
catch (e) {
|
|
1200
|
+
return refuse(`TMPDIR ${tmpGiven}`, { refused: e instanceof Error ? e.message.split('\n')[0] : String(e) });
|
|
1201
|
+
}
|
|
1202
|
+
// @implements A-SPEC-774.82 — this Holmes install, which run exec resolves itself (not an input spelling)
|
|
1203
|
+
const holmesPackage = fs.realpathSync.native(path.resolve(__dirname, '..', '..', '..'));
|
|
1204
|
+
let proxy = null; // @implements A-SPEC-774.60 — closed with everything else the run owns
|
|
1205
|
+
const cleanup = () => { proxy?.close(); removeRunTmp(tmp); }; // @implements A-SPEC-774.58
|
|
1206
|
+
// @implements A-SPEC-774.50, A-SPEC-774.53 — the canaries: files only this run's profile answers allow/deny for, made
|
|
1207
|
+
// and checked before the engine exists; teardown checks them again and asks sandbox_check about them.
|
|
1208
|
+
let canary;
|
|
1209
|
+
try {
|
|
1210
|
+
canary = makeCanary(tmp);
|
|
1211
|
+
}
|
|
1212
|
+
catch (e) {
|
|
1213
|
+
cleanup();
|
|
1214
|
+
io.stderr(`run exec refused: the run's sandbox canary could not be made (${e instanceof Error ? e.message : String(e)})\n`);
|
|
1215
|
+
return 3;
|
|
1216
|
+
}
|
|
1217
|
+
const python = detectorPython(deps.env ?? process.env);
|
|
1218
|
+
const engineHome = path.join(tmp, 'engine-home', rec.engine);
|
|
1219
|
+
const engineEnv = {};
|
|
1220
|
+
if (rec.engine === 'claude') {
|
|
1221
|
+
fs.mkdirSync(engineHome, { recursive: true, mode: 0o700 });
|
|
1222
|
+
engineEnv.CLAUDE_CONFIG_DIR = engineHome;
|
|
1223
|
+
}
|
|
1224
|
+
else if (rec.engine === 'codex') {
|
|
1225
|
+
let refusal;
|
|
1226
|
+
try {
|
|
1227
|
+
refusal = codexRunHome(engineHome, ownerCodexHome ?? path.join(home, '.codex'), [main, worktree]);
|
|
1228
|
+
}
|
|
1229
|
+
catch (e) {
|
|
1230
|
+
refusal = `the run's CODEX_HOME could not be prepared (${e instanceof Error ? e.message : String(e)})`;
|
|
1231
|
+
}
|
|
1232
|
+
if (refusal !== null) {
|
|
1233
|
+
cleanup();
|
|
1234
|
+
io.stderr(`run exec refused: ${refusal}\n`);
|
|
1235
|
+
return 3;
|
|
1236
|
+
}
|
|
1237
|
+
engineEnv.CODEX_HOME = engineHome;
|
|
1238
|
+
}
|
|
1239
|
+
const marker = crypto.randomBytes(12).toString('hex');
|
|
1240
|
+
// @implements A-SPEC-774.60 — the run's egress: its engine's service, and the pairs the orchestrator names
|
|
1241
|
+
if (!networkOpen) {
|
|
1242
|
+
const allowed = new Set([...(ENGINE_EGRESS[rec.engine] ?? []),
|
|
1243
|
+
...(baseEnv.HOLMES_RUN_EGRESS_ALLOW ?? '').split(',').map((s) => s.trim().toLowerCase()).filter((s) => /^[a-z0-9.-]+:\d{1,5}$/.test(s))]);
|
|
1244
|
+
const proxyToken = crypto.randomBytes(16).toString('hex'); // @implements A-SPEC-774.65 — the run's own credentials
|
|
1245
|
+
try {
|
|
1246
|
+
proxy = await startEgressProxy(allowed, proxyToken);
|
|
1247
|
+
}
|
|
1248
|
+
catch (e) {
|
|
1249
|
+
cleanup();
|
|
1250
|
+
io.stderr(`run exec refused: its egress proxy could not start (${e instanceof Error ? e.message : String(e)})\n`);
|
|
1251
|
+
return 3;
|
|
1252
|
+
}
|
|
1253
|
+
const url = `http://holmes:${proxyToken}@127.0.0.1:${proxy.port}`;
|
|
1254
|
+
for (const k of ['HTTPS_PROXY', 'HTTP_PROXY', 'https_proxy', 'http_proxy', 'ALL_PROXY'])
|
|
1255
|
+
engineEnv[k] = url;
|
|
1256
|
+
engineEnv.NODE_USE_ENV_PROXY = '1';
|
|
1257
|
+
}
|
|
1258
|
+
// @implements A-SPEC-774.63, A-SPEC-774.66 — the main checkout's untracked and ignored entries (outside .ax) are the
|
|
1259
|
+
// run's to read only when the orchestrator says so: a file by literal, a folded directory by subpath, each under the
|
|
1260
|
+
// given and the real spelling (the sandbox judges real paths); a directory holding the run's own paths stays open
|
|
1261
|
+
let denyRead = [];
|
|
1262
|
+
if (baseEnv.HOLMES_RUN_READ_MAIN_UNTRACKED !== '1') {
|
|
1263
|
+
try {
|
|
1264
|
+
const { judgmentGitEnv } = require('../review/verdicts');
|
|
1265
|
+
const list = (args) => (0, node_child_process_1.execFileSync)('git', ['-C', main, '-c', 'core.fsmonitor=false', 'ls-files', '--others', '--exclude-standard', '--directory', '-z', ...args], { encoding: 'utf8', env: judgmentGitEnv(baseEnv), stdio: ['ignore', 'pipe', 'ignore'], timeout: bounded_io_1.GIT_TIMEOUT_MS * 4, maxBuffer: bounded_io_1.GIT_MAX_BUFFER }).split('\0');
|
|
1266
|
+
// @implements A-SPEC-774.82 — main, the worktree and the temp dir passed the seam: one spelling each
|
|
1267
|
+
const own = [worktree, holmesPackage, tmp, engineHome];
|
|
1268
|
+
const holdsOwn = (dir) => own.some((o) => o === dir || o.startsWith(dir + path.sep));
|
|
1269
|
+
denyRead = [...new Set([...list([]), ...list(['--ignored'])])]
|
|
1270
|
+
.filter((e) => e !== '' && !/^\.ax(?:\/|$)/.test(e))
|
|
1271
|
+
.map((e) => ({ rel: e.replace(/\/$/, ''), dir: e.endsWith('/') }))
|
|
1272
|
+
.filter((e) => !e.dir || !holdsOwn(path.join(main, e.rel)))
|
|
1273
|
+
.map((e) => ({ path: path.join(main, e.rel), dir: e.dir }));
|
|
1274
|
+
}
|
|
1275
|
+
catch (e) {
|
|
1276
|
+
cleanup();
|
|
1277
|
+
io.stderr(`run exec refused: the main checkout's untracked files could not be listed (${e instanceof Error ? e.message.split('\n')[0] : String(e)})\n`);
|
|
1278
|
+
return 3;
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
// @implements A-SPEC-774.87 — the temp roots of every exec this checkout records (each entry's own tmp), none guessed
|
|
1282
|
+
const tmpRoots = [];
|
|
1283
|
+
try {
|
|
1284
|
+
const runsDir = path.join(main, '.ax', 'state', 'runs');
|
|
1285
|
+
for (const n of fs.readdirSync(runsDir).filter((x) => /\.exec\.\d+$/.test(x))) {
|
|
1286
|
+
try {
|
|
1287
|
+
const t = JSON.parse(fs.readFileSync(path.join(runsDir, n), 'utf8')).tmp;
|
|
1288
|
+
if (typeof t === 'string' && path.isAbsolute(t) && !/["\\\n\r]/.test(t))
|
|
1289
|
+
tmpRoots.push(path.dirname(t));
|
|
1290
|
+
}
|
|
1291
|
+
catch { /* half-written: its run will record again */ }
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
catch { /* no registry yet */ }
|
|
1295
|
+
let profile;
|
|
1296
|
+
try {
|
|
1297
|
+
profile = sandboxProfile({ worktree, ...layout, tmp, engine: rec.engine, home, engineHome, tmpRoots, ...(ownerCodexHome ? { ownerCodexHome } : {}), guard: canary.guard,
|
|
1298
|
+
...(proxy ? { proxyPort: proxy.port } : {}),
|
|
1299
|
+
// @implements A-SPEC-774.63 — the orchestrator's two read choices
|
|
1300
|
+
shellStartup: baseEnv.HOLMES_RUN_READ_SHELL_STARTUP === '1', denyRead,
|
|
1301
|
+
// @implements A-SPEC-774.59 — the main checkout, this Holmes package, and the orchestrator's absolute paths
|
|
1302
|
+
readAllow: [main, holmesPackage],
|
|
1303
|
+
// @implements A-SPEC-774.70 — named paths outrank the untracked denials and never the secrets
|
|
1304
|
+
readAllowNamed: (baseEnv.HOLMES_RUN_READ_ALLOW ?? '').split(path.delimiter).filter((d) => {
|
|
1305
|
+
if (d === '')
|
|
1306
|
+
return false;
|
|
1307
|
+
// @implements A-SPEC-774.71 — a dropped entry says why (it is never guessed relative to anything)
|
|
1308
|
+
if (!path.isAbsolute(d)) {
|
|
1309
|
+
io.stderr(`run exec: HOLMES_RUN_READ_ALLOW entry "${d}" ignored (not an absolute path)\n`);
|
|
1310
|
+
return false;
|
|
1311
|
+
}
|
|
1312
|
+
// @implements A-SPEC-774.82 — nor kept in a spelling that is not its own canonical path (no fold)
|
|
1313
|
+
const named = canonicalOrRefuse(d);
|
|
1314
|
+
if ('refused' in named) {
|
|
1315
|
+
io.stderr(`run exec: HOLMES_RUN_READ_ALLOW entry "${d}" ignored (${named.refused})\n`);
|
|
1316
|
+
return false;
|
|
1317
|
+
}
|
|
1318
|
+
return true;
|
|
1319
|
+
}) });
|
|
1320
|
+
}
|
|
1321
|
+
catch (e) {
|
|
1322
|
+
cleanup();
|
|
1323
|
+
io.stderr(`run exec refused: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
1324
|
+
return 3;
|
|
1325
|
+
}
|
|
1326
|
+
const profileFile = path.join(tmp, '.holmes-sandbox.sb');
|
|
1327
|
+
fs.writeFileSync(profileFile, profile, { mode: 0o600 });
|
|
1328
|
+
// @implements A-SPEC-774.41 — the watchdog and the registry entry exist before the engine does.
|
|
1329
|
+
const entryFile = execEntryFile(main, rec.run_id, process.pid);
|
|
1330
|
+
// @implements A-SPEC-774.42 — the run's start second and its own paths: what started since, in them, is the run's.
|
|
1331
|
+
const since = Math.floor(Date.now() / 1000);
|
|
1332
|
+
const dirs = [tmp, engineHome]; // @implements A-SPEC-774.44 — run-unique paths only, never the worktree
|
|
1333
|
+
const watchdog = (0, node_child_process_1.spawn)(process.execPath, ['-e', WATCHDOG, entryFile, tmp, String(since), JSON.stringify(dirs), layout.gitDir, JSON.stringify(canary), python], { cwd: '/', detached: true, stdio: ['pipe', 'ignore', 'ignore'] });
|
|
1334
|
+
watchdog.unref();
|
|
1335
|
+
const tell = (line) => { try {
|
|
1336
|
+
watchdog.stdin?.write(`${line}\n`);
|
|
1337
|
+
}
|
|
1338
|
+
catch { /* the watchdog is gone */ } };
|
|
1339
|
+
try {
|
|
1340
|
+
fs.mkdirSync(path.dirname(entryFile), { recursive: true });
|
|
1341
|
+
fs.writeFileSync(entryFile, JSON.stringify({ pid: process.pid, watchdog: watchdog.pid ?? 0, tmp, since, dirs, gitDir: layout.gitDir, canary }), { mode: 0o600 });
|
|
1342
|
+
}
|
|
1343
|
+
catch (e) {
|
|
1344
|
+
tell('done');
|
|
1345
|
+
watchdog.stdin?.end();
|
|
1346
|
+
cleanup();
|
|
1347
|
+
io.stderr(`run exec refused: its registry entry could not be written (${e instanceof Error ? e.message : String(e)})\n`);
|
|
1348
|
+
return 3;
|
|
1349
|
+
}
|
|
1350
|
+
const [cmd, ...args] = opts.command;
|
|
1351
|
+
// The group first, then the lineage the watchdog recorded and whatever holds the run's paths (A-SPEC-774.42) — until
|
|
1352
|
+
// none is left; then the run home and the auth copy (A-SPEC-774.36) and the registry entry.
|
|
1353
|
+
let child;
|
|
1354
|
+
let leaderStart;
|
|
1355
|
+
let poll;
|
|
1356
|
+
const ownTracked = {};
|
|
1357
|
+
let tornDown = false;
|
|
1358
|
+
const teardown = () => {
|
|
1359
|
+
if (tornDown)
|
|
1360
|
+
return;
|
|
1361
|
+
tornDown = true;
|
|
1362
|
+
if (poll)
|
|
1363
|
+
clearInterval(poll);
|
|
1364
|
+
// Our own child that has not exited cannot have had its pid reused: its group is the engine's, start check or not.
|
|
1365
|
+
if (child?.pid && child.exitCode === null && child.signalCode === null) {
|
|
1366
|
+
try {
|
|
1367
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
1368
|
+
}
|
|
1369
|
+
catch { /* gone */ }
|
|
1370
|
+
}
|
|
1371
|
+
let tracked = {};
|
|
1372
|
+
try {
|
|
1373
|
+
tracked = { ...(JSON.parse(fs.readFileSync(entryFile, 'utf8')).tracked ?? {}) };
|
|
1374
|
+
}
|
|
1375
|
+
catch { /* the watchdog recorded nothing */ }
|
|
1376
|
+
const taint = endRunProcesses({ pgid: child?.pid ?? 0, ...(leaderStart !== undefined ? { pgidStart: leaderStart } : {}), groupKnown: true, tracked: { ...ownTracked, ...tracked },
|
|
1377
|
+
dirs, since, spare: watchdog.pid ? [watchdog.pid] : [], canary, python });
|
|
1378
|
+
if (taint !== null)
|
|
1379
|
+
recordTaint(taintFileOf(entryFile), taint); // @implements A-SPEC-774.50
|
|
1380
|
+
removeGitLocks(layout.gitDir); // @implements A-SPEC-774.43
|
|
1381
|
+
cleanup();
|
|
1382
|
+
tell('done');
|
|
1383
|
+
try {
|
|
1384
|
+
watchdog.stdin?.end();
|
|
1385
|
+
}
|
|
1386
|
+
catch { /* gone */ }
|
|
1387
|
+
try {
|
|
1388
|
+
fs.rmSync(entryFile, { force: true });
|
|
1389
|
+
}
|
|
1390
|
+
catch { /* best effort */ }
|
|
1391
|
+
};
|
|
1392
|
+
// @implements A-SPEC-774.41 — a signal to run exec ends the engine too (an orchestrator may SIGKILL after its own
|
|
1393
|
+
// grace; the watchdog then finishes — docs/contracts/run.md). Handled
|
|
1394
|
+
// from before the engine exists: a TERM that lands while run exec is still learning its child must not orphan it.
|
|
1395
|
+
const onSignal = (sig) => { teardown(); process.exit(128 + (os.constants.signals[sig] ?? 0)); };
|
|
1396
|
+
const signals = ['SIGTERM', 'SIGINT', 'SIGHUP'];
|
|
1397
|
+
for (const s of signals)
|
|
1398
|
+
process.on(s, onSignal);
|
|
1399
|
+
child = (0, node_child_process_1.spawn)(SANDBOX_EXEC, ['-f', profileFile, cmd, ...args], {
|
|
1400
|
+
cwd: worktree, env: (() => {
|
|
1401
|
+
const env = { ...sandboxEnv(baseEnv, { id: rec.run_id, tmp, marker }), ...engineEnv };
|
|
1402
|
+
if (proxy) {
|
|
1403
|
+
delete env.NO_PROXY;
|
|
1404
|
+
delete env.no_proxy;
|
|
1405
|
+
} // @implements A-SPEC-774.60 — nothing bypasses the proxy
|
|
1406
|
+
return env;
|
|
1407
|
+
})(), detached: true, stdio: ['inherit', 'pipe', 'pipe'],
|
|
1408
|
+
});
|
|
1409
|
+
const enginePid = child.pid;
|
|
1410
|
+
if (enginePid)
|
|
1411
|
+
tell(`pgid ${enginePid} 0`); // the watchdog knows the group at once; its start follows
|
|
1412
|
+
// @implements A-SPEC-774.44 — the group leader's start, so a later reuse of its pgid is never taken for the engine's.
|
|
1413
|
+
for (let i = 0; enginePid && leaderStart === undefined && i < 10; i++)
|
|
1414
|
+
leaderStart = procTable()[String(enginePid)]?.start; // ps can fail under load
|
|
1415
|
+
if (enginePid && leaderStart !== undefined) {
|
|
1416
|
+
tell(`pgid ${enginePid} ${leaderStart}`);
|
|
1417
|
+
ownTracked[String(enginePid)] = leaderStart;
|
|
1418
|
+
}
|
|
1419
|
+
// @implements A-SPEC-774.42 — run exec polls the lineage itself too, from the first moment (a watchdog starting under
|
|
1420
|
+
// load can take longer than a short-lived parent lives); the watchdog's record covers the case run exec is killed.
|
|
1421
|
+
if (enginePid && leaderStart !== undefined && !tornDown) {
|
|
1422
|
+
poll = setInterval(() => { growLineage(procTable(), ownTracked, enginePid, since, leaderStart); }, 100);
|
|
1423
|
+
}
|
|
1424
|
+
child.stdout?.on('data', (b) => io.stdout(b.toString()));
|
|
1425
|
+
child.stderr?.on('data', (b) => io.stderr(b.toString()));
|
|
1426
|
+
const running = child;
|
|
1427
|
+
const code = await new Promise((res) => {
|
|
1428
|
+
running.on('error', (e) => { io.stderr(`run exec: ${e.message}\n`); res(127); });
|
|
1429
|
+
running.on('exit', (c, sig) => res(c ?? (sig ? 128 + (os.constants.signals[sig] ?? 0) : 1)));
|
|
1430
|
+
});
|
|
1431
|
+
for (const s of signals)
|
|
1432
|
+
process.off(s, onSignal);
|
|
1433
|
+
teardown();
|
|
1434
|
+
return code;
|
|
1435
|
+
}
|