@bbcsoftwarefactory/cli 0.1.1 → 1.1.2

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 (86) hide show
  1. package/dist/audit-ledger.d.ts +2 -0
  2. package/dist/audit-ledger.js +71 -0
  3. package/dist/bbc-install.d.ts +2 -0
  4. package/dist/bbc-install.js +1250 -0
  5. package/dist/bbc.js +87 -3
  6. package/dist/change-lane/classification.js +3 -1
  7. package/dist/check-issue-claim.d.ts +2 -0
  8. package/dist/check-issue-claim.js +146 -0
  9. package/dist/check-worktree-guard.d.ts +2 -0
  10. package/dist/check-worktree-guard.js +114 -0
  11. package/dist/error-scan.d.ts +3 -0
  12. package/dist/error-scan.js +216 -0
  13. package/dist/export-public.d.ts +9 -0
  14. package/dist/export-public.js +274 -0
  15. package/dist/fetch-issue-attachments.d.ts +22 -0
  16. package/dist/fetch-issue-attachments.js +325 -0
  17. package/dist/issue-claim/evaluation.d.ts +66 -0
  18. package/dist/issue-claim/evaluation.js +259 -0
  19. package/dist/issue-claim/loaders.d.ts +5 -0
  20. package/dist/issue-claim/loaders.js +116 -0
  21. package/dist/list-zed-commands.d.ts +7 -0
  22. package/dist/list-zed-commands.js +288 -0
  23. package/dist/plan-issue-triage.d.ts +3 -0
  24. package/dist/plan-issue-triage.js +404 -0
  25. package/dist/question-gate/ledger.d.ts +5 -0
  26. package/dist/question-gate/ledger.js +115 -0
  27. package/dist/question-gate/rules.d.ts +40 -0
  28. package/dist/question-gate/rules.js +483 -0
  29. package/dist/recap/board.d.ts +5 -0
  30. package/dist/recap/board.js +384 -0
  31. package/dist/recap/git-and-github.d.ts +11 -0
  32. package/dist/recap/git-and-github.js +620 -0
  33. package/dist/recap/report-and-hud.d.ts +2 -0
  34. package/dist/recap/report-and-hud.js +294 -0
  35. package/dist/recap/time-and-refs.d.ts +27 -0
  36. package/dist/recap/time-and-refs.js +148 -0
  37. package/dist/recap.d.ts +2 -0
  38. package/dist/recap.js +217 -0
  39. package/dist/render-workflow.js +12 -14
  40. package/dist/resolve-containers.d.ts +2 -0
  41. package/dist/resolve-containers.js +96 -0
  42. package/dist/review-loop.d.ts +7 -0
  43. package/dist/review-loop.js +622 -0
  44. package/dist/save-counts.d.ts +2 -0
  45. package/dist/save-counts.js +191 -0
  46. package/dist/summarize-logs.d.ts +2 -0
  47. package/dist/summarize-logs.js +41 -0
  48. package/dist/sweep-github.d.ts +10 -0
  49. package/dist/sweep-github.js +453 -0
  50. package/dist/sweep-issues.d.ts +56 -0
  51. package/dist/sweep-issues.js +650 -0
  52. package/dist/sweep.d.ts +2 -0
  53. package/dist/sweep.js +301 -0
  54. package/dist/triage-question.d.ts +2 -0
  55. package/dist/triage-question.js +189 -0
  56. package/dist/validate-skills.d.ts +2 -0
  57. package/dist/validate-skills.js +48 -0
  58. package/dist/watch-live.d.ts +7 -0
  59. package/dist/watch-live.js +83 -0
  60. package/dist/watcher/config.d.ts +11 -0
  61. package/dist/watcher/config.js +265 -0
  62. package/dist/watcher/live-classifier.d.ts +52 -0
  63. package/dist/watcher/live-classifier.js +510 -0
  64. package/dist/watcher/safe-fs.d.ts +9 -0
  65. package/dist/watcher/safe-fs.js +159 -0
  66. package/dist/watcher/stream.d.ts +27 -0
  67. package/dist/watcher/stream.js +340 -0
  68. package/dist/watcher/summarizer.d.ts +19 -0
  69. package/dist/watcher/summarizer.js +121 -0
  70. package/dist/wave3/process.d.ts +14 -0
  71. package/dist/wave3/process.js +84 -0
  72. package/dist/wave4/process.d.ts +14 -0
  73. package/dist/wave4/process.js +128 -0
  74. package/dist/workflow/render.d.ts +1 -1
  75. package/dist/workflow/render.js +1 -1
  76. package/dist/workflow-auditor/audit.d.ts +27 -0
  77. package/dist/workflow-auditor/audit.js +583 -0
  78. package/dist/workflow-auditor/ledger-io.d.ts +5 -0
  79. package/dist/workflow-auditor/ledger-io.js +99 -0
  80. package/dist/workflow-auditor/skills-validator.d.ts +10 -0
  81. package/dist/workflow-auditor/skills-validator.js +533 -0
  82. package/dist/worktree-guard/evaluation.d.ts +19 -0
  83. package/dist/worktree-guard/evaluation.js +84 -0
  84. package/dist/worktree-guard/git.d.ts +3 -0
  85. package/dist/worktree-guard/git.js +61 -0
  86. package/package.json +32 -33
