rungate 0.2.0 → 0.2.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.
Files changed (164) hide show
  1. package/package.json +14 -3
  2. package/.claude/agents/aditi.md +0 -47
  3. package/.claude/agents/marcus.md +0 -50
  4. package/.claude/agents/quinn.md +0 -58
  5. package/.claude/agents/rook.md +0 -47
  6. package/.claude/agents/serena.md +0 -46
  7. package/.claude/rungate.json +0 -11
  8. package/.fallowrc.json +0 -28
  9. package/.github/copilot-instructions.md +0 -20
  10. package/.rungate/conformity-findings.json +0 -648
  11. package/AGENTS.md +0 -106
  12. package/CODE-MAP.md +0 -50
  13. package/HARNESS.md +0 -88
  14. package/bun.lock +0 -26
  15. package/bunfig.toml +0 -2
  16. package/config/brief-policies.json +0 -28
  17. package/config/ceremony-profiles.json +0 -212
  18. package/config/consumer-cascade-map.json +0 -24
  19. package/config/doc-cascade-map.json +0 -24
  20. package/config/eval.json +0 -84
  21. package/config/profiles/account-plan.yaml +0 -36
  22. package/config/profiles/campaign.yaml +0 -94
  23. package/config/prove-evidence.schema.json +0 -65
  24. package/config/spec-policies.json +0 -36
  25. package/config/workflow-schema.json +0 -281
  26. package/gates/SCHEMA-GUIDE.md +0 -121
  27. package/gates/ac-quality.test.ts +0 -106
  28. package/gates/adversarial.test.ts +0 -274
  29. package/gates/brief-assembler.test.ts +0 -429
  30. package/gates/brief-assembler.ts +0 -334
  31. package/gates/bunfig.toml +0 -2
  32. package/gates/chain.test.ts +0 -91
  33. package/gates/e2e-smoke.test.ts +0 -234
  34. package/gates/error-classifier.test.ts +0 -249
  35. package/gates/error-classifier.ts +0 -89
  36. package/gates/orchestrator.test.ts +0 -950
  37. package/gates/orchestrator.ts +0 -569
  38. package/gates/preload.ts +0 -77
  39. package/gates/prompts/ac-adversary.md +0 -20
  40. package/gates/prompts/evidence-validator.md +0 -22
  41. package/gates/prompts/prove-reproducer.md +0 -53
  42. package/gates/prove.test.ts +0 -164
  43. package/gates/run-gate.ts +0 -936
  44. package/gates/schema-parity.test.ts +0 -197
  45. package/gates/schema.ts +0 -362
  46. package/gates/self-heal.test.ts +0 -511
  47. package/gates/self-heal.ts +0 -121
  48. package/gates/ship-orchestrator.test.ts +0 -379
  49. package/gates/ship-orchestrator.ts +0 -363
  50. package/gates/test-fixtures/broken-no-environments.json +0 -60
  51. package/gates/test-fixtures/valid-standard.json +0 -54
  52. package/gates/test-utils.ts +0 -43
  53. package/gates/witness.ts +0 -220
  54. package/gates/workflow.test.ts +0 -1053
  55. package/hooks/AgentBriefGuard.hook.ts +0 -586
  56. package/hooks/AgentVerdictCapture.hook.ts +0 -134
  57. package/hooks/AutoVerifyGate.hook.ts +0 -76
  58. package/hooks/GateEnforcement.hook.ts +0 -273
  59. package/hooks/IssueCloseGuard.hook.ts +0 -116
  60. package/hooks/MergeGuard.hook.ts +0 -55
  61. package/hooks/StaleTTLCleanup.hook.ts +0 -133
  62. package/hooks/VerifyPhaseLock.hook.ts +0 -81
  63. package/hooks/WorkflowStateGuard.hook.ts +0 -37
  64. package/hooks/lib/agentDetection.ts +0 -70
  65. package/hooks/lib/findWorkflow.ts +0 -101
  66. package/hooks/lib/parseStdin.ts +0 -37
  67. package/hooks/lib/paths.ts +0 -111
  68. package/hooks/lib/utils.ts +0 -81
  69. package/reference/migration-manifest.json +0 -554
  70. package/reference/prompts/agent-aditi.md +0 -38
  71. package/reference/prompts/agent-marcus.md +0 -38
  72. package/reference/prompts/agent-quinn.md +0 -38
  73. package/reference/prompts/agent-rook.md +0 -37
  74. package/reference/prompts/agent-serena.md +0 -37
  75. package/reference/prompts/council-skill.md +0 -170
  76. package/reference/prompts/goal-skill.md +0 -235
  77. package/reference/prompts/prove-skill.md +0 -283
  78. package/reference/prompts/quinn-standard.md +0 -246
  79. package/reference/prompts/ship-convergence.md +0 -65
  80. package/reference/prompts/ship-escalation.md +0 -43
  81. package/reference/prompts/ship-iteration.md +0 -382
  82. package/reference/prompts/ship-pending-patches.md +0 -246
  83. package/reference/prompts/ship-reference.md +0 -250
  84. package/reference/prompts/ship-skill.md +0 -347
  85. package/reference/prompts/ship-templates.md +0 -215
  86. package/reference/scripts/batch-status.sh +0 -68
  87. package/reference/scripts/chain-compat-check.sh +0 -67
  88. package/reference/scripts/context-audit.sh +0 -314
  89. package/reference/scripts/dead-export-check.sh +0 -61
  90. package/reference/scripts/generate-qc-tables.sh +0 -92
  91. package/reference/scripts/harness-init.sh +0 -111
  92. package/reference/scripts/pai-054-baseline-check.sh +0 -40
  93. package/reference/scripts/prove-smoke-test.sh +0 -112
  94. package/reference/scripts/setup-keychain-salt.sh +0 -12
  95. package/reference/scripts/skill-optimizer-friday.sh +0 -88
  96. package/reference/scripts/skill-qc-test.sh +0 -351
  97. package/reference/scripts/skill-synthesize-tonight.sh +0 -66
  98. package/reference/specs/HARNESS-EXTRACTION-SPEC.md +0 -263
  99. package/reference/specs/harness-v3-bash-deletion-plan.md +0 -65
  100. package/reference/specs/harness-v3-migration-plan.md +0 -188
  101. package/scripts/decision-reconcile.sh +0 -74
  102. package/scripts/decision-reconcile.ts +0 -152
  103. package/scripts/git-hooks/pre-commit +0 -76
  104. package/scripts/git-hooks/pre-push +0 -271
  105. package/scripts/harness-skill-check.sh +0 -52
  106. package/scripts/lib/gap-emit.sh +0 -65
  107. package/scripts/lib/jq-update.sh +0 -30
  108. package/scripts/lib/resolve-slug.sh +0 -30
  109. package/scripts/lib/verify-spec-compliance.sh +0 -102
  110. package/scripts/prove-backfill.sh +0 -87
  111. package/scripts/scaffold-rungate-config.ts +0 -91
  112. package/scripts/self-containment-check.sh +0 -109
  113. package/scripts/skill-qc-validator.sh +0 -402
  114. package/scripts/slug-resolver.sh +0 -14
  115. package/specs/BOOTSTRAP-DATA-FLOW-SPEC.md +0 -2493
  116. package/specs/BOOTSTRAP-TEST-PLAN.md +0 -571
  117. package/specs/HARNESS-GATES.md +0 -256
  118. package/specs/HARNESS-SKILL-CHAIN.md +0 -286
  119. package/specs/HARNESS-SKILL-CONTRACT.md +0 -93
  120. package/specs/HARNESS-STANDARD.md +0 -488
  121. package/specs/SPEC-TEMPLATE.md +0 -53
  122. package/specs/bootstrap-data-flow.png +0 -0
  123. package/specs/harness-automation-matrix.md +0 -314
  124. package/specs/harness-automation-matrix.rules.json +0 -64
  125. package/test/anti.test.ts +0 -80
  126. package/test/contract-negative.test.ts +0 -86
  127. package/test/contract.test.ts +0 -158
  128. package/test/external-deps.test.ts +0 -48
  129. package/test/fixtures/golden-project/.env.example +0 -3
  130. package/test/fixtures/golden-project/Makefile +0 -7
  131. package/test/fixtures/golden-project/docs/adr/ADR-001-framework.md +0 -23
  132. package/test/fixtures/golden-project/docs/setup-guide.md +0 -10
  133. package/test/fixtures/golden-project/package.json +0 -10
  134. package/test/fixtures/golden-project/specs/api-spec.md +0 -20
  135. package/test/fixtures/golden-project/src/auth.ts +0 -8
  136. package/test/fixtures/golden-project/src/db.ts +0 -11
  137. package/test/fixtures/golden-project/src/index.ts +0 -19
  138. package/test/fixtures/golden-project/src/utils/format.ts +0 -3
  139. package/test/fixtures/golden-project/test/auth.test.ts +0 -15
  140. package/test/fixtures/golden-project/tsconfig.json +0 -12
  141. package/test/meta-sc-coverage.test.ts +0 -159
  142. package/test/phase-0.test.ts +0 -846
  143. package/test/phase-1.test.ts +0 -617
  144. package/test/phase-2.test.ts +0 -620
  145. package/test/phase-3.test.ts +0 -99
  146. package/test/scaffold-conformity.test.ts +0 -8
  147. package/test/schema-canary.test.ts +0 -51
  148. package/test/spec-compliance-auto.test.ts +0 -64
  149. package/test/spec-compliance.test.ts +0 -295
  150. package/test/spec-discovery.test.ts +0 -68
  151. package/test/spec-drift.test.ts +0 -5
  152. package/test/structure.test.ts +0 -165
  153. package/test/unit/agent-brief-guard-ship.test.ts +0 -293
  154. package/test/unit/extract-constraints.test.ts +0 -145
  155. package/test/unit/issue-close-guard.test.ts +0 -204
  156. package/test/unit/scaffold-project.test.ts +0 -417
  157. package/test/unit/skill-cooccurrence.test.ts +0 -177
  158. package/test/unit/skill-sequence-logger.test.ts +0 -244
  159. package/test/unit/workflow-state-guard.test.ts +0 -95
  160. package/workflows/batch-ship.js +0 -295
  161. package/workflows/council.js +0 -481
  162. package/workflows/prove.js +0 -560
  163. package/workflows/ship.js +0 -789
  164. package/workflows/verify.js +0 -236
