@andorra-labs/code 0.1.9 → 0.1.10

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 (96) hide show
  1. package/dist/src/agent-execution.js +20 -0
  2. package/dist/src/app-server/protocol.d.ts +108 -1
  3. package/dist/src/app-server/protocol.js +8 -1
  4. package/dist/src/app-server.d.ts +25 -0
  5. package/dist/src/app-server.js +156 -11
  6. package/dist/src/auth/index.d.ts +1 -1
  7. package/dist/src/auth/index.js +1 -1
  8. package/dist/src/auth/store.d.ts +17 -1
  9. package/dist/src/auth/store.js +25 -2
  10. package/dist/src/browser-ui/app.js +19 -19
  11. package/dist/src/browser-ui/index.html +7 -7
  12. package/dist/src/cli.js +10 -5
  13. package/dist/src/commands.d.ts +1 -1
  14. package/dist/src/commands.js +1 -1
  15. package/dist/src/completion-gates.js +1 -1
  16. package/dist/src/completion.d.ts +1 -1
  17. package/dist/src/completion.js +1 -1
  18. package/dist/src/decision/checks.js +1 -1
  19. package/dist/src/file-diff.d.ts +105 -0
  20. package/dist/src/file-diff.js +244 -0
  21. package/dist/src/graph-manager-chat.js +15 -15
  22. package/dist/src/graph-server.js +9 -9
  23. package/dist/src/graph-ui/app.js +123 -118
  24. package/dist/src/graph-ui/embed.js +9 -9
  25. package/dist/src/graph-ui/icons.js +1 -0
  26. package/dist/src/graph-ui/index.html +3 -3
  27. package/dist/src/graph-ui/manager-state.js +3 -3
  28. package/dist/src/graph-ui/manager.js +14 -14
  29. package/dist/src/graph-ui/skill-picker.js +6 -6
  30. package/dist/src/graph-ui/studio-canvas.js +15 -15
  31. package/dist/src/graph-ui/studio.js +40 -40
  32. package/dist/src/graph-ui/style.css +3 -1
  33. package/dist/src/graph-ui/theme.js +2 -2
  34. package/dist/src/graphs.d.ts +7 -1
  35. package/dist/src/graphs.js +12 -2
  36. package/dist/src/mcp.d.ts +75 -0
  37. package/dist/src/mcp.js +240 -8
  38. package/dist/src/membership-errors.js +1 -1
  39. package/dist/src/provider-keys.d.ts +5 -1
  40. package/dist/src/provider-keys.js +7 -3
  41. package/dist/src/provider-settings.d.ts +4 -1
  42. package/dist/src/provider-settings.js +46 -5
  43. package/dist/src/qa/guidance.js +6 -19
  44. package/dist/src/qa/index.d.ts +0 -2
  45. package/dist/src/qa/index.js +0 -2
  46. package/dist/src/qa/profile/QaProfile.d.ts +5 -1
  47. package/dist/src/qa/profile/QaProfile.js +6 -2
  48. package/dist/src/qa/tools.d.ts +19 -1
  49. package/dist/src/qa/tools.js +20 -145
  50. package/dist/src/react-runtime.js +13 -2
  51. package/dist/src/remote/engine-pool.js +18 -6
  52. package/dist/src/screen-selection.d.ts +38 -0
  53. package/dist/src/screen-selection.js +103 -0
  54. package/dist/src/session-changes.d.ts +117 -0
  55. package/dist/src/session-changes.js +796 -0
  56. package/dist/src/stall-recovery.d.ts +11 -0
  57. package/dist/src/stall-recovery.js +12 -0
  58. package/dist/src/telemetry/schema.d.ts +1 -1
  59. package/dist/src/telemetry/schema.js +1 -2
  60. package/dist/src/terminal-ui.d.ts +64 -20
  61. package/dist/src/terminal-ui.js +310 -80
  62. package/dist/src/tool-diff-stats.d.ts +9 -0
  63. package/dist/src/tool-diff-stats.js +20 -0
  64. package/dist/src/tool-names.d.ts +1 -1
  65. package/dist/src/tool-result-filter.js +1 -1
  66. package/dist/src/tools.js +26 -2
  67. package/dist/src/transcript.d.ts +11 -0
  68. package/dist/src/transcript.js +14 -2
  69. package/dist/src/types.d.ts +6 -0
  70. package/docs/guides/desktop-app.md +1 -1
  71. package/docs/guides/tui.md +9 -9
  72. package/package.json +1 -1
  73. package/dist/src/qa/api/http-runner.d.ts +0 -3
  74. package/dist/src/qa/api/http-runner.js +0 -47
  75. package/dist/src/qa/git/ChangeDetector.d.ts +0 -26
  76. package/dist/src/qa/git/ChangeDetector.js +0 -177
  77. package/dist/src/qa/git/DiffReviewer.d.ts +0 -28
  78. package/dist/src/qa/git/DiffReviewer.js +0 -115
  79. package/dist/src/qa/orchestrator/ChangeClassifier.d.ts +0 -14
  80. package/dist/src/qa/orchestrator/ChangeClassifier.js +0 -28
  81. package/dist/src/qa/orchestrator/MergeGate.d.ts +0 -14
  82. package/dist/src/qa/orchestrator/MergeGate.js +0 -40
  83. package/dist/src/qa/orchestrator/QaOrchestrator.d.ts +0 -79
  84. package/dist/src/qa/orchestrator/QaOrchestrator.js +0 -373
  85. package/dist/src/qa/runners/CommandRunner.d.ts +0 -22
  86. package/dist/src/qa/runners/CommandRunner.js +0 -96
  87. package/dist/src/qa/runners/TestRunner.d.ts +0 -21
  88. package/dist/src/qa/runners/TestRunner.js +0 -66
  89. package/dist/src/qa/runtime/RuntimeSmoke.d.ts +0 -11
  90. package/dist/src/qa/runtime/RuntimeSmoke.js +0 -78
  91. package/dist/src/qa/runtime-detect.d.ts +0 -10
  92. package/dist/src/qa/runtime-detect.js +0 -72
  93. package/dist/src/qa/security/DependencyScanner.d.ts +0 -19
  94. package/dist/src/qa/security/DependencyScanner.js +0 -167
  95. package/dist/src/qa/security/SecretScanner.d.ts +0 -3
  96. package/dist/src/qa/security/SecretScanner.js +0 -55
