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.
Files changed (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +610 -2
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +82 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,125 @@
1
+ // Pure decisions for `pr-hero triage reply` (W1 / issues #21 #20 #22).
2
+ // The coding agent chooses the tag and writes reasoning; this module
3
+ // chooses WHICH posted comment is the parent and whether the driver should
4
+ // resolve the GitHub review thread. NO I/O — cli.ts/pr/pr.ts execute the plan.
5
+ //
6
+ // WHY a dedicated matcher, not matchPostedFindings (pr/inline.ts): that matcher
7
+ // uses FINDING_LINE_WINDOW and livePath/liveLine so a re-review can find a
8
+ // prior comment after a small drift. Using it here would pick a parent by
9
+ // "nearest line on the live diff" — the exact 1724 failure (Greptile sat
10
+ // on the same path:line; the agent replied there). Triage identity is the
11
+ // finding marker: path + post line + head + claim fingerprint — the post
12
+ // line comes from resolvePostLine (same as --post), not raw findings.json.
13
+
14
+ import {
15
+ type PostedFindingComment,
16
+ parseHunkAnchors,
17
+ resolvePostLine,
18
+ } from "#pr/inline";
19
+ import { claimFingerprint } from "#pr/preflight";
20
+ import { parseTriageMarker, type TriageVerdict } from "./triage";
21
+
22
+ export interface FindingIdentity {
23
+ path: string;
24
+ line: number;
25
+ claim: string;
26
+ }
27
+
28
+ // The marker pr-hero POSTED carries the in-diff post line (resolvePostLine
29
+ // in pr/pr.ts's resolveInlinePostPlan), not necessarily findings.json's hunter
30
+ // cite. Triage reply must remap the same way or F001 at :19 never binds to a
31
+ // comment posted at :27 after proof_ref re-anchoring (Musive re-review).
32
+ export function findingIdentityForMarkerMatch(input: {
33
+ path: string;
34
+ line: number;
35
+ claim: string;
36
+ proof_refs?: readonly string[];
37
+ diffPatch: string;
38
+ }): { identity: FindingIdentity; findingsLine: number } {
39
+ const anchors = parseHunkAnchors(input.diffPatch);
40
+ const postLine =
41
+ resolvePostLine(
42
+ {
43
+ id: "",
44
+ path: input.path,
45
+ line: input.line,
46
+ claim: input.claim,
47
+ tier: "blocking",
48
+ proof_refs: input.proof_refs,
49
+ },
50
+ anchors,
51
+ ) ?? input.line;
52
+ return {
53
+ identity: { path: input.path, line: postLine, claim: input.claim },
54
+ findingsLine: input.line,
55
+ };
56
+ }
57
+
58
+ export type FindingCommentMatch =
59
+ | { kind: "none" }
60
+ | { kind: "matched"; posted: PostedFindingComment }
61
+ | { kind: "ambiguous"; ids: number[] };
62
+
63
+ // Exact marker identity. `livePath`/`liveLine` are ignored on purpose:
64
+ // GitHub's live projection is what made 1724 look like "the comment at
65
+ // this line", and Greptile had already taken that line. Two posted
66
+ // comments that share the fingerprint is a driver bug (duplicate post),
67
+ // not a tie to break by proximity — fail closed.
68
+ export function matchPostedFindingExact(input: {
69
+ finding: FindingIdentity;
70
+ headSha: string;
71
+ posted: PostedFindingComment[];
72
+ }): FindingCommentMatch {
73
+ const fingerprint = claimFingerprint(input.finding.claim);
74
+ const hits = input.posted.filter(
75
+ (comment) =>
76
+ comment.marker.path === input.finding.path &&
77
+ comment.marker.line === input.finding.line &&
78
+ comment.marker.headSha === input.headSha &&
79
+ comment.marker.c === fingerprint,
80
+ );
81
+ if (hits.length === 0) return { kind: "none" };
82
+ if (hits.length === 1) {
83
+ const posted = hits[0];
84
+ if (posted === undefined) return { kind: "none" };
85
+ return { kind: "matched", posted };
86
+ }
87
+ return { kind: "ambiguous", ids: hits.map((comment) => comment.id) };
88
+ }
89
+
90
+ export type ThreadResolveDecision =
91
+ | "resolve"
92
+ | "skip-issue-channel"
93
+ | "skip-inconclusive";
94
+
95
+ // Inline review threads close when the finding is handled. Issue-comment
96
+ // findings have no review thread (#17). `inconclusive` stays open so the
97
+ // human objector can still see an unresolved conversation.
98
+ export function decideThreadResolve(input: {
99
+ channel: "review" | "issue";
100
+ verdict?: TriageVerdict;
101
+ }): ThreadResolveDecision {
102
+ if (input.channel === "issue") return "skip-issue-channel";
103
+ if (input.verdict === "inconclusive") return "skip-inconclusive";
104
+ return "resolve";
105
+ }
106
+
107
+ export interface ReviewReplyRef {
108
+ in_reply_to_id: number | null;
109
+ body: string;
110
+ }
111
+
112
+ // Same-head re-post guard: the finding marker's head is the budget unit
113
+ // (SKILL.md "One adjudication per finding per HEAD"). A second `triage
114
+ // reply` at that head must not create another comment.
115
+ export function existingTriageAtHead(input: {
116
+ parentId: number;
117
+ headSha: string;
118
+ replies: ReviewReplyRef[];
119
+ }): boolean {
120
+ return input.replies.some((reply) => {
121
+ if (reply.in_reply_to_id !== input.parentId) return false;
122
+ const marker = parseTriageMarker(reply.body);
123
+ return marker !== null && marker.headSha === input.headSha;
124
+ });
125
+ }
@@ -0,0 +1,255 @@
1
+ // Triage reply marker (ROADMAP B6b) — pure. The FIRST line of the consumer's
2
+ // coding agent's reply in a finding's own thread, so a future reader (a
3
+ // human, or 6c's ledger write-back) can tell "this finding was triaged" from
4
+ // "nobody has looked yet" without parsing prose.
5
+ //
6
+ // NO I/O. Same contract as pr/preflight.ts/pr/inline.ts: no gh, no git, no
7
+ // network, no filesystem, no clock. The consuming skill (this repo's
8
+ // `skills/crysk-loop/`) runs in the CONSUMER's coding agent, outside
9
+ // this process entirely — this module only defines the wire format both
10
+ // sides agree on.
11
+ //
12
+ import { MARKER_OPEN, matchMarkerPrefix } from "../brand";
13
+
14
+ // Disjoint from PR_COMMENT_MARKER_PREFIX and PR_FINDING_MARKER_PREFIX on
15
+ // purpose, same reasoning as their own disjointness (pr/preflight.ts): a
16
+ // triage reply lands in the SAME comment stream as the summary and the
17
+ // per-finding markers (review comment threads and issue comments alike), so
18
+ // a matcher that could confuse any of the three families would misfile a
19
+ // reply as a finding, or a finding as a reply. See the three-way
20
+ // disjointness test in test/triage/triage.test.ts.
21
+ export const TRIAGE_MARKER_PREFIX = `${MARKER_OPEN}triage `;
22
+
23
+ // The FOUR tags an author may write (ROADMAP B6b table) — deliberately NOT
24
+ // the `refuter_verdict` schema enum (review/findings.ts), which is sacred under
25
+ // rule 5 and not ours to extend. This is a separate, project-owned
26
+ // vocabulary the triage loop invented, so adding a tag here costs no schema
27
+ // change and no coordination with the lab.
28
+ export type TriageTag = "applied" | "dismissed" | "deferred" | "misclassified";
29
+
30
+ const TRIAGE_TAGS: ReadonlySet<string> = new Set<TriageTag>([
31
+ "applied",
32
+ "dismissed",
33
+ "deferred",
34
+ "misclassified",
35
+ ]);
36
+
37
+ // Who wrote the tag. Mirrors 6c's `actor` field on ComparisonRow (not wired
38
+ // here — this module only defines the marker both sides read/write) so a
39
+ // reader can eventually tell "a human overrode this row" from "the agent
40
+ // decided" without a second vocabulary.
41
+ export type TriageActor = "agent" | "human";
42
+
43
+ const TRIAGE_ACTORS: ReadonlySet<string> = new Set<TriageActor>([
44
+ "agent",
45
+ "human",
46
+ ]);
47
+
48
+ // The adjudicator's own vocabulary (ROADMAP B6b "What the adjudicator
49
+ // returns"), NOT the same set as TriageTag — the author's tag is what they
50
+ // claim, this is what the isolated judge independently ruled. Deliberately
51
+ // disjoint from `refuter_verdict` (review/findings.ts) for the same reason TriageTag
52
+ // is: that enum is schema-shared with the lab and sacred under rule 5, this
53
+ // one is project-owned and costs no coordination to extend.
54
+ export type TriageVerdict = "upheld" | "rejected" | "inconclusive";
55
+
56
+ const TRIAGE_VERDICTS: ReadonlySet<string> = new Set<TriageVerdict>([
57
+ "upheld",
58
+ "rejected",
59
+ "inconclusive",
60
+ ]);
61
+
62
+ const FULL_SHA = /^[0-9a-f]{40}$/;
63
+
64
+ // Tags that spawn an adjudicator (SKILL.md step 4) and therefore MUST carry
65
+ // its verdict on the marker. `applied` pays no adjudicator and is excluded
66
+ // on purpose — see the builder/parser below for what that means in both
67
+ // directions.
68
+ export const ADJUDICATED_TAGS: ReadonlySet<TriageTag> = new Set<TriageTag>([
69
+ "dismissed",
70
+ "deferred",
71
+ "misclassified",
72
+ ]);
73
+
74
+ export interface TriageMarkerFields {
75
+ tag: TriageTag;
76
+ headSha: string;
77
+ actor: TriageActor;
78
+ // Optional destination when tag is "deferred". W1 (issue #21/#22): a
79
+ // deferred finding is a TAG plus reasoning, not a mandate to create a
80
+ // GitHub issue — some agents run on providers that are not GitHub, and
81
+ // the coding agent decides whether an issue exists. When supplied it
82
+ // must be a positive integer; meaningless for every other tag and
83
+ // ignored if supplied there.
84
+ issue?: number;
85
+ // The isolated adjudicator's ruling (ROADMAP B6b "the label is the
86
+ // verdict and it closes the row"). REQUIRED for `dismissed`, `deferred`,
87
+ // and `misclassified` — the three tags that spawn an adjudicator — for
88
+ // the same reason `issue` is required for `deferred`: without it, 6c
89
+ // cannot tell a settled finding from an unsettled one, and the escalation
90
+ // rule (2 consecutive `inconclusive` heads) has nothing to count.
91
+ // FORBIDDEN for `applied`, stricter than `issue`'s "ignored if supplied":
92
+ // `applied` never spawns an adjudicator (SKILL.md, ROADMAP B6b), so a
93
+ // verdict on an `applied` marker is not harmless noise, it is a false
94
+ // claim that a ruling happened when the rule says none may. The builder
95
+ // throws and the parser rejects rather than silently drop it.
96
+ verdict?: TriageVerdict;
97
+ }
98
+
99
+ const TRIAGE_BADGE: Record<TriageTag, { emoji: string; label: string }> = {
100
+ applied: { emoji: "✅", label: "APPLIED" },
101
+ dismissed: { emoji: "❌", label: "DISMISSED" },
102
+ deferred: { emoji: "📋", label: "DEFERRED" },
103
+ misclassified: { emoji: "🏷️", label: "MISCLASSIFIED" },
104
+ };
105
+
106
+ // Visible second line of a triage reply. The marker is an HTML comment, so
107
+ // GitHub renders it invisible — a body that is only the marker tells the
108
+ // ledger everything and the human nothing (found on pr-hero PR #6). The
109
+ // driver owns this string so a skill cannot omit it the way the 1724
110
+ // Greptile-thread replies did.
111
+ export function triageBadge(fields: TriageMarkerFields): string {
112
+ const badge = TRIAGE_BADGE[fields.tag];
113
+ const parts = [`${badge.emoji} **${badge.label}**`, fields.actor];
114
+ if (fields.verdict !== undefined) {
115
+ parts.push(`adjudicator: ${fields.verdict}`);
116
+ }
117
+ if (fields.tag === "deferred" && fields.issue !== undefined) {
118
+ parts.push(`#${fields.issue}`);
119
+ }
120
+ return parts.join(" · ");
121
+ }
122
+
123
+ // Marker + badge + reasoning, in that order. The driver prepends the wire
124
+ // format; `--body-file` is reasoning prose only. A blank reasoning still
125
+ // emits marker and badge — applied can be a one-line pointer, and an empty
126
+ // file must not drop the human-visible tag.
127
+ export function renderTriageReplyBody(
128
+ fields: TriageMarkerFields,
129
+ reasoning: string,
130
+ ): string {
131
+ const head = `${triageMarker(fields)}\n\n${triageBadge(fields)}`;
132
+ const prose = reasoning.trim();
133
+ return prose.length === 0 ? `${head}\n` : `${head}\n\n${prose}\n`;
134
+ }
135
+
136
+ // Builds the marker. `verdict` is required for the three adjudicated tags
137
+ // and forbidden for `applied`. `issue` on `deferred` is optional.
138
+ export function triageMarker(fields: TriageMarkerFields): string {
139
+ if (
140
+ fields.tag === "deferred" &&
141
+ fields.issue !== undefined &&
142
+ (!Number.isInteger(fields.issue) || fields.issue <= 0)
143
+ ) {
144
+ throw new Error(
145
+ "triageMarker: tag=deferred issue must be a positive integer",
146
+ );
147
+ }
148
+ if (ADJUDICATED_TAGS.has(fields.tag) && fields.verdict === undefined) {
149
+ throw new Error(
150
+ `triageMarker: tag=${fields.tag} requires a verdict — it spawns an ` +
151
+ "adjudicator (ROADMAP B6b)",
152
+ );
153
+ }
154
+ if (fields.tag === "applied" && fields.verdict !== undefined) {
155
+ throw new Error(
156
+ "triageMarker: tag=applied must not carry a verdict — applied pays " +
157
+ "no adjudicator (ROADMAP B6b)",
158
+ );
159
+ }
160
+ const issuePart =
161
+ fields.tag === "deferred" && fields.issue !== undefined
162
+ ? ` issue=${fields.issue}`
163
+ : "";
164
+ const verdictPart =
165
+ fields.verdict !== undefined ? ` verdict=${fields.verdict}` : "";
166
+ return (
167
+ `${TRIAGE_MARKER_PREFIX}tag=${fields.tag} head=${fields.headSha} ` +
168
+ `actor=${fields.actor}${issuePart}${verdictPart} -->`
169
+ );
170
+ }
171
+
172
+ export interface ParsedTriageMarker {
173
+ tag: TriageTag;
174
+ headSha: string;
175
+ actor: TriageActor;
176
+ // Present only when tag is "deferred" AND the marker carried a valid
177
+ // `issue=` field. Absent is a valid deferred (reasoning-only).
178
+ issue?: number;
179
+ // Present only when tag is "dismissed", "deferred", or "misclassified"
180
+ // (parseTriageMarker enforces this the same way it enforces `issue`) —
181
+ // absent for "applied", which never returns null for a MISSING verdict
182
+ // but DOES for a PRESENT one (see parseTriageMarker).
183
+ verdict?: TriageVerdict;
184
+ }
185
+
186
+ // Parses ONLY the first line of a reply body, mirroring
187
+ // parseFindingMarker's exact-prefix contract: a marker quoted mid-reply
188
+ // (someone pasting a prior triage into a new comment) must never parse as a
189
+ // fresh one. Returns null for anything malformed rather than guessing — a
190
+ // mis-parsed triage becomes a silently wrong verdict in the store.
191
+ export function parseTriageMarker(body: string): ParsedTriageMarker | null {
192
+ const prefix = matchMarkerPrefix(body, TRIAGE_MARKER_PREFIX);
193
+ if (prefix === undefined) return null;
194
+ const firstLine = body.split("\n", 1)[0] ?? "";
195
+ if (!firstLine.endsWith(" -->")) return null;
196
+ const fields = firstLine.slice(
197
+ prefix.length,
198
+ firstLine.length - " -->".length,
199
+ );
200
+ const parts = new Map<string, string>();
201
+ for (const token of fields.split(" ")) {
202
+ if (token.length === 0) continue;
203
+ const eq = token.indexOf("=");
204
+ if (eq === -1) continue;
205
+ parts.set(token.slice(0, eq), token.slice(eq + 1));
206
+ }
207
+ const rawTag = parts.get("tag");
208
+ const headSha = parts.get("head");
209
+ const rawActor = parts.get("actor");
210
+ if (rawTag === undefined || headSha === undefined || rawActor === undefined) {
211
+ return null;
212
+ }
213
+ if (!TRIAGE_TAGS.has(rawTag)) return null;
214
+ if (!TRIAGE_ACTORS.has(rawActor)) return null;
215
+ if (!FULL_SHA.test(headSha)) return null;
216
+ const tag = rawTag as TriageTag;
217
+ const actor = rawActor as TriageActor;
218
+
219
+ // `applied` pays no adjudicator (SKILL.md, ROADMAP B6b), so a verdict on
220
+ // an `applied` marker is not a harmless extra field, it is a false claim
221
+ // that an adjudicator ruled when the rule says none may run — reject it
222
+ // the same way an unknown tag is rejected, rather than silently ignore it.
223
+ if (tag === "applied") {
224
+ if (parts.has("verdict")) return null;
225
+ return { tag, headSha, actor };
226
+ }
227
+
228
+ // `dismissed`, `deferred`, and `misclassified` all spawn an adjudicator
229
+ // (SKILL.md step 4) and therefore MUST carry its verdict — the same
230
+ // two-way guard `deferred`/`issue` already has, and for the same reason:
231
+ // a missing verdict would silently read as "settled" (6c would count it
232
+ // as answered) when in fact nobody has ruled on it at all, and the
233
+ // escalation rule (2 consecutive `inconclusive` heads) would have nothing
234
+ // to count.
235
+ const rawVerdict = parts.get("verdict");
236
+ if (rawVerdict === undefined || !TRIAGE_VERDICTS.has(rawVerdict)) {
237
+ return null;
238
+ }
239
+ const verdict = rawVerdict as TriageVerdict;
240
+
241
+ // `deferred` MAY carry a valid issue number. A missing `issue=` is a
242
+ // valid reasoning-only defer (W1). A present but non-positive / NaN
243
+ // value is still malformed — that is a broken destination, not "no
244
+ // destination".
245
+ if (tag === "deferred") {
246
+ const rawIssue = parts.get("issue");
247
+ if (rawIssue === undefined) {
248
+ return { tag, headSha, actor, verdict };
249
+ }
250
+ const issue = Number.parseInt(rawIssue, 10);
251
+ if (!Number.isInteger(issue) || issue <= 0) return null;
252
+ return { tag, headSha, actor, issue, verdict };
253
+ }
254
+ return { tag, headSha, actor, verdict };
255
+ }
@@ -0,0 +1,173 @@
1
+ import type { ActiveRunRecord, RunHistoryItem } from "#store/activity";
2
+ import { bold, box, cyan, dim, green, red } from "./primitives";
3
+
4
+ export interface ActivityRenderOptions {
5
+ styles: boolean;
6
+ width: number;
7
+ nowMs?: number;
8
+ }
9
+
10
+ export function formatElapsed(startedAt: string, nowMs = Date.now()): string {
11
+ const parsed = Date.parse(startedAt);
12
+ const diffMs = Number.isNaN(parsed) ? 0 : Math.max(0, nowMs - parsed);
13
+ const mins = Math.floor(diffMs / 60000);
14
+ const secs = Math.floor((diffMs % 60000) / 1000);
15
+ return `${String(mins).padStart(2, "0")}m ${String(secs).padStart(2, "0")}s`;
16
+ }
17
+
18
+ export function formatDuration(wallMs: number): string {
19
+ const ms = Math.max(0, wallMs);
20
+ const mins = Math.floor(ms / 60000);
21
+ const secs = Math.floor((ms % 60000) / 1000);
22
+ return `${String(mins).padStart(2, "0")}m ${String(secs).padStart(2, "0")}s`;
23
+ }
24
+
25
+ export function formatCost(costUsd: number): string {
26
+ return `$${costUsd.toFixed(2)}`;
27
+ }
28
+
29
+ export function formatFindingsSummary(
30
+ blocking: number,
31
+ advisory: number,
32
+ ): string {
33
+ if (blocking === 0 && advisory === 0) {
34
+ return "0 findings (clean)";
35
+ }
36
+ const total = blocking + advisory;
37
+ if (blocking > 0) {
38
+ return `${total} findings (${blocking} blocking)`;
39
+ }
40
+ return `${total} advisory findings`;
41
+ }
42
+
43
+ export function renderActiveRuns(
44
+ runs: ActiveRunRecord[],
45
+ selectedIndex = 0,
46
+ options: ActivityRenderOptions,
47
+ ): string[] {
48
+ const st = options.styles;
49
+ const nowMs = options.nowMs ?? Date.now();
50
+ const lines: string[] = [];
51
+
52
+ if (runs.length === 0) {
53
+ lines.push(dim(" No active reviews currently running.", st));
54
+ return lines;
55
+ }
56
+
57
+ for (let i = 0; i < runs.length; i++) {
58
+ const run = runs[i];
59
+ const isSelected = i === selectedIndex;
60
+ const marker = isSelected ? bold(cyan("▸ ", st), st) : " ";
61
+ const elapsed = formatElapsed(run.startedAt, nowMs);
62
+
63
+ const statusDot = cyan("● RUNNING", st);
64
+ const header = `${marker}${statusDot} (PID ${run.pid}) · Elapsed: ${elapsed}`;
65
+ lines.push(header);
66
+
67
+ const indent = " ";
68
+ lines.push(`${indent}Repo: ${bold(run.repo, st)}`);
69
+ if (run.pr !== undefined) {
70
+ lines.push(`${indent}Target: PR #${run.pr}`);
71
+ }
72
+ lines.push(`${indent}RunDir: ${dim(run.runDir, st)}`);
73
+
74
+ if (i < runs.length - 1) {
75
+ lines.push("");
76
+ }
77
+ }
78
+
79
+ return lines;
80
+ }
81
+
82
+ export function renderWatcherSpend(
83
+ spend: { launchedToday: number; dailyCap: number },
84
+ options: { styles: boolean; width: number },
85
+ ): string[] {
86
+ const st = options.styles;
87
+ return [
88
+ `Watcher today: ${bold(String(spend.launchedToday), st)}/${spend.dailyCap} launches (daily cap)`,
89
+ ];
90
+ }
91
+
92
+ export function renderRunHistory(
93
+ history: RunHistoryItem[],
94
+ options: { styles: boolean; width: number },
95
+ ): string[] {
96
+ const st = options.styles;
97
+ const lines: string[] = [];
98
+
99
+ if (history.length === 0) {
100
+ lines.push(dim(" No completed reviews found in store.", st));
101
+ return lines;
102
+ }
103
+
104
+ for (const item of history) {
105
+ const isOk = item.run_status === "complete" || item.run_status === "ok";
106
+ const statusIcon = isOk ? green("✓", st) : red("✗", st);
107
+ const target =
108
+ item.pr !== undefined && item.pr !== null
109
+ ? `PR #${item.pr}`
110
+ : "Branch review";
111
+ const findings = formatFindingsSummary(item.blocking, item.advisory);
112
+ const duration = formatDuration(item.wall_ms);
113
+ const cost = formatCost(item.cost_usd_est);
114
+
115
+ const line = ` ${statusIcon} ${bold(target, st)} · ${findings} · Duration: ${duration} · Cost: ${cost}`;
116
+ lines.push(line);
117
+ }
118
+
119
+ return lines;
120
+ }
121
+
122
+ export interface ActivityScreenData {
123
+ runs: ActiveRunRecord[];
124
+ spend: { launchedToday: number; dailyCap: number };
125
+ history: RunHistoryItem[];
126
+ selectedIndex?: number;
127
+ repoFilter?: string;
128
+ }
129
+
130
+ export function renderActivityScreen(
131
+ data: ActivityScreenData,
132
+ options: ActivityRenderOptions,
133
+ ): string[] {
134
+ const st = options.styles;
135
+ const selectedIndex = data.selectedIndex ?? 0;
136
+
137
+ const content: string[] = [];
138
+
139
+ // 1. Active Runs
140
+ content.push(bold("Active Reviews:", st));
141
+ content.push(...renderActiveRuns(data.runs, selectedIndex, options));
142
+ content.push("");
143
+
144
+ // 2. Watcher Spend
145
+ content.push(...renderWatcherSpend(data.spend, options));
146
+ content.push(dim("─".repeat(Math.max(20, options.width - 6)), st));
147
+
148
+ // 3. Recent Completed Reviews
149
+ content.push(
150
+ bold(
151
+ "Recent Completed Reviews (last 10, from prhero.db in the Crysk home):",
152
+ st,
153
+ ),
154
+ );
155
+ content.push(...renderRunHistory(data.history, options));
156
+ content.push("");
157
+
158
+ // 4. Footer hints
159
+ const selectedPid = data.runs[selectedIndex]?.pid;
160
+ const killHint =
161
+ selectedPid !== undefined
162
+ ? ` • enter: kill selected (PID ${selectedPid})`
163
+ : "";
164
+ content.push(dim(`j/k: move${killHint} • r: refresh • q/esc: back`, st));
165
+ if (selectedPid !== undefined) {
166
+ content.push(dim(`$ crysk activity --kill ${selectedPid}`, st));
167
+ }
168
+
169
+ return box("Active Reviews & Activity", content, {
170
+ styles: options.styles,
171
+ width: options.width,
172
+ });
173
+ }