package/dist/bbc.js CHANGED
@@ -7,12 +7,32 @@
7
7
  * keywords: [CliEntryPoint, CommandArguments]
8
8
  * GOAL: Translate command-line arguments into process output and exit status.
9
9
  */
10
+ import { auditLedger, auditLedgerUsage } from "./audit-ledger.js";
11
+ import { bbcInstall, bbcInstallUsage } from "./bbc-install.js";
12
+ import { checkIssueClaim, checkIssueClaimUsage } from "./check-issue-claim.js";
13
+ import { checkWorktreeGuard, checkWorktreeGuardUsage } from "./check-worktree-guard.js";
10
14
  import { classifyChangeLane, classifyChangeLaneUsage } from "./classify-change-lane.js";
15
+ import { errorScan, errorScanUsage } from "./error-scan.js";
16
+ import { exportPublic, exportPublicUsage } from "./export-public.js";
11
17
  import { extractDiffScope, extractDiffScopeUsage } from "./extract-diff-scope.js";
18
+ import { fetchIssueAttachments, fetchIssueAttachmentsUsage } from "./fetch-issue-attachments.js";
19
+ import { listZedCommands, listZedCommandsUsage } from "./list-zed-commands.js";
12
20
  import { measureBigo, measureBigoUsage } from "./measure-bigo.js";
21
+ import { planIssueTriage, planIssueTriageUsage } from "./plan-issue-triage.js";
22
+ import { recap, recapUsage } from "./recap.js";
13
23
  import { renderWorkflow, renderWorkflowUsage } from "./render-workflow.js";
24
+ import { resolveContainers, resolveContainersUsage } from "./resolve-containers.js";
25
+ import { reviewLoop, reviewLoopUsage } from "./review-loop.js";
26
+ import { saveCounts, saveCountsUsage } from "./save-counts.js";
27
+ import { summarizeLogs, summarizeLogsUsage } from "./summarize-logs.js";
28
+ import { sweepGithub, sweepGithubUsage } from "./sweep-github.js";
29
+ import { sweepIssues, sweepIssuesUsage } from "./sweep-issues.js";
30
+ import { sweep, sweepUsage } from "./sweep.js";
31
+ import { triageQuestion, triageQuestionUsage } from "./triage-question.js";
32
+ import { validateSkills, validateSkillsUsage } from "./validate-skills.js";
33
+ import { watchLive, watchLiveUsage } from "./watch-live.js";
14
34
  const usage = 'Usage: bbc <command> [arguments]\n';
