crysk 0.0.0 → 0.3.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/LICENSE +176 -0
- package/README.md +611 -3
- 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/SKILL-y8rv8msh.md +134 -0
- package/dist/SKILL-ygka1bs0.md +515 -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/ci-admission-qk9r9taq.md +124 -0
- package/dist/cli.js +42501 -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 +81 -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 +124 -0
- package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
- package/skills/crysk-loop/SKILL.md +515 -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 +945 -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 +910 -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 +984 -0
- package/src/pr/answered-findings.ts +169 -0
- package/src/pr/ci-admission-gate.ts +743 -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 +845 -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/ci/setup.ts
ADDED
|
@@ -0,0 +1,844 @@
|
|
|
1
|
+
// Pillar 3 Phase 4 (ROADMAP THE LAUNCH LINE): CI workflow scaffolding.
|
|
2
|
+
//
|
|
3
|
+
// generateCiWorkflowTemplate is PURE — a string builder with zero filesystem
|
|
4
|
+
// access, so its exact bytes are testable without touching disk (the "pure
|
|
5
|
+
// decisions pure, I/O in the shell" rule from CLAUDE.md). runCiSetup is the
|
|
6
|
+
// one impure edge in this module: it resolves the target path under the
|
|
7
|
+
// caller's repo, refuses to clobber a user's customized workflow without
|
|
8
|
+
// --force (a safety property, not a nicety — see spec.md §4.1), and writes
|
|
9
|
+
// the template.
|
|
10
|
+
//
|
|
11
|
+
// This module writes `.github/workflows/crysk.yml` into WHATEVER repo the
|
|
12
|
+
// caller points it at (via `crysk setup --ci` / `crysk ci init`); a repo that
|
|
13
|
+
// already has the pre-rename `pr-hero.yml` keeps that file, updated in place.
|
|
14
|
+
// Pillar 3 Phase 5 (tasks.md 5.2) reuses this SAME function to produce this
|
|
15
|
+
// repo's own canonical example workflow (which stays at `pr-hero.yml`: this
|
|
16
|
+
// repo is the existing-repo case), rather than
|
|
17
|
+
// hand-authoring a second copy that could silently drift from what every
|
|
18
|
+
// caller of `setup --ci` actually gets — test/packaging.test.ts asserts the
|
|
19
|
+
// committed file's bytes equal generateCiWorkflowTemplate()'s output exactly.
|
|
20
|
+
//
|
|
21
|
+
// That one file is the whole install. It reviews every push and answers a
|
|
22
|
+
// `/crysk review` pull request comment, which used to need a second,
|
|
23
|
+
// dispatch-only `pr-hero-force.yml`. The action now owns everything the
|
|
24
|
+
// workflow used to wire around it: credential detection, the comment's
|
|
25
|
+
// parsing and the commenter's permission check, the pull request and head
|
|
26
|
+
// resolution, and the run-directory upload. runCiSetup no longer writes a
|
|
27
|
+
// force workflow, and it leaves an existing one alone: the skip comment still
|
|
28
|
+
// names it for repos scaffolded before the comment trigger, and the action
|
|
29
|
+
// keeps the inputs it sets.
|
|
30
|
+
|
|
31
|
+
import { existsSync } from "node:fs";
|
|
32
|
+
import {
|
|
33
|
+
chmod,
|
|
34
|
+
mkdir,
|
|
35
|
+
readFile,
|
|
36
|
+
rename,
|
|
37
|
+
rm,
|
|
38
|
+
writeFile,
|
|
39
|
+
} from "node:fs/promises";
|
|
40
|
+
import path from "node:path";
|
|
41
|
+
import type { ErrorClass, SetupRecord } from "#ci/outcome";
|
|
42
|
+
import type { ConfigPlan } from "#ci/review-levels";
|
|
43
|
+
import {
|
|
44
|
+
OVERRIDE_COMMAND,
|
|
45
|
+
RECHECK_COMMAND,
|
|
46
|
+
REVIEW_COMMAND,
|
|
47
|
+
recordTempPath,
|
|
48
|
+
} from "#ci/trigger";
|
|
49
|
+
import { parseLocalConfig, parseRoutingConfig } from "#review/preflight";
|
|
50
|
+
import { commandForms } from "../brand";
|
|
51
|
+
import {
|
|
52
|
+
duplicateWorkflowProblem,
|
|
53
|
+
LEGACY_WORKFLOW_RELATIVE_PATH,
|
|
54
|
+
resolveIgnoreFileName,
|
|
55
|
+
resolveRepoDir,
|
|
56
|
+
resolveWorkflowRelativePath,
|
|
57
|
+
WORKFLOW_RELATIVE_PATH,
|
|
58
|
+
} from "../brand-paths";
|
|
59
|
+
import { CliError } from "../errors";
|
|
60
|
+
import { prheroLayout } from "../home-preflight";
|
|
61
|
+
import { parseIgnoreFile } from "../ignore-file";
|
|
62
|
+
import { resolveOpenCodeAuthPath } from "../security/credential-broker";
|
|
63
|
+
|
|
64
|
+
// The file a repo with no workflow yet gets. A repo that already has the
|
|
65
|
+
// pre-rename `pr-hero.yml` keeps it: use resolveWorkflowRelativePath to find the
|
|
66
|
+
// file to act on, and LEGACY_CI_WORKFLOW_RELATIVE_PATH to name that one.
|
|
67
|
+
export const CI_WORKFLOW_RELATIVE_PATH = WORKFLOW_RELATIVE_PATH;
|
|
68
|
+
export const LEGACY_CI_WORKFLOW_RELATIVE_PATH = LEGACY_WORKFLOW_RELATIVE_PATH;
|
|
69
|
+
|
|
70
|
+
// The action reference the generated workflow resolves. A consumer repo has
|
|
71
|
+
// no copy of this action, so it must go through the published tag — that is
|
|
72
|
+
// the default. This repo generates its OWN workflow with `./`, because the
|
|
73
|
+
// source is right there in the tree and pointing at a tag that is not
|
|
74
|
+
// published yet would paint every PR here permanently red. A red check that
|
|
75
|
+
// can never go green is strictly worse than no check: it teaches the team to
|
|
76
|
+
// stop reading CI, which is the exact failure this pillar exists to prevent.
|
|
77
|
+
// `./` is also the only form that tests the action being changed by the very
|
|
78
|
+
// PR that changes it.
|
|
79
|
+
export interface CiWorkflowTemplateOptions {
|
|
80
|
+
actionRef?: string;
|
|
81
|
+
// Repo-local override for the action's own `budget-usd` default. Omitted
|
|
82
|
+
// means "say nothing and inherit the action's default", which is what every
|
|
83
|
+
// scaffolded repo gets: raising a stranger's spend ceiling from a template
|
|
84
|
+
// they did not choose is not ours to do.
|
|
85
|
+
//
|
|
86
|
+
// Since issue #156 that inherited default is a POLICY, not a number:
|
|
87
|
+
// action.yml's `budget-usd` default is empty, and the CLI resolves the
|
|
88
|
+
// ceiling from the route's billing mode (ci/gates.ts's
|
|
89
|
+
// `resolveCiBudgetCeiling`) — no ceiling on a Claude subscription, a default
|
|
90
|
+
// ceiling on a metered ANTHROPIC_API_KEY route. Inheriting is therefore
|
|
91
|
+
// strictly better than it was: a scaffolded repo now gets a ceiling exactly
|
|
92
|
+
// when a ceiling means something.
|
|
93
|
+
//
|
|
94
|
+
// NOTHING sets this today, this repo included — see OWN_CI_WORKFLOW_OPTIONS
|
|
95
|
+
// for why the one override that existed went away. The knob stays because a
|
|
96
|
+
// repo that genuinely wants a fixed ceiling on a subscription route needs a
|
|
97
|
+
// way to say so, and that is the only thing an explicit value now means.
|
|
98
|
+
budgetUsd?: string;
|
|
99
|
+
// Repo-local override for the action's own `max-changed-lines` default, and
|
|
100
|
+
// omitted for the same reason as `budgetUsd`: a scaffolded repo inherits
|
|
101
|
+
// the route-derived limit (none on a subscription, 4000 on a metered key;
|
|
102
|
+
// resolveCiSizeLimits) and decides for itself. THIS repo raises it because its
|
|
103
|
+
// own slices routinely land near the line — D1-10c was skipped at 1023,
|
|
104
|
+
// twenty-three lines over, and a skipped review is indistinguishable from a
|
|
105
|
+
// clean one to anyone reading the checks.
|
|
106
|
+
//
|
|
107
|
+
// Raising it costs little and risks little HERE. It is a COST gate, never a
|
|
108
|
+
// quality one — the size<->quality question is unmeasured in this project
|
|
109
|
+
// (`scripts/scope-probe.ts`), so this number is not a claim that pr-hero
|
|
110
|
+
// reviews a 1500-line diff as well as a 300-line one.
|
|
111
|
+
//
|
|
112
|
+
// Since issue #156 it is also the ONLY gate bounding a self-review's scope
|
|
113
|
+
// here, which is what the number has to be read against: this comment used
|
|
114
|
+
// to lean on `budget-usd` as "the real spend ceiling, which still refuses
|
|
115
|
+
// the work outright". On this repo's subscription route it never was — it
|
|
116
|
+
// gated `estimate.high`, a token-derived figure, against $0.00 of real
|
|
117
|
+
// cash.
|
|
118
|
+
maxChangedLines?: string;
|
|
119
|
+
// The files half of the size gate, emitted right after the lines input.
|
|
120
|
+
maxChangedFiles?: string;
|
|
121
|
+
// THIS repo only: on a `/crysk review` comment, the workflow resolves
|
|
122
|
+
// the pull request's head commit BEFORE checkout and checks out exactly
|
|
123
|
+
// that commit, so `uses: ./` runs the engine under review. A comment run
|
|
124
|
+
// starts on the default branch, and without the pin it runs THAT branch's
|
|
125
|
+
// engine: on #305 (then a `workflow_dispatch` force run, which starts there
|
|
126
|
+
// too) main lagged dev, a stale engine posted a hollow review on the PR
|
|
127
|
+
// head, and its complete summary marker made every later run on that head
|
|
128
|
+
// skip discovery. The head sha, not `refs/pull/<n>/merge`: the merge ref is
|
|
129
|
+
// missing on a conflicted PR and moves with the base. A `pull_request` run
|
|
130
|
+
// already checks out the pull request, so the pin applies to comments only.
|
|
131
|
+
//
|
|
132
|
+
// Its own flag, never inferred from `actionRef === "./"`: a consumer
|
|
133
|
+
// template runs a published tag, where the checkout selects no engine, and
|
|
134
|
+
// the scaffolded output must not change shape because of a ref string.
|
|
135
|
+
forceEngineFromPr?: boolean;
|
|
136
|
+
// S4: the action's `mode` input. Always written (default `gate`), so the
|
|
137
|
+
// scaffolded file names the gate and does not inherit it silently. `advisory`
|
|
138
|
+
// keeps the status green whatever the review finds, as before S4.
|
|
139
|
+
mode?: "gate" | "advisory";
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export const DEFAULT_CI_ACTION_REF = "cryskai/crysk@v0";
|
|
143
|
+
|
|
144
|
+
// The options THIS repo generates its OWN workflow with. One exported source
|
|
145
|
+
// of truth rather than three hand-copied literals: the byte-equality drift
|
|
146
|
+
// tests and every regeneration read the same object, so a change here cannot
|
|
147
|
+
// leave the committed workflow and the tests disagreeing about what "ours"
|
|
148
|
+
// means. Nothing a scaffolded repo receives passes through here.
|
|
149
|
+
//
|
|
150
|
+
// `budgetUsd` is "0": the explicit, loud DISABLE, not a ceiling. History:
|
|
151
|
+
// it used to be "15.00", because a self-review's diff grows against the base
|
|
152
|
+
// every time a finding is answered, so an iterating PR walked toward the
|
|
153
|
+
// ceiling exactly when the check mattered most. Issue #156 dropped it on the
|
|
154
|
+
// promise that the route's billing mode would apply no ceiling on this repo's
|
|
155
|
+
// Claude subscription. That promise did not hold here: the route resolved as
|
|
156
|
+
// metered, and #326 (and earlier PRs) skipped at the $10 metered default on
|
|
157
|
+
// an `estimate.high` that is not this route's cash cost. A subscription has
|
|
158
|
+
// no dollar cost to cap, so this repo opts out explicitly; fixing the
|
|
159
|
+
// billing-mode resolution itself is a separate issue. `maxChangedLines`
|
|
160
|
+
// stays: that gate is real on any route.
|
|
161
|
+
export const OWN_CI_WORKFLOW_OPTIONS: CiWorkflowTemplateOptions = {
|
|
162
|
+
actionRef: "./",
|
|
163
|
+
maxChangedLines: "5000",
|
|
164
|
+
budgetUsd: "0",
|
|
165
|
+
mode: "gate",
|
|
166
|
+
forceEngineFromPr: true,
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
export function generateCiWorkflowTemplate(
|
|
170
|
+
options: CiWorkflowTemplateOptions = {},
|
|
171
|
+
): string {
|
|
172
|
+
const actionRef = options.actionRef ?? DEFAULT_CI_ACTION_REF;
|
|
173
|
+
const pinEngine = options.forceEngineFromPr === true;
|
|
174
|
+
const budgetLine =
|
|
175
|
+
options.budgetUsd === undefined
|
|
176
|
+
? ""
|
|
177
|
+
: `\n budget-usd: ${options.budgetUsd}`;
|
|
178
|
+
// Emitted before `budget-usd` to mirror action.yml's own declaration order,
|
|
179
|
+
// so the generated file reads in the same sequence as the inputs it sets.
|
|
180
|
+
const sizeGateLine =
|
|
181
|
+
options.maxChangedLines === undefined
|
|
182
|
+
? ""
|
|
183
|
+
: `\n max-changed-lines: ${options.maxChangedLines}`;
|
|
184
|
+
const filesGateLine =
|
|
185
|
+
options.maxChangedFiles === undefined
|
|
186
|
+
? ""
|
|
187
|
+
: `\n max-changed-files: ${options.maxChangedFiles}`;
|
|
188
|
+
// S4: always written, never inherited. The gate is what makes a scaffolded
|
|
189
|
+
// repo's pr-hero check red, so the file names it instead of relying on the
|
|
190
|
+
// action's default, and a reader sees the consequence where they edit.
|
|
191
|
+
const modeLine = `\n mode: ${options.mode ?? "gate"}`;
|
|
192
|
+
// Pinned, the sha is what checkout lands on, so the fork verdict and the
|
|
193
|
+
// sha come from ONE read: two reads could straddle a push and describe two
|
|
194
|
+
// different heads. An assignment, not a here-string into `read`, so a
|
|
195
|
+
// failing `gh` fails the step under `bash -e` instead of reading as a fork.
|
|
196
|
+
const gateStep = pinEngine
|
|
197
|
+
? ` # THIS repo only. A comment run starts on the default branch, and
|
|
198
|
+
# \`uses: ./\` runs whatever engine is checked out, so without this step
|
|
199
|
+
# a comment-forced review runs the default branch's engine, not the
|
|
200
|
+
# engine under review: on #305 main lagged dev, a stale engine posted a
|
|
201
|
+
# hollow review, and its complete summary marker made every later run
|
|
202
|
+
# on that head skip discovery. The gate resolves the pull request's
|
|
203
|
+
# head and checkout pins exactly that commit. The head sha, not
|
|
204
|
+
# refs/pull/<n>/merge: the merge ref is missing on a conflicted pull
|
|
205
|
+
# request and moves with the base.
|
|
206
|
+
#
|
|
207
|
+
# A fork is refused HERE, although the scaffolded workflow reviews one
|
|
208
|
+
# on a maintainer's comment: with \`uses: ./\` the checked-out fork would
|
|
209
|
+
# supply the engine itself, and run it with this repository's secrets.
|
|
210
|
+
#
|
|
211
|
+
# The commenter's write access is checked HERE too, first, although
|
|
212
|
+
# action.yml checks it again. With \`uses: ./\` the action.yml that runs
|
|
213
|
+
# is the checked-out head's own, so a same-repo head that predates that
|
|
214
|
+
# check (an old bot branch) would let anyone who can comment start a
|
|
215
|
+
# review with this repository's secrets. This step is the only code that
|
|
216
|
+
# runs before the head does. It fails closed: nothing but admin or write
|
|
217
|
+
# proceeds. A 404 (GitHub's answer for a non-collaborator) or an answer
|
|
218
|
+
# that is not admin or write refuses quietly with a notice, exit 0.
|
|
219
|
+
# Any other lookup failure (a 5xx,
|
|
220
|
+
# a rate limit, a timeout) says nothing about the commenter, so it is
|
|
221
|
+
# retried once and then fails the job red: a quiet refusal would show a
|
|
222
|
+
# maintainer whose command met a GitHub hiccup the same notice a
|
|
223
|
+
# stranger gets, on a default-branch run nobody sees from the PR.
|
|
224
|
+
- name: Resolve the pull request head
|
|
225
|
+
id: gate
|
|
226
|
+
if: github.event_name == 'issue_comment'
|
|
227
|
+
env:
|
|
228
|
+
PR: \${{ github.event.issue.number }}
|
|
229
|
+
COMMENTER: \${{ github.event.comment.user.login }}
|
|
230
|
+
GH_TOKEN: \${{ secrets.GITHUB_TOKEN }}
|
|
231
|
+
run: |
|
|
232
|
+
gh_err=$(mktemp)
|
|
233
|
+
trap 'rm -f "$gh_err"' EXIT
|
|
234
|
+
for attempt in 1 2; do
|
|
235
|
+
if permission=$(gh api "repos/$GITHUB_REPOSITORY/collaborators/$COMMENTER/permission" --jq .permission 2>"$gh_err"); then
|
|
236
|
+
break
|
|
237
|
+
fi
|
|
238
|
+
permission=""
|
|
239
|
+
case "$(<"$gh_err")" in
|
|
240
|
+
*"HTTP 404"*) break ;;
|
|
241
|
+
esac
|
|
242
|
+
if [ "$attempt" = 2 ]; then
|
|
243
|
+
echo "::error title=crysk::could not verify the commenter's write access: the GitHub API call failed twice, so nothing was reviewed or overridden. Comment /crysk review, /crysk recheck or /crysk override again to retry"
|
|
244
|
+
exit 1
|
|
245
|
+
fi
|
|
246
|
+
sleep 2
|
|
247
|
+
done
|
|
248
|
+
case "$permission" in
|
|
249
|
+
admin|write) ;;
|
|
250
|
+
*)
|
|
251
|
+
echo "::notice title=crysk::only users with write access to this repository can run /crysk review, /crysk recheck or /crysk override"
|
|
252
|
+
echo "proceed=false" >> "$GITHUB_OUTPUT"
|
|
253
|
+
exit 0
|
|
254
|
+
;;
|
|
255
|
+
esac
|
|
256
|
+
case "$PR" in
|
|
257
|
+
''|*[!0-9]*)
|
|
258
|
+
echo "::error title=crysk::pr must be a positive integer"
|
|
259
|
+
exit 1
|
|
260
|
+
;;
|
|
261
|
+
esac
|
|
262
|
+
# One read: the fork verdict and the commit checked out next must
|
|
263
|
+
# describe the same head, even if the branch moves in between.
|
|
264
|
+
pr_head=$(gh pr view "$PR" --repo "$GITHUB_REPOSITORY" --json headRepository,headRefOid --jq '.headRepository.nameWithOwner + " " + .headRefOid')
|
|
265
|
+
head_repo=\${pr_head% *}
|
|
266
|
+
sha=\${pr_head##* }
|
|
267
|
+
if [ "$head_repo" != "$GITHUB_REPOSITORY" ]; then
|
|
268
|
+
echo "::notice title=crysk::fork pull requests are not reviewed here: uses ./ would run the fork's own engine with this repository's secrets"
|
|
269
|
+
echo "proceed=false" >> "$GITHUB_OUTPUT"
|
|
270
|
+
exit 0
|
|
271
|
+
fi
|
|
272
|
+
# Only a full commit sha may reach checkout: an empty ref makes
|
|
273
|
+
# actions/checkout fall back to the default branch, which is the
|
|
274
|
+
# engine this pin exists to avoid, and any other value would be
|
|
275
|
+
# resolved as a ref name.
|
|
276
|
+
if [[ ! "$sha" =~ ^[0-9a-f]{40}$ ]]; then
|
|
277
|
+
echo "::error title=crysk::could not resolve the pull request head commit"
|
|
278
|
+
exit 1
|
|
279
|
+
fi
|
|
280
|
+
echo "proceed=true" >> "$GITHUB_OUTPUT"
|
|
281
|
+
echo "sha=$sha" >> "$GITHUB_OUTPUT"
|
|
282
|
+
|
|
283
|
+
`
|
|
284
|
+
: "";
|
|
285
|
+
// One clause per command and per name, new name first: an Actions expression
|
|
286
|
+
// has no regex, so the legacy /pr-hero forms are listed beside /crysk ones.
|
|
287
|
+
const commandBodies = [
|
|
288
|
+
REVIEW_COMMAND,
|
|
289
|
+
RECHECK_COMMAND,
|
|
290
|
+
OVERRIDE_COMMAND,
|
|
291
|
+
].flatMap(commandForms);
|
|
292
|
+
const newNamesFirst = [
|
|
293
|
+
...commandBodies.filter((c) => c.startsWith("/crysk")),
|
|
294
|
+
...commandBodies.filter((c) => !c.startsWith("/crysk")),
|
|
295
|
+
];
|
|
296
|
+
const ifCommentClauses = newNamesFirst
|
|
297
|
+
.map(
|
|
298
|
+
(c) =>
|
|
299
|
+
`(github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '${c}'))`,
|
|
300
|
+
)
|
|
301
|
+
.join(" ||\n ");
|
|
302
|
+
const groupCommentClauses = newNamesFirst
|
|
303
|
+
.map(
|
|
304
|
+
(c) =>
|
|
305
|
+
`(startsWith(github.event.comment.body, '${c}') && contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.comment.author_association))`,
|
|
306
|
+
)
|
|
307
|
+
.join(" || ");
|
|
308
|
+
const proceedIf =
|
|
309
|
+
"github.event_name != 'issue_comment' || steps.gate.outputs.proceed == 'true'";
|
|
310
|
+
const checkoutGate = pinEngine ? `\n if: ${proceedIf}` : "";
|
|
311
|
+
const checkoutRef = pinEngine
|
|
312
|
+
? `
|
|
313
|
+
# The gate's head sha on a comment. On pull_request the gate is
|
|
314
|
+
# skipped, its output is empty, and an empty ref keeps checkout on
|
|
315
|
+
# that event's own ref.
|
|
316
|
+
ref: \${{ steps.gate.outputs.sha }}`
|
|
317
|
+
: "";
|
|
318
|
+
const runStepGate = pinEngine ? `\n if: ${proceedIf}` : "";
|
|
319
|
+
return `# Generated by \`crysk setup --ci\` (or \`crysk ci init\`).
|
|
320
|
+
# Customize freely — re-running setup will not overwrite this file again
|
|
321
|
+
# unless you pass --force.
|
|
322
|
+
#
|
|
323
|
+
# This one file is the whole install. It reviews every push to a pull
|
|
324
|
+
# request. A pull request comment that is exactly \`/crysk review\` runs the
|
|
325
|
+
# review again with the skip gates bypassed, and \`/crysk review --full\`
|
|
326
|
+
# also re-discovers the whole range. A comment that is exactly
|
|
327
|
+
# \`/crysk override\` turns the gate green on that head with no review and
|
|
328
|
+
# no cost, and records who did it. A comment that is exactly
|
|
329
|
+
# \`/crysk recheck\` reviews the head and asks the CI adjudicator to rule on
|
|
330
|
+
# pending dismissals of blocking findings. The action parses the comment and
|
|
331
|
+
# refuses a commenter without write access. The older \`/pr-hero ...\` forms
|
|
332
|
+
# of these commands still work for one version.
|
|
333
|
+
name: Crysk Review
|
|
334
|
+
|
|
335
|
+
on:
|
|
336
|
+
pull_request:
|
|
337
|
+
types: [opened, synchronize, reopened]
|
|
338
|
+
# GitHub runs a comment-triggered workflow from the DEFAULT branch's copy
|
|
339
|
+
# of this file, never the pull request's. The comment trigger works only
|
|
340
|
+
# once this file is merged there; until then a comment starts nothing.
|
|
341
|
+
issue_comment:
|
|
342
|
+
types: [created]
|
|
343
|
+
|
|
344
|
+
# pull-requests: write lets Crysk post inline comments and a step summary.
|
|
345
|
+
# contents: read is enough for actions/checkout. issues: write lets it
|
|
346
|
+
# resolve/reply on review threads (GitHub models PR conversations as issues).
|
|
347
|
+
# checks: write persists the durable CI admission attempt ledger (WU-02).
|
|
348
|
+
# actions: read lets the admission gate list this workflow's past runs; a
|
|
349
|
+
# public repo serves that without the scope, a private one returns HTTP 403.
|
|
350
|
+
permissions:
|
|
351
|
+
actions: read
|
|
352
|
+
contents: read
|
|
353
|
+
pull-requests: write
|
|
354
|
+
issues: write
|
|
355
|
+
statuses: write
|
|
356
|
+
checks: write
|
|
357
|
+
|
|
358
|
+
jobs:
|
|
359
|
+
review:
|
|
360
|
+
# This \`if\` routes events; it never checks credentials. The secrets
|
|
361
|
+
# context is unreadable in a job-level \`if\`, so the action detects a
|
|
362
|
+
# missing credential itself and fails the run with the commands that
|
|
363
|
+
# fix it, instead of a skipped job that reads as a clean review.
|
|
364
|
+
#
|
|
365
|
+
# Fork pull_request runs are skipped: GitHub gives them no secrets, so
|
|
366
|
+
# they could never authenticate. A maintainer comments \`/crysk review\`
|
|
367
|
+
# instead, and that run (base-branch context, with secrets) reviews the
|
|
368
|
+
# fork's head.
|
|
369
|
+
#
|
|
370
|
+
# A comment starts the job only when it BEGINS with \`/crysk review\`,
|
|
371
|
+
# \`/crysk recheck\` or \`/crysk override\` (or the older \`/pr-hero\` forms
|
|
372
|
+
# of the three). The action then requires an exact match after
|
|
373
|
+
# trimming, so a near-miss such as "/crysk review please" starts a job the
|
|
374
|
+
# action ends without reviewing or overriding.
|
|
375
|
+
if: >-
|
|
376
|
+
(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) ||
|
|
377
|
+
${ifCommentClauses}
|
|
378
|
+
# Job-level and keyed on the pull request number. A workflow-level group
|
|
379
|
+
# on \`github.head_ref || github.ref\` put every comment on every pull
|
|
380
|
+
# request into ONE group, because head_ref is empty on issue_comment, so
|
|
381
|
+
# any comment anywhere could cancel any in-flight review.
|
|
382
|
+
#
|
|
383
|
+
# Only a new push cancels. The group filter is a prefix, so a near-miss
|
|
384
|
+
# comment can claim the pull request's group too; cancelling there would
|
|
385
|
+
# kill a paid in-flight review before the action ignored the comment. A
|
|
386
|
+
# comment run queues instead. A push never waits: it cancels whatever is
|
|
387
|
+
# running, a forced comment run included, because the head it reviewed
|
|
388
|
+
# is gone (comment again on the new head).
|
|
389
|
+
#
|
|
390
|
+
# GitHub keeps one PENDING run per group, and a newer run replaces it. So
|
|
391
|
+
# a comment enters the pull request's group only when it starts with
|
|
392
|
+
# /crysk review, /crysk recheck or /crysk override (or the older /pr-hero forms), and GitHub associates its author
|
|
393
|
+
# with the repository as OWNER, MEMBER or COLLABORATOR; every other comment
|
|
394
|
+
# gets its own group. Without that, anyone who can comment could replace a
|
|
395
|
+
# maintainer's queued review with a run the action then refuses. The job
|
|
396
|
+
# \`if:\` above does NOT check the association: a writer GitHub reports
|
|
397
|
+
# under another one (a private org member shown as CONTRIBUTOR) still
|
|
398
|
+
# runs, because the action checks the real permission, just in its own
|
|
399
|
+
# group. KNOWN GAP: an associated author's later comment (a writer's
|
|
400
|
+
# near-miss or second real command, or a read-only member's or
|
|
401
|
+
# collaborator's refused one) still replaces a comment run waiting
|
|
402
|
+
# behind a running review, and \`--full\` followed by a plain
|
|
403
|
+
# \`/crysk review\` loses the \`--full\`; comment again to recover. A
|
|
404
|
+
# writer reported under another association runs unserialized, beside
|
|
405
|
+
# any review already running.
|
|
406
|
+
#
|
|
407
|
+
# A fork's push never enters the pull request's group: its job is skipped
|
|
408
|
+
# above, and if a skipped job still claimed the group, the fork author's
|
|
409
|
+
# push would cancel a maintainer's in-flight review of that fork. Every
|
|
410
|
+
# other event gets a unique per-run group for the same reason, so a
|
|
411
|
+
# skipped job can never cancel or replace a review.
|
|
412
|
+
concurrency:
|
|
413
|
+
group: \${{ ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) || ${groupCommentClauses}) && format('pr-hero-review-{0}', github.event.pull_request.number || github.event.issue.number) || format('pr-hero-noop-{0}', github.run_id) }}
|
|
414
|
+
cancel-in-progress: \${{ github.event_name == 'pull_request' }}
|
|
415
|
+
runs-on: ubuntu-latest
|
|
416
|
+
# Backstop for a HUNG runner, not a second review budget. Crysk already
|
|
417
|
+
# enforces its own 75-minute whole-pipeline ceiling, which closes
|
|
418
|
+
# artifacts and reports before exiting; a CI bound at or below that would
|
|
419
|
+
# kill the job first and throw away the salvage. Above it, this only ever
|
|
420
|
+
# fires when the process is genuinely stuck.
|
|
421
|
+
timeout-minutes: 90
|
|
422
|
+
steps:
|
|
423
|
+
${gateStep} - name: Checkout${checkoutGate}
|
|
424
|
+
uses: actions/checkout@v4
|
|
425
|
+
with:${checkoutRef}
|
|
426
|
+
# fetch-depth: 0 is load-bearing, not cosmetic: Crysk computes
|
|
427
|
+
# the pull request's diff range and commit ancestry from full git
|
|
428
|
+
# history. actions/checkout's default is a SHALLOW clone, which
|
|
429
|
+
# cannot produce an accurate diff or blame — trimming this line
|
|
430
|
+
# does not fail loudly, it makes reviews silently miss context.
|
|
431
|
+
fetch-depth: 0
|
|
432
|
+
|
|
433
|
+
- name: Run Crysk
|
|
434
|
+
# The id keeps this step's outputs (\`status\`, \`run-dir\`, ...)
|
|
435
|
+
# readable from any step you add below.
|
|
436
|
+
# The action uploads the run directory as an artifact itself, so
|
|
437
|
+
# \`crysk triage reply --from\` has an input in CI (see action.yml).
|
|
438
|
+
id: pr-hero${runStepGate}
|
|
439
|
+
uses: ${actionRef}
|
|
440
|
+
with:
|
|
441
|
+
github-token: \${{ secrets.GITHUB_TOKEN }}
|
|
442
|
+
# Provide a Claude credential and/or OpenCode auth (never leave every
|
|
443
|
+
# credential blank). Inputs are wired unconditionally: an unset secret
|
|
444
|
+
# or var expands to empty, which the action treats as absent, so
|
|
445
|
+
# leaving the one you do not use in place costs nothing. Deleting the
|
|
446
|
+
# line for the secret you DID set is what breaks — the credential
|
|
447
|
+
# never reaches the action, and it fails to authenticate silently.
|
|
448
|
+
# ANTHROPIC_API_KEY — pay-as-you-go key (billed per token via Anthropic Console), or
|
|
449
|
+
# CLAUDE_CODE_OAUTH_TOKEN — from \`claude setup-token\`: a long-lived
|
|
450
|
+
# (~1 year) token that draws on your Claude subscription at no
|
|
451
|
+
# extra API cost. It must come from that command. The session
|
|
452
|
+
# token \`/login\` leaves in the keychain expires in HOURS and is
|
|
453
|
+
# kept alive by a refresh token CI does not have, so pasting that
|
|
454
|
+
# one here yields a secret that works for a day and then breaks
|
|
455
|
+
# reviews with no signal.
|
|
456
|
+
# OPENCODE_AUTH_JSON — whole OpenCode auth.json store
|
|
457
|
+
# vars.CRYSK_ROUTING — person-layer routing JSON; quoted so an
|
|
458
|
+
# unset var is the empty string rather than broken YAML. The
|
|
459
|
+
# older vars.PRHERO_ROUTING is read when this one is unset.
|
|
460
|
+
anthropic-api-key: \${{ secrets.ANTHROPIC_API_KEY }}
|
|
461
|
+
claude-token: \${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
|
462
|
+
routing: "\${{ vars.CRYSK_ROUTING || vars.PRHERO_ROUTING }}"
|
|
463
|
+
opencode-auth: \${{ secrets.OPENCODE_AUTH_JSON }}${sizeGateLine}${filesGateLine}${budgetLine}${modeLine}
|
|
464
|
+
`;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
export interface RunCiSetupOptions {
|
|
468
|
+
cwd?: string;
|
|
469
|
+
force?: boolean;
|
|
470
|
+
exists?: (p: string) => boolean;
|
|
471
|
+
// What the person chose in setup --ci; absent keeps the template's defaults.
|
|
472
|
+
template?: Pick<
|
|
473
|
+
CiWorkflowTemplateOptions,
|
|
474
|
+
"mode" | "budgetUsd" | "maxChangedLines" | "maxChangedFiles"
|
|
475
|
+
>;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
export type CiSetupResult =
|
|
479
|
+
| { status: "created"; path: string }
|
|
480
|
+
| { status: "overwritten"; path: string }
|
|
481
|
+
| { status: "skipped-existing"; path: string; hint: string }
|
|
482
|
+
// Both workflow files exist: writing either would leave two workflows
|
|
483
|
+
// reviewing every pull request, so nothing is written, --force or not.
|
|
484
|
+
| { status: "refused-duplicate"; hint: string };
|
|
485
|
+
|
|
486
|
+
export async function runCiSetup(
|
|
487
|
+
options: RunCiSetupOptions = {},
|
|
488
|
+
): Promise<CiSetupResult> {
|
|
489
|
+
const cwd = options.cwd ?? process.cwd();
|
|
490
|
+
const exists = options.exists ?? existsSync;
|
|
491
|
+
const duplicate = duplicateWorkflowProblem(cwd, exists);
|
|
492
|
+
if (duplicate !== undefined) {
|
|
493
|
+
return { status: "refused-duplicate", hint: duplicate };
|
|
494
|
+
}
|
|
495
|
+
// The file a repo already has is rewritten in place; only a repo with none
|
|
496
|
+
// gets the new name.
|
|
497
|
+
const relativePath = resolveWorkflowRelativePath(cwd, exists);
|
|
498
|
+
const targetPath = path.join(cwd, relativePath);
|
|
499
|
+
const alreadyExisted = exists(targetPath);
|
|
500
|
+
|
|
501
|
+
if (alreadyExisted && !options.force) {
|
|
502
|
+
return {
|
|
503
|
+
status: "skipped-existing",
|
|
504
|
+
path: targetPath,
|
|
505
|
+
hint: `${relativePath} already exists; pass --force to overwrite it`,
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
await mkdir(path.dirname(targetPath), { recursive: true });
|
|
510
|
+
// Only this one file. A legacy pr-hero-force.yml next to it is left as it
|
|
511
|
+
// is: it still works, and deleting a file the user may dispatch is not a
|
|
512
|
+
// scaffolder's call (see the header comment).
|
|
513
|
+
await writeFile(targetPath, generateCiWorkflowTemplate(options.template));
|
|
514
|
+
|
|
515
|
+
return {
|
|
516
|
+
status: alreadyExisted ? "overwritten" : "created",
|
|
517
|
+
path: targetPath,
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// Merges the setup choices into <repo>/.prhero/config.json, keeping every key
|
|
522
|
+
// already there. The merged file goes through parseLocalConfig, the parser a
|
|
523
|
+
// review reads it with, BEFORE anything is written: a value a review would
|
|
524
|
+
// refuse never reaches disk. A file that is not valid JSON is refused, never
|
|
525
|
+
// replaced, because replacing it would delete whatever the team wrote there.
|
|
526
|
+
export interface RepoReviewConfigWrite {
|
|
527
|
+
file: string;
|
|
528
|
+
// The file as written: what the summary reports as in force.
|
|
529
|
+
config: Record<string, unknown>;
|
|
530
|
+
// Keys that already held a different value and now hold the chosen one.
|
|
531
|
+
changed: { key: string; from: unknown; to: unknown }[];
|
|
532
|
+
// Keys already in the file that nobody chose this run, left untouched, with
|
|
533
|
+
// the value they keep.
|
|
534
|
+
kept: Record<string, unknown>;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
export async function writeRepoReviewConfig(
|
|
538
|
+
repoRoot: string,
|
|
539
|
+
plan: ConfigPlan,
|
|
540
|
+
): Promise<RepoReviewConfigWrite> {
|
|
541
|
+
const file = path.join(resolveRepoDir(repoRoot), "config.json");
|
|
542
|
+
let current: Record<string, unknown> = {};
|
|
543
|
+
if (existsSync(file)) {
|
|
544
|
+
const raw = await readFile(file, "utf-8");
|
|
545
|
+
let parsed: unknown;
|
|
546
|
+
try {
|
|
547
|
+
parsed = JSON.parse(raw);
|
|
548
|
+
} catch (error) {
|
|
549
|
+
throw new CliError(
|
|
550
|
+
`${file} is not valid JSON (${(error as Error).message}); fix it, then run setup --ci again`,
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
if (
|
|
554
|
+
parsed === null ||
|
|
555
|
+
typeof parsed !== "object" ||
|
|
556
|
+
Array.isArray(parsed)
|
|
557
|
+
) {
|
|
558
|
+
throw new CliError(
|
|
559
|
+
`${file} must hold a JSON object; fix it, then run setup --ci again`,
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
current = parsed as Record<string, unknown>;
|
|
563
|
+
}
|
|
564
|
+
const next: Record<string, unknown> = { ...current };
|
|
565
|
+
const changed: RepoReviewConfigWrite["changed"] = [];
|
|
566
|
+
const kept: Record<string, unknown> = {};
|
|
567
|
+
// ci_max_reviews is the legacy name of ci_max_attempts: a file that sets it
|
|
568
|
+
// has already decided the pass count, so filling ci_max_attempts would
|
|
569
|
+
// silently override it (resolveCiReviewPolicy reads ci_max_attempts first).
|
|
570
|
+
const has = (key: string): boolean =>
|
|
571
|
+
key in current ||
|
|
572
|
+
(key === "ci_max_attempts" && "ci_max_reviews" in current);
|
|
573
|
+
for (const group of plan.fillIfAbsent) {
|
|
574
|
+
const present = Object.keys(group).filter(has);
|
|
575
|
+
if (present.length === 0) Object.assign(next, group);
|
|
576
|
+
for (const key of present) {
|
|
577
|
+
const fileKey =
|
|
578
|
+
key in current
|
|
579
|
+
? key
|
|
580
|
+
: key === "ci_max_attempts"
|
|
581
|
+
? "ci_max_reviews"
|
|
582
|
+
: key;
|
|
583
|
+
kept[fileKey] = current[fileKey];
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
// A chosen preset drops the level keys it does not set (and the legacy
|
|
587
|
+
// alias), so switching presets never leaves an orphan behind.
|
|
588
|
+
for (const key of plan.remove) {
|
|
589
|
+
if (key in current) {
|
|
590
|
+
changed.push({ key, from: current[key], to: undefined });
|
|
591
|
+
delete next[key];
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
for (const [key, value] of Object.entries(plan.set)) {
|
|
595
|
+
if (
|
|
596
|
+
key in current &&
|
|
597
|
+
JSON.stringify(current[key]) !== JSON.stringify(value)
|
|
598
|
+
) {
|
|
599
|
+
changed.push({ key, from: current[key], to: value });
|
|
600
|
+
}
|
|
601
|
+
next[key] = value;
|
|
602
|
+
}
|
|
603
|
+
const body = `${JSON.stringify(next, null, 2)}\n`;
|
|
604
|
+
parseLocalConfig(body);
|
|
605
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
606
|
+
await writeFile(file, body);
|
|
607
|
+
return { file, config: next, changed, kept };
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
// Why these .prheroignore patterns would be refused, or undefined when they
|
|
611
|
+
// parse. Asked before anything is written, so a bad pattern stops setup with
|
|
612
|
+
// the repository unchanged instead of halfway through.
|
|
613
|
+
// `existing` is the current .prheroignore text: the file is parsed whole after
|
|
614
|
+
// the append, so a line already broken there must stop setup here too.
|
|
615
|
+
export function ignorePatternsError(
|
|
616
|
+
patterns: readonly string[],
|
|
617
|
+
existing = "",
|
|
618
|
+
): string | undefined {
|
|
619
|
+
if (patterns.length === 0) return undefined;
|
|
620
|
+
try {
|
|
621
|
+
parseIgnoreFile(`${existing}\n${patterns.join("\n")}\n`, "user");
|
|
622
|
+
return undefined;
|
|
623
|
+
} catch (error) {
|
|
624
|
+
return (error as Error).message;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// Appends exclusion patterns to <repo>/.prheroignore, skipping lines already
|
|
629
|
+
// there. Validated with the same parser a review uses, before writing.
|
|
630
|
+
export async function appendIgnorePatterns(
|
|
631
|
+
repoRoot: string,
|
|
632
|
+
patterns: readonly string[],
|
|
633
|
+
): Promise<string> {
|
|
634
|
+
const file = path.join(repoRoot, resolveIgnoreFileName(repoRoot));
|
|
635
|
+
const current = existsSync(file) ? await readFile(file, "utf-8") : "";
|
|
636
|
+
const present = new Set(current.split("\n").map((line) => line.trim()));
|
|
637
|
+
const added = patterns
|
|
638
|
+
.map((p) => p.trim())
|
|
639
|
+
.filter((p) => p.length > 0 && !present.has(p));
|
|
640
|
+
if (added.length === 0) return file;
|
|
641
|
+
const prefix = current.length === 0 || current.endsWith("\n") ? "" : "\n";
|
|
642
|
+
const body = `${current}${prefix}${added.join("\n")}\n`;
|
|
643
|
+
parseIgnoreFile(body, "user");
|
|
644
|
+
await writeFile(file, body);
|
|
645
|
+
return file;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
export interface MaterializeCiOpenCodeDataOptions {
|
|
649
|
+
routing?: string;
|
|
650
|
+
opencodeAuth?: string;
|
|
651
|
+
home?: string;
|
|
652
|
+
env?: Readonly<Record<string, string | undefined>>;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// The file the publisher reads when this step fails on a malformed input, and
|
|
656
|
+
// the outcome directory the workflow binds for it (odd/tasks/agent-first-ci.md, A1).
|
|
657
|
+
const SETUP_RECORD_FILE = "setup.json";
|
|
658
|
+
const ROUTING_CLASS: ErrorClass = { kind: "config-parse", source: "routing" };
|
|
659
|
+
const AUTH_CLASS: ErrorClass = {
|
|
660
|
+
kind: "credential",
|
|
661
|
+
failureClass: "malformed_payload",
|
|
662
|
+
};
|
|
663
|
+
// The details the record carries. Each names the input that is wrong and never
|
|
664
|
+
// its content, so a secret or a routing value cannot reach the PR.
|
|
665
|
+
const ROUTING_NOT_JSON = "the routing input is not valid JSON";
|
|
666
|
+
const ROUTING_NOT_OBJECT = "the routing input is not a valid routing object";
|
|
667
|
+
const AUTH_NOT_JSON = "the opencode-auth input is not valid JSON";
|
|
668
|
+
const AUTH_NOT_OBJECT = "the opencode-auth input must be a JSON object";
|
|
669
|
+
|
|
670
|
+
// A routing or OpenCode auth input the user configured wrongly. `message` is the
|
|
671
|
+
// line stderr has always printed; `cls` and `detail` are what the record carries.
|
|
672
|
+
class SetupInputError extends Error {
|
|
673
|
+
readonly cls: ErrorClass;
|
|
674
|
+
readonly detail: string;
|
|
675
|
+
|
|
676
|
+
constructor(cls: ErrorClass, detail: string, message: string) {
|
|
677
|
+
super(message);
|
|
678
|
+
this.name = "SetupInputError";
|
|
679
|
+
this.cls = cls;
|
|
680
|
+
this.detail = detail;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
function messageOf(error: unknown): string {
|
|
685
|
+
return error instanceof Error ? error.message : "unknown error";
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// CI data plane: person-layer routing + 0600 auth.json. HOME must be a real
|
|
689
|
+
// directory — empty/unset fails loud with no cwd fallback, because falling
|
|
690
|
+
// back would write routing into the checkout (.prhero/config.json), which
|
|
691
|
+
// the repo parser rejects. Never log the auth blob; never inject readerFn.
|
|
692
|
+
export async function materializeCiOpenCodeData(
|
|
693
|
+
options: MaterializeCiOpenCodeDataOptions = {},
|
|
694
|
+
): Promise<void> {
|
|
695
|
+
const env = options.env ?? process.env;
|
|
696
|
+
const home = options.home ?? env.HOME ?? "";
|
|
697
|
+
if (home.trim() === "") {
|
|
698
|
+
throw new Error(
|
|
699
|
+
"HOME is empty or unset; refusing to materialize OpenCode CI data",
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const routingRaw = options.routing ?? env.ROUTING_INPUT ?? "";
|
|
704
|
+
const authRaw = options.opencodeAuth ?? env.OPENCODE_AUTH_INPUT ?? "";
|
|
705
|
+
|
|
706
|
+
let routingConfig: ReturnType<typeof parseRoutingConfig> | null = null;
|
|
707
|
+
if (routingRaw.trim() !== "") {
|
|
708
|
+
let parsed: unknown;
|
|
709
|
+
try {
|
|
710
|
+
parsed = JSON.parse(routingRaw);
|
|
711
|
+
} catch (error) {
|
|
712
|
+
throw new SetupInputError(
|
|
713
|
+
ROUTING_CLASS,
|
|
714
|
+
ROUTING_NOT_JSON,
|
|
715
|
+
`CI routing input is not valid JSON: ${messageOf(error)}`,
|
|
716
|
+
);
|
|
717
|
+
}
|
|
718
|
+
try {
|
|
719
|
+
routingConfig = parseRoutingConfig(parsed, "~/.crysk/config.json");
|
|
720
|
+
} catch (error) {
|
|
721
|
+
// parseRoutingConfig names the offending key in its message: that message
|
|
722
|
+
// stays on stderr, and the record carries only the fixed detail.
|
|
723
|
+
throw new SetupInputError(
|
|
724
|
+
ROUTING_CLASS,
|
|
725
|
+
ROUTING_NOT_OBJECT,
|
|
726
|
+
messageOf(error),
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
if (routingConfig === undefined) {
|
|
730
|
+
throw new SetupInputError(
|
|
731
|
+
ROUTING_CLASS,
|
|
732
|
+
ROUTING_NOT_OBJECT,
|
|
733
|
+
"CI routing input must be a JSON object",
|
|
734
|
+
);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
let authBody: string | undefined;
|
|
739
|
+
if (authRaw.trim() !== "") {
|
|
740
|
+
let parsed: unknown;
|
|
741
|
+
try {
|
|
742
|
+
parsed = JSON.parse(authRaw);
|
|
743
|
+
} catch {
|
|
744
|
+
throw new SetupInputError(
|
|
745
|
+
AUTH_CLASS,
|
|
746
|
+
AUTH_NOT_JSON,
|
|
747
|
+
"CI opencode-auth is not valid JSON",
|
|
748
|
+
);
|
|
749
|
+
}
|
|
750
|
+
if (
|
|
751
|
+
typeof parsed !== "object" ||
|
|
752
|
+
parsed === null ||
|
|
753
|
+
Array.isArray(parsed)
|
|
754
|
+
) {
|
|
755
|
+
throw new SetupInputError(
|
|
756
|
+
AUTH_CLASS,
|
|
757
|
+
AUTH_NOT_OBJECT,
|
|
758
|
+
"CI opencode-auth must be a JSON object",
|
|
759
|
+
);
|
|
760
|
+
}
|
|
761
|
+
authBody = authRaw;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
if (routingConfig !== null) {
|
|
765
|
+
const layout = prheroLayout(home);
|
|
766
|
+
await mkdir(layout.dir, { recursive: true });
|
|
767
|
+
await writeFile(
|
|
768
|
+
layout.reviewConfigPath,
|
|
769
|
+
`${JSON.stringify({ routing: routingConfig }, null, 2)}\n`,
|
|
770
|
+
);
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
if (authBody !== undefined) {
|
|
774
|
+
const authPath = resolveOpenCodeAuthPath(env, home);
|
|
775
|
+
await mkdir(path.dirname(authPath), { recursive: true });
|
|
776
|
+
await writeFile(authPath, authBody, { mode: 0o600 });
|
|
777
|
+
await chmod(authPath, 0o600);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
interface CiOpenCodeSetupDeps {
|
|
782
|
+
env: Readonly<Record<string, string | undefined>>;
|
|
783
|
+
stderr: (text: string) => void;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// WHY tmp then rename, the same as the trigger's record: the publisher reads the
|
|
787
|
+
// file in a later step and must never see a half-written one.
|
|
788
|
+
async function writeSetupRecord(
|
|
789
|
+
dir: string,
|
|
790
|
+
record: SetupRecord,
|
|
791
|
+
): Promise<void> {
|
|
792
|
+
const finalPath = path.join(dir, SETUP_RECORD_FILE);
|
|
793
|
+
// The temp name is unique per write (recordTempPath), so a stale file an earlier job
|
|
794
|
+
// left at the fixed name cannot make this record's write fail (F003 on #330).
|
|
795
|
+
const tempPath = recordTempPath(finalPath);
|
|
796
|
+
await mkdir(dir, { recursive: true });
|
|
797
|
+
try {
|
|
798
|
+
await writeFile(tempPath, `${JSON.stringify(record)}\n`);
|
|
799
|
+
await rename(tempPath, finalPath);
|
|
800
|
+
} catch (error) {
|
|
801
|
+
await rm(tempPath, { force: true }).catch(() => undefined);
|
|
802
|
+
throw error;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// The step's whole job. Returns the exit code. A malformed routing or auth input
|
|
807
|
+
// is the user's configuration, so it also leaves setup.json for the publisher;
|
|
808
|
+
// any other failure (HOME, a write) stays unclassified, with no record.
|
|
809
|
+
async function runCiOpenCodeSetup(deps: CiOpenCodeSetupDeps): Promise<number> {
|
|
810
|
+
try {
|
|
811
|
+
await materializeCiOpenCodeData({ env: deps.env });
|
|
812
|
+
return 0;
|
|
813
|
+
} catch (error) {
|
|
814
|
+
deps.stderr(
|
|
815
|
+
`crysk: failed to materialize OpenCode CI data: ${messageOf(error)}\n`,
|
|
816
|
+
);
|
|
817
|
+
const outcomeDir = deps.env.CRYSK_OUTCOME_DIR ?? "";
|
|
818
|
+
if (error instanceof SetupInputError && outcomeDir !== "") {
|
|
819
|
+
try {
|
|
820
|
+
await writeSetupRecord(outcomeDir, {
|
|
821
|
+
v: 1,
|
|
822
|
+
cls: error.cls,
|
|
823
|
+
detail: error.detail,
|
|
824
|
+
});
|
|
825
|
+
} catch {
|
|
826
|
+
deps.stderr(
|
|
827
|
+
"crysk: could not write its setup outcome record, so the publisher reports this as an install failure.\n",
|
|
828
|
+
);
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
return 1;
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
if (import.meta.main) {
|
|
836
|
+
process.exit(
|
|
837
|
+
await runCiOpenCodeSetup({
|
|
838
|
+
env: process.env,
|
|
839
|
+
stderr: (text) => {
|
|
840
|
+
process.stderr.write(text);
|
|
841
|
+
},
|
|
842
|
+
}),
|
|
843
|
+
);
|
|
844
|
+
}
|