@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,3 +1,4 @@
1
+ import { type FileDiff } from './file-diff.js';
1
2
  export interface LineDiffStats {
2
3
  linesAdded: number;
3
4
  linesRemoved: number;
@@ -22,3 +23,11 @@ export declare function fileDiffTarget(name: string, args: Record<string, unknow
22
23
  export declare function readFileSnapshot(target: string): Promise<string | null | undefined>;
23
24
  /** The added/removed line counts for a snapshot pair; nothing when either half was unmeasurable. */
24
25
  export declare function diffLineStats(before: string | null | undefined, after: string | null | undefined): LineDiffStats | undefined;
26
+ /** Diff lines a completed call's event carries: a row shows the start and says how many more there are. */
27
+ export declare const CALL_DIFF_LINES = 200;
28
+ /**
29
+ * One call's change to its file as numbered hunks, for the `fileDiff` of its `node.tool.completed` event: what
30
+ * the file held before the call against what it holds after, so a Write over an existing file shows the lines
31
+ * it really changed and every line carries its number. Nothing for a call that changed nothing.
32
+ */
33
+ export declare function callFileDiff(before: string | null, after: string | null): Pick<FileDiff, 'hunks' | 'hiddenLines'> | undefined;
@@ -1,6 +1,7 @@
1
1
  import * as fs from 'node:fs/promises';
2
2
  import * as path from 'node:path';
3
3
  import { canonicalCodingToolName } from './tool-names.js';
4
+ import { textDiff } from './file-diff.js';
4
5
  /**
5
6
  * The line counts behind a successful file mutation, reported on its `node.tool.completed` event.
6
7
  *
@@ -120,3 +121,22 @@ function countDiff(oldLines, newLines) {
120
121
  const common = previous[midOld.length];
121
122
  return [midNew.length - common, midOld.length - common];
122
123
  }
124
+ /** Diff lines a completed call's event carries: a row shows the start and says how many more there are. */
125
+ export const CALL_DIFF_LINES = 200;
126
+ /** Characters of diff text a completed call's event carries, so one minified line cannot fill the journal. */
127
+ const CALL_DIFF_CHARS = 24_000;
128
+ const CALL_DIFF_LINE_CHARS = 400;
129
+ /**
130
+ * One call's change to its file as numbered hunks, for the `fileDiff` of its `node.tool.completed` event: what
131
+ * the file held before the call against what it holds after, so a Write over an existing file shows the lines
132
+ * it really changed and every line carries its number. Nothing for a call that changed nothing.
133
+ */
134
+ export function callFileDiff(before, after) {
135
+ // A NUL byte is a binary file read as text: its "lines" are not something a reader can check.
136
+ if (before?.includes('\0') || after?.includes('\0'))
137
+ return undefined;
138
+ const diff = textDiff(before ?? '', after ?? '', { maxLines: CALL_DIFF_LINES, maxChars: CALL_DIFF_CHARS, lineChars: CALL_DIFF_LINE_CHARS });
139
+ if (diff.coarse || !diff.hunks.length)
140
+ return undefined;
141
+ return { hunks: diff.hunks, hiddenLines: diff.hiddenLines };
142
+ }
@@ -13,7 +13,7 @@ export declare function toolNameMatches(configured: string, actual: string): boo
13
13
  export declare function canonicalizeToolList(names: readonly string[] | undefined): string[] | undefined;
14
14
  /**
15
15
  * Rewrites the tool names one provider request sees and restores Andorra's names on everything
16
- * that comes back. Canonical Andorra tool names use dots (`qa.fast`, `browser.panel`), while
16
+ * that comes back. Canonical Andorra tool names use dots (`qa.terminal`, `browser.panel`), while
17
17
  * strict providers validate `function.name` against `^[a-zA-Z0-9_-]+$` and reject the whole
18
18
  * request with an HTTP 400. The provider-side names are a pure transport encoding: journals,
19
19
  * the executor and the desktop keep the canonical spellings.
@@ -16,7 +16,7 @@
16
16
  * @module tool-result-filter
17
17
  */
18
18
  import { canonicalToolName } from './tool-names.js';
19
- const SHELL_TOOLS = new Set(['Bash', 'PowerShell', 'NativeExec', 'AsyncProcess', 'PowerShellFast', 'ShellMetrics', 'shell', 'bash', 'powershell', 'qa.test', 'qa.fast', 'qa.deep', 'qa.terminal', 'qa.status']);
19
+ const SHELL_TOOLS = new Set(['Bash', 'PowerShell', 'NativeExec', 'AsyncProcess', 'PowerShellFast', 'ShellMetrics', 'shell', 'bash', 'powershell', 'qa.terminal']);
20
20
  const SEARCH_TOOLS = new Set(['Grep', 'grep', 'search_files']);
21
21
  const LISTING_TOOLS = new Set(['Glob', 'find', 'ls', 'list_files']);
22
22
  /** A shell command that prints source or a patch is a read, whatever its size. */
package/dist/src/tools.js CHANGED
@@ -265,6 +265,10 @@ async function atomicWrite(context, name, content, expectedContent) {
265
265
  const resolved = await safePath(context, name, true);
266
266
  await mutationPermission(context, name);
267
267
  assertMutationPermission(context);
268
+ // The review record (Keep / Undo) notes the folders this write will create before any is made. Its lock
269
+ // is held from just before the rename until the write is recorded (see the rename below). It never fails
270
+ // the write: a recorder that cannot keep the file answers nothing.
271
+ const recording = await context.fileChanges?.beforeWrite(resolved).catch(() => undefined);
268
272
  await mkdir(path.dirname(resolved), { recursive: true });
269
273
  if (!samePath(await safePath(context, name, true), resolved))
270
274
  throw new Error('File path changed before write; retry');
@@ -303,8 +307,28 @@ async function atomicWrite(context, name, content, expectedContent) {
303
307
  context.signal.throwIfAborted();
304
308
  await mutationPermission(context, name);
305
309
  assertMutationPermission(context);
306
- await rename(temporary, resolved);
307
- created = false;
310
+ // From here to the record the session's review lock is held, so a Keep or Undo can neither run between
311
+ // the freshness check and the rename nor overwrite the write before it is recorded. Nothing in the window
312
+ // waits on a person. A lock that cannot be taken leaves the write unrecorded rather than failing it.
313
+ const locked = recording ? await recording.begin().then(() => true, () => false) : false;
314
+ try {
315
+ // Re-checked inside the window: an Undo that finished just before it may have restored the file.
316
+ if (locked && expectedContent !== undefined && await read(context, name) !== expectedContent)
317
+ throw new Error('File changed while writing; retry');
318
+ // Taking the lock can wait behind an Undo or another write, and a stop or a live permission change in
319
+ // that wait still decides: both are checked again with nothing awaited between them and the rename.
320
+ context.signal.throwIfAborted();
321
+ assertMutationPermission(context);
322
+ await rename(temporary, resolved);
323
+ created = false;
324
+ }
325
+ catch (error) {
326
+ if (locked)
327
+ await recording.abort().catch(() => { });
328
+ throw error;
329
+ }
330
+ if (locked)
331
+ await recording.commit().catch(() => { });
308
332
  }
309
333
  finally {
310
334
  if (created) {
@@ -24,6 +24,17 @@ export interface TranscriptEntry {
24
24
  * @returns a paint color: a palette index or an SGR parameter string.
25
25
  */
26
26
  export declare function transcriptColor(text: string): number | string;
27
+ /**
28
+ * Render an agent's answer on its own: markdown drawn the way a live message is, with a
29
+ * collapsed code block's full text as `detail` for Ctrl+O.
30
+ *
31
+ * A resumed session replays its saved answers through this, so a restored conversation reads
32
+ * the same as it did when the answers were first printed instead of showing raw `**` and `##`.
33
+ * Only outer blank lines are stripped; leading spaces can be a fenced block's indentation.
34
+ * @param summary - the answer's markdown source.
35
+ * @returns the rendered entry.
36
+ */
37
+ export declare function formatAnswer(summary: string): TranscriptEntry;
27
38
  export interface RunResultView {
28
39
  id: string;
29
40
  status: string;
@@ -93,6 +93,19 @@ export function transcriptColor(text) {
93
93
  return GRAY;
94
94
  return DIM;
95
95
  }
96
+ /**
97
+ * Render an agent's answer on its own: markdown drawn the way a live message is, with a
98
+ * collapsed code block's full text as `detail` for Ctrl+O.
99
+ *
100
+ * A resumed session replays its saved answers through this, so a restored conversation reads
101
+ * the same as it did when the answers were first printed instead of showing raw `**` and `##`.
102
+ * Only outer blank lines are stripped; leading spaces can be a fenced block's indentation.
103
+ * @param summary - the answer's markdown source.
104
+ * @returns the rendered entry.
105
+ */
106
+ export function formatAnswer(summary) {
107
+ return renderMarkdown(clean(summary).replace(/^(?:[ \t]*\n)+/, '').replace(/\s+$/, ''));
108
+ }
96
109
  /**
97
110
  * Render a finished run for the transcript: the completion summary as rendered markdown, the
98
111
  * checks the agent reports under their own heading, and the run line last.
@@ -105,8 +118,7 @@ export function transcriptColor(text) {
105
118
  * shows the whole answer in place.
106
119
  */
107
120
  export function formatRunResult(result) {
108
- const summary = clean(result.summary).replace(/^(?:[ \t]*\n)+/, '').replace(/\s+$/, '');
109
- const rendered = renderMarkdown(summary);
121
+ const rendered = formatAnswer(result.summary);
110
122
  const checks = (result.tests ?? []).map(check => line(check)).filter(Boolean);
111
123
  const trailer = [
112
124
  ...(checks.length ? ['', `${HEADING_PREFIX} Checks`, ...checks.map(check => ` • ${check}`)] : []),
@@ -264,6 +264,12 @@ export interface ToolContext {
264
264
  sessionScope?: string;
265
265
  /** The session's pull request backing `pull_request`; absent means the tool reports itself unavailable. */
266
266
  pullRequests?: import('./pull-requests.js').PullRequestControl;
267
+ /**
268
+ * Where the run's file writes are reported for review (Keep / Undo). Every agent write to a workspace
269
+ * file reports its path just before it lands and again once it has; a subagent's context inherits the
270
+ * recorder. Absent where no session keeps a review record, which writes exactly as before.
271
+ */
272
+ fileChanges?: import('./session-changes.js').FileChangeRecorder;
267
273
  }
268
274
  export type ToolFamily = 'filesystem-read' | 'filesystem-write' | 'code-search' | 'codegraph' | 'git' | 'shell' | 'qa' | 'memory' | 'web' | 'browser' | 'subagents' | 'artifact';
269
275
  export interface Tool extends ToolSchema {
@@ -33,7 +33,7 @@ macOS and Linux bundles have no installer step.
33
33
  **The check at startup (every platform).** Before the window starts an engine it reads the
34
34
  installed CLI's `package.json` (it does not run it). A missing CLI, or one from another version,
35
35
  stops at the startup screen with the reason and the command that fixes it, for example
36
- `npm install -g @andorra-labs/code@0.1.9`; **Check again** retries after you run it. This is what
36
+ `npm install -g @andorra-labs/code@0.1.10`; **Check again** retries after you run it. This is what
37
37
  you see after an in-app update on macOS or Linux, where nothing installs the new CLI for you, and
38
38
  after updating or removing the CLI by hand. An `andorra` launcher on `PATH` whose package cannot
39
39
  be located is started without a version check.
@@ -3,7 +3,7 @@
3
3
  The default `andorra` command opens a full-screen terminal UI: a welcome panel, conversation and tool transcript, a bordered input composer, and a live status bar. While a task runs, the transcript shows public assistant progress, tool actions, and compact result previews.
4
4
 
5
5
  - Press **Ctrl+O** to expand or collapse tool and approval details.
6
- - Scroll with Page Up/Page Down, or with the mouse wheel/trackpad while a run streams or a screen is open. Select text by dragging, as in any terminal program.
6
+ - Scroll with the mouse wheel/trackpad or Page Up/Page Down, in every state. Select text by dragging; releasing the button copies it.
7
7
  - File proposals show numbered green additions and red removals; edit numbers are relative to the replaced snippets. Errors are red and tool headings are cyan. Approval prompts retain the full arguments in expandable details.
8
8
  - Updates appear after each model response; token-by-token streaming is not supported. `--json` remains machine-readable and does not include display formatting.
9
9
  - Text wraps at word boundaries where possible; tokens wider than the terminal still split safely.
@@ -24,17 +24,17 @@ Type `/` as the first character to open command suggestions. Typing filters the
24
24
 
25
25
  ## Mouse, selection and scrolling
26
26
 
27
- Andorra never captures the mouse. Drag-to-select, double-click word selection and your terminal's copy shortcut work in every state — at the idle prompt, while a run streams, and while a selection or settings screen is open — with no Shift or Option bypass to remember. The composer additionally has its own keyboard selection (Shift with an arrow, Home or End; Ctrl+C copies, Ctrl+X cuts).
27
+ Andorra holds the mouse for the whole session, so the wheel is always a wheel:
28
28
 
29
- What the wheel does depends on where you are:
29
+ - **The wheel scrolls** the transcript at the idle prompt, while a run streams, and while an approval or clarification question is open. On a selection, settings or usage screen it scrolls the screen or moves the highlight. Page Up/Page Down scroll from the keyboard.
30
+ - **Up/Down recall input history** at the prompt, or move the caret inside a multi-line draft. They never scroll there. While a run streams with nothing typed they scroll the transcript, because there is no history to recall.
31
+ - **Dragging selects text** on the screen and draws it in reverse video. Releasing the button copies the selection to the clipboard; the highlight stays until the next key, click or wheel tick. Double-click copies the word under the pointer. A drag that starts in the conversation stays out of the side panel.
32
+ - **The copy** goes to the system clipboard, and falls back to an OSC 52 sequence that asks the terminal to set its clipboard. Over SSH only the OSC 52 path is used, since the system clipboard there belongs to the remote machine. A terminal that ignores OSC 52 copies nothing over SSH; use its own selection there.
33
+ - **Your terminal's own selection** is still available through its bypass: Shift+drag in Windows Terminal, GNOME Terminal and most others, Option+drag in iTerm2 and Terminal.app. Right-click and middle-click are swallowed; paste with the terminal's paste shortcut.
30
34
 
31
- - **While a run streams** with no question on screen, the wheel scrolls the transcript. Up/Down and Page Up/Page Down do the same from the keyboard. If you have started typing a steer, Up/Down move inside that draft instead; the wheel and Page Up/Page Down still scroll.
32
- - **On a selection, settings or usage screen**, the wheel scrolls the screen or moves the highlight, like Up/Down.
33
- - **At the resting prompt**, and while an approval or clarification question is open, the wheel does nothing. Up/Down recall input history there, and Page Up/Page Down scroll the transcript.
35
+ The mouse is held because of how terminals report an uncaptured wheel in a full-screen program: under *alternate scroll mode* they send the same bytes as the Up and Down keys. Windows Terminal, GNOME Terminal and iTerm2 have that mode on by default, so an uncaptured wheel either recalls the previous prompt on every tick or has to be switched off, which left it doing nothing at the idle prompt. A selection is taken from the rows as drawn, so text that wrapped on screen is copied with a line break at each wrap, and a drag does not scroll the transcript past the edge of the screen. The composer additionally has its own keyboard selection (Shift with an arrow, Home or End; Ctrl+C copies, Ctrl+X cuts).
34
36
 
35
- The reason for the resting-prompt exception is how terminals report an uncaptured wheel in a full-screen program: under *alternate scroll mode* they send the same bytes as the Up and Down keys. Windows Terminal, GNOME Terminal and iTerm2 have that mode on by default, which once made the wheel recall the previous prompt. Andorra therefore switches the mode on only in the states above, where Up/Down cannot reach history, and off everywhere else. A terminal that ignores the mode request and always translates the wheel will still recall history on wheel-up at the prompt; a terminal that never translates it has an inert wheel during runs, where Page Up/Page Down and the arrow keys still work.
36
-
37
- Collapsed long-prompt boxes expand and collapse with Ctrl+O, and the live reasoning preview toggles with Ctrl+Y. Dragging works while a task runs: the screen redraws eight times a second for its animation, but only the rows whose text actually changed are rewritten, so an unchanged row is never refreshed out from under your selection. Rows that do change — the animated indicator and counters — may move your selection with them, as in any terminal.
37
+ Collapsed long-prompt boxes expand and collapse with Ctrl+O, and the live reasoning preview toggles with Ctrl+Y; neither reacts to a click. Dragging works while a task runs. The selection is held in screen positions, so when the rows under it change (the animated indicator, the counters, new output) the highlight covers the new text, and what is copied is what is on screen when the button is released.
38
38
 
39
39
  ## Selection screens
40
40
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andorra-labs/code",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "Terminal-first coding agent with a ReAct graph runtime",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "type": "module",
@@ -1,3 +0,0 @@
1
- import type { QaApiSmokeTest, QaCheckResult } from '../types.js';
2
- /** Execute configured HTTP smoke expectations; every request failure is an error issue. */
3
- export declare function runApiSmokeTests(tests: QaApiSmokeTest[], signal: AbortSignal): Promise<QaCheckResult>;
@@ -1,47 +0,0 @@
1
- const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
2
- /** Execute configured HTTP smoke expectations; every request failure is an error issue. */
3
- export async function runApiSmokeTests(tests, signal) {
4
- if (!tests.length) {
5
- return { id: 'api_smoke', category: 'runtime', status: 'skipped', durationMs: 0, summary: 'no api_smoke_tests configured (.andorra/qa.yaml)' };
6
- }
7
- const startedAt = Date.now();
8
- const issues = [];
9
- const summaries = [];
10
- for (const test of tests) {
11
- signal.throwIfAborted();
12
- const timeout = test.expect?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
13
- try {
14
- const response = await fetch(test.request.url, {
15
- method: test.request.method,
16
- headers: test.request.headers,
17
- body: test.request.body,
18
- signal: AbortSignal.any([signal, AbortSignal.timeout(timeout)]),
19
- });
20
- const text = await response.text().catch(() => '');
21
- if (test.expect?.status !== undefined && response.status !== test.expect.status) {
22
- issues.push({ severity: 'error', message: `${test.name}: ${test.request.method} ${test.request.url} returned ${response.status}, expected ${test.expect.status}`, code: 'api-smoke-status' });
23
- continue;
24
- }
25
- if (test.expect?.bodyContains && !text.includes(test.expect.bodyContains)) {
26
- issues.push({ severity: 'error', message: `${test.name}: ${test.request.method} ${test.request.url} body missing "${test.expect.bodyContains}"`, code: 'api-smoke-body' });
27
- continue;
28
- }
29
- summaries.push(`${test.name}: ${response.status}`);
30
- }
31
- catch (error) {
32
- if (signal.aborted)
33
- throw error;
34
- const message = error instanceof Error ? error.message : String(error);
35
- issues.push({ severity: 'error', message: `${test.name}: ${test.request.method} ${test.request.url} failed: ${message.slice(0, 200)}`, code: 'api-smoke-error' });
36
- }
37
- }
38
- const durationMs = Date.now() - startedAt;
39
- return {
40
- id: 'api_smoke', category: 'runtime',
41
- status: issues.length ? 'failed' : 'passed',
42
- durationMs,
43
- summary: issues.length ? `${issues.length}/${tests.length} API smoke tests failed` : `all ${tests.length} API smoke tests passed`,
44
- errors: issues.length ? issues : undefined,
45
- importantOutput: summaries.length ? summaries : undefined,
46
- };
47
- }
@@ -1,26 +0,0 @@
1
- export interface ChangeSet {
2
- isGit: boolean;
3
- /** HEAD commit when available; undefined before the first commit or without Git. */
4
- head?: string;
5
- /** Modified, staged, renamed and untracked workspace-relative paths, QA dirs excluded. */
6
- changedFiles: string[];
7
- untrackedFiles: string[];
8
- insertions: number;
9
- deletions: number;
10
- /** Working-tree diff (tracked via `git diff HEAD`, untracked synthesized as added lines). */
11
- diff?: string;
12
- }
13
- export interface GitRunnerOptions {
14
- cwd: string;
15
- signal?: AbortSignal;
16
- timeoutMs?: number;
17
- }
18
- /**
19
- * Collect the workspace's current change set and a fingerprint of its state.
20
- * The fingerprint mixes HEAD, the porcelain status, diff bytes and untracked
21
- * identity so any later edit invalidates QA results recorded against it.
22
- * Non-git workspaces report `isGit: false` with a stat-based fallback fingerprint.
23
- */
24
- export declare function detectChanges(options: GitRunnerOptions): Promise<ChangeSet & {
25
- fingerprint: string;
26
- }>;
@@ -1,177 +0,0 @@
1
- import { execFile } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
3
- import { promisify } from 'node:util';
4
- import { opendir, readFile, stat } from 'node:fs/promises';
5
- import path from 'node:path';
6
- import { QA_EXCLUDED_DIRS } from '../profile/QaProfile.js';
7
- const executeFile = promisify(execFile);
8
- const GIT_TIMEOUT_MS = 10_000;
9
- async function git(args, options) {
10
- try {
11
- const { stdout } = await executeFile('git', ['--no-pager', '-c', 'core.fsmonitor=false', '-c', 'core.hooksPath=', '-c', 'core.quotePath=false', ...args], {
12
- cwd: options.cwd, signal: options.signal, windowsHide: true,
13
- timeout: options.timeoutMs ?? GIT_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, encoding: 'utf8',
14
- });
15
- return { stdout, code: 0 };
16
- }
17
- catch (error) {
18
- const failure = error;
19
- if (failure.code === 'ENOENT')
20
- throw new Error('git executable is unavailable');
21
- // Nonzero exits (empty diff, no HEAD yet) still carry usable stdout.
22
- const code = typeof failure.status === 'number' ? failure.status : typeof failure.code === 'number' ? failure.code : 1;
23
- if (typeof failure.stdout === 'string')
24
- return { stdout: failure.stdout, code };
25
- throw error;
26
- }
27
- }
28
- function relevant(file) {
29
- const parts = file.split('/');
30
- return !parts.some(part => QA_EXCLUDED_DIRS.has(part)) && !file.startsWith('.andorra/');
31
- }
32
- /** Parse `--porcelain=1` entries; rename lines carry `old -> new`. */
33
- function parsePorcelain(output) {
34
- const changed = [], untracked = [];
35
- for (const rawLine of output.split('\n')) {
36
- if (rawLine.length < 4)
37
- continue;
38
- // Porcelain format is fixed: two status columns, a space, then the path.
39
- const status = rawLine.slice(0, 2);
40
- let file = rawLine.slice(3);
41
- if (file.startsWith('"')) {
42
- try {
43
- file = JSON.parse(file);
44
- }
45
- catch {
46
- file = file.slice(1, -1);
47
- }
48
- }
49
- const rename = file.indexOf(' -> ');
50
- if (rename >= 0) {
51
- changed.push(file.slice(rename + 4));
52
- continue;
53
- }
54
- if (status === '??')
55
- untracked.push(file);
56
- else
57
- changed.push(file);
58
- }
59
- return { changed, untracked };
60
- }
61
- /**
62
- * Render untracked text files as `+` diff lines. `git diff HEAD` never shows
63
- * them, yet brand-new files are exactly where regressions and leaked secrets
64
- * appear first, so reviewers and scanners must see their content as added lines.
65
- */
66
- async function synthesizeUntrackedDiff(cwd, files, signal) {
67
- const sections = [];
68
- let total = 0;
69
- for (const file of files) {
70
- if (sections.length >= 50 || total >= 1_048_576)
71
- break;
72
- signal?.throwIfAborted();
73
- let content;
74
- try {
75
- const buffer = await readFile(path.join(cwd, file));
76
- if (buffer.length > 262_144 || buffer.includes(0))
77
- continue;
78
- content = buffer.toString('utf8');
79
- if (content.includes('�'))
80
- continue;
81
- }
82
- catch {
83
- continue;
84
- }
85
- const body = content.split('\n');
86
- if (body.length && body[body.length - 1] === '')
87
- body.pop();
88
- const section = `diff --git a/${file} b/${file}\nnew file mode 100644\n--- /dev/null\n+++ b/${file}\n@@ -0,0 +1,${body.length} @@\n${body.map(line => `+${line}`).join('\n')}\n`;
89
- sections.push(section);
90
- total += section.length;
91
- }
92
- return sections.join('');
93
- }
94
- /**
95
- * Collect the workspace's current change set and a fingerprint of its state.
96
- * The fingerprint mixes HEAD, the porcelain status, diff bytes and untracked
97
- * identity so any later edit invalidates QA results recorded against it.
98
- * Non-git workspaces report `isGit: false` with a stat-based fallback fingerprint.
99
- */
100
- export async function detectChanges(options) {
101
- options.signal?.throwIfAborted();
102
- const inside = await git(['rev-parse', '--is-inside-work-tree'], options)
103
- .then(result => result.code === 0 && result.stdout.trim() === 'true').catch(() => false);
104
- if (!inside) {
105
- return { isGit: false, changedFiles: [], untrackedFiles: [], insertions: 0, deletions: 0, fingerprint: await statFingerprint(options.cwd) };
106
- }
107
- const headResult = await git(['rev-parse', 'HEAD'], options).catch(() => ({ stdout: '', code: 1 }));
108
- const head = headResult.code === 0 ? headResult.stdout.trim() : undefined;
109
- const status = await git(['status', '--porcelain=1', '--untracked-files=all'], options).then(result => result.stdout).catch(() => '');
110
- const { changed, untracked } = parsePorcelain(status);
111
- const changedFiles = [...new Set([...changed, ...untracked])].filter(relevant).sort();
112
- const untrackedFiles = untracked.filter(relevant).sort();
113
- const realDiff = await git(['diff', 'HEAD'], options).then(result => result.stdout || '').catch(() => '');
114
- const synthesized = await synthesizeUntrackedDiff(options.cwd, untrackedFiles, options.signal);
115
- const diff = realDiff + synthesized;
116
- const numstat = await git(['diff', 'HEAD', '--numstat'], options).then(result => result.stdout).catch(() => '');
117
- let insertions = 0, deletions = 0;
118
- for (const line of numstat.split('\n')) {
119
- const [added, removed] = line.split('\t');
120
- if (/^\d+$/.test(added))
121
- insertions += Number(added);
122
- if (/^\d+$/.test(removed))
123
- deletions += Number(removed);
124
- }
125
- // New files reach the diff only through the synthesized sections; count their lines.
126
- for (const line of synthesized.split('\n')) {
127
- if (line.startsWith('+') && !line.startsWith('+++'))
128
- insertions++;
129
- }
130
- const hash = createHash('sha1');
131
- hash.update(JSON.stringify([head ?? '', changedFiles, diff]));
132
- for (const file of untrackedFiles) {
133
- try {
134
- const info = await stat(path.join(options.cwd, file));
135
- hash.update(JSON.stringify([file, info.size, Math.round(info.mtimeMs)]));
136
- }
137
- catch {
138
- hash.update(JSON.stringify([file, 'gone']));
139
- }
140
- }
141
- return { isGit: true, head, changedFiles, untrackedFiles, insertions, deletions, diff, fingerprint: hash.digest('hex') };
142
- }
143
- /** Best-effort tree fingerprint for non-git workspaces: relative paths, sizes and mtimes. */
144
- async function statFingerprint(workspace) {
145
- const entries = [];
146
- const walk = async (directory, depth, budget) => {
147
- if (depth > 4 || budget.count > 2_000)
148
- return;
149
- let handle;
150
- try {
151
- handle = await opendir(path.join(workspace, directory));
152
- }
153
- catch {
154
- return;
155
- }
156
- for await (const entry of handle) {
157
- if (++budget.count > 2_000)
158
- return;
159
- if (entry.isSymbolicLink() || QA_EXCLUDED_DIRS.has(entry.name))
160
- continue;
161
- const rel = directory === '.' ? entry.name : `${directory}/${entry.name}`;
162
- if (entry.isDirectory())
163
- await walk(rel, depth + 1, budget);
164
- else {
165
- try {
166
- const info = await stat(path.join(workspace, rel));
167
- entries.push(`${rel}:${info.size}:${Math.round(info.mtimeMs)}`);
168
- }
169
- catch {
170
- entries.push(`${rel}:gone`);
171
- }
172
- }
173
- }
174
- };
175
- await walk('.', 0, { count: 0 });
176
- return `nogit:${createHash('sha1').update(JSON.stringify([...entries].sort())).digest('hex')}`;
177
- }
@@ -1,28 +0,0 @@
1
- import type { QaIssue } from '../types.js';
2
- export interface DiffReviewResult {
3
- passed: boolean;
4
- issues: QaIssue[];
5
- stats: {
6
- filesChanged: number;
7
- insertions: number;
8
- deletions: number;
9
- };
10
- }
11
- export interface AddedLine {
12
- file: string;
13
- line: number;
14
- text: string;
15
- }
16
- /** Extract added working-tree lines from a `git diff HEAD` capture. */
17
- export declare function addedLines(diff: string): AddedLine[];
18
- /**
19
- * Heuristic review of the working-tree diff: debug leftovers, conflict markers,
20
- * secrets, stale TODOs, generated files, dependency churn and missing test updates.
21
- * `error` findings fail the review; `warning`/`info` findings are reported for judgment.
22
- */
23
- export declare function reviewDiff(changeSet: {
24
- diff?: string;
25
- changedFiles: string[];
26
- insertions: number;
27
- deletions: number;
28
- }, secretHits?: QaIssue[]): DiffReviewResult;
@@ -1,115 +0,0 @@
1
- const DEBUG_LOGGING = [
2
- { pattern: /\bconsole\.(log|debug|dir|trace)\(/, severity: 'warning', message: 'debug logging (console.*) added to the diff' },
3
- { pattern: /\bdebugger\b/, severity: 'error', message: '`debugger` statement left in the diff' },
4
- { pattern: /\bfmt\.(Println|Printf|Print)\(/, severity: 'warning', message: 'debug printing (fmt.Print*) added to the diff' },
5
- { pattern: /^\s*print\(/, severity: 'info', message: 'print() call added to the diff' },
6
- { pattern: /\bpdb\.set_trace\(/, severity: 'error', message: 'Python debugger breakpoint left in the diff' },
7
- { pattern: /\bbreakpoint\(\)/, severity: 'warning', message: 'breakpoint() left in the diff' },
8
- ];
9
- const STALE_MARKERS = /\b(TODO|FIXME|HACK|XXX)\b/;
10
- const CONFLICT_MARKER = /^(<{7}|={7}|>{7})(\s|$)/;
11
- const GENERATED = /(^|\/)(dist|build|out|coverage|__generated__)\//;
12
- const MINIFIED = /\.min\.(js|css)$/;
13
- const DEPENDENCY_FILE = /(^|\/)(package(-lock)?\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|Cargo\.lock|go\.sum|poetry\.lock|composer\.lock)$/;
14
- const TEST_FILE = /(\.|_)(test|spec)\.[a-z]+$|(^|\/)(tests?|__tests__|spec)\//;
15
- /** Extract added working-tree lines from a `git diff HEAD` capture. */
16
- export function addedLines(diff) {
17
- const lines = [];
18
- let file = '';
19
- let oldLine = 0, newLine = 0;
20
- let inHunk = false;
21
- for (const raw of diff.split('\n')) {
22
- const header = /^(\+\+\+|---|diff --git|index |old mode|new mode|similarity|rename|new file|deleted file|Binary)/.exec(raw);
23
- if (raw.startsWith('diff --git ')) {
24
- inHunk = false;
25
- file = raw.replace(/^diff --git a\/\S+ b\//, '').trim();
26
- continue;
27
- }
28
- if (raw.startsWith('+++ ')) {
29
- const target = raw.slice(4).trim();
30
- file = target === '/dev/null' ? file : target.replace(/^b\//, '');
31
- continue;
32
- }
33
- if (header && !raw.startsWith('+++'))
34
- continue;
35
- const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(raw);
36
- if (hunk) {
37
- oldLine = Number(hunk[1]);
38
- newLine = Number(hunk[2]);
39
- inHunk = true;
40
- continue;
41
- }
42
- if (!inHunk)
43
- continue;
44
- if (raw.startsWith('+')) {
45
- lines.push({ file, line: newLine, text: raw.slice(1) });
46
- newLine++;
47
- }
48
- else if (raw.startsWith('-'))
49
- oldLine++;
50
- else if (!raw.startsWith('\\')) {
51
- newLine++;
52
- oldLine++;
53
- }
54
- }
55
- return lines;
56
- }
57
- /**
58
- * Heuristic review of the working-tree diff: debug leftovers, conflict markers,
59
- * secrets, stale TODOs, generated files, dependency churn and missing test updates.
60
- * `error` findings fail the review; `warning`/`info` findings are reported for judgment.
61
- */
62
- export function reviewDiff(changeSet, secretHits = []) {
63
- const issues = [...secretHits];
64
- const added = changeSet.diff ? addedLines(changeSet.diff) : [];
65
- const commentedRuns = new Map();
66
- for (const line of added) {
67
- const text = line.text;
68
- if (!text.trim())
69
- continue;
70
- if (CONFLICT_MARKER.test(text)) {
71
- issues.push({ file: line.file, line: line.line, severity: 'error', message: 'merge conflict marker added', code: 'conflict-marker' });
72
- continue;
73
- }
74
- for (const rule of DEBUG_LOGGING) {
75
- if (rule.pattern.test(text)) {
76
- issues.push({ file: line.file, line: line.line, severity: rule.severity, message: rule.message, code: 'debug-leftover' });
77
- break;
78
- }
79
- }
80
- if (STALE_MARKERS.test(text)) {
81
- issues.push({ file: line.file, line: line.line, severity: 'warning', message: 'new TODO/FIXME/HACK marker added', code: 'stale-todo' });
82
- }
83
- const commented = /^\s*(\/\/|#)\s*(if\s*\(|if\s+|for\s*\(|for\s+|while\s*\(|while\s+|const |let |var |def |class |function |return |import |from )/.exec(text);
84
- if (commented)
85
- commentedRuns.set(line.file, (commentedRuns.get(line.file) ?? 0) + 1);
86
- }
87
- for (const [file, count] of commentedRuns) {
88
- if (count >= 3)
89
- issues.push({ file, severity: 'warning', message: `${count} commented-out code lines added`, code: 'commented-out-code' });
90
- }
91
- for (const file of changeSet.changedFiles) {
92
- if (GENERATED.test(file))
93
- issues.push({ file, severity: 'error', message: 'generated output committed; build artifacts should not be checked in', code: 'generated-file' });
94
- else if (MINIFIED.test(file))
95
- issues.push({ file, severity: 'error', message: 'minified bundle committed', code: 'generated-file' });
96
- else if (DEPENDENCY_FILE.test(file))
97
- issues.push({ file, severity: 'info', message: 'dependency/lockfile changed; verify the dependency change is intended', code: 'dependency-change' });
98
- }
99
- if (changeSet.changedFiles.length) {
100
- const testsChanged = changeSet.changedFiles.some(file => TEST_FILE.test(file));
101
- const sourceChanged = changeSet.changedFiles.some(file => !TEST_FILE.test(file) && /\.(ts|tsx|js|jsx|mjs|cjs|py|rs|go|java|cs|rb|php|vue|svelte)$/.test(file));
102
- if (sourceChanged && !testsChanged) {
103
- issues.push({ severity: 'info', message: 'no test file changed alongside source changes', code: 'missing-test-update' });
104
- }
105
- if (changeSet.insertions > 2_000) {
106
- issues.push({ severity: 'warning', message: `very large diff: ${changeSet.insertions} inserted lines`, code: 'oversized-diff' });
107
- }
108
- }
109
- const failed = issues.some(issue => issue.severity === 'error');
110
- return {
111
- passed: !failed,
112
- issues: issues.slice(0, 50),
113
- stats: { filesChanged: changeSet.changedFiles.length, insertions: changeSet.insertions, deletions: changeSet.deletions },
114
- };
115
- }