@@ -1,152 +0,0 @@
1
- #!/usr/bin/env bun
2
- // decision-reconcile.ts — Verify council decisions are present in target documents
3
- // Usage: decision-reconcile.ts <council-synthesis.json> [--target <file>]
4
- // Without --target: checks ALL decisions against their declared targets
5
- // With --target: checks only decisions targeting that specific file
6
-
7
- import { readFileSync, existsSync } from "fs";
8
- import { resolve } from "path";
9
- import { homedir } from "os";
10
-
11
- interface Decision {
12
- id: string;
13
- statement: string;
14
- target?: {
15
- ref?: string;
16
- section?: string;
17
- };
18
- }
19
-
20
- interface Synthesis {
21
- decisions?: Decision[];
22
- }
23
-
24
- type ResultStatus = "FOUND" | "MISSING";
25
-
26
- interface Result {
27
- status: ResultStatus;
28
- id: string;
29
- statement: string;
30
- detail?: string;
31
- }
32
-
33
- function expandHome(filepath: string): string {
34
- return filepath.startsWith("~") ? filepath.replace("~", homedir()) : filepath;
35
- }
36
-
37
- function usage(): never {
38
- console.error(
39
- "Usage: decision-reconcile.ts <council-synthesis.json> [--target <file>]"
40
- );
41
- process.exit(1);
42
- }
43
-
44
- // Parse args
45
- const args = process.argv.slice(2);
46
- if (args.length === 0) usage();
47
-
48
- const synthesisPath = resolve(args[0]);
49
- let targetFilter = "";
50
-
51
- if (args[1] === "--target") {
52
- if (!args[2]) usage();
53
- targetFilter = args[2];
54
- }
55
-
56
- // Validate synthesis file
57
- if (!existsSync(synthesisPath)) {
58
- console.error(`FAIL: ${synthesisPath} not found`);
59
- process.exit(1);
60
- }
61
-
62
- let data: Synthesis;
63
- try {
64
- data = JSON.parse(readFileSync(synthesisPath, "utf-8"));
65
- } catch {
66
- console.error(`FAIL: ${synthesisPath} is invalid JSON`);
67
- process.exit(1);
68
- }
69
-
70
- const decisions = data.decisions ?? [];
71
- const results: Result[] = [];
72
-
73
- for (const d of decisions) {
74
- const ref = d.target?.ref;
75
- if (!ref) continue;
76
- if (targetFilter && ref !== targetFilter) continue;
77
-
78
- const filepath = expandHome(ref);
79
-
80
- if (!existsSync(filepath)) {
81
- results.push({
82
- status: "MISSING",
83
- id: d.id,
84
- statement: d.statement.slice(0, 60),
85
- detail: `file not found: ${ref}`,
86
- });
87
- continue;
88
- }
89
-
90
- const content = readFileSync(filepath, "utf-8");
91
-
92
- // Extract key words (>3 chars) from statement, take first 3 as key phrase
93
- const words = d.statement.split(/\s+/).filter((w) => w.length > 3);
94
- const keyPhrase = words.slice(0, 3).join(" ");
95
- const contentLower = content.toLowerCase();
96
-
97
- if (
98
- keyPhrase.toLowerCase() &&
99
- contentLower.includes(keyPhrase.toLowerCase())
100
- ) {
101
- results.push({
102
- status: "FOUND",
103
- id: d.id,
104
- statement: d.statement.slice(0, 60),
105
- });
106
- } else if (content.includes(d.id)) {
107
- results.push({
108
- status: "FOUND",
109
- id: d.id,
110
- statement: d.statement.slice(0, 60),
111
- });
112
- } else {
113
- // Check section match as fallback
114
- const section = d.target?.section;
115
- if (section && contentLower.includes(section.toLowerCase())) {
116
- results.push({
117
- status: "FOUND",
118
- id: d.id,
119
- statement: d.statement.slice(0, 60),
120
- detail: "via section match",
121
- });
122
- } else {
123
- results.push({
124
- status: "MISSING",
125
- id: d.id,
126
- statement: d.statement.slice(0, 60),
127
- detail: `not found in ${ref}`,
128
- });
129
- }
130
- }
131
- }
132
-
133
- // Report
134
- let found = 0;
135
- let missing = 0;
136
-
137
- for (const r of results) {
138
- if (r.status === "FOUND") {
139
- found++;
140
- const suffix = r.detail ? ` (${r.detail})` : "";
141
- console.log(` FOUND: ${r.id} — ${r.statement}${suffix}`);
142
- } else {
143
- missing++;
144
- console.log(` MISSING: ${r.id} — ${r.statement} (${r.detail})`);
145
- }
146
- }
147
-
148
- console.log("");
149
- console.log(
150
- `=== Reconcile: ${found} found, ${missing} missing out of ${found + missing} decisions ===`
151
- );
152
- process.exit(missing === 0 ? 0 : 1);
@@ -1,76 +0,0 @@
1
- #!/bin/bash
2
- # Dump current crontab before every commit so scripts/crontab.txt never drifts.
3
-
4
- CRONTAB_FILE="$(git rev-parse --show-toplevel)/scripts/crontab.txt"
5
-
6
- {
7
- echo "# PAI Crontab — restore with: crontab ~/.claude/scripts/crontab.txt"
8
- echo "# Last updated: $(date '+%Y-%m-%d')"
9
- echo ""
10
- crontab -l 2>/dev/null || true
11
- } > "$CRONTAB_FILE"
12
-
13
- git add "$CRONTAB_FILE"
14
-
15
- # ─── Secret Scanner ─────────────────────────────────────────────────
16
- # Scans staged diff content for leaked secrets. Blocks commit on match.
17
-
18
- REPO_ROOT="$(git rev-parse --show-toplevel)"
19
- ALLOWLIST="$REPO_ROOT/.secret-scan-allowlist"
20
-
21
- # Build grep pattern for all 8 secret types
22
- SECRET_PATTERNS='(ghp_[A-Za-z0-9]{36}|gho_[A-Za-z0-9]{36}|ghs_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9]{22}_[A-Za-z0-9]{59}|AKIA[A-Z0-9]{16}|sk-[A-Za-z0-9]{48}|-----BEGIN (RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----|sk-ant-[A-Za-z0-9\-]{90,})'
23
-
24
- # Get staged diff (added/copied/modified files only, exclude crontab.txt)
25
- STAGED_DIFF="$(git diff --cached --diff-filter=ACM -U0 -- . ':!scripts/crontab.txt')"
26
-
27
- if [ -n "$STAGED_DIFF" ]; then
28
- MATCHES=""
29
- CURRENT_FILE=""
30
- IS_BINARY=false
31
-
32
- while IFS= read -r line; do
33
- # Track which file we're in
34
- if [[ "$line" =~ ^diff\ --git\ a/(.+)\ b/ ]]; then
35
- CURRENT_FILE="${BASH_REMATCH[1]}"
36
- IS_BINARY=false
37
- continue
38
- fi
39
-
40
- # Skip binary files
41
- if [[ "$line" == "Binary files"* ]] || [[ "$line" == "GIT binary patch"* ]]; then
42
- IS_BINARY=true
43
- continue
44
- fi
45
- if [ "$IS_BINARY" = true ]; then
46
- continue
47
- fi
48
-
49
- # Only check added lines (start with +, but not +++ header)
50
- if [[ "$line" =~ ^\+[^+] ]] || [[ "$line" == "+" ]]; then
51
- # Check against allowlist
52
- if [ -n "$CURRENT_FILE" ] && [ -f "$ALLOWLIST" ]; then
53
- if grep -qxF "$CURRENT_FILE" "$ALLOWLIST" 2>/dev/null; then
54
- continue
55
- fi
56
- fi
57
-
58
- # Scan for secret patterns
59
- if echo "$line" | grep -qE "$SECRET_PATTERNS"; then
60
- MATCHES="${MATCHES}[SECRET SCAN] BLOCKED: potential secret found in ${CURRENT_FILE}\n"
61
- fi
62
- fi
63
- done <<< "$STAGED_DIFF"
64
-
65
- if [ -n "$MATCHES" ]; then
66
- echo ""
67
- echo "════════════════════════════════════════════════════"
68
- echo " SECRET SCAN FAILED — commit blocked"
69
- echo "════════════════════════════════════════════════════"
70
- echo ""
71
- echo -e "$MATCHES"
72
- echo "To allowlist a file, add its path to .secret-scan-allowlist"
73
- echo "════════════════════════════════════════════════════"
74
- exit 1
75
- fi
76
- fi
@@ -1,271 +0,0 @@
1
- #!/usr/bin/env bun
2
- /**
3
- * Pre-push hook — blocks push to main when ship verify-gate hasn't passed.
4
- * TypeScript port of the bash pre-push (ADR-008 #448).
5
- *
6
- * Uses findWorkflowForIssue() from hooks/lib/findWorkflow.ts for resolution.
7
- * Resolution priority: projectRoot > issue number > mtime fallback.
8
- */
9
-
10
- import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'fs';
11
- import { join, dirname } from 'path';
12
- import { execSync } from 'child_process';
13
- import { harnessRoot } from '../../lib/paths';
14
- const _hr = harnessRoot();
15
- const { findWorkflowForIssue, extractIssueNumber } = await import(join(_hr, 'hooks/lib/findWorkflow'));
16
- const { verifyWitnessChain } = await import(join(_hr, 'gates/witness'));
17
-
18
- const BASE_DIR = process.env.PAI_DIR || join(process.env.HOME!, '.claude');
19
- const WORK_DIR = process.env.PAI_WORK_DIR || join(process.env.HOME!, '.pai-work');
20
- const SIGNALS_DIR = join(BASE_DIR, 'MEMORY/LEARNING/SIGNALS');
21
-
22
- const TTL_SECONDS = 14400; // 4 hours
23
-
24
- // ── Helpers ──────────────────────────────────────────────────────────
25
-
26
- function git(cmd: string): string {
27
- try {
28
- return execSync(`git ${cmd}`, { encoding: 'utf-8' }).trim();
29
- } catch {
30
- return '';
31
- }
32
- }
33
-
34
- function resolveSlugFromPath(absPath: string): string {
35
- return absPath.replace(WORK_DIR + '/', '');
36
- }
37
-
38
- function nowISO(): string {
39
- return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
40
- }
41
-
42
- function writeSignal(prefix: string, data: Record<string, unknown>): void {
43
- mkdirSync(SIGNALS_DIR, { recursive: true });
44
- const file = join(SIGNALS_DIR, `${prefix}-${Math.floor(Date.now() / 1000)}.json`);
45
- writeFileSync(file, JSON.stringify(data, null, 2) + '\n');
46
- }
47
-
48
- // ── Read stdin: determine if pushing to main ─────────────────────────
49
-
50
- const stdin = readFileSync(0, 'utf-8');
51
- const remote = process.argv[2] || '';
52
- const url = process.argv[3] || '';
53
-
54
- let pushingToMain = false;
55
- for (const line of stdin.split('\n')) {
56
- const parts = line.trim().split(/\s+/);
57
- const remoteRef = parts[2] || '';
58
- if (remoteRef === 'refs/heads/main' || remoteRef === 'refs/heads/master') {
59
- pushingToMain = true;
60
- }
61
- }
62
-
63
- if (!pushingToMain) process.exit(0);
64
-
65
- // ── Commit-prefix fast-path ──────────────────────────────────────────
66
-
67
- const commitMsg = git('log --oneline -1 HEAD');
68
- if (/^[a-f0-9]+ (docs:|chore:|backup:|nightly:)/.test(commitMsg)) {
69
- process.exit(0);
70
- }
71
-
72
- // ── Find active workflow via shared resolution ───────────────────────
73
-
74
- const repoRoot = git('rev-parse --show-toplevel');
75
- const issueNum = extractIssueNumber(commitMsg);
76
-
77
- // Active phases — exclude DONE and CIRCUIT_BREAK
78
- const activePhases = ['BUILD', 'VERIFY', 'SCOPE', 'SHIP'];
79
-
80
- const workflow = findWorkflowForIssue(issueNum, activePhases, undefined, repoRoot || undefined);
81
-
82
- // ── No active workflow → audit for orphans, allow push ───────────────
83
-
84
- if (!workflow) {
85
- // Check for orphaned workflow-state.json (marker deletion bypass)
86
- if (existsSync(WORK_DIR)) {
87
- try {
88
- const scanDirs = (base: string) => {
89
- for (const d of readdirSync(base, { withFileTypes: true })) {
90
- if (!d.isDirectory()) continue;
91
- const wfPath = join(base, d.name, 'workflow-state.json');
92
- if (!existsSync(wfPath)) continue;
93
- try {
94
- const data = JSON.parse(readFileSync(wfPath, 'utf-8'));
95
- const phase = data.phase;
96
- if (phase && phase !== 'DONE' && phase !== 'CIRCUIT_BREAK') {
97
- const shipActive = join(base, d.name, '.ship-active');
98
- if (!existsSync(shipActive)) {
99
- writeSignal('marker-missing', {
100
- ts: nowISO(),
101
- type: 'marker_missing',
102
- phase,
103
- slug: resolveSlugFromPath(join(base, d.name)),
104
- issue: data.issue || 0,
105
- remote,
106
- url,
107
- user: process.env.USER || 'unknown',
108
- });
109
- console.error('⚠️ Ship marker missing for active issue — audit logged');
110
- }
111
- }
112
- } catch {}
113
- }
114
- };
115
- scanDirs(WORK_DIR);
116
- // Scan nested (e.g., pai/361)
117
- for (const d of readdirSync(WORK_DIR, { withFileTypes: true })) {
118
- if (d.isDirectory()) scanDirs(join(WORK_DIR, d.name));
119
- }
120
- } catch {}
121
- }
122
- process.exit(0);
123
- }
124
-
125
- const wfDir = dirname(workflow.path);
126
- const wfData = workflow.data;
127
- const shipIssue: number = wfData.issue || 0;
128
-
129
- // ── HOTFIX override ─────────────────────────────────────────────────
130
-
131
- const hotfix = process.env.HOTFIX;
132
- if (hotfix) {
133
- // Format validation — restrict to known categories
134
- if (!/^(issue-\d+|docs|chore|backup|nightly)$/.test(hotfix)) {
135
- console.error(`HOTFIX format invalid: '${hotfix}' (expected: issue-NNN, docs, chore, backup, nightly)`);
136
- process.exit(1);
137
- }
138
-
139
- // Rate-limit warning — flag repeated overrides for same ref
140
- if (existsSync(SIGNALS_DIR)) {
141
- try {
142
- const oneHourAgo = Date.now() - 3600000;
143
- const recentCount = readdirSync(SIGNALS_DIR)
144
- .filter(f => f.startsWith('hotfix-'))
145
- .filter(f => {
146
- const fPath = join(SIGNALS_DIR, f);
147
- if (statSync(fPath).mtimeMs < oneHourAgo) return false;
148
- try {
149
- const content = JSON.parse(readFileSync(fPath, 'utf-8'));
150
- return content.hotfix_ref === hotfix;
151
- } catch { return false; }
152
- }).length;
153
- if (recentCount >= 2) {
154
- console.error(`⚠️ WARN: ${recentCount} HOTFIX overrides for '${hotfix}' in last hour`);
155
- }
156
- } catch {}
157
- }
158
-
159
- writeSignal('hotfix', {
160
- ts: nowISO(),
161
- type: 'hotfix_override',
162
- issue: shipIssue,
163
- hotfix_ref: hotfix,
164
- remote,
165
- url,
166
- user: process.env.USER || 'unknown',
167
- hostname: execSync('hostname -s', { encoding: 'utf-8' }).trim(),
168
- });
169
- console.error(`⚠️ HOTFIX override — audit logged to ${SIGNALS_DIR}`);
170
- process.exit(0);
171
- }
172
-
173
- // ── GATE_PASSED_PUSH bypass ──────────────────────────────────────────
174
-
175
- if (process.env.GATE_PASSED_PUSH) {
176
- const gateSha = wfData.gates?.ship?.commitSha;
177
- const headSha = git('rev-parse HEAD');
178
- if (gateSha && gateSha === headSha) {
179
- console.error(` Gate-passed push — SHA verified (${gateSha})`);
180
- process.exit(0);
181
- }
182
- console.error(gateSha
183
- ? ` Gate SHA mismatch (${gateSha} vs ${headSha}) — running gates`
184
- : ' Cannot verify gate SHA — running gates');
185
- }
186
-
187
- // ── Verify gate results from workflow-state ──────────────────────────
188
- // Pre-push is ADVISORY — IssueCloseGuard is the enforcement point.
189
-
190
- const headSha = git('rev-parse HEAD');
191
- let allPass = true;
192
- let missingGates: string[] = [];
193
-
194
- for (const gate of ['scope', 'verify', 'ship'] as const) {
195
- const gateResult: string = wfData.gates?.[gate]?.result || '';
196
- const gateSha: string = wfData.gates?.[gate]?.commitSha || '';
197
-
198
- if (gateResult === 'PASS') {
199
- if (gateSha && gateSha === headSha) {
200
- console.error(` ✓ ${gate} — PASS (SHA verified)`);
201
- } else {
202
- console.error(` ⚠ ${gate} — PASS but SHA mismatch (${gateSha} vs ${headSha}) — WARN`);
203
- }
204
- } else if (!gateResult) {
205
- console.error(` ○ ${gate} — not run yet`);
206
- missingGates.push(gate);
207
- allPass = false;
208
- } else {
209
- console.error(` ✗ ${gate} — ${gateResult}`);
210
- allPass = false;
211
- }
212
- }
213
-
214
- if (allPass) {
215
- console.error(' All gates PASS — push allowed');
216
- } else if (missingGates.length > 0) {
217
- // Active workflow but gates not run — BLOCK unless ship gate PASS
218
- const shipGate = wfData.gates?.ship?.result;
219
- if (shipGate !== 'PASS') {
220
- console.error(` BLOCKED: Active workflow exists but ship gate not PASS (missing: ${missingGates.join(', ')})`);
221
- console.error(' Run gate checks or set HOTFIX=issue-NNN to override.');
222
- process.exit(1);
223
- }
224
- console.error(` ⚠️ WARN: Gates not run: ${missingGates.join(', ')} — push allowed (ship gate PASS)`);
225
- } else {
226
- // Active workflow with failed gates — BLOCK
227
- console.error(' BLOCKED: Gates not PASS — fix gate failures before pushing.');
228
- console.error(' Set HOTFIX=issue-NNN to override.');
229
- process.exit(1);
230
- }
231
-
232
- // ── Stale-PASS detection ─────────────────────────────────────────────
233
-
234
- const staleSha = wfData.gates?.ship?.commitSha || wfData.gates?.verify?.commitSha;
235
- if (staleSha && staleSha !== headSha) {
236
- console.error(`⚠️ WARN: Gates passed at commit ${staleSha} but HEAD is now ${headSha}`);
237
- console.error(' New commits since gate-run may not be validated.');
238
- }
239
-
240
- // ── Witness chain verification (#471) ───────────────────────────────
241
- // Ground-truth check: verify HMAC-signed witness files match gate results
242
-
243
- const wfSlug = resolveSlugFromPath(wfDir);
244
- try {
245
- const chain = verifyWitnessChain(wfSlug, headSha);
246
- if (chain.valid) {
247
- console.error(` ✓ Witness chain verified (${chain.witnesses.length} witnesses)`);
248
- } else {
249
- for (const err of chain.errors) {
250
- console.error(` ⚠ Witness: ${err}`);
251
- }
252
- // WARN, not BLOCK — witness chain is additive; workflow-state gates are primary
253
- console.error(' ⚠️ WARN: Witness chain verification failed — audit logged');
254
- writeSignal('witness-chain-fail', {
255
- ts: nowISO(),
256
- type: 'witness_chain_failure',
257
- slug: wfSlug,
258
- issue: shipIssue,
259
- errors: chain.errors,
260
- witnessCount: chain.witnesses.length,
261
- remote,
262
- url,
263
- user: process.env.USER || 'unknown',
264
- });
265
- }
266
- } catch (e: any) {
267
- // Witness module not available or salt missing — degrade gracefully
268
- console.error(` ○ Witness chain: ${e.message}`);
269
- }
270
-
271
- process.exit(0);
@@ -1,52 +0,0 @@
1
- #!/usr/bin/env bash
2
- # harness-skill-check.sh — Validate a skill's SKILL.md meets the harness contract
3
- # Usage: harness-skill-check.sh skills/{name}/SKILL.md
4
- set -euo pipefail
5
-
6
- if [[ -z "${1:-}" ]]; then
7
- echo "Usage: harness-skill-check.sh skills/<name>/SKILL.md"
8
- exit 1
9
- fi
10
- SKILL_FILE="$1"
11
-
12
- if [[ ! -f "$SKILL_FILE" ]]; then
13
- echo "FAIL: $SKILL_FILE not found"
14
- exit 1
15
- fi
16
-
17
- PASSES=0 FAILS=0
18
- check() {
19
- local name=$1 pattern=$2
20
- if grep -q "$pattern" "$SKILL_FILE" 2>/dev/null; then
21
- echo " ✓ $name"
22
- PASSES=$((PASSES + 1))
23
- else
24
- echo " ✗ $name — missing"
25
- FAILS=$((FAILS + 1))
26
- fi
27
- }
28
-
29
- SKILL_NAME=$(basename "$(dirname "$SKILL_FILE")")
30
- echo "Checking skill: $SKILL_NAME"
31
- echo "File: $SKILL_FILE"
32
- echo "---"
33
-
34
- # YAML frontmatter exists
35
- check "YAML frontmatter" "^---"
36
-
37
- # Required contract fields
38
- check "contract.input" "input:"
39
- check "contract.gateIn" "gateIn:"
40
- check "contract.gateOut" "gateOut:"
41
- check "contract.artifact" "artifact:"
42
- check "contract.telemetry" "telemetry:"
43
- check "contract.errorRecovery" "errorRecovery:"
44
-
45
- # Required sections
46
- check "Trigger conditions" "## Trigger"
47
- check "Workflow section" "## Workflow"
48
- check "Error handling" "[Ee]rror"
49
-
50
- echo "---"
51
- echo "=== Results: $PASSES pass, $FAILS fail ==="
52
- [[ $FAILS -eq 0 ]] && exit 0 || exit 1
@@ -1,65 +0,0 @@
1
- #!/usr/bin/env bash
2
- # gap-emit.sh — Read gate-runs.jsonl and produce gap summary (D-036)
3
- # Thin normalizer: PAI emits, AgentGrit analyzes (D-039)
4
- # --file mode: create GitHub issues from gaps (D-035)
5
- set -euo pipefail
6
-
7
- AFK_GAP_CAP="${AFK_GAP_CAP:-5}"
8
- FILE_MODE=false
9
- ISSUE_REPO=""
10
- SOURCE_ISSUE=0
11
-
12
- # Parse flags
13
- case "${1:-}" in
14
- --file)
15
- FILE_MODE=true
16
- WORK_DIR="${2:?Usage: gap-emit.sh --file <work-dir> [repo] [source-issue]}"
17
- ISSUE_REPO="${3:-hornjason/pai-config}"
18
- SOURCE_ISSUE="${4:-0}"
19
- ;;
20
- *)
21
- WORK_DIR="${1:?Usage: gap-emit.sh [--file] <work-dir> [repo] [source-issue]}"
22
- ISSUE_REPO="${2:-hornjason/pai-config}"
23
- SOURCE_ISSUE="${3:-0}"
24
- ;;
25
- esac
26
-
27
- GATE_RUNS="$WORK_DIR/gate-runs.jsonl"
28
-
29
- [[ -f "$GATE_RUNS" ]] || { echo "No gaps detected"; exit 0; }
30
-
31
- gap_count=$(wc -l < "$GATE_RUNS" | tr -d ' ')
32
- fail_count=$(grep -c '"FAIL"' "$GATE_RUNS" 2>/dev/null || echo 0)
33
- warn_count=$(grep -c '"WARN"' "$GATE_RUNS" 2>/dev/null || echo 0)
34
- top_types=$(jq -r '.gap_type' "$GATE_RUNS" 2>/dev/null | sort | uniq -c | sort -rn | head -5 | awk '{print $2}' | paste -sd, -)
35
-
36
- echo "Gaps: $gap_count total ($fail_count FAIL, $warn_count WARN)"
37
- echo "Top types: ${top_types:-none}"
38
- echo "AFK auto-file cap: $AFK_GAP_CAP per cycle"
39
-
40
- # --file mode: create GitHub issues from gaps (D-035)
41
- if [[ "$FILE_MODE" == "true" ]]; then
42
- if [[ "${PAI_AFK:-}" == "1" ]] || ! test -t 0; then
43
- # AFK or non-interactive: auto-file up to AFK_GAP_CAP issues
44
- filed=0
45
- while IFS= read -r gap_line && [ "$filed" -lt "$AFK_GAP_CAP" ]; do
46
- gap_type=$(echo "$gap_line" | jq -r '.gap_type')
47
- detail=$(echo "$gap_line" | jq -r '.detail')
48
- check=$(echo "$gap_line" | jq -r '.check')
49
-
50
- gh issue create --repo "$ISSUE_REPO" --title "Gap: $check — $detail" \
51
- --label "needs-triage" \
52
- --body "Auto-filed by learning loop (D-035).
53
-
54
- Source: #$SOURCE_ISSUE
55
- Gap type: $gap_type
56
- Check: $check
57
- Detail: $detail" 2>/dev/null && filed=$((filed + 1))
58
- done < <(jq -c '.' "$GATE_RUNS" 2>/dev/null | head -"$AFK_GAP_CAP")
59
-
60
- echo " Filed $filed gap issues (cap: $AFK_GAP_CAP)"
61
- else
62
- # Interactive: just output summary — DA decides what to file
63
- echo " Interactive mode — review gaps above, file manually if needed"
64
- fi
65
- fi
@@ -1,30 +0,0 @@
1
- #!/usr/bin/env bash
2
- # jq-update.sh — Atomic JSON update with file locking
3
- # Decision #7: Deep modules, thin consumers
4
- # Usage: source this file, then call jq_update [jq-args] file.json
5
-
6
- jq_update() {
7
- local src="${@: -1}"
8
- local tmp; tmp=$(mktemp "${src}.XXXXXX")
9
- (
10
- if command -v flock >/dev/null 2>&1; then
11
- flock -w 5 200 || { echo "WARN: jq_update lock timeout — skipping" >&2; rm -f "$tmp"; exit 1; }
12
- fi
13
- if jq "${@:1:$#-1}" "$src" > "$tmp" 2>/dev/null; then
14
- if [[ -s "$tmp" ]] && jq empty "$tmp" 2>/dev/null; then
15
- mv "$tmp" "$src"
16
- else
17
- echo "WARN: jq_update produced invalid JSON — original preserved" >&2
18
- rm -f "$tmp"
19
- exit 1
20
- fi
21
- else
22
- echo "WARN: jq_update failed — original preserved" >&2
23
- rm -f "$tmp"
24
- exit 1
25
- fi
26
- ) 200>"${src}.lock"
27
- local rc=$?
28
- rm -f "${src}.lock" 2>/dev/null
29
- return $rc
30
- }
@@ -1,30 +0,0 @@
1
- # resolve-slug.sh — Shared slug resolution functions.
2
- # Source this file; do not execute directly.
3
- # No shebang, no set -euo — inherited from caller.
4
-
5
- # resolve_slug_from_path(abs_path) — converts work dir path to relative slug.
6
- # Example: /Users/jhorn/.rungate/pai/361 -> pai/361
7
- resolve_slug_from_path() {
8
- local abs_path="$1"
9
- local work_dir="${RUNGATE_WORK_DIR:-${HOME}/.rungate}"
10
- echo "${abs_path#${work_dir}/}"
11
- }
12
-
13
- # resolve_slug_from_repo(repo_identifier) — maps repo to short prefix.
14
- # Input: "hornjason/pai-config" or full git URL.
15
- # Output: short name (e.g., "pai", "ddb").
16
- # Returns 1 on unknown repo.
17
- resolve_slug_from_repo() {
18
- local repo="$1"
19
- # Strip URL prefix if present
20
- repo=$(echo "$repo" | sed 's|.*github.com[:/]||' | sed 's|\.git$||')
21
- case "$repo" in
22
- hornjason/pai-config) echo "pai" ;;
23
- hornjason/asaCommandCenter) echo "ddb" ;;
24
- hornjason/daily-brief-dashboard) echo "ddb" ;;
25
- *)
26
- echo "FAIL: unknown repo '$repo' — add mapping to scripts/lib/resolve-slug.sh" >&2
27
- return 1
28
- ;;
29
- esac
30
- }