15
- function main([command, ...args]) {
35
+ async function main([command, ...args]) {
16
36
  const [argument] = args;
17
37
  if (command === undefined) {
18
38
  process.stderr.write(usage);
@@ -23,7 +43,31 @@ function main([command, ...args]) {
23
43
  return 1;
24
44
  }
25
45
  if (command === '--help') {
26
- process.stdout.write(`${usage}\nCommands:\n ${measureBigoUsage}\n ${classifyChangeLaneUsage}\n ${renderWorkflowUsage}\n ${extractDiffScopeUsage}\n`);
46
+ process.stdout.write(`${usage}\nCommands:\n` +
47
+ ` ${measureBigoUsage}\n` +
48
+ ` ${classifyChangeLaneUsage}\n` +
49
+ ` ${renderWorkflowUsage}\n` +
50
+ ` ${extractDiffScopeUsage}\n` +
51
+ ` ${checkWorktreeGuardUsage}\n` +
52
+ ` ${checkIssueClaimUsage}\n` +
53
+ ` ${triageQuestionUsage}\n` +
54
+ ` ${auditLedgerUsage}\n` +
55
+ ` ${validateSkillsUsage}\n` +
56
+ ` ${resolveContainersUsage}\n` +
57
+ ` ${summarizeLogsUsage}\n` +
58
+ ` ${watchLiveUsage}\n` +
59
+ ` ${errorScanUsage}\n` +
60
+ ` ${saveCountsUsage}\n` +
61
+ ` ${planIssueTriageUsage}\n` +
62
+ ` ${fetchIssueAttachmentsUsage}\n` +
63
+ ` ${reviewLoopUsage}\n` +
64
+ ` ${sweepUsage}\n` +
65
+ ` ${sweepIssuesUsage}\n` +
66
+ ` ${sweepGithubUsage}\n` +
67
+ ` ${recapUsage}\n` +
68
+ ` ${bbcInstallUsage}\n` +
69
+ ` ${listZedCommandsUsage}\n` +
70
+ ` ${exportPublicUsage}\n`);
27
71
  return 0;
28
72
  }
29
73
  if (command === 'measure-bigo')
@@ -34,7 +78,47 @@ function main([command, ...args]) {
34
78
  return renderWorkflow(args);
35
79
  if (command === 'extract-diff-scope')
36
80
  return extractDiffScope(args);
81
+ if (command === 'check-worktree-guard')
82
+ return checkWorktreeGuard(args);
83
+ if (command === 'check-issue-claim')
84
+ return checkIssueClaim(args);
85
+ if (command === 'triage-question')
86
+ return triageQuestion(args);
87
+ if (command === 'audit-ledger')
88
+ return auditLedger(args);
89
+ if (command === 'validate-skills')
90
+ return validateSkills(args);
91
+ if (command === 'resolve-containers')
92
+ return resolveContainers(args);
93
+ if (command === 'summarize-logs')
94
+ return summarizeLogs(args);
95
+ if (command === 'watch-live')
96
+ return watchLive(args);
97
+ if (command === 'error-scan')
98
+ return errorScan(args);
99
+ if (command === 'save-counts')
100
+ return saveCounts(args);
101
+ if (command === 'plan-issue-triage')
102
+ return planIssueTriage(args);
103
+ if (command === 'fetch-issue-attachments')
104
+ return fetchIssueAttachments(args);
105
+ if (command === 'review-loop')
106
+ return reviewLoop(args);
107
+ if (command === 'sweep')
108
+ return sweep(args);
109
+ if (command === 'sweep-issues')
110
+ return sweepIssues(args);
111
+ if (command === 'sweep-github')
112
+ return sweepGithub(args);
113
+ if (command === 'recap')
114
+ return recap(args);
115
+ if (command === 'bbc-install')
116
+ return bbcInstall(args);
117
+ if (command === 'list-zed-commands')
118
+ return listZedCommands(args);
119
+ if (command === 'export-public')
120
+ return exportPublic(args);
37
121
  process.stderr.write(`Unknown command: ${JSON.stringify(command)}\n${usage}`);
38
122
  return 1;
39
123
  }
40
- process.exitCode = main(process.argv.slice(2));
124
+ process.exitCode = await main(process.argv.slice(2));
@@ -21,6 +21,8 @@ const riskPatterns = [
21
21
  /(^|\/)skills\/question-gate\/scripts\/triage-question\.py$/i,
22
22
  /(^|\/)skills\/delivery-coordinator\/scripts\/check-worktree-guard\.py$/i,
23
23
  /(^|\/)tools\/export-public\.py$/i,
24
+ /(^|\/)packages\/cli\/src\/(?:audit-ledger|triage-question|check-worktree-guard|export-public)\.ts$/i,
25
+ /(^|\/)packages\/cli\/src\/(?:workflow-auditor|question-gate|worktree-guard)\//i,
24
26
  /(^|\/)\.github\/workflows\//i,
25
27
  /(^|\/)(?:auth|oauth|jwt|session|token|crypto|secret|permission|rbac|security|migration|migrations|prisma|schema|deploy|infra)(?:\/|[._-]|$)/i,
26
28
  /\.sql$/i,
@@ -30,7 +32,7 @@ const plans = {
30
32
  test_mode: 'proportional',
31
33
  required_stages: ['specify', 'implement', 'quality', 'docs', 'commit_pr', 'review'],
32
34
  skipped_stages: ['requirements-spec-full-prd', 'risk-scout', 'reproduce-runtime-red', 'verify-runtime-green'],
33
- extra_checks: ['documentation-steward', 'validate-skills.py'],
35
+ extra_checks: ['documentation-steward', 'bbc validate-skills'],
34
36
  },
35
37
  standard: {
36
38
  test_mode: 'tdd',
@@ -0,0 +1,2 @@
1
+ export declare const checkIssueClaimUsage = "bbc check-issue-claim --phase check|verify|release|status --issue-json <file> [options]";
2
+ export declare function checkIssueClaim(argv: readonly string[]): number;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * LAYER: Interface
3
+ * Contains: CLI argument parsing and JSON report emission for check-issue-claim.
4
+ * Rules: Match check-issue-claim.py stdout/exit codes byte-for-byte.
5
+ * BigO: O(n) score:3
6
+ * keywords: [IssueClaimCli, ClaimArguments]
7
+ * GOAL: Run offline issue-claim checks (CL1-CL12) from the bbc CLI.
8
+ */
9
+ import { evaluateClaim, parseIsoTime, STOP_VERDICTS, UnusableClaimError, } from "./issue-claim/evaluation.js";
10
+ import { loadBranches, loadEvents, loadIssue, loadPulls } from "./issue-claim/loaders.js";
11
+ export const checkIssueClaimUsage = 'bbc check-issue-claim --phase check|verify|release|status --issue-json <file> [options]';
12
+ const PHASES = new Set(['check', 'verify', 'release', 'status']);
13
+ const DEFAULT_LABEL = 'status:in-progress';
14
+ const DEFAULT_STALE_DAYS = 7;
15
+ const HELP = 'Usage: bbc check-issue-claim --phase check|verify|release|status\n' +
16
+ ' --issue-json <file> gh api repos/<o>/<r>/issues/<n> (or gh issue view <n> --json ...)\n' +
17
+ ' --pulls-json <file> gh api --paginate --slurp "repos/<o>/<r>/pulls?state=open&per_page=100"\n' +
18
+ ' --branches <file> git ls-remote --heads <remote> "feat/<n>-*"\n' +
19
+ ' --events-json <file> gh api --paginate --slurp repos/<o>/<r>/issues/<n>/events (verify)\n' +
20
+ ' --claimant <login> GitHub login of the person (check, verify, release)\n' +
21
+ ' --branch <feat/<n>-<slug>> the branch this delivery will use (check, verify)\n' +
22
+ ' [--repo <owner/repo>] [--label status:in-progress] [--stale-days 7] [--now <ISO-8601>]\n' +
23
+ 'Exit 0: proceed (free, claimed-by-you, released, claimed, unclaimed); 1: stop; 2: unusable.';
24
+ const FLAG_KEYS = {
25
+ '--phase': 'phase',
26
+ '--issue-json': 'issue',
27
+ '--pulls-json': 'pulls',
28
+ '--branches': 'branches',
29
+ '--events-json': 'events',
30
+ '--claimant': 'claimant',
31
+ '--branch': 'branch',
32
+ '--repo': 'repo',
33
+ '--label': 'label',
34
+ '--stale-days': 'stale_days',
35
+ '--now': 'now',
36
+ };
37
+ function writeJsonOut(value) {
38
+ const escaped = JSON.stringify(value, null, 2).replace(/[\u007f-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
39
+ process.stdout.write(`${escaped}\n`);
40
+ }
41
+ function parseArgs(argv) {
42
+ const raw = {
43
+ phase: null,
44
+ issue: null,
45
+ pulls: null,
46
+ branches: null,
47
+ events: null,
48
+ claimant: null,
49
+ branch: null,
50
+ repo: null,
51
+ label: DEFAULT_LABEL,
52
+ stale_days: String(DEFAULT_STALE_DAYS),
53
+ now: null,
54
+ };
55
+ for (let i = 0; i < argv.length; i++) {
56
+ const arg = argv[i] ?? '';
57
+ if (arg === '-h' || arg === '--help')
58
+ return null;
59
+ const key = FLAG_KEYS[arg];
60
+ const value = argv[i + 1];
61
+ if (key === undefined || value === undefined) {
62
+ throw new UnusableClaimError(`Unexpected argument ${arg}; see --help.`);
63
+ }
64
+ raw[key] = value;
65
+ i++;
66
+ }
67
+ const phase = raw.phase ?? null;
68
+ if (phase === null || !PHASES.has(phase)) {
69
+ throw new UnusableClaimError('--phase must be one of: check, verify, release, status.');
70
+ }
71
+ const issuePath = raw.issue ?? null;
72
+ if (issuePath === null) {
73
+ throw new UnusableClaimError('--issue-json is required.');
74
+ }
75
+ const pullsPath = raw.pulls ?? null;
76
+ const branchesPath = raw.branches ?? null;
77
+ if (phase !== 'release' && (pullsPath === null || branchesPath === null)) {
78
+ throw new UnusableClaimError(`--pulls-json and --branches are required for ${phase}.`);
79
+ }
80
+ const claimant = raw.claimant ?? null;
81
+ if (phase !== 'status' && !claimant) {
82
+ throw new UnusableClaimError(`--claimant is required for ${phase}.`);
83
+ }
84
+ const branch = raw.branch ?? null;
85
+ if ((phase === 'check' || phase === 'verify') && !branch) {
86
+ throw new UnusableClaimError(`--branch is required for ${phase}.`);
87
+ }
88
+ const staleRaw = raw.stale_days ?? '';
89
+ if (!/^-?\d+$/.test(staleRaw)) {
90
+ throw new UnusableClaimError('--stale-days must be an integer.');
91
+ }
92
+ const staleDays = Number.parseInt(staleRaw, 10);
93
+ const now = raw.now ? parseIsoTime(raw.now) : Date.now();
94
+ if (now === null) {
95
+ throw new UnusableClaimError('--now must be an ISO-8601 time.');
96
+ }
97
+ return {
98
+ issuePath,
99
+ pullsPath,
100
+ branchesPath,
101
+ eventsPath: raw.events ?? null,
102
+ options: {
103
+ phase: phase,
104
+ claimant,
105
+ branch,
106
+ repo: raw.repo ?? null,
107
+ label: raw.label ?? DEFAULT_LABEL,
108
+ stale_days: staleDays,
109
+ now,
110
+ },
111
+ };
112
+ }
113
+ export function checkIssueClaim(argv) {
114
+ try {
115
+ const parsed = parseArgs(argv);
116
+ if (parsed === null) {
117
+ process.stdout.write(`${HELP}\n`);
118
+ return 0;
119
+ }
120
+ const issue = loadIssue(parsed.issuePath);
121
+ const pulls = parsed.pullsPath ? loadPulls(parsed.pullsPath) : [];
122
+ const branches = parsed.branchesPath ? loadBranches(parsed.branchesPath) : [];
123
+ const events = parsed.eventsPath ? loadEvents(parsed.eventsPath) : null;
124
+ const { verdict, findings, holders } = evaluateClaim(issue, pulls, branches, events, parsed.options);
125
+ const proceed = !STOP_VERDICTS.has(verdict);
126
+ writeJsonOut({
127
+ verdict,
128
+ proceed,
129
+ phase: parsed.options.phase,
130
+ issue: issue.number,
131
+ claimant: parsed.options.claimant,
132
+ holders,
133
+ findings,
134
+ });
135
+ return proceed ? 0 : 1;
136
+ }
137
+ catch (error) {
138
+ const detail = error instanceof UnusableClaimError ? error.message : String(error);
139
+ writeJsonOut({
140
+ verdict: 'unusable',
141
+ proceed: false,
142
+ findings: [{ rule: 'CL1', verdict: 'unusable', detail }],
143
+ });
144
+ return 2;
145
+ }
146
+ }
@@ -0,0 +1,2 @@
1
+ export declare const checkWorktreeGuardUsage = "bbc check-worktree-guard [--path <dir>] [--target-path <file>] [--stdin --format json|claude-hook|cursor-hook|codex-hook]";
2
+ export declare function checkWorktreeGuard(argv: readonly string[]): number;
@@ -0,0 +1,114 @@
1
+ /**
2
+ * LAYER: Interface
3
+ * Contains: CLI argument parsing, stdin reading, and JSON formatting for check-worktree-guard.
4
+ * Rules: Match check-worktree-guard.py stdout/stderr/exit codes byte-for-byte.
5
+ * BigO: O(n) score:3
6
+ * keywords: [WorktreeGuardCli, HookStdin]
7
+ * GOAL: Enforce linked feat/<task> worktree isolation from the bbc CLI.
8
+ */
9
+ import { readFileSync } from 'node:fs';
10
+ import { EOL } from 'node:os';
11
+ import { evaluateGitInfo, extractPayloadPath, formatHookOutput, } from "./worktree-guard/evaluation.js";
12
+ import { findExistingDirectory, probeGitWorktree } from "./worktree-guard/git.js";
13
+ export const checkWorktreeGuardUsage = 'bbc check-worktree-guard [--path <dir>] [--target-path <file>] [--stdin --format json|claude-hook|cursor-hook|codex-hook]';
14
+ const HELP = 'Usage: bbc check-worktree-guard [--path <dir>] [--target-path <file>] [--stdin --format json|claude-hook|cursor-hook|codex-hook]\n' +
15
+ 'Exit 0: allowed linked feat/<task> worktree; 1: blocked (primary/non-feat); 2: unusable.';
16
+ const VALID_FORMATS = new Set(['json', 'claude-hook', 'cursor-hook', 'codex-hook']);
17
+ function escapeAscii(json) {
18
+ return json.replace(/[\u007f-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
19
+ }
20
+ function pythonJsonPretty(value) {
21
+ return escapeAscii(JSON.stringify(value, null, 2));
22
+ }
23
+ function pythonJsonCompact(value) {
24
+ if (value === null || typeof value !== 'object')
25
+ return escapeAscii(JSON.stringify(value));
26
+ if (Array.isArray(value))
27
+ return `[${value.map(pythonJsonCompact).join(', ')}]`;
28
+ const entries = Object.entries(value);
29
+ return `{${entries.map(([key, val]) => `${escapeAscii(JSON.stringify(key))}: ${pythonJsonCompact(val)}`).join(', ')}}`;
30
+ }
31
+ function writeOut(line) {
32
+ process.stdout.write(`${line}\n`);
33
+ }
34
+ function parseArgs(argv) {
35
+ let pathArg;
36
+ let targetPath;
37
+ let useStdin = false;
38
+ let format = 'json';
39
+ for (let i = 0; i < argv.length; i++) {
40
+ const arg = argv[i] ?? '';
41
+ if (arg === '-h' || arg === '--help')
42
+ return { kind: 'help' };
43
+ if (arg === '--stdin') {
44
+ useStdin = true;
45
+ continue;
46
+ }
47
+ if (arg === '--path' || arg === '--target-path' || arg === '--format') {
48
+ const value = argv[i + 1];
49
+ if (value === undefined || value === '')
50
+ return { kind: 'error', message: `error: ${arg} requires a value` };
51
+ if (arg === '--path')
52
+ pathArg = value;
53
+ else if (arg === '--target-path')
54
+ targetPath = value;
55
+ else {
56
+ if (!VALID_FORMATS.has(value))
57
+ return { kind: 'error', message: `error: invalid --format: ${value}` };
58
+ format = value;
59
+ }
60
+ i++;
61
+ continue;
62
+ }
63
+ return { kind: 'error', message: `error: unknown option: ${arg}` };
64
+ }
65
+ return { kind: 'run', pathArg, targetPath, useStdin, format };
66
+ }
67
+ function evaluatePath(pathStr) {
68
+ const directory = findExistingDirectory(pathStr);
69
+ if (directory === undefined) {
70
+ return { report: { decision: 'unusable', reason: `Path does not exist: ${pathStr}` }, status: 2 };
71
+ }
72
+ const info = probeGitWorktree(directory);
73
+ if (info === undefined) {
74
+ return { report: { decision: 'unusable', reason: 'Target directory is not inside a Git worktree.' }, status: 2 };
75
+ }
76
+ return evaluateGitInfo(info);
77
+ }
78
+ export function checkWorktreeGuard(argv) {
79
+ const parsed = parseArgs(argv);
80
+ if (parsed.kind === 'help') {
81
+ writeOut(HELP);
82
+ return 0;
83
+ }
84
+ if (parsed.kind === 'error') {
85
+ process.stderr.write(`${parsed.message}${EOL}`);
86
+ return 1;
87
+ }
88
+ let resolvedTarget = parsed.targetPath || parsed.pathArg;
89
+ if (parsed.useStdin) {
90
+ const rawStdin = readFileSync(0, 'utf8').trim();
91
+ if (rawStdin !== '') {
92
+ let payload;
93
+ try {
94
+ payload = JSON.parse(rawStdin);
95
+ }
96
+ catch {
97
+ writeOut(pythonJsonCompact({ decision: 'unusable', reason: 'Invalid JSON on stdin.' }));
98
+ return 2;
99
+ }
100
+ const extracted = extractPayloadPath(payload);
101
+ if (extracted !== undefined && !parsed.targetPath)
102
+ resolvedTarget = extracted;
103
+ }
104
+ }
105
+ if (!resolvedTarget)
106
+ resolvedTarget = '.';
107
+ const { report, status } = evaluatePath(resolvedTarget);
108
+ if (parsed.format === 'json') {
109
+ writeOut(pythonJsonPretty(report));
110
+ return status;
111
+ }
112
+ writeOut(pythonJsonCompact(formatHookOutput(report, status, parsed.format)));
113
+ return 0;
114
+ }
@@ -0,0 +1,3 @@
1
+ export declare const errorScanUsage = "bbc error-scan [--project <uuid>] <ssh-alias> <exact-container> [minutes | --tail <lines>]";
2
+ export declare function digest(body: string, record?: Record<string, unknown> | null): string;
3
+ export declare function errorScan(argv: readonly string[]): Promise<number>;
@@ -0,0 +1,216 @@
1
+ /**
2
+ * LAYER: Interface
3
+ * Contains: CLI entry point and allowlisted digest builder for bbc error-scan.
4
+ * Rules: Match error-scan.py help, output, digest allowlist, and tmp_logs/scan/ save contract.
5
+ * BigO: O(n^2) score:1
6
+ * keywords: [ErrorScanCli, DigestAllowlist, BoundedScan]
7
+ * GOAL: Perform one bounded historical error scan and optionally save an allowlisted digest.
8
+ */
9
+ import { EOL } from 'node:os';
10
+ import { aliasPattern, ConfigError, CONTAINER_RE, resolveSshExecutable, SSH_OPTIONS, } from "./watcher/config.js";
11
+ import { CODES, EXCEPTIONS, jsonHit, jsonLevel, LEVELS, PATTERNS, PLAIN_LEVEL_RE, stripHeaders, } from "./watcher/live-classifier.js";
12
+ import { saveScanReport } from "./watcher/safe-fs.js";
13
+ import { runBoundedLineScan } from "./watcher/stream.js";
14
+ export const errorScanUsage = 'bbc error-scan [--project <uuid>] <ssh-alias> <exact-container> [minutes | --tail <lines>]';
15
+ const MAX_BYTES = 16 * 1024 * 1024;
16
+ const MAX_MINUTES = 120;
17
+ const MAX_TAIL = 50_000;
18
+ const MAX_ROWS = 40;
19
+ const DEADLINE_MS = 60_000;
20
+ const PROJECT_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
21
+ const EVENT_RE = /"event":"([^"]+)"/;
22
+ const HELP = 'Usage: bbc error-scan [--project <uuid>] <ssh-alias> <exact-container> [minutes | --tail <lines>]\n' +
23
+ 'Read one bounded window once (1-120 minutes, or 1-50000 lines) and report only warn/error signal.\n' +
24
+ '--project keeps only lines that contain that project uuid (any field name, any case).';
25
+ const DIGEST_WORDS = new Set([
26
+ 'error', 'errors', 'warn', 'warning', 'fatal', 'critical', 'failed', 'failure', 'fails', 'fail',
27
+ 'timeout', 'timed', 'out', 'refused', 'reset', 'closed', 'broken', 'pipe', 'connection',
28
+ 'connect', 'socket', 'retry', 'retrying', 'retries', 'unavailable', 'upstream', 'downstream',
29
+ 'denied', 'forbidden', 'unauthorized', 'auth', 'authentication', 'expired', 'invalid',
30
+ 'missing', 'not', 'found', 'exceeded', 'limit', 'rate', 'quota', 'crash', 'crashed', 'killed',
31
+ 'memory', 'disk', 'full', 'database', 'db', 'query', 'request', 'response', 'webhook', 'message',
32
+ 'send', 'sent', 'delivery', 'deliver', 'template', 'queue', 'job', 'worker', 'payment', 'charge',
33
+ 'handshake', 'tls', 'ssl', 'dns', 'lookup', 'parse', 'json', 'unexpected', 'token', 'status',
34
+ 'server', 'client', 'internal', 'gateway', 'bad', 'service', 'for', 'to', 'from', 'with', 'on',
35
+ 'in', 'of', 'the', 'a', 'an', 'is', 'was', 'while', 'after', 'during', 'cannot', 'could',
36
+ ]);
37
+ const DIGEST_EXACT = { ...CODES, ...EXCEPTIONS };
38
+ const DIGEST_MESSAGE_KEYS = ['msg', 'message', 'error', 'err'];
39
+ const DIGEST_TOKENS = 16;
40
+ const DIGEST_CHARS = 220;
41
+ const REDACTED = '[redacted]';
42
+ function writeOut(text) {
43
+ process.stdout.write(`${text.replaceAll('\n', EOL)}${EOL}`);
44
+ }
45
+ function writeErr(text) {
46
+ process.stderr.write(`${text.replaceAll('\n', EOL)}${EOL}`);
47
+ }
48
+ export function digest(body, record = null) {
49
+ let text = body;
50
+ if (record !== null) {
51
+ const key = DIGEST_MESSAGE_KEYS.find((k) => typeof record[k] === 'string');
52
+ text = key !== undefined ? record[key] : '';
53
+ }
54
+ const out = [];
55
+ for (const raw of text.trim().split(/\s+/).filter((t) => t !== '').slice(0, DIGEST_TOKENS)) {
56
+ const token = raw.replace(/^[.,;:()[\]{}"'!?]+|[.,;:()[\]{}"'!?]+$/g, '');
57
+ const exact = Object.hasOwn(DIGEST_EXACT, token) ? DIGEST_EXACT[token] : undefined;
58
+ const lowered = token.toLowerCase();
59
+ const word = exact ?? (DIGEST_WORDS.has(lowered) ? lowered : REDACTED);
60
+ if (word !== REDACTED || out.length === 0 || out.at(-1) !== REDACTED)
61
+ out.push(word);
62
+ }
63
+ return out.join(' ').slice(0, DIGEST_CHARS);
64
+ }
65
+ function classifyLine(line) {
66
+ const body = stripHeaders(line.trim());
67
+ let record = null;
68
+ const brace = body.indexOf('{');
69
+ if (brace >= 0 && body.trimEnd().endsWith('}')) {
70
+ try {
71
+ const parsed = JSON.parse(body.slice(brace));
72
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
73
+ record = parsed;
74
+ }
75
+ }
76
+ catch {
77
+ record = null;
78
+ }
79
+ }
80
+ let level = record !== null ? jsonLevel(record) : null;
81
+ let hit = record !== null ? jsonHit(record) : null;
82
+ if (level === null) {
83
+ const match = PLAIN_LEVEL_RE.exec(body);
84
+ if (match !== null)
85
+ level = LEVELS[(match[1] ?? match[2] ?? '').toLowerCase()] ?? null;
86
+ }
87
+ if (hit === null) {
88
+ const idx = PATTERNS.findIndex(([, regex]) => regex.test(body));
89
+ hit = idx === -1 ? null : idx;
90
+ }
91
+ return { level: level ?? (hit !== null ? 'error' : null), hit, body, record };
92
+ }
93
+ class Tally {
94
+ project;
95
+ filtered = 0;
96
+ counts = { error: 0, warn: 0, info: 0, debug: 0, unclassified: 0 };
97
+ hits = new Array(PATTERNS.length).fill(0);
98
+ events = {};
99
+ rows = [];
100
+ constructor(project) {
101
+ this.project = project;
102
+ }
103
+ feed(segment) {
104
+ const decoded = new TextDecoder('utf-8', { fatal: false }).decode(segment);
105
+ for (const raw of decoded.split(/\r\n|\n|\r/)) {
106
+ if (raw.trim() === '')
107
+ continue;
108
+ if (this.project !== null && !raw.toLowerCase().includes(this.project)) {
109
+ this.filtered += 1;
110
+ continue;
111
+ }
112
+ const { level, hit, body, record } = classifyLine(raw);
113
+ const bucket = level ?? 'unclassified';
114
+ this.counts[bucket] = (this.counts[bucket] ?? 0) + 1;
115
+ if (hit !== null)
116
+ this.hits[hit] = (this.hits[hit] ?? 0) + 1;
117
+ const event = EVENT_RE.exec(raw);
118
+ if (event !== null) {
119
+ const name = event[1];
120
+ this.events[name] = (this.events[name] ?? 0) + 1;
121
+ }
122
+ if ((level === 'error' || level === 'warn' || hit !== null) && this.rows.length < MAX_ROWS) {
123
+ this.rows.push({
124
+ level: level ?? 'signature',
125
+ signature: hit !== null ? PATTERNS[hit][0] : null,
126
+ digest: digest(body, record),
127
+ });
128
+ }
129
+ }
130
+ }
131
+ }
132
+ function parseSelector(args) {
133
+ if (args.length === 2)
134
+ return { kind: 'since', value: 15 };
135
+ if (args.length === 3 && /^\d+$/.test(args[2])) {
136
+ const minutes = Number.parseInt(args[2], 10);
137
+ if (minutes >= 1 && minutes <= MAX_MINUTES)
138
+ return { kind: 'since', value: minutes };
139
+ }
140
+ if (args.length === 4 && args[2] === '--tail' && /^\d+$/.test(args[3])) {
141
+ const tail = Number.parseInt(args[3], 10);
142
+ if (tail >= 1 && tail <= MAX_TAIL)
143
+ return { kind: 'tail', value: tail };
144
+ }
145
+ return null;
146
+ }
147
+ export async function errorScan(argv) {
148
+ let args = [...argv];
149
+ let project = null;
150
+ if (args[0] === '--project') {
151
+ if (args.length < 2 || !PROJECT_RE.test(args[1])) {
152
+ writeErr(HELP);
153
+ return 1;
154
+ }
155
+ project = args[1].toLowerCase();
156
+ args = args.slice(2);
157
+ }
158
+ if (args.length < 2 || args.length > 4) {
159
+ writeErr(HELP);
160
+ return 1;
161
+ }
162
+ let aliasOk;
163
+ try {
164
+ aliasOk = aliasPattern();
165
+ }
166
+ catch (error) {
167
+ if (error instanceof ConfigError) {
168
+ writeErr(error.message);
169
+ return 1;
170
+ }
171
+ throw error;
172
+ }
173
+ const [alias, container] = [args[0], args[1]];
174
+ const selector = parseSelector(args);
175
+ if (!aliasOk.test(alias) || !CONTAINER_RE.test(container) || selector === null) {
176
+ writeErr(HELP);
177
+ return 1;
178
+ }
179
+ const ssh = resolveSshExecutable();
180
+ if (ssh === null) {
181
+ writeErr('Watcher scan failed; no counts.');
182
+ return 1;
183
+ }
184
+ const flag = selector.kind === 'since' ? `--since=${selector.value}m` : `--tail=${selector.value}`;
185
+ const tally = new Tally(project);
186
+ let totalBytes = 0;
187
+ try {
188
+ const res = await runBoundedLineScan(ssh, [...SSH_OPTIONS, alias, 'docker', 'logs', flag, '--timestamps', '--', container], DEADLINE_MS, MAX_BYTES, (segment) => tally.feed(segment));
189
+ totalBytes = res.totalBytes;
190
+ }
191
+ catch (error) {
192
+ const msg = error instanceof Error ? error.message : 'Watcher scan failed; no counts.';
193
+ writeErr(msg);
194
+ return 1;
195
+ }
196
+ const total = Object.values(tally.counts).reduce((a, b) => a + b, 0);
197
+ const scope = project !== null ? ` project=${project} filtered_out=${tally.filtered}` : '';
198
+ const label = selector.kind === 'since' ? `${selector.value}m` : `${selector.value}l`;
199
+ writeOut(`scan alias=${alias} container=${container} selector=${label} lines=${total} bytes=${totalBytes}${scope}`);
200
+ writeOut(`severity ${Object.entries(tally.counts).map(([k, v]) => `${k}=${v}`).join(' ')}`);
201
+ const ranked = PATTERNS.map(([name], i) => [name, tally.hits[i] ?? 0])
202
+ .filter(([, n]) => n > 0)
203
+ .sort((a, b) => b[1] - a[1]);
204
+ writeOut(`signatures ${ranked.length > 0 ? ranked.map(([name, n]) => `${name}:${n}`).join(', ') : 'none'}`);
205
+ const topEvents = Object.entries(tally.events).sort((a, b) => b[1] - a[1]).slice(0, 8);
206
+ writeOut(`events ${topEvents.length > 0 ? topEvents.map(([name, n]) => `${name}:${n}`).join(', ') : 'none'}`);
207
+ writeOut(`evidence rows=${tally.rows.length}`);
208
+ for (const row of tally.rows) {
209
+ const sig = row.signature !== null ? ` sig=${row.signature}` : '';
210
+ writeOut(` [${row.level}]${sig} ${row.digest}`);
211
+ }
212
+ const saved = saveScanReport(alias, container, selector, tally.counts, tally.hits, PATTERNS.map(([name]) => name), tally.events, tally.rows, totalBytes, project, tally.filtered);
213
+ if (saved !== null)
214
+ writeOut(`saved=${saved}`);
215
+ return 0;
216
+ }
@@ -0,0 +1,9 @@
1
+ export declare const exportPublicUsage = "bbc export-public <out-dir> --public-repo <owner/name> [--repo <repo-root>]";
2
+ export declare class ExportRefusedError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ export declare function trackedFiles(root: string): string[];
6
+ export declare function privateProfiles(root: string): Map<string, string[]>;
7
+ export declare function dropMarked(text: string, srcName: string): string;
8
+ export declare function exportPublicEdition(rootInput: string, outInput: string, publicRepo: string): Record<string, unknown>;
9
+ export declare function exportPublic(argv: readonly string[]): number;