crysk 0.0.0-stage → 0.3.0
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/LICENSE +176 -0
- package/README.md +610 -2
- package/bin/pr-hero.js +166 -0
- package/config/models/anthropic.json +5 -0
- package/dist/SKILL-7e3725zn.md +496 -0
- package/dist/SKILL-7q35wcaz.md +66 -0
- package/dist/SKILL-9at22381.md +74 -0
- package/dist/SKILL-ex2hxxh3.md +134 -0
- package/dist/adjudicator-dtg2axnh.md +86 -0
- package/dist/admission-config.example-a9vqmmad.json +9 -0
- package/dist/ci-admission-camfbx2b.md +122 -0
- package/dist/cli.js +42292 -0
- package/dist/consolidate-ac0mnfyj.md +24 -0
- package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
- package/dist/deep-review-logic-a6b1gczf.md +156 -0
- package/dist/deep-review-parity-0ec904db.md +120 -0
- package/dist/deep-review-reliability-qyakbjb9.md +125 -0
- package/dist/deep-review-resilience-3tz8y26e.md +118 -0
- package/dist/index.js +20190 -0
- package/dist/opencode-ci-7b0be64p.md +141 -0
- package/dist/review-refuter-j4e9gezy.md +71 -0
- package/dist/scout-yvp153q7.md +140 -0
- package/dist/summarizer-zca44nxa.md +18 -0
- package/dist/workflow-w1g9szna.yml +151 -0
- package/package.json +82 -4
- package/prompts/consolidate.md +24 -0
- package/prompts/default/PROVENANCE.md +18 -0
- package/prompts/default/deep-review-lifecycle.md +362 -0
- package/prompts/default/deep-review-logic.md +156 -0
- package/prompts/default/deep-review-parity.md +120 -0
- package/prompts/default/deep-review-reliability.md +125 -0
- package/prompts/default/deep-review-resilience.md +118 -0
- package/prompts/default/review-refuter.md +71 -0
- package/prompts/scout.md +140 -0
- package/prompts/summarizer.md +18 -0
- package/skills/crysk/SKILL.md +74 -0
- package/skills/crysk-ci-setup/SKILL.md +134 -0
- package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
- package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
- package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
- package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
- package/skills/crysk-loop/SKILL.md +496 -0
- package/skills/crysk-loop/adjudicator.md +86 -0
- package/skills/crysk-pr/SKILL.md +66 -0
- package/src/agent-env.ts +1084 -0
- package/src/asset-manifest.ts +83 -0
- package/src/assets.d.ts +6 -0
- package/src/assets.ts +183 -0
- package/src/brand-paths.ts +155 -0
- package/src/brand.ts +255 -0
- package/src/ci/admission-ledger.ts +350 -0
- package/src/ci/classify-error.ts +73 -0
- package/src/ci/cli-record.ts +271 -0
- package/src/ci/force-comment.ts +39 -0
- package/src/ci/gates.ts +923 -0
- package/src/ci/outcome.ts +2181 -0
- package/src/ci/override.ts +187 -0
- package/src/ci/publish.ts +1639 -0
- package/src/ci/reporter.ts +626 -0
- package/src/ci/review-admission.ts +901 -0
- package/src/ci/review-levels.ts +310 -0
- package/src/ci/review-policy.ts +18 -0
- package/src/ci/review-risk.ts +184 -0
- package/src/ci/setup.ts +844 -0
- package/src/ci/trigger.ts +1353 -0
- package/src/cli.ts +348 -0
- package/src/commands/activity.ts +67 -0
- package/src/commands/ci-setup-questions.ts +397 -0
- package/src/commands/ci-setup.ts +381 -0
- package/src/commands/config.ts +99 -0
- package/src/commands/doctor.ts +108 -0
- package/src/commands/init.ts +139 -0
- package/src/commands/mcp.ts +10 -0
- package/src/commands/menu.ts +129 -0
- package/src/commands/post.ts +302 -0
- package/src/commands/skills.ts +83 -0
- package/src/commands/status.ts +173 -0
- package/src/commands/triage.ts +342 -0
- package/src/commands/uninstall.ts +37 -0
- package/src/commands/upgrade.ts +214 -0
- package/src/commands/usage.ts +98 -0
- package/src/compare/compare.ts +28 -0
- package/src/compare/floor-test.ts +471 -0
- package/src/compare/martian-adapter.ts +80 -0
- package/src/config/config.ts +267 -0
- package/src/corpus/corpus.ts +1094 -0
- package/src/corpus/preflight.ts +1789 -0
- package/src/diversity/accounting.ts +90 -0
- package/src/diversity/adjudication.ts +145 -0
- package/src/diversity/admission.ts +60 -0
- package/src/diversity/benchmark.ts +195 -0
- package/src/diversity/clustering.ts +285 -0
- package/src/diversity/errors.ts +7 -0
- package/src/diversity/identity.ts +285 -0
- package/src/diversity/index.ts +11 -0
- package/src/diversity/pipeline-integration.ts +448 -0
- package/src/diversity/projection.ts +57 -0
- package/src/diversity/self-contained.ts +68 -0
- package/src/diversity/target-validation.ts +179 -0
- package/src/doctor-migration.ts +209 -0
- package/src/doctor.ts +723 -0
- package/src/errors.ts +83 -0
- package/src/execution/admission.ts +75 -0
- package/src/execution/atomic-write.ts +35 -0
- package/src/execution/attempt-evidence.ts +415 -0
- package/src/execution/bucket-id.ts +136 -0
- package/src/execution/concurrency-limiter.ts +175 -0
- package/src/execution/contracts.ts +443 -0
- package/src/execution/failure-classification.ts +42 -0
- package/src/execution/failure-policy.ts +240 -0
- package/src/execution/harness.ts +2548 -0
- package/src/execution/settlement.ts +348 -0
- package/src/execution/spawned-process.ts +66 -0
- package/src/execution/spend-limiter.ts +424 -0
- package/src/execution/step-artifacts.ts +55 -0
- package/src/execution/usage-normalized.ts +469 -0
- package/src/git/git.ts +396 -0
- package/src/git/identity.ts +64 -0
- package/src/git/refs.ts +140 -0
- package/src/home-preflight.ts +443 -0
- package/src/home.ts +243 -0
- package/src/ignore-file.ts +336 -0
- package/src/ignore-read.ts +118 -0
- package/src/index.ts +34 -0
- package/src/legacy-launchd.ts +29 -0
- package/src/mcp/mcp.ts +150 -0
- package/src/mcp/preflight.ts +407 -0
- package/src/menu-context.ts +192 -0
- package/src/model/catalog.ts +251 -0
- package/src/model/exec-snapshots.ts +390 -0
- package/src/model/free-discovery.ts +302 -0
- package/src/model/provider-capabilities.ts +814 -0
- package/src/model/routing.ts +600 -0
- package/src/pr/admission.ts +847 -0
- package/src/pr/ci-admission-gate.ts +665 -0
- package/src/pr/ci-publish.ts +76 -0
- package/src/pr/discovery.ts +432 -0
- package/src/pr/inline.ts +507 -0
- package/src/pr/plan.ts +366 -0
- package/src/pr/posting.ts +115 -0
- package/src/pr/pr-status.ts +787 -0
- package/src/pr/pr.ts +3642 -0
- package/src/pr/preflight.ts +1031 -0
- package/src/pr/publish-outcome.ts +361 -0
- package/src/pr/range.ts +119 -0
- package/src/pr/reverts-preflight.ts +606 -0
- package/src/pr/reverts.ts +377 -0
- package/src/pr/review-pr.ts +927 -0
- package/src/pr/status.ts +154 -0
- package/src/pr/target.ts +388 -0
- package/src/pr/teardown.ts +437 -0
- package/src/pr/worktree-setup.ts +60 -0
- package/src/production-runtime.ts +1877 -0
- package/src/progress.ts +487 -0
- package/src/rereview/adjudicate.ts +89 -0
- package/src/rereview/classify.ts +362 -0
- package/src/rereview/identity.ts +211 -0
- package/src/rereview/plan.ts +308 -0
- package/src/rereview/prepare.ts +1025 -0
- package/src/rereview/state.ts +767 -0
- package/src/rereview/verify.ts +241 -0
- package/src/review/boundary.ts +105 -0
- package/src/review/consolidate.ts +246 -0
- package/src/review/dedupe.ts +368 -0
- package/src/review/drafts.ts +448 -0
- package/src/review/findings-conformance.ts +120 -0
- package/src/review/findings.ts +714 -0
- package/src/review/pipeline.ts +3977 -0
- package/src/review/preflight.ts +3575 -0
- package/src/review/prompt-set.ts +177 -0
- package/src/review/proof-refs.ts +187 -0
- package/src/review/report.ts +1821 -0
- package/src/review/review.ts +490 -0
- package/src/review/root-cause.ts +120 -0
- package/src/review/route-preflight.ts +289 -0
- package/src/review/run.ts +601 -0
- package/src/review/scout.ts +323 -0
- package/src/review/size-gate.ts +595 -0
- package/src/review/spec.ts +235 -0
- package/src/review/step-runner.ts +233 -0
- package/src/runner-authority.ts +596 -0
- package/src/security/binding-policy.ts +115 -0
- package/src/security/credential-broker.ts +773 -0
- package/src/security/evidence-redaction.ts +62 -0
- package/src/security/execution-authority.ts +27 -0
- package/src/security/redact.ts +71 -0
- package/src/security/workspace-read-broker.ts +466 -0
- package/src/server/client.ts +190 -0
- package/src/server/preflight.ts +217 -0
- package/src/server/server.ts +327 -0
- package/src/signal-handler.ts +50 -0
- package/src/store/activity.ts +413 -0
- package/src/store/backfill-preflight.ts +49 -0
- package/src/store/backfill.ts +141 -0
- package/src/store/gc-preflight.ts +206 -0
- package/src/store/gc.ts +424 -0
- package/src/store/metrics-preflight.ts +229 -0
- package/src/store/metrics.ts +236 -0
- package/src/store/preflight.ts +748 -0
- package/src/store/store.ts +693 -0
- package/src/system-tools.ts +355 -0
- package/src/transport-registry.ts +1124 -0
- package/src/transports/claude-code-cli.ts +1348 -0
- package/src/transports/opencode-admission.ts +515 -0
- package/src/transports/opencode-client.ts +3328 -0
- package/src/transports/opencode-evidence.ts +557 -0
- package/src/transports/opencode-mcp.ts +248 -0
- package/src/transports/opencode-sdk.ts +2294 -0
- package/src/transports/opencode-server.ts +535 -0
- package/src/triage/adjudication.ts +113 -0
- package/src/triage/reply.ts +125 -0
- package/src/triage/triage.ts +255 -0
- package/src/ui/activity.ts +173 -0
- package/src/ui/config-edit.ts +816 -0
- package/src/ui/config.ts +462 -0
- package/src/ui/menu.ts +1325 -0
- package/src/ui/plan.ts +1039 -0
- package/src/ui/primitives.ts +300 -0
- package/src/ui/progress.ts +298 -0
- package/src/ui/result.ts +552 -0
- package/src/ui/review-menu.ts +312 -0
- package/src/ui/select.ts +528 -0
- package/src/ui/tree.ts +178 -0
- package/src/uninstaller.ts +479 -0
- package/src/updater.ts +836 -0
- package/src/usage.ts +77 -0
- package/src/watch/preflight.ts +1389 -0
- package/src/watch/watch.ts +1235 -0
- package/src/wizard.ts +877 -0
package/src/errors.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// Generic CLI error classes, shared by every domain. Neither is review logic:
|
|
2
|
+
// a usage mistake or a runtime failure (git, gh, the filesystem) can surface
|
|
3
|
+
// from any I/O shell, so both live in this neutral, dependency-free module
|
|
4
|
+
// instead of being owned by whichever shell happened to throw them first.
|
|
5
|
+
// C1 git-layering slice: moved out of review/preflight.ts, which still
|
|
6
|
+
// re-exports both for the ~55 existing consumers (see the re-export note
|
|
7
|
+
// there).
|
|
8
|
+
//
|
|
9
|
+
// The one import below is type-only, erased at transpile time, so this module
|
|
10
|
+
// stays free of runtime dependencies. The class an error names is the record
|
|
11
|
+
// class the CI writes to cli.json (odd/tasks/agent-first-ci.md, T2d-1).
|
|
12
|
+
|
|
13
|
+
import type { CliErrorClass } from "./ci/outcome";
|
|
14
|
+
|
|
15
|
+
// The class a throw site names is optional: a CliUsageError without one is
|
|
16
|
+
// classified as unknown, exactly as before. The message never changes with it.
|
|
17
|
+
export interface CliErrorOptions {
|
|
18
|
+
cls?: CliErrorClass;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// `cls` is declared, not a field initialiser: under the class-field semantics this
|
|
22
|
+
// repo compiles with (target ESNext), a plain `readonly cls` declaration defines an
|
|
23
|
+
// own `cls: undefined` on every instance. Bun's uncaught print shows own enumerable
|
|
24
|
+
// properties, so that would add a `cls: undefined` line to every local crash. The
|
|
25
|
+
// constructor assigns it only when a class was named.
|
|
26
|
+
export class CliUsageError extends Error {
|
|
27
|
+
declare readonly cls?: CliErrorClass;
|
|
28
|
+
|
|
29
|
+
constructor(message: string, options: CliErrorOptions = {}) {
|
|
30
|
+
super(message);
|
|
31
|
+
if (options.cls !== undefined) this.cls = options.cls;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Runtime failure (git, gh, the filesystem) as opposed to a usage error.
|
|
36
|
+
// Defined here rather than in a shell so every I/O shell (cli.ts, pr/pr.ts,
|
|
37
|
+
// and others) can throw the same class without importing each other.
|
|
38
|
+
export class CliError extends Error {
|
|
39
|
+
declare readonly cls?: CliErrorClass;
|
|
40
|
+
|
|
41
|
+
constructor(message: string, options: CliErrorOptions = {}) {
|
|
42
|
+
super(message);
|
|
43
|
+
if (options.cls !== undefined) this.cls = options.cls;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The record class of an error that is not a CliError. main() in src/cli.ts prints a
|
|
48
|
+
// CliError as one line and lets every other error take the uncaught-exception path,
|
|
49
|
+
// which local runs have always used. Such an error must stay the object it was thrown
|
|
50
|
+
// as: same type, same message, same stack, so the excerpt Bun prints still points at
|
|
51
|
+
// the throw site. Its class therefore sits beside it, in a WeakMap. An own property
|
|
52
|
+
// would not do: the uncaught print shows every enumerable property of an error.
|
|
53
|
+
const recordClasses = new WeakMap<object, CliErrorClass>();
|
|
54
|
+
|
|
55
|
+
export function withRecordClass<T>(error: T, cls: CliErrorClass): T {
|
|
56
|
+
if (typeof error === "object" && error !== null) {
|
|
57
|
+
recordClasses.set(error, cls);
|
|
58
|
+
}
|
|
59
|
+
return error;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function recordClassOf(error: unknown): CliErrorClass | undefined {
|
|
63
|
+
return typeof error === "object" && error !== null
|
|
64
|
+
? recordClasses.get(error)
|
|
65
|
+
: undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// A parser's boundary: every CliUsageError thrown inside `parse` that carries no
|
|
69
|
+
// class gets `cls`, with the same message. The parser's own throws and their
|
|
70
|
+
// messages stay as they are, and errors that are not usage errors pass through
|
|
71
|
+
// unchanged. WHY at the boundary and not per throw: one parser's throws are one
|
|
72
|
+
// kind of failure, and the class depends on which parser was asked (the repo
|
|
73
|
+
// layer, the routing object, the extra hunters), not on the throw.
|
|
74
|
+
export function withUsageClass<T>(cls: CliErrorClass, parse: () => T): T {
|
|
75
|
+
try {
|
|
76
|
+
return parse();
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error instanceof CliUsageError && error.cls === undefined) {
|
|
79
|
+
throw new CliUsageError(error.message, { cls });
|
|
80
|
+
}
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// D1-08 PR5a (§9.2): the attempt-scoped, lease-returning admission gate.
|
|
2
|
+
// `StepAdmissionGate` (contracts.ts) is admitted ONCE per STEP, before the
|
|
3
|
+
// retry loop, and returns nothing releasable — design decision D4 leaves it
|
|
4
|
+
// untouched: it has 5 implementors, 3 of them in test/security/* and
|
|
5
|
+
// test/harness/security-admission.test.ts, and rule 4 requires those
|
|
6
|
+
// assertions stay green UNMODIFIED. `AttemptAdmissionGate` is a NEW,
|
|
7
|
+
// separate contract admitted per ATTEMPT, inside the retry loop, returning
|
|
8
|
+
// an `AttemptLease` the harness releases exactly once in `finally` — the
|
|
9
|
+
// shape the concurrency limiter's FIFO/breaker semantics actually need to
|
|
10
|
+
// gate paid spawns.
|
|
11
|
+
//
|
|
12
|
+
// This module is a thin, mechanical wrapper on purpose: `ConcurrencyLimiter`
|
|
13
|
+
// (PR3) already owns every FIFO/breaker rule and is tested directly at that
|
|
14
|
+
// layer (test/execution/concurrency-limiter.test.ts) — per that module's own
|
|
15
|
+
// header comment, PR5a's job is "wrap this in AttemptAdmissionGate," not
|
|
16
|
+
// "invent FIFO/breaker semantics under time pressure."
|
|
17
|
+
|
|
18
|
+
import type { ConcurrencyLimiter } from "./concurrency-limiter";
|
|
19
|
+
|
|
20
|
+
export interface AttemptLease {
|
|
21
|
+
readonly leaseId: string;
|
|
22
|
+
readonly rateLimitBucketId: string;
|
|
23
|
+
// Idempotent — §9.2 "released exactly once in finally" is the CALLER's
|
|
24
|
+
// contract; this mirrors ConcurrencyLimiter's own idempotent release so a
|
|
25
|
+
// caller bug (a double-release) cannot corrupt the underlying slot count.
|
|
26
|
+
release(): void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface AttemptAdmissionGate {
|
|
30
|
+
// Rejects on abort (the limiter's FIFO queue is abort-aware) or on a
|
|
31
|
+
// tripped bucket breaker — never silently grants a slot.
|
|
32
|
+
acquire(input: {
|
|
33
|
+
readonly sessionId: string;
|
|
34
|
+
readonly attempt: number;
|
|
35
|
+
readonly rateLimitBucketId: string;
|
|
36
|
+
readonly signal: AbortSignal;
|
|
37
|
+
}): Promise<AttemptLease>;
|
|
38
|
+
// Called by the harness when an attempt's settlement receipt outcome is
|
|
39
|
+
// `local_fenced_remote_unconfirmed` (spec: "Circuit Breaker Fences An
|
|
40
|
+
// Unconfirmed-Abort Bucket"): trips this bucket's breaker to zero new
|
|
41
|
+
// capacity for the rest of the run. Optional so a minimal stub gate in
|
|
42
|
+
// tests (or a future gate implementation with no breaker semantics) can
|
|
43
|
+
// omit it without breaking the interface.
|
|
44
|
+
reportUnconfirmedRemote?(rateLimitBucketId: string): void;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class ConcurrencyAttemptAdmissionGate implements AttemptAdmissionGate {
|
|
48
|
+
constructor(private readonly limiter: ConcurrencyLimiter) {}
|
|
49
|
+
|
|
50
|
+
async acquire(input: {
|
|
51
|
+
readonly sessionId: string;
|
|
52
|
+
readonly attempt: number;
|
|
53
|
+
readonly rateLimitBucketId: string;
|
|
54
|
+
readonly signal: AbortSignal;
|
|
55
|
+
}): Promise<AttemptLease> {
|
|
56
|
+
const lease = await this.limiter.acquire(
|
|
57
|
+
input.rateLimitBucketId,
|
|
58
|
+
input.signal,
|
|
59
|
+
);
|
|
60
|
+
let released = false;
|
|
61
|
+
return {
|
|
62
|
+
leaseId: `${input.sessionId}#${input.attempt}`,
|
|
63
|
+
rateLimitBucketId: input.rateLimitBucketId,
|
|
64
|
+
release: () => {
|
|
65
|
+
if (released) return;
|
|
66
|
+
released = true;
|
|
67
|
+
lease.release();
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
reportUnconfirmedRemote(rateLimitBucketId: string): void {
|
|
73
|
+
this.limiter.tripBreaker(rateLimitBucketId);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { mkdir, rename } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
// WHY its own module rather than a helper inside harness.ts, where this writer
|
|
5
|
+
// was born: TWO impure callers need the identical tmp+rename guarantee — the
|
|
6
|
+
// harness's per-step artifacts and the pipeline's partial snapshot (§5.3 step 7)
|
|
7
|
+
// — and `harness.ts` is a 1000-line impure module carrying transports, spawn,
|
|
8
|
+
// credential projection and settlement. `pipeline.ts` importing it wholesale to
|
|
9
|
+
// reach one four-line function would drag all of that into the pipeline's
|
|
10
|
+
// dependency graph. A plain `Bun.write` is not a substitute: a crash or a
|
|
11
|
+
// concurrent reader mid-write sees a TRUNCATED artifact, and every reader of
|
|
12
|
+
// these files (parsePipelineMeta, floor-test, the CLI, backfill) parses JSON and
|
|
13
|
+
// fails hard on one.
|
|
14
|
+
|
|
15
|
+
export async function writeJsonAtomically(
|
|
16
|
+
outPath: string,
|
|
17
|
+
value: unknown,
|
|
18
|
+
// PR #228 review, F003: pretty-printing (the default, and every OTHER
|
|
19
|
+
// caller's shape) is never appropriate for a size-capped diagnostic
|
|
20
|
+
// capture — `JSON.stringify(value, null, 2)`'s per-level indentation and
|
|
21
|
+
// newlines inflate a multi-thousand-record array well past the compact
|
|
22
|
+
// size a caller already checked against a byte cap. `compact: true` opts
|
|
23
|
+
// a single caller (the OpenCode capture file) into the exact bytes that
|
|
24
|
+
// were measured, without changing the formatting of anything else this
|
|
25
|
+
// function writes.
|
|
26
|
+
options: { compact?: boolean } = {},
|
|
27
|
+
): Promise<void> {
|
|
28
|
+
const tmpPath = `${outPath}.tmp`;
|
|
29
|
+
await mkdir(path.dirname(outPath), { recursive: true });
|
|
30
|
+
const text = options.compact
|
|
31
|
+
? JSON.stringify(value)
|
|
32
|
+
: `${JSON.stringify(value, null, 2)}\n`;
|
|
33
|
+
await Bun.write(tmpPath, text);
|
|
34
|
+
await rename(tmpPath, outPath);
|
|
35
|
+
}
|
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { mkdir, readFile, realpath } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import type { StepSpec } from "#review/step-runner";
|
|
6
|
+
import {
|
|
7
|
+
redactEvidence,
|
|
8
|
+
redactEvidenceText,
|
|
9
|
+
} from "../security/evidence-redaction";
|
|
10
|
+
import { writeJsonAtomically } from "./atomic-write";
|
|
11
|
+
import type { TransportOutcome, TransportRequest } from "./contracts";
|
|
12
|
+
import type { SettlementReceipt } from "./settlement";
|
|
13
|
+
import { attemptEvidencePath } from "./step-artifacts";
|
|
14
|
+
|
|
15
|
+
export const evidenceSha256 = (value: string | Uint8Array): string =>
|
|
16
|
+
createHash("sha256").update(value).digest("hex");
|
|
17
|
+
export interface ExecutionAttemptEvidence {
|
|
18
|
+
schemaVersion: 1;
|
|
19
|
+
sessionId: string;
|
|
20
|
+
attempt: number;
|
|
21
|
+
stepName: string;
|
|
22
|
+
identity: {
|
|
23
|
+
route: TransportRequest["route"];
|
|
24
|
+
executionModel: string;
|
|
25
|
+
systemPromptSha256: string;
|
|
26
|
+
userPromptSha256: string;
|
|
27
|
+
canonicalCwdSha256: string;
|
|
28
|
+
toolsConfigSha256?: string;
|
|
29
|
+
executableSha256?: string;
|
|
30
|
+
};
|
|
31
|
+
outcome?: Pick<
|
|
32
|
+
TransportOutcome,
|
|
33
|
+
"completion" | "protocolIntegrity" | "terminalProof" | "usage"
|
|
34
|
+
>;
|
|
35
|
+
settlement: SettlementReceipt;
|
|
36
|
+
delivered: boolean;
|
|
37
|
+
outputSha256?: string;
|
|
38
|
+
outputPath?: string;
|
|
39
|
+
requestPlan?: { relativePath: string; sha256: string };
|
|
40
|
+
capture?: {
|
|
41
|
+
schema: string;
|
|
42
|
+
status: "complete" | "incomplete" | "unavailable";
|
|
43
|
+
sha256: string;
|
|
44
|
+
relativePath: string;
|
|
45
|
+
};
|
|
46
|
+
// A capture the transport actually produced but that this function could
|
|
47
|
+
// not persist (too large, an unrecognized schema, or a parse/write
|
|
48
|
+
// failure) is a diagnostic loss worth recording — silently proceeding
|
|
49
|
+
// without either `capture` or this field left every one of a real
|
|
50
|
+
// production run's failed steps with NO way to tell whether a capture was
|
|
51
|
+
// ever taken. Set only when `outcome.diagnosticEvidence` was present and
|
|
52
|
+
// `capture` above was not populated for it.
|
|
53
|
+
captureDropped?: { reason: string; bytes?: number };
|
|
54
|
+
}
|
|
55
|
+
interface ParsedCaptureRecord {
|
|
56
|
+
seq: number;
|
|
57
|
+
observedMs: number;
|
|
58
|
+
kind: string;
|
|
59
|
+
data: unknown;
|
|
60
|
+
}
|
|
61
|
+
interface ParsedCaptureWrapper {
|
|
62
|
+
schemaVersion: number;
|
|
63
|
+
sessionId: string;
|
|
64
|
+
attempt: number;
|
|
65
|
+
records: ParsedCaptureRecord[];
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Parses and structurally validates a capture's `redactedJson` as the
|
|
69
|
+
* `{schemaVersion, sessionId, attempt, records: [{seq, observedMs, kind,
|
|
70
|
+
* data}]}` wrapper `OpenCodeEvidenceCollector.snapshot()` produces. Returns
|
|
71
|
+
* `undefined` on a JSON parse failure OR any shape mismatch — both mean the
|
|
72
|
+
* same thing to the caller: this is not a capture whose records can be
|
|
73
|
+
* redacted one at a time, so it must not fall back to redacting whatever
|
|
74
|
+
* WAS parsed as one undifferentiated blob.
|
|
75
|
+
*/
|
|
76
|
+
function parseCaptureWrapper(
|
|
77
|
+
redactedJson: string,
|
|
78
|
+
): ParsedCaptureWrapper | undefined {
|
|
79
|
+
let value: unknown;
|
|
80
|
+
try {
|
|
81
|
+
value = JSON.parse(redactedJson);
|
|
82
|
+
} catch {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
86
|
+
return undefined;
|
|
87
|
+
const v = value as Record<string, unknown>;
|
|
88
|
+
if (
|
|
89
|
+
typeof v.schemaVersion !== "number" ||
|
|
90
|
+
typeof v.sessionId !== "string" ||
|
|
91
|
+
typeof v.attempt !== "number" ||
|
|
92
|
+
!Number.isInteger(v.attempt) ||
|
|
93
|
+
!Array.isArray(v.records)
|
|
94
|
+
)
|
|
95
|
+
return undefined;
|
|
96
|
+
const records: ParsedCaptureRecord[] = [];
|
|
97
|
+
for (const item of v.records) {
|
|
98
|
+
if (typeof item !== "object" || item === null || Array.isArray(item))
|
|
99
|
+
return undefined;
|
|
100
|
+
const r = item as Record<string, unknown>;
|
|
101
|
+
if (
|
|
102
|
+
typeof r.seq !== "number" ||
|
|
103
|
+
typeof r.observedMs !== "number" ||
|
|
104
|
+
typeof r.kind !== "string" ||
|
|
105
|
+
!("data" in r)
|
|
106
|
+
)
|
|
107
|
+
return undefined;
|
|
108
|
+
records.push({
|
|
109
|
+
seq: r.seq,
|
|
110
|
+
observedMs: r.observedMs,
|
|
111
|
+
kind: r.kind,
|
|
112
|
+
data: r.data,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
schemaVersion: v.schemaVersion,
|
|
117
|
+
sessionId: v.sessionId,
|
|
118
|
+
attempt: v.attempt,
|
|
119
|
+
records,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/** Diagnostic control-plane persistence. Failure never changes execution/billing. */
|
|
123
|
+
export async function persistAttemptEvidence(
|
|
124
|
+
step: StepSpec,
|
|
125
|
+
request: TransportRequest,
|
|
126
|
+
execution: {
|
|
127
|
+
outcome?: TransportOutcome;
|
|
128
|
+
receipt: SettlementReceipt;
|
|
129
|
+
delivery?: { delivered: boolean };
|
|
130
|
+
frozenIdentity?: FrozenAttemptIdentity;
|
|
131
|
+
},
|
|
132
|
+
): Promise<void> {
|
|
133
|
+
const file = attemptEvidencePath(step.outPath, step.name, request.attempt);
|
|
134
|
+
const outcome = execution.outcome;
|
|
135
|
+
const evidence: ExecutionAttemptEvidence = {
|
|
136
|
+
schemaVersion: 1,
|
|
137
|
+
sessionId: request.sessionId,
|
|
138
|
+
attempt: request.attempt,
|
|
139
|
+
stepName: step.name,
|
|
140
|
+
identity: {
|
|
141
|
+
route: request.route,
|
|
142
|
+
executionModel: request.executionModel,
|
|
143
|
+
systemPromptSha256: request.systemPromptSha256,
|
|
144
|
+
userPromptSha256: evidenceSha256(request.userPrompt),
|
|
145
|
+
canonicalCwdSha256: evidenceSha256(request.cwd),
|
|
146
|
+
},
|
|
147
|
+
settlement: execution.receipt,
|
|
148
|
+
delivered: execution.delivery?.delivered === true,
|
|
149
|
+
};
|
|
150
|
+
if (outcome)
|
|
151
|
+
evidence.outcome = {
|
|
152
|
+
completion: outcome.completion,
|
|
153
|
+
protocolIntegrity: outcome.protocolIntegrity,
|
|
154
|
+
...(outcome.terminalProof
|
|
155
|
+
? { terminalProof: outcome.terminalProof }
|
|
156
|
+
: {}),
|
|
157
|
+
usage: outcome.usage,
|
|
158
|
+
};
|
|
159
|
+
if (execution.frozenIdentity) {
|
|
160
|
+
const { requestPlan, pendingRequestPlan, ...identity } =
|
|
161
|
+
execution.frozenIdentity;
|
|
162
|
+
Object.assign(evidence.identity, identity);
|
|
163
|
+
// The freeze may return before its plan write finished (see
|
|
164
|
+
// freezeAttemptEvidenceIdentity). By settlement that write is long done,
|
|
165
|
+
// so wait for it here instead of losing the pointer.
|
|
166
|
+
const plan = requestPlan ?? (await pendingRequestPlan);
|
|
167
|
+
if (plan) evidence.requestPlan = plan;
|
|
168
|
+
}
|
|
169
|
+
if (evidence.delivered) {
|
|
170
|
+
evidence.outputSha256 = evidenceSha256(await readFile(step.outPath));
|
|
171
|
+
evidence.outputPath = path.basename(step.outPath);
|
|
172
|
+
}
|
|
173
|
+
const capture = outcome?.diagnosticEvidence;
|
|
174
|
+
if (capture) {
|
|
175
|
+
const captureBytes = Buffer.byteLength(capture.redactedJson);
|
|
176
|
+
if (captureBytes > 4 * 1024 * 1024) {
|
|
177
|
+
evidence.captureDropped = {
|
|
178
|
+
reason: "capture exceeds the 4 MiB persist cap",
|
|
179
|
+
bytes: captureBytes,
|
|
180
|
+
};
|
|
181
|
+
} else if (!/^pr-hero\.[a-z0-9.-]+$/.test(capture.schema)) {
|
|
182
|
+
evidence.captureDropped = {
|
|
183
|
+
reason: `capture schema "${capture.schema}" is not recognized`,
|
|
184
|
+
bytes: captureBytes,
|
|
185
|
+
};
|
|
186
|
+
} else {
|
|
187
|
+
// WHY per-record, not whole-blob: `redactEvidence()` bounds its
|
|
188
|
+
// traversal to one shared 20000-node / depth-12 budget
|
|
189
|
+
// (src/security/evidence-redaction.ts:35-38). Redacting the entire
|
|
190
|
+
// parsed capture in ONE call spends that whole budget across every
|
|
191
|
+
// record combined, and a real multi-minute hunter stream's capture
|
|
192
|
+
// has thousands of them — the budget blew every time, throwing
|
|
193
|
+
// "capture shape limit" for every real production capture, not just
|
|
194
|
+
// pathological ones. `OpenCodeEvidenceCollector.record()` already
|
|
195
|
+
// redacts each record's `data` individually at record time, each
|
|
196
|
+
// call getting its OWN fresh budget; redacting per record here again,
|
|
197
|
+
// instead of once for the whole blob, keeps exactly that same
|
|
198
|
+
// per-record bound rather than a shared one a few thousand records
|
|
199
|
+
// exhausts together. Raising the shared budget instead would weaken
|
|
200
|
+
// it for every OTHER caller of `redactEvidence`, so that decision is
|
|
201
|
+
// left to a human call — this function works within the existing
|
|
202
|
+
// bound rather than asking for a wider one.
|
|
203
|
+
const wrapper = parseCaptureWrapper(capture.redactedJson);
|
|
204
|
+
if (!wrapper) {
|
|
205
|
+
evidence.captureDropped = {
|
|
206
|
+
reason: "capture wrapper shape is not recognized",
|
|
207
|
+
bytes: captureBytes,
|
|
208
|
+
};
|
|
209
|
+
} else {
|
|
210
|
+
try {
|
|
211
|
+
const safe = {
|
|
212
|
+
schemaVersion: wrapper.schemaVersion,
|
|
213
|
+
sessionId: wrapper.sessionId,
|
|
214
|
+
attempt: wrapper.attempt,
|
|
215
|
+
records: wrapper.records.map((r) => ({
|
|
216
|
+
seq: r.seq,
|
|
217
|
+
observedMs: r.observedMs,
|
|
218
|
+
kind: redactEvidenceText(r.kind),
|
|
219
|
+
data: redactEvidence(r.data),
|
|
220
|
+
})),
|
|
221
|
+
};
|
|
222
|
+
// PR #228 review, F003: `writeJsonAtomically` used to
|
|
223
|
+
// pretty-print unconditionally, so a capture whose ORIGINAL
|
|
224
|
+
// (compact) `redactedJson` sat just under the 4 MiB check above
|
|
225
|
+
// could still land ~20-30% larger on disk once indentation and
|
|
226
|
+
// newlines were added — close enough to `readEvidenceFile`'s
|
|
227
|
+
// separate 5 MiB read bound (attempt-evidence.ts) that a live
|
|
228
|
+
// capture was observed persisted at 4.9 MB. Serialized here
|
|
229
|
+
// once, compact, and checked as THIS exact string — not the
|
|
230
|
+
// pre-redaction estimate above, since redaction can itself grow
|
|
231
|
+
// or shrink a record's size — so the file is never written
|
|
232
|
+
// unless the exact bytes about to hit disk already fit, and the
|
|
233
|
+
// persisted size always equals the checked size.
|
|
234
|
+
const compactRedacted = JSON.stringify(safe);
|
|
235
|
+
const redactedBytes = Buffer.byteLength(compactRedacted);
|
|
236
|
+
if (redactedBytes > 4 * 1024 * 1024) {
|
|
237
|
+
evidence.captureDropped = {
|
|
238
|
+
reason: "capture exceeds the 4 MiB persist cap",
|
|
239
|
+
bytes: redactedBytes,
|
|
240
|
+
};
|
|
241
|
+
} else {
|
|
242
|
+
const captureFile = file.replace(/\.json$/, ".capture.json");
|
|
243
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
244
|
+
await writeJsonAtomically(captureFile, safe, { compact: true });
|
|
245
|
+
const bytes = await readFile(captureFile);
|
|
246
|
+
evidence.capture = {
|
|
247
|
+
schema: capture.schema,
|
|
248
|
+
status: capture.status,
|
|
249
|
+
sha256: evidenceSha256(bytes),
|
|
250
|
+
relativePath: path.basename(captureFile),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
} catch (error) {
|
|
254
|
+
// Qualification requires an actual usable capture, but a capture
|
|
255
|
+
// that WAS produced and then lost to a redaction or write failure
|
|
256
|
+
// is still a diagnostic loss worth recording, never a silent
|
|
257
|
+
// no-op.
|
|
258
|
+
evidence.captureDropped = {
|
|
259
|
+
reason:
|
|
260
|
+
error instanceof Error
|
|
261
|
+
? `capture persist failed: ${error.message}`
|
|
262
|
+
: "capture persist failed",
|
|
263
|
+
bytes: captureBytes,
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
270
|
+
await writeJsonAtomically(file, redactEvidence(evidence));
|
|
271
|
+
}
|
|
272
|
+
/** Untrusted artifact references cannot read outside their owned run root. */
|
|
273
|
+
export async function readEvidenceFile(
|
|
274
|
+
root: string,
|
|
275
|
+
relative: string,
|
|
276
|
+
maxBytes = 5 * 1024 * 1024,
|
|
277
|
+
parseJson = true,
|
|
278
|
+
): Promise<{ bytes: Uint8Array; value: unknown }> {
|
|
279
|
+
if (path.isAbsolute(relative) || relative.split(/[\\/]/).includes(".."))
|
|
280
|
+
throw new Error("unsafe evidence path");
|
|
281
|
+
const base = await realpath(root);
|
|
282
|
+
const file = await realpath(path.resolve(root, relative));
|
|
283
|
+
if (!file.startsWith(`${base}${path.sep}`))
|
|
284
|
+
throw new Error("evidence escapes run root");
|
|
285
|
+
const handle = await import("node:fs/promises").then((fs) =>
|
|
286
|
+
fs.open(
|
|
287
|
+
file,
|
|
288
|
+
constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW,
|
|
289
|
+
),
|
|
290
|
+
);
|
|
291
|
+
try {
|
|
292
|
+
const metadata = await handle.stat();
|
|
293
|
+
if (!metadata.isFile()) throw new Error("evidence is not a regular file");
|
|
294
|
+
if (metadata.size > maxBytes) throw new Error("evidence exceeds bound");
|
|
295
|
+
const bytes = Buffer.alloc(maxBytes + 1);
|
|
296
|
+
const { bytesRead } = await handle.read(bytes, 0, maxBytes + 1, 0);
|
|
297
|
+
if (bytesRead > maxBytes) throw new Error("evidence exceeds bound");
|
|
298
|
+
const bounded = bytes.subarray(0, bytesRead);
|
|
299
|
+
return {
|
|
300
|
+
bytes: bounded,
|
|
301
|
+
value: parseJson ? JSON.parse(bounded.toString("utf8")) : undefined,
|
|
302
|
+
};
|
|
303
|
+
} finally {
|
|
304
|
+
await handle.close();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export interface FrozenAttemptIdentity {
|
|
309
|
+
toolsConfigSha256?: string;
|
|
310
|
+
executableSha256?: string;
|
|
311
|
+
requestPlan?: { relativePath: string; sha256: string };
|
|
312
|
+
/** The plan write when it outlived the freeze timer; never rejects. */
|
|
313
|
+
pendingRequestPlan?: Promise<
|
|
314
|
+
{ relativePath: string; sha256: string } | undefined
|
|
315
|
+
>;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export async function freezeAttemptEvidenceIdentity(
|
|
319
|
+
request: TransportRequest,
|
|
320
|
+
step: StepSpec,
|
|
321
|
+
): Promise<FrozenAttemptIdentity> {
|
|
322
|
+
const frozen: {
|
|
323
|
+
toolsConfigSha256?: string;
|
|
324
|
+
executableSha256?: string;
|
|
325
|
+
requestPlan?: { relativePath: string; sha256: string };
|
|
326
|
+
} = {};
|
|
327
|
+
try {
|
|
328
|
+
frozen.toolsConfigSha256 = evidenceSha256(
|
|
329
|
+
JSON.stringify({
|
|
330
|
+
tools: request.tools,
|
|
331
|
+
mcp: request.mcpConfigPath
|
|
332
|
+
? await readFile(request.mcpConfigPath, {
|
|
333
|
+
encoding: "utf8",
|
|
334
|
+
signal: AbortSignal.timeout(100),
|
|
335
|
+
})
|
|
336
|
+
: null,
|
|
337
|
+
}),
|
|
338
|
+
);
|
|
339
|
+
} catch {}
|
|
340
|
+
try {
|
|
341
|
+
frozen.executableSha256 = evidenceSha256(
|
|
342
|
+
await readFile(request.isolation.verifiedBinaryPath, {
|
|
343
|
+
signal: AbortSignal.timeout(100),
|
|
344
|
+
}),
|
|
345
|
+
);
|
|
346
|
+
} catch {}
|
|
347
|
+
const file = attemptEvidencePath(
|
|
348
|
+
step.outPath,
|
|
349
|
+
step.name,
|
|
350
|
+
request.attempt,
|
|
351
|
+
).replace(/\.json$/, ".request.json");
|
|
352
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
353
|
+
// The timer keeps the spawn from waiting on disk I/O, but losing the race
|
|
354
|
+
// must not lose the pointer: parallel steps hash the ~274 MB claude binary
|
|
355
|
+
// synchronously, and one step's hash can block the event loop past another
|
|
356
|
+
// step's timer (Martian dev-default arm, 2026-10-25: every run quarantined
|
|
357
|
+
// as "missing frozen request plan" with each plan file on disk). The write
|
|
358
|
+
// keeps going and persistAttemptEvidence awaits it at settlement.
|
|
359
|
+
const planWrite = (async () => {
|
|
360
|
+
const plan = {
|
|
361
|
+
schemaVersion: 1,
|
|
362
|
+
sessionId: request.sessionId,
|
|
363
|
+
attempt: request.attempt,
|
|
364
|
+
stepName: step.name,
|
|
365
|
+
route: request.route,
|
|
366
|
+
systemPromptSha256: request.systemPromptSha256,
|
|
367
|
+
userPromptSha256: evidenceSha256(request.userPrompt),
|
|
368
|
+
systemPromptPath: path.relative(
|
|
369
|
+
path.dirname(file),
|
|
370
|
+
step.systemPromptPath,
|
|
371
|
+
),
|
|
372
|
+
// #299: the NAMES behind `toolsConfigSha256`. The hash can only
|
|
373
|
+
// confirm a list someone already has; when a hunter returned a clean
|
|
374
|
+
// bill without opening the code, the first question is whether it
|
|
375
|
+
// was ever offered tools, and a digest cannot answer it. Additive:
|
|
376
|
+
// the hash stays, and the plan's readers compare fields by name.
|
|
377
|
+
toolNames: [...request.tools],
|
|
378
|
+
// #299: the effort the engine REQUESTED, and whether this backend
|
|
379
|
+
// could apply it. The CLI's implicit default (medium on the 5.5
|
|
380
|
+
// family) is what the artifacts could not show before. OpenCode has
|
|
381
|
+
// no `--effort`, so there the level is intent only, and
|
|
382
|
+
// `effortApplied: false` keeps a reader from taking it as a fact
|
|
383
|
+
// about the run. Additive, and deliberately NOT in `identity` or the
|
|
384
|
+
// route fingerprint: those are compared across runs by the lab.
|
|
385
|
+
effort: request.effort,
|
|
386
|
+
effortApplied: request.route.backend === "claude-code",
|
|
387
|
+
...frozen,
|
|
388
|
+
};
|
|
389
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
390
|
+
await writeJsonAtomically(file, plan);
|
|
391
|
+
frozen.requestPlan = {
|
|
392
|
+
relativePath: path.basename(file),
|
|
393
|
+
sha256: evidenceSha256(await readFile(file)),
|
|
394
|
+
};
|
|
395
|
+
})();
|
|
396
|
+
try {
|
|
397
|
+
await Promise.race([
|
|
398
|
+
planWrite,
|
|
399
|
+
new Promise<void>((resolve) => {
|
|
400
|
+
timer = setTimeout(resolve, Math.min(100, Math.max(1, step.timeoutMs)));
|
|
401
|
+
}),
|
|
402
|
+
]);
|
|
403
|
+
} catch {
|
|
404
|
+
} finally {
|
|
405
|
+
clearTimeout(timer);
|
|
406
|
+
}
|
|
407
|
+
if (frozen.requestPlan) return { ...frozen };
|
|
408
|
+
return {
|
|
409
|
+
...frozen,
|
|
410
|
+
pendingRequestPlan: planWrite.then(
|
|
411
|
+
() => frozen.requestPlan,
|
|
412
|
+
() => undefined,
|
|
413
|
+
),
|
|
414
|
+
};
|
|
415
|
+
}
|