@@ -1,14 +0,0 @@
1
- export interface ChangeClassification {
2
- frontend: boolean;
3
- backend: boolean;
4
- api: boolean;
5
- database: boolean;
6
- buildConfig: boolean;
7
- documentation: boolean;
8
- securitySensitive: boolean;
9
- dependency: boolean;
10
- testOnly: boolean;
11
- sourceChanged: boolean;
12
- }
13
- /** Classify changed paths into the buckets that drive the dynamic merge gate. */
14
- export declare function classifyChanges(files: string[]): ChangeClassification;
@@ -1,28 +0,0 @@
1
- const FRONTEND_EXT = /\.(tsx|jsx|vue|svelte|astro|css|scss|sass|less|html)$/i;
2
- const FRONTEND_PATH = /(^|\/)(pages|components|views|styles|app|public)\//i;
3
- const API_PATH = /(^|\/)(api|routes|controllers|handlers|graphql)\//i;
4
- const API_FILE = /(^|\/)(openapi|swagger)\.(ya?ml|json)$|\.proto$/i;
5
- const DATABASE = /(^|\/)(migrations?|schema|db|database|prisma|alembic)\//i;
6
- const DATABASE_FILE = /\.sql$/i;
7
- const BUILD_CONFIG = /(^|\/)(package\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|tsconfig[^/]*\.json|jsconfig[^/]*\.json|vite\.config\.[cm]?[jt]s|webpack[^/]*\.[cm]?[jt]s|rollup\.config\.[cm]?[jt]s|babel\.config\.[cm]?[jt]s|jest\.config\.[cm]?[jt]s|vitest\.config\.[cm]?[jt]s|playwright\.config\.[cm]?[jt]s|pyproject\.toml|setup\.py|setup\.cfg|requirements[^/]*\.txt|poetry\.lock|Cargo\.toml|Cargo\.lock|go\.mod|go\.sum|pom\.xml|build\.gradle\.kts?|settings\.gradle\.kts?|Dockerfile[^/]*|docker-compose[^/]*\.ya?ml|Makefile|meson\.build|\.semgrep[^/]*|eslint\.config\.[cm]?[jt]s|biome\.jsonc?|ruff\.toml|\.golangci\.[my]?a?ml?|\.github\/workflows\/)/i;
8
- const DOCUMENTATION = /\.(md|mdx|rst|adoc|txt)$/i;
9
- const SECURITY_SENSITIVE = /(auth|oauth|token|secret|credential|crypto|permission|acl|session|security|rbac|jwt)/i;
10
- const LOCKFILE = /(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|Cargo\.lock|go\.sum|poetry\.lock|composer\.lock)$/i;
11
- const TEST_FILE = /(\.|_)(test|spec)\.[a-z]+$|(^|\/)(tests?|__tests__|spec)\//i;
12
- const SOURCE_EXT = /\.(ts|tsx|js|jsx|mjs|cjs|py|rs|go|java|cs|rb|php|vue|svelte)$/i;
13
- /** Classify changed paths into the buckets that drive the dynamic merge gate. */
14
- export function classifyChanges(files) {
15
- const relevant = files.filter(file => !file.startsWith('.andorra/'));
16
- return {
17
- frontend: relevant.some(file => FRONTEND_EXT.test(file) || FRONTEND_PATH.test(file)),
18
- backend: relevant.some(file => SOURCE_EXT.test(file) && !FRONTEND_EXT.test(file) && !TEST_FILE.test(file) && !SECURITY_SENSITIVE.test(file)),
19
- api: relevant.some(file => API_PATH.test(file) || API_FILE.test(file)),
20
- database: relevant.some(file => DATABASE.test(file) || DATABASE_FILE.test(file)),
21
- buildConfig: relevant.some(file => BUILD_CONFIG.test(file)),
22
- documentation: relevant.length > 0 && relevant.every(file => DOCUMENTATION.test(file)),
23
- securitySensitive: relevant.some(file => SECURITY_SENSITIVE.test(file)),
24
- dependency: relevant.some(file => LOCKFILE.test(file)),
25
- testOnly: relevant.length > 0 && relevant.every(file => TEST_FILE.test(file)),
26
- sourceChanged: relevant.some(file => SOURCE_EXT.test(file)),
27
- };
28
- }
@@ -1,14 +0,0 @@
1
- import type { QaProfile } from '../types.js';
2
- import type { ChangeClassification } from './ChangeClassifier.js';
3
- /**
4
- * Required gate steps for a change set: the configured baseline plus checks
5
- * the classification adds (browser trio for frontend changes, runtime smoke
6
- * when a startup exists, API smoke for API changes, dependency audit for
7
- * lockfile/security-sensitive edits, semgrep only when explicitly enabled).
8
- */
9
- export declare function computeMergeGate(profile: QaProfile, classification: ChangeClassification): string[];
10
- export interface GateVerdictInput {
11
- status: 'passed' | 'failed' | 'skipped' | 'blocked';
12
- }
13
- /** BLOCKED when any required step could not run; FAILED on any real failure. */
14
- export declare function gateVerdict(results: GateVerdictInput[]): 'ready' | 'failed' | 'blocked';
@@ -1,40 +0,0 @@
1
- /**
2
- * Required gate steps for a change set: the configured baseline plus checks
3
- * the classification adds (browser trio for frontend changes, runtime smoke
4
- * when a startup exists, API smoke for API changes, dependency audit for
5
- * lockfile/security-sensitive edits, semgrep only when explicitly enabled).
6
- */
7
- export function computeMergeGate(profile, classification) {
8
- const steps = [];
9
- const add = (...ids) => { for (const id of ids)
10
- if (!steps.includes(id))
11
- steps.push(id); };
12
- add(...profile.mergeGate);
13
- if (classification.frontend && profile.browser.enabled) {
14
- add('browser_smoke', 'console_errors', 'network_errors');
15
- if (profile.browser.accessibility)
16
- add('accessibility');
17
- }
18
- if (profile.startup && (classification.frontend || classification.backend || classification.api || classification.buildConfig)) {
19
- add('runtime_smoke');
20
- }
21
- if (profile.apiSmokeTests.length && (classification.api || classification.frontend))
22
- add('api_smoke');
23
- if (classification.database)
24
- add('migration_validation');
25
- if (classification.securitySensitive || classification.dependency || profile.security.dependencyScan)
26
- add('dependency_audit');
27
- if (classification.securitySensitive)
28
- add('secret_scan');
29
- if (profile.security.semgrep)
30
- add('semgrep');
31
- return steps;
32
- }
33
- /** BLOCKED when any required step could not run; FAILED on any real failure. */
34
- export function gateVerdict(results) {
35
- if (results.some(result => result.status === 'failed'))
36
- return 'failed';
37
- if (results.some(result => result.status === 'blocked'))
38
- return 'blocked';
39
- return 'ready';
40
- }
@@ -1,79 +0,0 @@
1
- import type { QaCheckResult, QaProfile, QaSessionState } from '../types.js';
2
- import { type TestCommandRequest } from '../runners/TestRunner.js';
3
- import { type ChangeClassification } from './ChangeClassifier.js';
4
- export interface QaRunReport {
5
- runId: string;
6
- fingerprint: string;
7
- results: QaCheckResult[];
8
- verdict: 'clean' | 'issues' | 'blocked';
9
- changedFiles: string[];
10
- gate?: {
11
- steps: string[];
12
- verdict: 'ready' | 'failed' | 'blocked';
13
- };
14
- }
15
- /**
16
- * Per-workspace QA session: derives/caches the project profile, runs check
17
- * pipelines, records normalized results with a working-tree fingerprint for
18
- * staleness, bounds the repair loop, and prunes run logs to a retention set.
19
- */
20
- export declare class QaOrchestrator {
21
- readonly workspace: string;
22
- readonly state: QaSessionState;
23
- private profileEntry;
24
- private lastRunFingerprint;
25
- private readonly qaRoot;
26
- constructor(workspace: string);
27
- getProfile(signal: AbortSignal): Promise<QaProfile>;
28
- /** Every command this session could execute under the current profile, for pre-flight policy checks. */
29
- plannedCommands(profile: QaProfile): string[];
30
- profileSummary(signal: AbortSignal): Promise<string>;
31
- private newRun;
32
- private pruneLogs;
33
- private audit;
34
- private record;
35
- private verdictFor;
36
- /** qa.fast: lint, typecheck, related tests, optional build, diff review and secret scan. */
37
- fast(options: {
38
- includeBuild: boolean;
39
- signal: AbortSignal;
40
- authorize?: (command: string) => Promise<void>;
41
- }): Promise<QaRunReport>;
42
- /** qa.test: run the unit suite scoped by mode. */
43
- test(request: TestCommandRequest, options: {
44
- signal: AbortSignal;
45
- authorize?: (command: string) => Promise<void>;
46
- }): Promise<QaCheckResult>;
47
- /** qa.security: built-in secret scan, dependency audit, and semgrep when enabled. */
48
- security(options: {
49
- signal: AbortSignal;
50
- authorize?: (command: string) => Promise<void>;
51
- }): Promise<QaCheckResult[]>;
52
- private semgrepCheck;
53
- /** qa.browser: load a URL in Playwright and report smoke/console/network(/a11y). */
54
- browser(options: {
55
- url?: string;
56
- accessibility?: boolean;
57
- signal: AbortSignal;
58
- }): Promise<QaCheckResult[]>;
59
- /** qa.deep: the full dynamic merge gate over the current change set. */
60
- deep(options: {
61
- signal: AbortSignal;
62
- authorize?: (command: string) => Promise<void>;
63
- checks?: string[];
64
- }): Promise<QaRunReport>;
65
- private gateStep;
66
- /** qa.status: session view — profile summary, last results, staleness, gate verdict. */
67
- status(signal: AbortSignal): Promise<{
68
- summary: string;
69
- state: QaSessionState;
70
- }>;
71
- /** True when results recorded at the last run no longer reflect the tree. */
72
- isStale(currentFingerprint: string): boolean;
73
- changeSnapshot(signal: AbortSignal): Promise<{
74
- changedFiles: string[];
75
- classification: ChangeClassification;
76
- fingerprint: string;
77
- }>;
78
- }
79
- export declare function getQaOrchestrator(workspace: string): QaOrchestrator;
@@ -1,373 +0,0 @@
1
- import { mkdir, readdir, rm, appendFile } from 'node:fs/promises';
2
- import path from 'node:path';
3
- import { randomUUID } from 'node:crypto';
4
- import { executeShell } from '../../shell.js';
5
- import { emptyQaState } from '../types.js';
6
- import { deriveProfile } from '../profile/ProjectInspector.js';
7
- import { detectChanges } from '../git/ChangeDetector.js';
8
- import { reviewDiff } from '../git/DiffReviewer.js';
9
- import { scanAddedLinesForSecrets } from '../security/SecretScanner.js';
10
- import { runDependencyAudit } from '../security/DependencyScanner.js';
11
- import { runCommandCheck } from '../runners/CommandRunner.js';
12
- import { buildTestCommand } from '../runners/TestRunner.js';
13
- import { runRuntimeSmoke } from '../runtime/RuntimeSmoke.js';
14
- import { runApiSmokeTests } from '../api/http-runner.js';
15
- import { runBrowserQa } from '../browser/PlaywrightRunner.js';
16
- import { classifyChanges } from './ChangeClassifier.js';
17
- import { computeMergeGate, gateVerdict } from './MergeGate.js';
18
- import { describeRuntimeCapabilities } from '../runtime-detect.js';
19
- const LINT_TIMEOUT_MS = 120_000;
20
- const TEST_TIMEOUT_MS = 300_000;
21
- const LOG_RETENTION = 20;
22
- function shortRunId() {
23
- return `${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
24
- }
25
- /**
26
- * Per-workspace QA session: derives/caches the project profile, runs check
27
- * pipelines, records normalized results with a working-tree fingerprint for
28
- * staleness, bounds the repair loop, and prunes run logs to a retention set.
29
- */
30
- export class QaOrchestrator {
31
- workspace;
32
- state = emptyQaState();
33
- profileEntry;
34
- lastRunFingerprint;
35
- qaRoot;
36
- constructor(workspace) {
37
- this.workspace = workspace;
38
- this.qaRoot = path.join(workspace, '.andorra', 'runtime', 'qa');
39
- }
40
- async getProfile(signal) {
41
- const derived = await deriveProfile(this.workspace);
42
- if (!this.profileEntry || this.profileEntry.fingerprint !== derived.fingerprint)
43
- this.profileEntry = derived;
44
- signal.throwIfAborted();
45
- return this.profileEntry.profile;
46
- }
47
- /** Every command this session could execute under the current profile, for pre-flight policy checks. */
48
- plannedCommands(profile) {
49
- const commands = [];
50
- for (const key of ['lint', 'typecheck', 'unit', 'build', 'e2e']) {
51
- const spec = profile.qa[key];
52
- if (spec)
53
- commands.push(spec.command);
54
- }
55
- if (profile.startup)
56
- commands.push(profile.startup.command);
57
- if (profile.security.dependencyScan)
58
- commands.push(`${profile.project.packageManager ?? 'npm'} audit --json`);
59
- if (profile.security.semgrep)
60
- commands.push('semgrep scan --error --config p/default --metrics off');
61
- return commands;
62
- }
63
- async profileSummary(signal) {
64
- const profile = await this.getProfile(signal);
65
- const lines = [
66
- `language=${profile.project.language}${profile.project.framework ? ` framework=${profile.project.framework}` : ''}${profile.project.packageManager ? ` packageManager=${profile.project.packageManager}` : ''}`,
67
- ...['lint', 'typecheck', 'unit', 'build', 'e2e'].map(key => `qa.${key}: ${profile.qa[key]?.command ?? 'not configured'}`),
68
- profile.startup ? `startup: ${profile.startup.command}${profile.startup.healthUrl ? ` (health ${profile.startup.healthUrl})` : ''}` : 'startup: not configured',
69
- `browser: ${profile.browser.enabled ? `enabled${profile.browser.url ? ` url=${profile.browser.url}` : ' (no url configured)'}` : 'disabled'}`,
70
- `merge gate: ${profile.mergeGate.join(', ')}`,
71
- profile.configError ? `qa.yaml error: ${profile.configError}` : undefined,
72
- ].filter((line) => line !== undefined);
73
- return (await lines.join('\n')) + `\n${await describeRuntimeCapabilities()}`;
74
- }
75
- async newRun(signal) {
76
- const runId = shortRunId();
77
- const logDir = path.join(this.qaRoot, runId);
78
- await mkdir(logDir, { recursive: true });
79
- await this.pruneLogs();
80
- signal.throwIfAborted();
81
- return { runId, logDir };
82
- }
83
- async pruneLogs() {
84
- try {
85
- const entries = await readdir(this.qaRoot, { withFileTypes: true });
86
- const dirs = entries.filter(entry => entry.isDirectory() && entry.name !== 'processes').map(entry => entry.name);
87
- if (dirs.length <= LOG_RETENTION)
88
- return;
89
- const stats = await Promise.all(dirs.map(async (name) => ({ name, mtime: (await statMtime(path.join(this.qaRoot, name))).getTime() })));
90
- stats.sort((a, b) => b.mtime - a.mtime);
91
- await Promise.all(stats.slice(LOG_RETENTION).map(entry => rm(path.join(this.qaRoot, entry.name), { recursive: true, force: true })));
92
- }
93
- catch { /* pruning is best-effort */ }
94
- }
95
- async audit(record) {
96
- try {
97
- await mkdir(this.qaRoot, { recursive: true });
98
- await appendFile(path.join(this.qaRoot, 'audit.ndjson'), `${JSON.stringify(record)}\n`, 'utf8');
99
- }
100
- catch { /* audit is best-effort */ }
101
- }
102
- record(result, fingerprint, profile) {
103
- let stored = result;
104
- if (result.status === 'failed') {
105
- const count = (this.state.failureCounts[result.id] ?? 0) + 1;
106
- this.state.failureCounts[result.id] = count;
107
- if (profile.autoRepair.enabled && count >= profile.autoRepair.maxAttemptsPerCheck) {
108
- stored = { ...stored, repairExhausted: true, summary: `BLOCKED: ${result.id} still fails after ${count} repair attempts. ${stored.summary}` };
109
- }
110
- }
111
- else if (result.status === 'passed') {
112
- this.state.failureCounts[result.id] = 0;
113
- }
114
- stored = { ...stored, fingerprint };
115
- this.state.checks[stored.id] = stored;
116
- return stored;
117
- }
118
- verdictFor(results) {
119
- if (results.some(result => result.status === 'failed'))
120
- return 'issues';
121
- if (results.some(result => result.status === 'blocked'))
122
- return 'blocked';
123
- return 'clean';
124
- }
125
- /** qa.fast: lint, typecheck, related tests, optional build, diff review and secret scan. */
126
- async fast(options) {
127
- const profile = await this.getProfile(options.signal);
128
- const changeSet = await detectChanges({ cwd: this.workspace, signal: options.signal });
129
- const { runId, logDir } = await this.newRun(options.signal);
130
- const results = [];
131
- const command = async (id, category, key, defaultTimeoutMs) => {
132
- const spec = profile.qa[key];
133
- if (!spec)
134
- return { id, category, status: 'skipped', durationMs: 0, summary: `no ${key} command configured or detected` };
135
- await options.authorize?.(spec.command);
136
- const result = await runCommandCheck({ id, category, command: spec, workspace: this.workspace, logDir, defaultTimeoutMs, signal: options.signal });
137
- await this.audit({ time: new Date().toISOString(), runId, id, command: spec.command, status: result.status, durationMs: result.durationMs });
138
- return result;
139
- };
140
- results.push(await command('lint', 'lint', 'lint', LINT_TIMEOUT_MS));
141
- results.push(await command('typecheck', 'typecheck', 'typecheck', LINT_TIMEOUT_MS));
142
- const relatedFiles = changeSet.changedFiles;
143
- if (!relatedFiles.length) {
144
- results.push({ id: 'related_tests', category: 'unit', status: 'skipped', durationMs: 0, summary: 'no changed files to scope tests to' });
145
- }
146
- else {
147
- const built = buildTestCommand(profile, { mode: 'related', files: relatedFiles });
148
- if (built.blocked || !built.command) {
149
- results.push({ id: 'related_tests', category: 'unit', status: 'blocked', durationMs: 0, summary: built.blocked ?? 'test command could not be built' });
150
- }
151
- else {
152
- await options.authorize?.(built.command);
153
- const result = await runCommandCheck({ id: 'related_tests', category: 'unit', command: { command: built.command, timeoutMs: built.timeoutMs }, workspace: this.workspace, logDir, defaultTimeoutMs: TEST_TIMEOUT_MS, signal: options.signal });
154
- if (built.note)
155
- result.summary = `${result.summary} (${built.note})`;
156
- await this.audit({ time: new Date().toISOString(), runId, id: 'related_tests', command: built.command, status: result.status, durationMs: result.durationMs });
157
- results.push(result);
158
- }
159
- }
160
- if (options.includeBuild)
161
- results.push(await command('build', 'build', 'build', TEST_TIMEOUT_MS));
162
- else
163
- results.push({ id: 'build', category: 'build', status: 'skipped', durationMs: 0, summary: 'build not requested; pass includeBuild to run it' });
164
- const secretHits = scanAddedLinesForSecrets(changeSet.diff ?? '');
165
- results.push(secretHits.length
166
- ? { id: 'secret_scan', category: 'security', status: 'failed', durationMs: 0, summary: `${secretHits.length} possible secret(s) added to the working tree`, errors: secretHits }
167
- : { id: 'secret_scan', category: 'security', status: 'passed', durationMs: 0, summary: 'no credential-shaped strings added to the diff' });
168
- const review = reviewDiff(changeSet, []);
169
- results.push({
170
- id: 'diff_review', category: 'diff',
171
- status: review.passed ? 'passed' : 'failed',
172
- durationMs: 0,
173
- summary: `${review.stats.filesChanged} files, +${review.stats.insertions}/-${review.stats.deletions}: ${review.passed ? 'no blocking findings' : `${review.issues.filter(issue => issue.severity === 'error').length} blocking finding(s)`}`,
174
- errors: review.issues.length ? review.issues : undefined,
175
- });
176
- const recorded = results.map(result => this.record(result, changeSet.fingerprint, profile));
177
- this.state.lastFastRun = runId;
178
- this.lastRunFingerprint = changeSet.fingerprint;
179
- this.state.changedSinceLastQa = false;
180
- return { runId, fingerprint: changeSet.fingerprint, results: recorded, verdict: this.verdictFor(recorded), changedFiles: changeSet.changedFiles };
181
- }
182
- /** qa.test: run the unit suite scoped by mode. */
183
- async test(request, options) {
184
- const { signal, authorize } = options;
185
- const profile = await this.getProfile(signal);
186
- const built = buildTestCommand(profile, request);
187
- if (built.blocked || !built.command) {
188
- return { id: 'related_tests', category: 'unit', status: 'blocked', durationMs: 0, summary: built.blocked ?? 'test command could not be built' };
189
- }
190
- const { runId, logDir } = await this.newRun(signal);
191
- await authorize?.(built.command);
192
- const result = await runCommandCheck({ id: 'related_tests', category: 'unit', command: { command: built.command, timeoutMs: built.timeoutMs }, workspace: this.workspace, logDir, defaultTimeoutMs: TEST_TIMEOUT_MS, signal });
193
- if (built.note)
194
- result.summary = `${result.summary} (${built.note})`;
195
- await this.audit({ time: new Date().toISOString(), runId, id: 'related_tests', mode: request.mode, command: built.command, status: result.status, durationMs: result.durationMs });
196
- const changeSet = await detectChanges({ cwd: this.workspace, signal });
197
- return this.record(result, changeSet.fingerprint, profile);
198
- }
199
- /** qa.security: built-in secret scan, dependency audit, and semgrep when enabled. */
200
- async security(options) {
201
- const { signal, authorize } = options;
202
- const profile = await this.getProfile(signal);
203
- const { runId, logDir } = await this.newRun(signal);
204
- const results = [];
205
- const changeSet = await detectChanges({ cwd: this.workspace, signal });
206
- const secretHits = scanAddedLinesForSecrets(changeSet.diff ?? '');
207
- results.push(this.record(secretHits.length
208
- ? { id: 'secret_scan', category: 'security', status: 'failed', durationMs: 0, summary: `${secretHits.length} possible secret(s) added to the working tree`, errors: secretHits }
209
- : { id: 'secret_scan', category: 'security', status: 'passed', durationMs: 0, summary: 'no credential-shaped strings added to the diff' }, changeSet.fingerprint, profile));
210
- if (profile.security.dependencyScan) {
211
- await authorize?.(`${profile.project.packageManager ?? 'npm'} audit --json`);
212
- const audit = await runDependencyAudit({ workspace: this.workspace, packageManager: profile.project.packageManager, failOn: profile.security.failOn, signal });
213
- results.push(this.record({
214
- id: 'dependency_audit', category: 'security', status: audit.status, durationMs: audit.durationMs,
215
- summary: audit.summary, errors: audit.issues.length ? audit.issues : undefined,
216
- importantOutput: audit.importantOutput.length ? audit.importantOutput : undefined,
217
- }, changeSet.fingerprint, profile));
218
- }
219
- else {
220
- results.push({ id: 'dependency_audit', category: 'security', status: 'skipped', durationMs: 0, summary: 'dependency scan disabled in configuration' });
221
- }
222
- if (profile.security.semgrep) {
223
- results.push(this.record(await this.semgrepCheck(logDir, runId, signal, authorize), changeSet.fingerprint, profile));
224
- }
225
- return results;
226
- }
227
- async semgrepCheck(logDir, runId, signal, authorize) {
228
- try {
229
- await executeShell('semgrep --version', this.workspace, 10_000, signal);
230
- }
231
- catch {
232
- return { id: 'semgrep', category: 'security', status: 'blocked', durationMs: 0, summary: 'semgrep is enabled in configuration but not installed' };
233
- }
234
- const command = 'semgrep scan --error --config p/default --metrics off';
235
- await authorize?.(command);
236
- const result = await runCommandCheck({ id: 'semgrep', category: 'security', command: { command }, workspace: this.workspace, logDir, defaultTimeoutMs: 300_000, signal });
237
- await this.audit({ time: new Date().toISOString(), runId, id: 'semgrep', status: result.status, durationMs: result.durationMs });
238
- return result;
239
- }
240
- /** qa.browser: load a URL in Playwright and report smoke/console/network(/a11y). */
241
- async browser(options) {
242
- const profile = await this.getProfile(options.signal);
243
- const outcome = await runBrowserQa({ workspace: this.workspace, profile, ...(options.url ? { url: options.url } : {}), ...(options.accessibility !== undefined ? { accessibility: options.accessibility } : {}), signal: options.signal });
244
- const changeSet = await detectChanges({ cwd: this.workspace, signal: options.signal });
245
- const results = [outcome.smoke, outcome.consoleErrors, outcome.networkErrors, ...(outcome.accessibility ? [outcome.accessibility] : [])];
246
- return results.map(result => this.record(result, changeSet.fingerprint, profile));
247
- }
248
- /** qa.deep: the full dynamic merge gate over the current change set. */
249
- async deep(options) {
250
- const { signal, authorize } = options;
251
- const profile = await this.getProfile(signal);
252
- const changeSet = await detectChanges({ cwd: this.workspace, signal });
253
- const classification = classifyChanges(changeSet.changedFiles);
254
- const steps = options.checks?.length ? options.checks : computeMergeGate(profile, classification);
255
- const { runId, logDir } = await this.newRun(signal);
256
- const results = [];
257
- let browserOutcome;
258
- for (const step of steps) {
259
- signal.throwIfAborted();
260
- if (step === 'browser_smoke' || step === 'console_errors' || step === 'network_errors' || step === 'accessibility') {
261
- browserOutcome ??= await runBrowserQa({ workspace: this.workspace, profile, signal });
262
- const pick = step === 'browser_smoke' ? browserOutcome.smoke
263
- : step === 'console_errors' ? browserOutcome.consoleErrors
264
- : step === 'network_errors' ? browserOutcome.networkErrors
265
- : browserOutcome.accessibility ?? { id: 'accessibility', category: 'accessibility', status: 'skipped', durationMs: 0, summary: 'accessibility not requested' };
266
- results.push(pick);
267
- continue;
268
- }
269
- results.push(await this.gateStep(step, profile, changeSet.changedFiles, { runId, logDir }, signal, authorize));
270
- }
271
- const recorded = results.map(result => this.record(result, changeSet.fingerprint, profile));
272
- const verdict = gateVerdict(recorded);
273
- this.state.lastDeepRun = runId;
274
- this.state.mergeReady = verdict === 'ready';
275
- this.state.lastGateVerdict = verdict;
276
- this.lastRunFingerprint = changeSet.fingerprint;
277
- this.state.changedSinceLastQa = false;
278
- return { runId, fingerprint: changeSet.fingerprint, results: recorded, verdict: verdict === 'ready' ? 'clean' : verdict === 'failed' ? 'issues' : 'blocked', changedFiles: changeSet.changedFiles, gate: { steps, verdict } };
279
- }
280
- async gateStep(step, profile, changedFiles, run, signal, authorize) {
281
- switch (step) {
282
- case 'lint':
283
- case 'typecheck':
284
- case 'build': {
285
- const spec = profile.qa[step];
286
- if (!spec)
287
- return { id: step, category: step, status: 'skipped', durationMs: 0, summary: `no ${step} command configured or detected` };
288
- await authorize?.(spec.command);
289
- const result = await runCommandCheck({ id: step, category: step, command: spec, workspace: this.workspace, logDir: run.logDir, defaultTimeoutMs: step === 'build' ? TEST_TIMEOUT_MS : LINT_TIMEOUT_MS, signal });
290
- await this.audit({ time: new Date().toISOString(), runId: run.runId, id: step, command: spec.command, status: result.status, durationMs: result.durationMs });
291
- return result;
292
- }
293
- case 'related_tests': {
294
- if (!changedFiles.length)
295
- return { id: 'related_tests', category: 'unit', status: 'skipped', durationMs: 0, summary: 'no changed files to test' };
296
- const built = buildTestCommand(profile, { mode: 'related', files: changedFiles });
297
- if (built.blocked || !built.command)
298
- return { id: 'related_tests', category: 'unit', status: 'blocked', durationMs: 0, summary: built.blocked ?? 'test command could not be built' };
299
- await authorize?.(built.command);
300
- const result = await runCommandCheck({ id: 'related_tests', category: 'unit', command: { command: built.command, timeoutMs: built.timeoutMs }, workspace: this.workspace, logDir: run.logDir, defaultTimeoutMs: TEST_TIMEOUT_MS, signal });
301
- if (built.note)
302
- result.summary = `${result.summary} (${built.note})`;
303
- await this.audit({ time: new Date().toISOString(), runId: run.runId, id: 'related_tests', command: built.command, status: result.status, durationMs: result.durationMs });
304
- return result;
305
- }
306
- case 'diff_review': {
307
- const changeSet = await detectChanges({ cwd: this.workspace, signal });
308
- const review = reviewDiff(changeSet, []);
309
- const blocking = review.issues.filter(issue => issue.severity === 'error').length;
310
- return {
311
- id: 'diff_review', category: 'diff', status: review.passed ? 'passed' : 'failed', durationMs: 0,
312
- summary: `${review.stats.filesChanged} files, +${review.stats.insertions}/-${review.stats.deletions}: ${review.passed ? 'no blocking findings' : `${blocking} blocking finding(s)`}`,
313
- errors: review.issues.length ? review.issues : undefined,
314
- };
315
- }
316
- case 'secret_scan': {
317
- const changeSet = await detectChanges({ cwd: this.workspace, signal });
318
- const secretHits = scanAddedLinesForSecrets(changeSet.diff ?? '');
319
- return secretHits.length
320
- ? { id: 'secret_scan', category: 'security', status: 'failed', durationMs: 0, summary: `${secretHits.length} possible secret(s) added to the working tree`, errors: secretHits }
321
- : { id: 'secret_scan', category: 'security', status: 'passed', durationMs: 0, summary: 'no credential-shaped strings added to the diff' };
322
- }
323
- case 'dependency_audit': {
324
- if (!profile.security.dependencyScan)
325
- return { id: 'dependency_audit', category: 'security', status: 'skipped', durationMs: 0, summary: 'dependency scan disabled in configuration' };
326
- await authorize?.(`${profile.project.packageManager ?? 'npm'} audit --json`);
327
- const audit = await runDependencyAudit({ workspace: this.workspace, packageManager: profile.project.packageManager, failOn: profile.security.failOn, signal });
328
- return { id: 'dependency_audit', category: 'security', status: audit.status, durationMs: audit.durationMs, summary: audit.summary, errors: audit.issues.length ? audit.issues : undefined, importantOutput: audit.importantOutput.length ? audit.importantOutput : undefined };
329
- }
330
- case 'runtime_smoke': {
331
- if (profile.startup)
332
- await authorize?.(profile.startup.command);
333
- return runRuntimeSmoke({ workspace: this.workspace, profile, logDir: run.logDir, signal });
334
- }
335
- case 'api_smoke':
336
- return runApiSmokeTests(profile.apiSmokeTests, signal);
337
- case 'migration_validation':
338
- return { id: 'migration_validation', category: 'runtime', status: 'skipped', durationMs: 0, summary: 'migration validation is not implemented in this release; run migrations against a scratch database' };
339
- case 'semgrep':
340
- return this.semgrepCheck(run.logDir, run.runId, signal, authorize);
341
- default:
342
- return { id: step, category: 'runtime', status: 'skipped', durationMs: 0, summary: `gate step "${step}" is not implemented in this release` };
343
- }
344
- }
345
- /** qa.status: session view — profile summary, last results, staleness, gate verdict. */
346
- async status(signal) {
347
- const changeSet = await detectChanges({ cwd: this.workspace, signal });
348
- if (this.lastRunFingerprint !== undefined)
349
- this.state.changedSinceLastQa = changeSet.fingerprint !== this.lastRunFingerprint;
350
- return { summary: await this.profileSummary(signal), state: this.state };
351
- }
352
- /** True when results recorded at the last run no longer reflect the tree. */
353
- isStale(currentFingerprint) {
354
- return this.lastRunFingerprint !== undefined && this.lastRunFingerprint !== currentFingerprint;
355
- }
356
- async changeSnapshot(signal) {
357
- const changeSet = await detectChanges({ cwd: this.workspace, signal });
358
- return { changedFiles: changeSet.changedFiles, classification: classifyChanges(changeSet.changedFiles), fingerprint: changeSet.fingerprint };
359
- }
360
- }
361
- async function statMtime(target) {
362
- const { stat } = await import('node:fs/promises');
363
- return (await stat(target)).mtime;
364
- }
365
- const orchestrators = new Map();
366
- export function getQaOrchestrator(workspace) {
367
- let orchestrator = orchestrators.get(workspace);
368
- if (!orchestrator) {
369
- orchestrator = new QaOrchestrator(workspace);
370
- orchestrators.set(workspace, orchestrator);
371
- }
372
- return orchestrator;
373
- }
@@ -1,22 +0,0 @@
1
- import type { QaCheckCategory, QaCheckResult, QaCommandSpec, QaIssue } from '../types.js';
2
- export declare const QA_MAX_TIMEOUT_MS = 900000;
3
- /** Extract actionable error lines from mixed stdout/stderr without shipping whole logs to the model. */
4
- export declare function extractImportantOutput(text: string): string[];
5
- /** Parse common toolchain failure formats (tsc, eslint stylish, jest/vitest, pytest) into issues. */
6
- export declare function parseToolOutput(text: string): QaIssue[];
7
- export interface CommandCheckOptions {
8
- id: string;
9
- category: QaCheckCategory;
10
- command: QaCommandSpec;
11
- workspace: string;
12
- /** Directory receiving `<id>.log` for this run (absolute). */
13
- logDir: string;
14
- defaultTimeoutMs: number;
15
- signal: AbortSignal;
16
- }
17
- /**
18
- * Run one QA command through the structured shell and normalize the outcome:
19
- * exit 0 passed, nonzero/timeout failed, spawn failure blocked. Full output is
20
- * written to the QA run log directory and only bounded error lines are returned.
21
- */
22
- export declare function runCommandCheck(options: CommandCheckOptions): Promise<QaCheckResult>;