rungate 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/hooks/ActionVerificationGate.hook.ts +96 -0
- package/hooks/AgentBriefGuard.hook.ts +38 -0
- package/hooks/AgentVerdictCapture.hook.ts +87 -0
- package/hooks/AutoVerifyGate.hook.ts +79 -0
- package/hooks/BashToolGuard.hook.ts +65 -0
- package/hooks/BashWriteGuard.hook.ts +60 -0
- package/hooks/CommitEnforcement.hook.ts +130 -0
- package/hooks/DocHygiene.hook.ts +148 -0
- package/hooks/GateEnforcement.hook.ts +58 -0
- package/hooks/GateResultProtection.hook.ts +69 -0
- package/hooks/HarnessAFKGate.hook.ts +85 -0
- package/hooks/HookCurrency.hook.ts +99 -0
- package/hooks/IssueCloseGuard.hook.ts +149 -0
- package/hooks/MergeGuard.hook.ts +58 -0
- package/hooks/PostCompact.hook.ts +60 -0
- package/hooks/ProjectStateSync.hook.ts +103 -0
- package/hooks/SkillGuard.hook.ts +69 -0
- package/hooks/SpecConformityTrigger.hook.ts +43 -0
- package/hooks/SpecSCGuard.hook.ts +123 -0
- package/hooks/StaleTTLCleanup.hook.ts +141 -0
- package/hooks/TaskCompleted.hook.ts +51 -0
- package/hooks/TeamInit.hook.ts +85 -0
- package/hooks/TestSuiteGuard.hook.ts +70 -0
- package/hooks/TestSuiteRelease.hook.ts +85 -0
- package/hooks/TopLevelCdGuard.hook.ts +108 -0
- package/hooks/VerifyPhaseLock.hook.ts +84 -0
- package/hooks/WorkflowStateGuard.hook.ts +40 -0
- package/hooks/lib/agent-config.json +9 -0
- package/hooks/lib/agentDetection.ts +201 -0
- package/hooks/lib/comment-template.ts +86 -0
- package/hooks/lib/findWorkflow.ts +101 -0
- package/hooks/lib/parseStdin.ts +37 -0
- package/hooks/lib/paths.ts +111 -0
- package/hooks/lib/utils.ts +338 -0
- package/lib/affected-tests.ts +427 -0
- package/lib/agent-audit.ts +2 -3
- package/lib/agent-worktree.ts +287 -0
- package/lib/agents-md-sections.ts +81 -16
- package/lib/bash-write-guard.ts +373 -0
- package/lib/behavioral-cache.ts +150 -2
- package/lib/branch-cleanup.ts +279 -7
- package/lib/branch-protection.ts +790 -0
- package/lib/brief-ac-alignment.ts +104 -0
- package/lib/brief-references.ts +205 -0
- package/lib/bun-version.ts +93 -14
- package/lib/check-remedy.ts +140 -0
- package/lib/ci-checkout.ts +17 -0
- package/lib/ci-history-depth.ts +159 -0
- package/lib/ci-setup-step.ts +96 -0
- package/lib/claude-code-action.ts +85 -0
- package/lib/claude-tool-vocabulary.ts +188 -0
- package/lib/cli-commands.ts +15 -0
- package/lib/commit-sha.ts +42 -0
- package/lib/commit-subject.ts +90 -0
- package/lib/compliance-report.ts +377 -45
- package/lib/compliance.ts +191 -17
- package/lib/config-loader.ts +39 -1
- package/lib/config-trackable.ts +400 -0
- package/lib/conformity.ts +1087 -100
- package/lib/containment.ts +238 -0
- package/lib/content-hash.ts +24 -0
- package/lib/create-sc.ts +249 -16
- package/lib/dev-liveness.ts +180 -0
- package/lib/discovery-branch-points.ts +432 -0
- package/lib/discovery-stability.ts +481 -0
- package/lib/distribution-currency.ts +236 -0
- package/lib/doc-routing.ts +157 -0
- package/lib/evidence-prevalidator.ts +224 -2
- package/lib/evidence-satisfiability.ts +534 -12
- package/lib/failure-intake.ts +323 -0
- package/lib/fallow-availability.ts +157 -0
- package/lib/fs-write-capabilities.ts +232 -0
- package/lib/gate-enforcement.ts +222 -28
- package/lib/gate-names.ts +72 -0
- package/lib/gate-result-protection.ts +427 -0
- package/lib/gate-run-split.ts +147 -0
- package/lib/generators/agents-md.ts +140 -32
- package/lib/git-isolation.ts +140 -0
- package/lib/github.ts +15 -0
- package/lib/google-auth-action.ts +93 -0
- package/lib/harness-project.ts +48 -0
- package/lib/harness-provenance.ts +255 -0
- package/lib/hook-evidence.ts +235 -0
- package/lib/hook-scopes.ts +386 -0
- package/lib/hook-target-tree.ts +398 -0
- package/lib/hook-trees.ts +447 -0
- package/lib/intake-sources.ts +380 -0
- package/lib/js-top-level-code.ts +78 -10
- package/lib/junit-checks.ts +52 -0
- package/lib/late-env-spawn.ts +331 -0
- package/lib/launch-base.ts +376 -0
- package/lib/line-citation.ts +372 -0
- package/lib/orphan-reaper.ts +468 -0
- package/lib/parity-binding.ts +205 -0
- package/lib/paths.ts +96 -3
- package/lib/per-test-timeouts.ts +219 -0
- package/lib/phase2-decomposition.ts +1 -1
- package/lib/plan-coverage.ts +151 -0
- package/lib/prior-branch.ts +201 -8
- package/lib/process-table.ts +146 -0
- package/lib/project-state-derivation.ts +219 -0
- package/lib/project-state-root.ts +258 -0
- package/lib/published-artifact.ts +669 -0
- package/lib/readdir-sorted.ts +45 -0
- package/lib/review-execution-reading.ts +206 -0
- package/lib/review-tool-agreement.ts +433 -0
- package/lib/rule-promotion.ts +234 -0
- package/lib/rule-retirement.ts +525 -0
- package/lib/run-branch.ts +612 -0
- package/lib/rungate-schema.ts +19 -0
- package/lib/runner-home.ts +274 -0
- package/lib/sc-id-cross-tree.ts +103 -15
- package/lib/sc-ids.ts +121 -13
- package/lib/sc-reservations.ts +289 -0
- package/lib/scaffold/ai-review-findings.ts +409 -0
- package/lib/scaffold/ai-review-step.ts +5406 -64
- package/lib/scaffold/defaults.ts +82 -1
- package/lib/scaffold/managed-workflow.ts +587 -192
- package/lib/scaffold/owned-files.ts +152 -45
- package/lib/scaffold/pre-push-hook.ts +49 -5
- package/lib/scaffold/steps.ts +1836 -275
- package/lib/scaffold/workflow-census.ts +217 -0
- package/lib/scaffold/workflow-drift.ts +217 -0
- package/lib/scaffold/write-steps.ts +4 -0
- package/lib/scan-budget.ts +247 -0
- package/lib/scanner.ts +43 -51
- package/lib/scratch-roots.ts +50 -5
- package/lib/screenshot-discovery.ts +121 -0
- package/lib/screenshot-upload.ts +41 -1
- package/lib/secret-patterns.ts +511 -8
- package/lib/security-verdict.ts +1 -1
- package/lib/shell-path-interpolation.ts +594 -0
- package/lib/ship-mode.ts +219 -0
- package/lib/source-slice.ts +294 -0
- package/lib/stale-cleanup.ts +37 -3
- package/lib/suite-flake.ts +278 -0
- package/lib/suite-measurement.ts +23 -4
- package/lib/suite-run-reading.ts +241 -1
- package/lib/suite-timeout-margin.ts +193 -0
- package/lib/test-case-bodies.ts +883 -0
- package/lib/test-case-deletion.ts +653 -0
- package/lib/test-census.ts +97 -29
- package/lib/test-command-positions.ts +274 -0
- package/lib/test-suite-lock.ts +159 -16
- package/lib/text-dependents.ts +875 -0
- package/lib/tool-probe.ts +31 -9
- package/lib/top-level-cd.ts +393 -0
- package/lib/tree-entries.ts +89 -0
- package/lib/ts-ast.ts +200 -0
- package/lib/walk-test-files.ts +97 -0
- package/lib/workflow-actions.ts +263 -0
- package/lib/workflow-security.ts +29 -0
- package/lib/workflow-taint.ts +732 -0
- package/lib/worktree-cleanup.ts +65 -38
- package/lib/worktree-collect.ts +177 -5
- package/lib/worktree-repo.ts +68 -3
- package/package.json +4 -1
- package/scripts/ai-review-findings.ts +45 -0
- package/scripts/check-installed-hook-currency.ts +825 -0
- package/scripts/create-sc.ts +21 -1
- package/scripts/extract-constraints.ts +107 -7
- package/scripts/generate-code-map.ts +23 -30
- package/scripts/scaffold-project.ts +8 -1
- package/scripts/sync-sc-status.ts +77 -16
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Issue-comment template validation, lifted out of IssueCloseGuard.
|
|
3
|
+
*
|
|
4
|
+
* HOOK-ARCHITECTURE-SPEC wants hooks to be thin triggers that delegate to
|
|
5
|
+
* lib, and SC-371 caps a hook at 150 lines — which the guard crossed when
|
|
6
|
+
* #140 made its failure handling explicit. Moving this out is the fix the
|
|
7
|
+
* spec asks for rather than a cap raise, and it makes the rules unit-testable
|
|
8
|
+
* without driving a subprocess.
|
|
9
|
+
*
|
|
10
|
+
* Returns the reason a comment should be refused, or null to allow it. The
|
|
11
|
+
* caller owns the blocking, so the rules stay pure.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { readFileSync } from 'fs';
|
|
15
|
+
|
|
16
|
+
export const TEMPLATE_RULES = [
|
|
17
|
+
{ marker: '## AC-', required: ['Type:', 'Metric:', 'Threshold:', 'Baseline:', 'Evidence Method:', 'Pass Criteria:'] },
|
|
18
|
+
{ marker: '## ATTEMPT', required: ['Approach:', 'Files Changed:', 'Result:', 'Evidence:', 'Why It Failed:'] },
|
|
19
|
+
{ marker: '## DISCOVERY', required: ['### Docs read', '### Issue context'] },
|
|
20
|
+
{ marker: '## Completion Report', required: ['### Evidence per AC', '### Ship Scorecard'] },
|
|
21
|
+
{ marker: '## Sizing Declaration', required: ['Predicted:', 'Files:'] },
|
|
22
|
+
{ marker: '## Sizing Outcome', required: ['Declared:', 'Actual:'] },
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Whether this command posts an issue comment.
|
|
27
|
+
*
|
|
28
|
+
* Two forms now. `gh issue comment` is what a person types. `github-op.ts
|
|
29
|
+
* comment` is what workflow steps run since #137 — the MCP tools those steps
|
|
30
|
+
* used to name do not exist in this harness, so they went through the Octokit
|
|
31
|
+
* script instead. Matching only the first would have quietly exempted every
|
|
32
|
+
* comment the harness itself posts, which is most of them.
|
|
33
|
+
*/
|
|
34
|
+
export const COMMENT_INVOCATION = /gh\s+issue\s+comment\s+\d+|github-op\.ts\s+comment\b/;
|
|
35
|
+
|
|
36
|
+
/** The `--body` text of a comment command — heredoc, quoted, or a file. */
|
|
37
|
+
export function extractCommentBody(
|
|
38
|
+
command: string,
|
|
39
|
+
readFile: (path: string) => string = defaultReadFile,
|
|
40
|
+
): string {
|
|
41
|
+
const heredoc = command.match(/--body\s+"?\$\(cat\s+<<'?EOF'?\s*\n?([\s\S]*?)\nEOF/);
|
|
42
|
+
if (heredoc) return heredoc[1];
|
|
43
|
+
|
|
44
|
+
// `--body-file` is how #137 passes anything with a newline in it, so the
|
|
45
|
+
// template rules have to follow the body into the file or stop applying to
|
|
46
|
+
// exactly the comments that carry templates.
|
|
47
|
+
const file = command.match(/--body-file[\s=]+['"]?([^\s'"]+)/);
|
|
48
|
+
if (file) {
|
|
49
|
+
try {
|
|
50
|
+
return readFile(file[1]);
|
|
51
|
+
} catch {
|
|
52
|
+
// Unreadable here means unreadable for the command too, which will fail
|
|
53
|
+
// on its own. Nothing to validate, and refusing would block on a path
|
|
54
|
+
// this hook simply cannot see (a heredoc writes it in the same command).
|
|
55
|
+
return '';
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const quoted = command.match(/(?:--body|-b)\s+["']([^"']*(?:(?:\\.)[^"']*)*)['"]/);
|
|
60
|
+
return quoted ? quoted[1] : '';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function defaultReadFile(path: string): string {
|
|
64
|
+
return readFileSync(path, 'utf-8');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function commentTemplateViolation(command: string): string | null {
|
|
68
|
+
const body = extractCommentBody(command);
|
|
69
|
+
if (!body) return null;
|
|
70
|
+
|
|
71
|
+
if (/^## AC-\d+/m.test(body))
|
|
72
|
+
return 'ACs (## AC-N) must be posted to the issue body via "gh issue edit --body", not as comments.';
|
|
73
|
+
if (body.includes('### Docs read') && !body.includes('## DISCOVERY'))
|
|
74
|
+
return 'Comment contains "### Docs read" but no "## DISCOVERY" heading. Use the DISCOVERY template.';
|
|
75
|
+
if (body.includes('### Evidence per AC') && !body.includes('## Completion Report'))
|
|
76
|
+
return 'Comment contains "### Evidence per AC" but no "## Completion Report" heading.';
|
|
77
|
+
if (body.includes('REPLACE:'))
|
|
78
|
+
return 'Comment body contains unfilled REPLACE: placeholder(s).';
|
|
79
|
+
|
|
80
|
+
for (const rule of TEMPLATE_RULES) {
|
|
81
|
+
if (!body.includes(rule.marker)) continue;
|
|
82
|
+
const missing = rule.required.filter(f => !body.includes(f));
|
|
83
|
+
if (missing.length) return `Template "${rule.marker}" missing fields: ${missing.join(', ')}. See TEMPLATES.md.`;
|
|
84
|
+
}
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* findWorkflow.ts — Shared workflow discovery for hooks
|
|
3
|
+
*
|
|
4
|
+
* Used by: ScopeGateGuard, AutoVerifyGate
|
|
5
|
+
* Issue: #269
|
|
6
|
+
*
|
|
7
|
+
* Finds workflow-state.json by issue number (preferred) or mtime fallback.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readdirSync, readFileSync, existsSync, statSync } from 'fs';
|
|
11
|
+
import { join } from 'path';
|
|
12
|
+
|
|
13
|
+
const RUNGATE_WORK_DIR = process.env.RUNGATE_WORK_DIR || process.env.RUNGATE_WORK_DIR || join(process.env.HOME!, '.rungate');
|
|
14
|
+
|
|
15
|
+
interface WorkflowState {
|
|
16
|
+
path: string;
|
|
17
|
+
data: any;
|
|
18
|
+
slug: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function findWorkflowForIssue(issueNum?: string, phases?: string[], repo?: string, projectRoot?: string): WorkflowState | null {
|
|
22
|
+
if (!existsSync(RUNGATE_WORK_DIR)) return null;
|
|
23
|
+
|
|
24
|
+
const validPhases = phases || ['BUILD', 'VERIFY', 'SCOPE', 'SHIP', 'DONE'];
|
|
25
|
+
let candidates: { path: string; data: any; mtime: number; slug: string }[] = [];
|
|
26
|
+
|
|
27
|
+
// Collect all valid workflow entries
|
|
28
|
+
const collectWorkflow = (wfPath: string, slug: string) => {
|
|
29
|
+
if (!existsSync(wfPath)) return;
|
|
30
|
+
try {
|
|
31
|
+
const data = JSON.parse(readFileSync(wfPath, 'utf-8'));
|
|
32
|
+
if (!validPhases.includes(data.phase)) return;
|
|
33
|
+
const mtime = statSync(wfPath).mtimeMs;
|
|
34
|
+
candidates.push({ path: wfPath, data, mtime, slug });
|
|
35
|
+
} catch {}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
const dirs = readdirSync(RUNGATE_WORK_DIR, { withFileTypes: true })
|
|
40
|
+
.filter(d => d.isDirectory());
|
|
41
|
+
|
|
42
|
+
for (const d of dirs) {
|
|
43
|
+
// Level 1: direct children
|
|
44
|
+
collectWorkflow(join(RUNGATE_WORK_DIR, d.name, 'workflow-state.json'), d.name);
|
|
45
|
+
|
|
46
|
+
// Level 2: nested subdirectories (e.g., pai/361)
|
|
47
|
+
const subDir = join(RUNGATE_WORK_DIR, d.name);
|
|
48
|
+
try {
|
|
49
|
+
const subDirs = readdirSync(subDir, { withFileTypes: true }).filter(sd => sd.isDirectory());
|
|
50
|
+
for (const sd of subDirs) {
|
|
51
|
+
collectWorkflow(join(subDir, sd.name, 'workflow-state.json'), `${d.name}/${sd.name}`);
|
|
52
|
+
}
|
|
53
|
+
} catch {}
|
|
54
|
+
}
|
|
55
|
+
} catch {}
|
|
56
|
+
|
|
57
|
+
if (candidates.length === 0) return null;
|
|
58
|
+
|
|
59
|
+
// Resolution priority: projectRoot > issueNum > mtime fallback
|
|
60
|
+
|
|
61
|
+
// Priority 1: Match by projectRoot
|
|
62
|
+
if (projectRoot) {
|
|
63
|
+
const byRoot = candidates.filter(c => c.data.projectRoot === projectRoot);
|
|
64
|
+
if (byRoot.length === 1) return { path: byRoot[0].path, data: byRoot[0].data, slug: byRoot[0].slug };
|
|
65
|
+
if (byRoot.length > 1) {
|
|
66
|
+
// Multiple matches — narrow by issue if available
|
|
67
|
+
if (issueNum) {
|
|
68
|
+
const rootAndIssue = byRoot.find(c => String(c.data.issue) === issueNum);
|
|
69
|
+
if (rootAndIssue) return { path: rootAndIssue.path, data: rootAndIssue.data, slug: rootAndIssue.slug };
|
|
70
|
+
}
|
|
71
|
+
// Return most recent among projectRoot matches
|
|
72
|
+
byRoot.sort((a, b) => b.mtime - a.mtime);
|
|
73
|
+
return { path: byRoot[0].path, data: byRoot[0].data, slug: byRoot[0].slug };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Priority 2: Match by issue number
|
|
78
|
+
if (issueNum) {
|
|
79
|
+
const byIssue = candidates.filter(c => String(c.data.issue) === issueNum);
|
|
80
|
+
if (byIssue.length > 0) {
|
|
81
|
+
// Narrow by repo if provided
|
|
82
|
+
if (repo) {
|
|
83
|
+
const byRepo = byIssue.find(c => c.data.repo === repo);
|
|
84
|
+
if (byRepo) return { path: byRepo.path, data: byRepo.data, slug: byRepo.slug };
|
|
85
|
+
}
|
|
86
|
+
return { path: byIssue[0].path, data: byIssue[0].data, slug: byIssue[0].slug };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// If issueNum was specified but not matched, don't fall back to mtime
|
|
91
|
+
if (issueNum) return null;
|
|
92
|
+
|
|
93
|
+
// Priority 3: Most recent by mtime (last resort)
|
|
94
|
+
candidates.sort((a, b) => b.mtime - a.mtime);
|
|
95
|
+
return { path: candidates[0].path, data: candidates[0].data, slug: candidates[0].slug };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function extractIssueNumber(text: string): string | undefined {
|
|
99
|
+
const match = text.match(/#(\d+)/);
|
|
100
|
+
return match ? match[1] : undefined;
|
|
101
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared Stdin Parsing
|
|
3
|
+
*
|
|
4
|
+
* Centralizes JSON stdin reading used by all hooks.
|
|
5
|
+
* Single source of truth — replaces stream, text, and event patterns.
|
|
6
|
+
*
|
|
7
|
+
* Issue: #370 (extracted from 34 hooks)
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export interface HookInput {
|
|
11
|
+
tool_name?: string;
|
|
12
|
+
tool_input?: { command?: string; file_path?: string; prompt?: string; [k: string]: unknown };
|
|
13
|
+
tool_response?: { output?: string; [k: string]: unknown } | string;
|
|
14
|
+
session_id?: string;
|
|
15
|
+
transcript_path?: string;
|
|
16
|
+
hook_event_name?: string;
|
|
17
|
+
[k: string]: unknown;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Read and parse JSON from stdin with timeout.
|
|
22
|
+
* Returns parsed object or null on failure/timeout/empty.
|
|
23
|
+
*/
|
|
24
|
+
export async function parseHookInput<T = HookInput>(timeoutMs = 2000): Promise<T | null> {
|
|
25
|
+
try {
|
|
26
|
+
const raw = await Promise.race([
|
|
27
|
+
Bun.stdin.text(),
|
|
28
|
+
new Promise<string>((_, reject) =>
|
|
29
|
+
setTimeout(() => reject(new Error('stdin timeout')), timeoutMs),
|
|
30
|
+
),
|
|
31
|
+
]);
|
|
32
|
+
if (!raw?.trim()) return null;
|
|
33
|
+
return JSON.parse(raw) as T;
|
|
34
|
+
} catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Centralized Path Resolution
|
|
3
|
+
*
|
|
4
|
+
* Handles environment variable expansion for portable PAI configuration.
|
|
5
|
+
* Claude Code doesn't expand $HOME in settings.json env values, so we do it here.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
* import { getPaiDir, getSettingsPath } from './lib/paths';
|
|
9
|
+
* const paiDir = getPaiDir(); // Always returns expanded absolute path
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { homedir } from 'os';
|
|
13
|
+
import { join } from 'path';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Expand shell variables in a path string
|
|
17
|
+
* Supports: $HOME, ${HOME}, ~
|
|
18
|
+
*/
|
|
19
|
+
export function expandPath(path: string): string {
|
|
20
|
+
const home = homedir();
|
|
21
|
+
|
|
22
|
+
return path
|
|
23
|
+
.replace(/^\$HOME(?=\/|$)/, home)
|
|
24
|
+
.replace(/^\$\{HOME\}(?=\/|$)/, home)
|
|
25
|
+
.replace(/^~(?=\/|$)/, home);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Get the PAI directory (expanded)
|
|
30
|
+
* Priority: PAI_DIR env var (expanded) → ~/.claude
|
|
31
|
+
*/
|
|
32
|
+
export function getPaiDir(): string {
|
|
33
|
+
const envPaiDir = process.env.PAI_DIR;
|
|
34
|
+
|
|
35
|
+
if (envPaiDir) {
|
|
36
|
+
return expandPath(envPaiDir);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return join(homedir(), '.claude');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Get the settings.json path
|
|
44
|
+
*/
|
|
45
|
+
export function getSettingsPath(): string {
|
|
46
|
+
return join(getPaiDir(), 'settings.json');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Get a path relative to PAI_DIR
|
|
51
|
+
*/
|
|
52
|
+
export function paiPath(...segments: string[]): string {
|
|
53
|
+
return join(getPaiDir(), ...segments);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Get the hooks directory
|
|
58
|
+
* Priority: PAI_HOOKS_DIR env var → ~/.pai/hooks
|
|
59
|
+
*/
|
|
60
|
+
export function getHooksDir(): string {
|
|
61
|
+
const envHooksDir = process.env.PAI_HOOKS_DIR;
|
|
62
|
+
if (envHooksDir) return expandPath(envHooksDir);
|
|
63
|
+
return join(homedir(), '.pai', 'hooks');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Get the skills directory
|
|
68
|
+
*/
|
|
69
|
+
export function getSkillsDir(): string {
|
|
70
|
+
return paiPath('skills');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Get the MEMORY directory
|
|
75
|
+
*/
|
|
76
|
+
export function getMemoryDir(): string {
|
|
77
|
+
return paiPath('MEMORY');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Get the PAI work directory (expanded)
|
|
82
|
+
* Priority: RUNGATE_WORK_DIR env var (expanded) → ~/.rungate
|
|
83
|
+
*/
|
|
84
|
+
export function getWorkDir(): string {
|
|
85
|
+
const envWorkDir = process.env.RUNGATE_WORK_DIR;
|
|
86
|
+
|
|
87
|
+
if (envWorkDir) {
|
|
88
|
+
return expandPath(envWorkDir);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return join(homedir(), '.rungate');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Get a path relative to WORK_DIR
|
|
96
|
+
*/
|
|
97
|
+
export function workPath(...segments: string[]): string {
|
|
98
|
+
return join(getWorkDir(), ...segments);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Get the signals directory
|
|
103
|
+
*/
|
|
104
|
+
export function getSignalDir(): string {
|
|
105
|
+
return workPath('signals');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Convenience constants (evaluated once at module load)
|
|
109
|
+
export const BASE_DIR = getPaiDir();
|
|
110
|
+
export const WORK_DIR = getWorkDir();
|
|
111
|
+
export const SIGNAL_DIR = getSignalDir();
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, existsSync, statSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
|
|
4
|
+
export const WORK_DIR = join(process.env.RUNGATE_WORK_DIR || process.env.HOME!, '.rungate');
|
|
5
|
+
export const HARNESS_ROOT = process.env.HARNESS_ROOT || join(process.env.HOME!, 'Projects', 'rungate');
|
|
6
|
+
|
|
7
|
+
export interface HookInput {
|
|
8
|
+
tool_name?: string;
|
|
9
|
+
tool_input?: { command?: string; name?: string; subagent_type?: string; prompt?: string; [k: string]: unknown };
|
|
10
|
+
tool_response?: { output?: string; content?: string; [k: string]: unknown } | string;
|
|
11
|
+
session_id?: string;
|
|
12
|
+
/**
|
|
13
|
+
* The working directory the tool call was made from.
|
|
14
|
+
*
|
|
15
|
+
* Typed because #239 depends on it: sub-agent Bash calls reach the hooks
|
|
16
|
+
* carrying the PARENT session's id, so `session_id` cannot tell two sibling
|
|
17
|
+
* agents apart. Each runs in its own worktree, so the cwd can.
|
|
18
|
+
*/
|
|
19
|
+
cwd?: string;
|
|
20
|
+
[k: string]: unknown;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function parseHookInput(timeoutMs = 2000): Promise<HookInput | null> {
|
|
24
|
+
try {
|
|
25
|
+
const raw = await Promise.race([
|
|
26
|
+
Bun.stdin.text(),
|
|
27
|
+
new Promise<string>((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs)),
|
|
28
|
+
]);
|
|
29
|
+
if (!raw?.trim()) return null;
|
|
30
|
+
return JSON.parse(raw) as HookInput;
|
|
31
|
+
} catch { return null; }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const AGENT_CONFIG: Record<string, { match: string[]; exclude: string[] }> = {
|
|
35
|
+
marcus: { match: ['marcus', 'engineer', 'marcus webb'], exclude: ['council'] },
|
|
36
|
+
quinn: { match: ['quinn', 'qatester', 'quinn torres'], exclude: [] },
|
|
37
|
+
rook: { match: ['rook', 'pentester', 'rook blackburn'], exclude: [] },
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export function detectAgent(toolInput: { name?: string; subagent_type?: string; prompt?: string }): { key: string; name: string } | null {
|
|
41
|
+
const name = (toolInput.name || '').toLowerCase();
|
|
42
|
+
const type = (toolInput.subagent_type || '').toLowerCase();
|
|
43
|
+
const prompt = (toolInput.prompt || '').toLowerCase();
|
|
44
|
+
for (const [key, cfg] of Object.entries(AGENT_CONFIG)) {
|
|
45
|
+
if (cfg.exclude.some(ex => prompt.includes(ex))) continue;
|
|
46
|
+
if (cfg.match.some(p => name.includes(p) || type === p || prompt.includes(p)))
|
|
47
|
+
return { key, name: toolInput.name || key };
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface WorkflowResult { path: string; data: any; slug: string }
|
|
53
|
+
|
|
54
|
+
export function findWorkflowState(issueNum?: string, phases?: string[]): WorkflowResult | null {
|
|
55
|
+
if (!existsSync(WORK_DIR)) return null;
|
|
56
|
+
const validPhases = phases || ['BUILD', 'VERIFY', 'SCOPE', 'SHIP', 'DONE'];
|
|
57
|
+
const candidates: (WorkflowResult & { mtime: number })[] = [];
|
|
58
|
+
|
|
59
|
+
const collect = (wfPath: string, slug: string) => {
|
|
60
|
+
if (!existsSync(wfPath)) return;
|
|
61
|
+
try {
|
|
62
|
+
const data = JSON.parse(readFileSync(wfPath, 'utf-8'));
|
|
63
|
+
if (!validPhases.includes(data.phase)) return;
|
|
64
|
+
candidates.push({ path: wfPath, data, slug, mtime: statSync(wfPath).mtimeMs });
|
|
65
|
+
} catch {}
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
try {
|
|
69
|
+
for (const d of readdirSync(WORK_DIR, { withFileTypes: true }).filter(d => d.isDirectory())) {
|
|
70
|
+
collect(join(WORK_DIR, d.name, 'workflow-state.json'), d.name);
|
|
71
|
+
try {
|
|
72
|
+
for (const sd of readdirSync(join(WORK_DIR, d.name), { withFileTypes: true }).filter(sd => sd.isDirectory()))
|
|
73
|
+
collect(join(WORK_DIR, d.name, sd.name, 'workflow-state.json'), `${d.name}/${sd.name}`);
|
|
74
|
+
} catch {}
|
|
75
|
+
}
|
|
76
|
+
} catch {}
|
|
77
|
+
|
|
78
|
+
if (!candidates.length) return null;
|
|
79
|
+
if (issueNum) {
|
|
80
|
+
const match = candidates.find(c => String(c.data.issue) === issueNum);
|
|
81
|
+
return match ? { path: match.path, data: match.data, slug: match.slug } : null;
|
|
82
|
+
}
|
|
83
|
+
candidates.sort((a, b) => b.mtime - a.mtime);
|
|
84
|
+
return { path: candidates[0].path, data: candidates[0].data, slug: candidates[0].slug };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function extractIssueNumber(text: string): string | undefined {
|
|
88
|
+
return text.match(/#(\d+)/)?.[1];
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The `owner/name` a `gh` command targets, or undefined if it names none.
|
|
93
|
+
*
|
|
94
|
+
* Split out of IssueCloseGuard (#140) so it can be tested without driving the
|
|
95
|
+
* hook, and because HOOK-ARCHITECTURE-SPEC wants the logic in lib rather than
|
|
96
|
+
* in the trigger.
|
|
97
|
+
*
|
|
98
|
+
* The previous pattern was `--repo\s+(\S+)`, which ran to the next space and
|
|
99
|
+
* so captured whatever punctuation followed — `owner/name"}}'` when the close
|
|
100
|
+
* appeared inside a nested shell string. The lookup then 404'd on the mangled
|
|
101
|
+
* slug. That was harmless while the guard swallowed errors; now that an
|
|
102
|
+
* unreadable label set blocks the close, a sloppy parse refuses legitimate
|
|
103
|
+
* work. Match the slug's shape and stop.
|
|
104
|
+
*
|
|
105
|
+
* This parses a command string to infer what `gh` will do, which is a
|
|
106
|
+
* differential by construction: anywhere the two disagree, the guard checks
|
|
107
|
+
* one repository's labels and `gh` closes an issue in another. Three
|
|
108
|
+
* disagreements were found by checking against the real binary rather than
|
|
109
|
+
* assuming, and all three are closed here:
|
|
110
|
+
*
|
|
111
|
+
* gh issue view 23 --repo a/pai-config --repo b/pai-harness -> LAST wins
|
|
112
|
+
* gh issue view 23 -R b/pai-harness -> `-R` is a real alias
|
|
113
|
+
* GH_REPO=b/pai-harness gh issue view 23 -> env is honoured
|
|
114
|
+
*
|
|
115
|
+
* The first was a guard bypass: taking the first occurrence let
|
|
116
|
+
* `--repo unprotected/x --repo protected/y` be vetted against `unprotected/x`
|
|
117
|
+
* and closed in `protected/y`.
|
|
118
|
+
*/
|
|
119
|
+
export type CloseTarget =
|
|
120
|
+
| { kind: "none" }
|
|
121
|
+
| { kind: "ambiguous"; reason: string }
|
|
122
|
+
| { kind: "one"; issue: string; repo?: string };
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* What a command closes, or a refusal to guess.
|
|
126
|
+
*
|
|
127
|
+
* Inferring a `gh` invocation by regex over an arbitrary shell string is a
|
|
128
|
+
* parser differential by construction: wherever this disagrees with the shell
|
|
129
|
+
* and with `gh`, the guard vets one issue's labels while another issue gets
|
|
130
|
+
* closed. Three rounds of security review found three such disagreements in
|
|
131
|
+
* three successive versions of this parser, which is the signal to stop
|
|
132
|
+
* tightening the pattern and change what the pattern is FOR.
|
|
133
|
+
*
|
|
134
|
+
* So the parse no longer decides *what to check*. It decides *whether the
|
|
135
|
+
* command is simple enough to check at all*. Anything with more than one
|
|
136
|
+
* close, a command separator, a substitution, or a flag value this cannot
|
|
137
|
+
* read literally is reported ambiguous, and the caller blocks. Detection
|
|
138
|
+
* stays deliberately over-broad because its failure mode is now a refusal
|
|
139
|
+
* rather than a wave-through.
|
|
140
|
+
*
|
|
141
|
+
* The bypass that forced this: `closeMatch` took the FIRST issue number while
|
|
142
|
+
* the repo scan took the LAST slug, so
|
|
143
|
+
*
|
|
144
|
+
* gh issue close 1 --repo unprotected/x; gh issue close 99 --repo protected/y
|
|
145
|
+
*
|
|
146
|
+
* vetted issue 1 against protected/y and closed 99 in it. No amount of
|
|
147
|
+
* regex care fixes that class; refusing to answer does.
|
|
148
|
+
*/
|
|
149
|
+
/** A `gh issue close` anywhere in a segment, with nothing required after it. */
|
|
150
|
+
const GH_CLOSE = /\bgh\b.*?\bissue\b.*?\bclose\b/;
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The harness's own close path, added by #137.
|
|
154
|
+
*
|
|
155
|
+
* Moving workflow steps onto `scripts/github-op.ts` would otherwise have
|
|
156
|
+
* walked every automated close straight around this guard — the detector
|
|
157
|
+
* above looks for `gh`, and the new path is `bun scripts/github-op.ts
|
|
158
|
+
* issue-update --issue N --state closed`. A control that stops applying to
|
|
159
|
+
* the caller it was written for is worse than no control, because the report
|
|
160
|
+
* still says it ran.
|
|
161
|
+
*/
|
|
162
|
+
const OP_CLOSE = /github-op\.ts\s+issue-update\b[^\n]*--state[\s=]+['"]?closed\b/;
|
|
163
|
+
|
|
164
|
+
const CLOSE_INVOCATION = new RegExp(`${GH_CLOSE.source}|${OP_CLOSE.source}`);
|
|
165
|
+
|
|
166
|
+
/** `https://github.com/owner/name/issues/123`, which `gh` accepts in place of a number. */
|
|
167
|
+
// Host-anchored. `[^\\s"'`]*?github\\.com` matched the literal anywhere in
|
|
168
|
+
// the URL, so https://evil.example/github.com/a/b/issues/1 yielded a/b — a
|
|
169
|
+
// repository gh would never have touched. Userinfo and the www. prefix are
|
|
170
|
+
// the only things allowed before the host.
|
|
171
|
+
const ISSUE_URL = /https?:\/\/(?:[^/@\s]*@)?(?:www\.)?github\.com\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)\/issues\/(\d+)/;
|
|
172
|
+
|
|
173
|
+
export function parseCloseTarget(command: string, env: NodeJS.ProcessEnv = process.env): CloseTarget {
|
|
174
|
+
// Detection is deliberately loose and requires NOTHING after `close`. The
|
|
175
|
+
// previous version demanded `close\s+(\d+)`, so `gh issue close --repo a/b 23`
|
|
176
|
+
// — flag first, number last, which gh accepts — matched nothing, returned
|
|
177
|
+
// "no close here", and the guard stepped aside entirely. A detector that
|
|
178
|
+
// can under-match is a bypass; a detector that over-matches is at worst an
|
|
179
|
+
// inconvenient refusal.
|
|
180
|
+
if (!CLOSE_INVOCATION.test(command)) return { kind: "none" };
|
|
181
|
+
|
|
182
|
+
const ambiguous = (reason: string): CloseTarget => ({ kind: "ambiguous", reason });
|
|
183
|
+
|
|
184
|
+
// Indirection that cannot be resolved from the source text. `gh` acts on
|
|
185
|
+
// the expanded command; we only ever see what was typed.
|
|
186
|
+
if (/\$\(|`|\$\{/.test(command)) return ambiguous("a command substitution makes the target unreadable — run the close on its own");
|
|
187
|
+
if (/\beval\b/.test(command)) return ambiguous("an eval makes the target unreadable — run the close on its own");
|
|
188
|
+
|
|
189
|
+
// Split on separators rather than rejecting them outright, so an ordinary
|
|
190
|
+
// `cd somewhere && gh issue close 23 --repo a/b` still gets vetted. Exactly
|
|
191
|
+
// one segment may be closing an issue: two let the issue number from one be
|
|
192
|
+
// paired with the repository from the other, which is the bypass that
|
|
193
|
+
// prompted all of this.
|
|
194
|
+
const closing = command.split(/[;|&\n]+/).filter(s => CLOSE_INVOCATION.test(s));
|
|
195
|
+
if (closing.length !== 1) {
|
|
196
|
+
return ambiguous(`${closing.length} issue closes in one command — run them separately so each can be checked`);
|
|
197
|
+
}
|
|
198
|
+
const segment = closing[0];
|
|
199
|
+
|
|
200
|
+
// The github-op form is parsed on its own terms rather than squeezed
|
|
201
|
+
// through the gh rules below. Its grammar is strictly `--flag value`, with
|
|
202
|
+
// no positional issue number and no URL form, so none of the ambiguity the
|
|
203
|
+
// gh path has to reason about exists here — and reusing those rules would
|
|
204
|
+
// have been a fourth parser differential waiting to happen.
|
|
205
|
+
if (OP_CLOSE.test(segment)) {
|
|
206
|
+
// No GH_REPO fallback: scripts/github-op.ts requires --repo and does not
|
|
207
|
+
// read the environment, so inheriting one here would vet a repository the
|
|
208
|
+
// command is not going to touch.
|
|
209
|
+
const repo = parseRepoSlug(segment, {} as NodeJS.ProcessEnv);
|
|
210
|
+
if (!repo) {
|
|
211
|
+
return ambiguous("github-op needs a literal --repo owner/name so the close can be checked");
|
|
212
|
+
}
|
|
213
|
+
// Last wins, matching the script's own flag parsing, where a repeated
|
|
214
|
+
// flag overwrites the earlier value.
|
|
215
|
+
const issues = [...segment.matchAll(/--issue[\s=]+['"]?([^\s'"]+)/g)];
|
|
216
|
+
const last = issues.length ? issues[issues.length - 1][1] : undefined;
|
|
217
|
+
if (!last || !/^\d+$/.test(last)) {
|
|
218
|
+
return ambiguous("the --issue value is not a literal number — pass it literally so it can be checked");
|
|
219
|
+
}
|
|
220
|
+
return { kind: "one", issue: last, repo };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// An inline or exported GH_REPO is honoured by gh and invisible to the
|
|
224
|
+
// regex below, which matches only --repo/-R. Measured: with the session's
|
|
225
|
+
// GH_REPO set to this repo, `GH_REPO=unprotected/x gh issue close 23`
|
|
226
|
+
// resolved to this repo while gh would have closed it in unprotected/x.
|
|
227
|
+
// Reading the assignment properly means tracking shell variable scope, so
|
|
228
|
+
// refuse instead — the operator can pass --repo.
|
|
229
|
+
//
|
|
230
|
+
// Tested against the WHOLE command, not the closing segment. The first
|
|
231
|
+
// version checked the segment and so caught the inline-prefix form while
|
|
232
|
+
// missing the natural one: `export GH_REPO=unprotected/x && gh issue close
|
|
233
|
+
// 23` splits on `&&`, and the closing segment contains no assignment at
|
|
234
|
+
// all. A control that only covers the awkward spelling is not a control.
|
|
235
|
+
//
|
|
236
|
+
// Only when the close names no repository of its own. An explicit
|
|
237
|
+
// --repo/-R beats GH_REPO in gh too, so there is no differential left to
|
|
238
|
+
// refuse, and refusing anyway would block an ordinary command that happens
|
|
239
|
+
// to set the variable for an earlier step. Deliberately NOT parseRepoSlug's
|
|
240
|
+
// env-aware form — the environment is exactly what is in question here.
|
|
241
|
+
if (/\bGH_REPO=/.test(command) && !parseRepoSlug(segment, {} as NodeJS.ProcessEnv)) {
|
|
242
|
+
return ambiguous("GH_REPO is being set inside the command, which the guard cannot follow — pass --repo owner/name instead");
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// A URL carries its own owner/name, which overrides --repo. If both are
|
|
246
|
+
// present and disagree, we cannot tell which gh will use.
|
|
247
|
+
//
|
|
248
|
+
// It counts only when it IS the thing being closed. Matching it anywhere in
|
|
249
|
+
// the segment meant a URL in a `--comment` body took over the whole target:
|
|
250
|
+
//
|
|
251
|
+
// gh issue close 99 --comment "see https://github.com/unprotected/x/issues/1"
|
|
252
|
+
// => { issue: '1', repo: 'unprotected/x' }
|
|
253
|
+
//
|
|
254
|
+
// The guard then read #1's labels in a repository nobody named while gh
|
|
255
|
+
// closed #99 here, and an unlabelled decoy was enough to permit the close
|
|
256
|
+
// of a protected issue. It needed no attacker: an ordinary dedup close
|
|
257
|
+
// links the duplicate. The `direct` branch below already says the
|
|
258
|
+
// positional number "is unambiguous even when other digits appear in a
|
|
259
|
+
// comment body" — the intent was written down and the match order defeated
|
|
260
|
+
// it.
|
|
261
|
+
//
|
|
262
|
+
// A stray URL is refused rather than ignored. Ignoring handles the comment
|
|
263
|
+
// case but not `gh issue close --repo a/b https://github.com/c/d/issues/5`,
|
|
264
|
+
// where the URL is the real target, is not positional because a flag comes
|
|
265
|
+
// first, and the number heuristic would then pair issue 5 with repo a/b.
|
|
266
|
+
const flagRepo = parseRepoSlug(segment, env);
|
|
267
|
+
const positional = segment.match(/\bclose\b\s+['"]?([^\s'"]+)/)?.[1];
|
|
268
|
+
const positionalUrl = positional ? positional.match(ISSUE_URL) : null;
|
|
269
|
+
if (positionalUrl) {
|
|
270
|
+
const urlRepo = `${positionalUrl[1]}/${positionalUrl[2]}`;
|
|
271
|
+
if (flagRepo && flagRepo !== urlRepo) {
|
|
272
|
+
return ambiguous("the issue URL and --repo name different repositories — pass one of them");
|
|
273
|
+
}
|
|
274
|
+
return { kind: "one", issue: positionalUrl[3], repo: urlRepo };
|
|
275
|
+
}
|
|
276
|
+
if (ISSUE_URL.test(segment)) {
|
|
277
|
+
return ambiguous("an issue URL appears but is not the issue being closed — pass the issue number right after `close`, or the URL as the only argument");
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// A flag is present but its value is not a literal slug (`--repo "$REPO"`).
|
|
281
|
+
// Defaulting here would vet an entirely different repository.
|
|
282
|
+
if (/(?:--repo|-R)[\s=]/.test(segment) && !flagRepo) {
|
|
283
|
+
return ambiguous("the --repo value is not a literal owner/name — pass it literally so it can be checked");
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Prefer the number immediately after `close`, which is the ordinary form
|
|
287
|
+
// and is unambiguous even when other digits appear in a comment body.
|
|
288
|
+
const direct = segment.match(/\bclose\b\s+['"]?#?(\d+)\b/);
|
|
289
|
+
if (direct) return { kind: "one", issue: direct[1], repo: flagRepo };
|
|
290
|
+
|
|
291
|
+
// Otherwise gh is taking the number from somewhere later in the line. Only
|
|
292
|
+
// act when exactly one candidate exists; guessing between several is how
|
|
293
|
+
// the wrong issue gets vetted.
|
|
294
|
+
const after = segment.slice(segment.search(/\bclose\b/));
|
|
295
|
+
const numbers = [...new Set((after.match(/(?<![\w/.-])#?(\d+)\b/g) || []).map(n => n.replace("#", "")))];
|
|
296
|
+
if (numbers.length === 1) return { kind: "one", issue: numbers[0], repo: flagRepo };
|
|
297
|
+
return ambiguous(
|
|
298
|
+
numbers.length === 0
|
|
299
|
+
? "no issue number could be read from the command — pass it directly after `close`"
|
|
300
|
+
: `several numbers could be the issue (${numbers.join(", ")}) — put the issue number directly after \`close\``,
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export function parseRepoSlug(command: string, env: NodeJS.ProcessEnv = process.env): string | undefined {
|
|
305
|
+
// Global, and keep the last — `gh` lets a later flag override an earlier one.
|
|
306
|
+
const matches = [...command.matchAll(/(?:--repo|-R)[\s=]+['"]?([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+)/g)];
|
|
307
|
+
const explicit = matches.length ? matches[matches.length - 1][1] : undefined;
|
|
308
|
+
// `gh` falls back to GH_REPO when no flag is given.
|
|
309
|
+
const slug = explicit ?? env.GH_REPO?.trim();
|
|
310
|
+
if (!slug) return undefined;
|
|
311
|
+
|
|
312
|
+
// `[A-Za-z0-9._-]+` admits `.` and `..`, so `--repo ../..` parsed as a slug
|
|
313
|
+
// and reached Octokit, which built `/repos/../../issues/N` and issued it —
|
|
314
|
+
// the request normalises to a different endpoint entirely. Observed: the
|
|
315
|
+
// guard answering "Not Found - https://docs.github.com/rest" for a crafted
|
|
316
|
+
// `--repo`. A GET with the operator's own token is a small prize, but a
|
|
317
|
+
// relative segment is never part of a real `owner/name`, so refuse it.
|
|
318
|
+
const parts = slug.split("/");
|
|
319
|
+
if (parts.length !== 2) return undefined;
|
|
320
|
+
if (parts.some(seg => !seg || seg === "." || seg === ".." || !/^[A-Za-z0-9._-]+$/.test(seg))) {
|
|
321
|
+
return undefined;
|
|
322
|
+
}
|
|
323
|
+
return slug;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Strip credential-shaped substrings from text that is about to be printed.
|
|
328
|
+
*
|
|
329
|
+
* Hook output lands in transcripts and, downstream, in issue comments. An API
|
|
330
|
+
* error can carry the request URL, and a base URL given as
|
|
331
|
+
* `https://user:token@host` would put a secret somewhere durable. Cheap
|
|
332
|
+
* insurance at the one place that prints an upstream error verbatim (#140).
|
|
333
|
+
*/
|
|
334
|
+
export function redactSecrets(text: string): string {
|
|
335
|
+
return String(text)
|
|
336
|
+
.replace(/\b(gh[pousr]_|github_pat_)[A-Za-z0-9_]+/g, "$1[REDACTED]")
|
|
337
|
+
.replace(/\/\/[^/@\s]+:[^/@\s]+@/g, "//[REDACTED]@");
|
|
338
|
+
}
|