vouchington-tooling 0.55.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +9 -0
  2. package/dist/gh-api-shell-quoting/logical-line.mjs +14 -74
  3. package/dist/input-otp-mock/index.d.mts +25 -0
  4. package/dist/input-otp-mock/index.mjs +34 -0
  5. package/dist/jsdom-stubs/index.d.mts +12 -0
  6. package/dist/jsdom-stubs/index.mjs +85 -0
  7. package/dist/mcp-server/policy-run.d.mts +2 -0
  8. package/dist/mcp-server/policy-run.mjs +6 -2
  9. package/dist/mcp-server/policy-spawn.d.mts +1 -0
  10. package/dist/mcp-server/policy-spawn.mjs +10 -2
  11. package/dist/next-navigation-mock/index.d.mts +27 -0
  12. package/dist/next-navigation-mock/index.mjs +58 -0
  13. package/dist/retrospective-transcript/codex-records.mjs +4 -0
  14. package/dist/retrospective-transcript/command-prefix.d.mts +1 -0
  15. package/dist/retrospective-transcript/command-prefix.mjs +1 -1
  16. package/dist/retrospective-transcript/command-segments.d.mts +1 -1
  17. package/dist/retrospective-transcript/command-segments.mjs +3 -48
  18. package/dist/retrospective-transcript/escalations.d.mts +6 -0
  19. package/dist/retrospective-transcript/escalations.mjs +34 -0
  20. package/dist/retrospective-transcript/format.mjs +13 -0
  21. package/dist/retrospective-transcript/index.mjs +2 -1
  22. package/dist/retrospective-transcript/malformed-record.d.mts +1 -0
  23. package/dist/retrospective-transcript/malformed-record.mjs +13 -0
  24. package/dist/retrospective-transcript/shared.d.mts +2 -1
  25. package/dist/retrospective-transcript/shared.mjs +1 -12
  26. package/dist/shell-parse/index.d.mts +2 -0
  27. package/dist/shell-parse/index.mjs +2 -0
  28. package/dist/shell-parse/shell-command-segments.d.mts +6 -0
  29. package/dist/shell-parse/shell-command-segments.mjs +26 -0
  30. package/dist/shell-parse/shell-tokenizer-operators.d.mts +2 -4
  31. package/dist/shell-parse/shell-tokenizer-operators.mjs +14 -4
  32. package/dist/shell-parse/shell-tokenizer.d.mts +9 -5
  33. package/dist/shell-parse/shell-tokenizer.mjs +5 -1
  34. package/dist/shell-parse/shell-walk.d.mts +8 -0
  35. package/dist/shell-parse/shell-walk.mjs +62 -0
  36. package/package.json +29 -1
  37. package/scripts/__pycache__/run_bounded_process.cpython-312.pyc +0 -0
  38. package/skills/blackboard/SKILL.md +19 -0
  39. package/skills/github-issue/SKILL.md +12 -0
  40. package/skills/manifest.json +20 -20
  41. package/skills/retrospective/SKILL.md +17 -1
  42. package/skills/retrospective/references/ci-failures.md +48 -0
  43. package/skills/retrospective/references/sandbox-audit.md +48 -0
  44. package/skills/retrospective-distill/SKILL.md +11 -3
  45. package/skills/retrospective-distill/references/issue-body.md +40 -0
  46. package/skills/stacked-prs/references/gh-stack.md +5 -1
package/README.md CHANGED
@@ -584,6 +584,15 @@ there at construction and leaves the directory and other files alone. Applicatio
584
584
  directory are parameters. `checkFiniteTimeoutProfiles` writes one scratch project per admission
585
585
  profile and can take a caller-supplied runner.
586
586
 
587
+ `next-navigation-mock`, `jsdom-stubs` and `input-otp-mock` are test-only helpers for Vitest component
588
+ tests; `next` and `react` are optional peers, and each subpath imports only what it needs.
589
+ `vi.mock('next/navigation', () => navMockModule)` swaps in a singleton router whose spies and
590
+ state (`setSearchParams`, `setPathname`, `setParams`, `reset`) come from `createNavMock()`.
591
+ `installJsdomStubs()` adds no-op `ResizeObserver`, `IntersectionObserver`, `matchMedia` and
592
+ `scrollIntoView` only where jsdom lacks them. `installMemoryLocalStorage()` swaps in an in-memory
593
+ `localStorage` and returns it so `afterEach` can clear it. `vi.mock(import('input-otp'),
594
+ inputOtpMockFactory)` replaces the library's post-teardown timer with a plain input.
595
+
587
596
  `playwright` monitors browser console errors, web errors, dialogs, page crashes, and failed
588
597
  requests during Playwright tests. `@playwright/test` is an optional peer. `createBrowserTest` and
589
598
  `withMonitoredPage` install the generic telemetry blocks (Google Tag Manager, Google Analytics, and
@@ -1,3 +1,4 @@
1
+ import { walkUnquotedShell } from "../shell-parse/index.mjs";
1
2
  import { consumeArgumentCharacter } from "./argument-scan.mjs";
2
3
  const GH_API_BOUNDARY = /[\s;|&(){}]/;
3
4
  const GH_API_HEAD = /^gh[ \t]+api\b/;
@@ -7,84 +8,23 @@ function matchGhApiHead(text, index) {
7
8
  const match = GH_API_HEAD.exec(text.slice(index));
8
9
  return match ? match[0].length : 0;
9
10
  }
10
- function newFrame() {
11
- return { inSingleQuote: false, inDoubleQuote: false, scanningArgs: false, parenDepth: 0 };
12
- }
13
- function pushSubstitutionFrame(stack) {
14
- const frame = newFrame();
15
- frame.parenDepth = 1;
16
- stack.push(frame);
17
- }
18
11
  // Scans one already-joined logical line for `gh api` calls and returns at most one hit per call —
19
12
  // the first unquoted `?` or `&`, whichever comes first. `offsets[k]` maps character k of `text`
20
13
  // back to its absolute offset in the original source, so callers can report real line numbers.
14
+ // Quote, escape, comment, and `$(...)` nesting state comes from `walkUnquotedShell`, which keeps
15
+ // each substitution level independent (`VAR="$(gh api "…?a=1&b=2")"` is a common idiom) and, unlike
16
+ // the shell tokenizer, does not treat a quoted `${VAR}` as making a later `?` unquoted.
21
17
  export function scanLogicalLine(text, offsets) {
22
18
  const hits = [];
23
- const stack = [newFrame()];
24
- let i = 0;
25
- while (i < text.length) {
26
- const frame = stack[stack.length - 1];
27
- const char = text[i];
28
- if (frame.inSingleQuote) {
29
- if (char === "'")
30
- frame.inSingleQuote = false;
31
- i += 1;
32
- continue;
33
- }
34
- if (char === '\\') {
35
- i += 2;
36
- continue;
37
- }
38
- if (frame.inDoubleQuote) {
39
- if (char === '"') {
40
- frame.inDoubleQuote = false;
41
- i += 1;
42
- continue;
43
- }
44
- if (char === '$' && text[i + 1] === '(') {
45
- pushSubstitutionFrame(stack);
46
- i += 2;
47
- continue;
48
- }
49
- i += 1;
50
- continue;
51
- }
52
- if (char === '#' && (i === 0 || /\s/.test(text[i - 1])))
53
- break;
54
- if (char === "'") {
55
- frame.inSingleQuote = true;
56
- i += 1;
57
- continue;
58
- }
59
- if (char === '"') {
60
- frame.inDoubleQuote = true;
61
- i += 1;
62
- continue;
63
- }
64
- if (char === '$' && text[i + 1] === '(') {
65
- pushSubstitutionFrame(stack);
66
- i += 2;
67
- continue;
68
- }
69
- if (stack.length > 1 && (char === '(' || char === ')')) {
70
- frame.parenDepth += char === '(' ? 1 : -1;
71
- i += 1;
72
- if (frame.parenDepth === 0)
73
- stack.pop();
74
- continue;
75
- }
76
- const argumentIndex = consumeArgumentCharacter(text, i, frame, hits, offsets);
77
- if (argumentIndex !== undefined) {
78
- i = argumentIndex;
79
- continue;
80
- }
81
- const headLength = frame.scanningArgs ? 0 : matchGhApiHead(text, i);
82
- if (headLength > 0) {
83
- frame.scanningArgs = true;
84
- i += headLength;
85
- continue;
86
- }
87
- i += 1;
88
- }
19
+ walkUnquotedShell(text, () => ({ scanningArgs: false }), (index, frame) => {
20
+ const argumentIndex = consumeArgumentCharacter(text, index, frame, hits, offsets);
21
+ if (argumentIndex !== undefined)
22
+ return argumentIndex;
23
+ const headLength = frame.scanningArgs ? 0 : matchGhApiHead(text, index);
24
+ if (headLength === 0)
25
+ return undefined;
26
+ frame.scanningArgs = true;
27
+ return index + headLength;
28
+ });
89
29
  return hits;
90
30
  }
@@ -0,0 +1,25 @@
1
+ import type { ComponentType, InputHTMLAttributes, ReactNode } from 'react';
2
+ type InputOtpProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'pattern'> & {
3
+ children?: ReactNode;
4
+ onChange?: (value: string) => void;
5
+ containerClassName?: string;
6
+ pattern?: string | RegExp;
7
+ };
8
+ /**
9
+ * Factory for `vi.mock(import('input-otp'), inputOtpMockFactory)`. The real library schedules a
10
+ * password-manager timeout that can fire after jsdom teardown ("window is not defined"); this
11
+ * renders a plain text input that forwards `onChange(value)` instead.
12
+ */
13
+ export declare function inputOtpMockFactory(): Promise<{
14
+ OTPInput: ComponentType<InputOtpProps>;
15
+ OTPInputContext: import("react").Context<{
16
+ slots: {
17
+ char: string;
18
+ hasFakeCaret: boolean;
19
+ isActive: boolean;
20
+ }[];
21
+ }>;
22
+ REGEXP_ONLY_DIGITS: RegExp;
23
+ REGEXP_ONLY_DIGITS_AND_CHARS: RegExp;
24
+ }>;
25
+ export {};
@@ -0,0 +1,34 @@
1
+ const SLOT_COUNT = 8;
2
+ /**
3
+ * Factory for `vi.mock(import('input-otp'), inputOtpMockFactory)`. The real library schedules a
4
+ * password-manager timeout that can fire after jsdom teardown ("window is not defined"); this
5
+ * renders a plain text input that forwards `onChange(value)` instead.
6
+ */
7
+ export async function inputOtpMockFactory() {
8
+ const React = await import('react');
9
+ const OTPInputContext = React.createContext({
10
+ slots: Array.from({ length: SLOT_COUNT }, () => ({
11
+ char: '',
12
+ hasFakeCaret: false,
13
+ isActive: false,
14
+ })),
15
+ });
16
+ const OTPInput = React.forwardRef(function OTPInputMock({ children, maxLength, onChange, containerClassName, pattern, ...rest }, ref) {
17
+ const source = pattern instanceof RegExp ? pattern.source : pattern;
18
+ return React.createElement('div', { 'data-input-otp': true, maxLength, className: containerClassName }, React.createElement('input', {
19
+ type: 'text',
20
+ maxLength,
21
+ ref,
22
+ onChange: (event) => onChange?.(event.target.value),
23
+ pattern: source,
24
+ ...rest,
25
+ }), children);
26
+ });
27
+ OTPInput.displayName = 'OTPInput';
28
+ return {
29
+ OTPInput,
30
+ OTPInputContext,
31
+ REGEXP_ONLY_DIGITS: /^\d*$/,
32
+ REGEXP_ONLY_DIGITS_AND_CHARS: /^[a-zA-Z0-9]*$/,
33
+ };
34
+ }
@@ -0,0 +1,12 @@
1
+ /** In-memory `Storage`. Keep the returned object to `clear()` it between tests. */
2
+ export declare function createMemoryStorage(): Storage;
3
+ /**
4
+ * Replaces `localStorage` on `target` (and its `window`, when present) with a fresh in-memory
5
+ * store and returns it so the caller can clear it in `afterEach`.
6
+ */
7
+ export declare function installMemoryLocalStorage(target?: object): Storage;
8
+ /**
9
+ * Installs no-op `ResizeObserver`, `IntersectionObserver`, `matchMedia` and
10
+ * `HTMLElement.prototype.scrollIntoView` stubs, each only when jsdom leaves it undefined.
11
+ */
12
+ export declare function installJsdomStubs(target?: object): void;
@@ -0,0 +1,85 @@
1
+ const noop = () => { };
2
+ class StubResizeObserver {
3
+ observe = noop;
4
+ unobserve = noop;
5
+ disconnect = noop;
6
+ }
7
+ class StubIntersectionObserver {
8
+ observe = noop;
9
+ unobserve = noop;
10
+ disconnect = noop;
11
+ takeRecords() {
12
+ return [];
13
+ }
14
+ }
15
+ function stubMatchMedia(query) {
16
+ return {
17
+ matches: false,
18
+ media: query,
19
+ onchange: null,
20
+ addListener: noop,
21
+ removeListener: noop,
22
+ addEventListener: noop,
23
+ removeEventListener: noop,
24
+ dispatchEvent: () => false,
25
+ };
26
+ }
27
+ /** In-memory `Storage`. Keep the returned object to `clear()` it between tests. */
28
+ export function createMemoryStorage() {
29
+ const store = new Map();
30
+ return {
31
+ getItem: (key) => store.get(key) ?? null,
32
+ setItem: (key, value) => {
33
+ store.set(key, value);
34
+ },
35
+ removeItem: (key) => {
36
+ store.delete(key);
37
+ },
38
+ clear: () => {
39
+ store.clear();
40
+ },
41
+ get length() {
42
+ return store.size;
43
+ },
44
+ key: (index) => [...store.keys()][index] ?? null,
45
+ };
46
+ }
47
+ function asTarget(target) {
48
+ return target;
49
+ }
50
+ function define(target, name, value) {
51
+ Object.defineProperty(target, name, { configurable: true, writable: true, value });
52
+ }
53
+ /**
54
+ * Replaces `localStorage` on `target` (and its `window`, when present) with a fresh in-memory
55
+ * store and returns it so the caller can clear it in `afterEach`.
56
+ */
57
+ export function installMemoryLocalStorage(target = globalThis) {
58
+ const storage = createMemoryStorage();
59
+ define(target, 'localStorage', storage);
60
+ const win = target.window;
61
+ if (win !== undefined && win !== target)
62
+ define(win, 'localStorage', storage);
63
+ return storage;
64
+ }
65
+ /**
66
+ * Installs no-op `ResizeObserver`, `IntersectionObserver`, `matchMedia` and
67
+ * `HTMLElement.prototype.scrollIntoView` stubs, each only when jsdom leaves it undefined.
68
+ */
69
+ export function installJsdomStubs(target = globalThis) {
70
+ const global = asTarget(target);
71
+ if (global.ResizeObserver === undefined)
72
+ define(global, 'ResizeObserver', StubResizeObserver);
73
+ if (global.IntersectionObserver === undefined) {
74
+ define(global, 'IntersectionObserver', StubIntersectionObserver);
75
+ }
76
+ const win = global.window;
77
+ if (win === undefined)
78
+ return;
79
+ if (win.matchMedia === undefined)
80
+ define(win, 'matchMedia', stubMatchMedia);
81
+ const proto = win.HTMLElement?.prototype;
82
+ if (proto !== undefined && proto.scrollIntoView === undefined) {
83
+ define(proto, 'scrollIntoView', noop);
84
+ }
85
+ }
@@ -22,6 +22,8 @@ export type PolicyRun = {
22
22
  env: NodeJS.ProcessEnv;
23
23
  /** Test seam: replaces the real child process. */
24
24
  spawn?: PolicySpawner;
25
+ /** Test seam: replaces `process.execPath` as the Node binary to launch. */
26
+ nodePath?: string;
25
27
  };
26
28
  /**
27
29
  * Runs one export of the worktree's declared policy module in a fresh child process (never in
@@ -1,6 +1,7 @@
1
+ import { existsSync } from 'node:fs';
1
2
  import { fileURLToPath } from 'node:url';
2
3
  import { resolvePolicyModule } from "./policy-config.mjs";
3
- import { policyEnvironment, spawnPolicy, } from "./policy-spawn.mjs";
4
+ import { missingNodeError, policyEnvironment, spawnPolicy, } from "./policy-spawn.mjs";
4
5
  /** How long each policy export may run before its process is killed, in milliseconds. */
5
6
  export const POLICY_TIMEOUTS_MS = {
6
7
  validateRetrospective: 30_000,
@@ -83,9 +84,12 @@ async function runUnscrubbed(run, spawn) {
83
84
  const module = await resolvePolicyModule(run.worktree);
84
85
  if (module === undefined)
85
86
  return { status: 'no-policy' };
87
+ const node = run.nodePath ?? process.execPath;
88
+ if (!existsSync(node))
89
+ throw missingNodeError(node);
86
90
  const timeoutMs = POLICY_TIMEOUTS_MS[name];
87
91
  const outcome = await spawn({
88
- command: process.execPath,
92
+ command: node,
89
93
  args: [RUNNER, module],
90
94
  cwd: run.worktree,
91
95
  env: policyEnvironment(run.env),
@@ -16,6 +16,7 @@ export type PolicyOutcome = {
16
16
  overflowed: boolean;
17
17
  };
18
18
  export type PolicySpawner = (request: PolicyRequest) => Promise<PolicyOutcome>;
19
+ export declare function missingNodeError(node: string): Error;
19
20
  /**
20
21
  * The child's whole environment. Blackboard credentials and NODE_OPTIONS are never passed; GitHub
21
22
  * tokens are passed only when the server has them, for the checks that call `gh`.
@@ -1,6 +1,9 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { accessSync, constants } from 'node:fs';
2
+ import { accessSync, constants, existsSync } from 'node:fs';
3
3
  import { delimiter, dirname, join } from 'node:path';
4
+ export function missingNodeError(node) {
5
+ return new Error(`The MCP server's Node binary (${node}) was removed, likely by a Node version upgrade. Reconnect the server: \`/mcp\` in Claude Code, or restart Codex.`);
6
+ }
4
7
  function isExecutable(path) {
5
8
  try {
6
9
  accessSync(path, constants.X_OK);
@@ -79,7 +82,12 @@ export const spawnPolicy = (request) => new Promise((resolve, reject) => {
79
82
  });
80
83
  child.on('error', (error) => {
81
84
  clearTimeout(timer);
82
- reject(error);
85
+ // ENOENT also means a missing cwd, so only a binary that is gone gets the reconnect message.
86
+ reject(error.code === 'ENOENT' &&
87
+ request.command === process.execPath &&
88
+ !existsSync(request.command)
89
+ ? missingNodeError(request.command)
90
+ : error);
83
91
  });
84
92
  // Reap anything the policy left running in its group as soon as the runner exits: a descendant
85
93
  // would otherwise keep the GitHub token it inherited, and one holding an inherited pipe would
@@ -0,0 +1,27 @@
1
+ type NextNavigation = typeof import('next/navigation.js');
2
+ type SearchParamsInit = string | URLSearchParams | undefined;
3
+ /**
4
+ * Pass to `vi.mock('next/navigation', () => navMockModule)`. Hooks read the mutable state lazily,
5
+ * so changes made between tests apply on the next render. Import it before the component under
6
+ * test so the factory is initialized when the mock is evaluated.
7
+ */
8
+ export declare const navMockModule: NextNavigation;
9
+ /**
10
+ * Control object for the shared `navMockModule` singleton: repeated calls share spies and state.
11
+ * Call `reset()` in `beforeEach`.
12
+ */
13
+ export declare function createNavMock(): {
14
+ push: import("vitest").Mock<(...args: unknown[]) => unknown>;
15
+ replace: import("vitest").Mock<(...args: unknown[]) => unknown>;
16
+ refresh: import("vitest").Mock<(...args: unknown[]) => unknown>;
17
+ back: import("vitest").Mock<(...args: unknown[]) => unknown>;
18
+ forward: import("vitest").Mock<(...args: unknown[]) => unknown>;
19
+ prefetch: import("vitest").Mock<(...args: unknown[]) => unknown>;
20
+ /** Accepts the same init forms as `new URLSearchParams()`; `undefined` clears it. */
21
+ setSearchParams(init?: SearchParamsInit): void;
22
+ setPathname(pathname: string): void;
23
+ setParams(params: Record<string, string | string[]>): void;
24
+ /** Restores empty search params, pathname `/`, empty params, and clears spy history. */
25
+ reset(): void;
26
+ };
27
+ export {};
@@ -0,0 +1,58 @@
1
+ import { vi } from 'vitest';
2
+ const state = {
3
+ // A plain URLSearchParams at runtime; the cast only satisfies the real hook's return type.
4
+ searchParams: new URLSearchParams(),
5
+ pathname: '/',
6
+ params: {},
7
+ };
8
+ const push = vi.fn();
9
+ const replace = vi.fn();
10
+ const refresh = vi.fn();
11
+ const back = vi.fn();
12
+ const forward = vi.fn();
13
+ const prefetch = vi.fn();
14
+ const spies = [push, replace, refresh, back, forward, prefetch];
15
+ const router = { push, replace, refresh, back, forward, prefetch };
16
+ /**
17
+ * Pass to `vi.mock('next/navigation', () => navMockModule)`. Hooks read the mutable state lazily,
18
+ * so changes made between tests apply on the next render. Import it before the component under
19
+ * test so the factory is initialized when the mock is evaluated.
20
+ */
21
+ export const navMockModule = {
22
+ useRouter: () => router,
23
+ useSearchParams: () => state.searchParams,
24
+ usePathname: () => state.pathname,
25
+ useParams: () => state.params,
26
+ };
27
+ /**
28
+ * Control object for the shared `navMockModule` singleton: repeated calls share spies and state.
29
+ * Call `reset()` in `beforeEach`.
30
+ */
31
+ export function createNavMock() {
32
+ return {
33
+ push,
34
+ replace,
35
+ refresh,
36
+ back,
37
+ forward,
38
+ prefetch,
39
+ /** Accepts the same init forms as `new URLSearchParams()`; `undefined` clears it. */
40
+ setSearchParams(init) {
41
+ state.searchParams = new URLSearchParams(init);
42
+ },
43
+ setPathname(pathname) {
44
+ state.pathname = pathname;
45
+ },
46
+ setParams(params) {
47
+ state.params = params;
48
+ },
49
+ /** Restores empty search params, pathname `/`, empty params, and clears spy history. */
50
+ reset() {
51
+ state.searchParams = new URLSearchParams();
52
+ state.pathname = '/';
53
+ state.params = {};
54
+ for (const spy of spies)
55
+ spy.mockReset();
56
+ },
57
+ };
58
+ }
@@ -1,4 +1,5 @@
1
1
  import { CodexMessageCounter } from "./codex-messages.mjs";
2
+ import { escalationOf } from "./escalations.mjs";
2
3
  import { commands, hasFailedOutcome } from "./codex-payload.mjs";
3
4
  import { applyCommand, asNumber, asRecord, emptyTokens, } from "./shared.mjs";
4
5
  function usage(record) {
@@ -75,6 +76,9 @@ export function applyRecords(records, facts, subagent, baseline = emptyTokens())
75
76
  calls.add(id);
76
77
  if (payload.name === 'advisor')
77
78
  facts.advisorCalls++;
79
+ const escalation = escalationOf(payload);
80
+ if (escalation)
81
+ facts.escalations.push(escalation);
78
82
  for (const rawCommand of commands(payload))
79
83
  applyCommand(rawCommand, facts);
80
84
  }
@@ -1 +1,2 @@
1
+ export declare function redactOverlongToken(token: string): string;
1
2
  export declare function normalizeCommandPrefix(command: string): string;
@@ -11,7 +11,7 @@ import { isPackageRunner, splitCommandSegments } from "./command-segments.mjs";
11
11
  // for a privacy boundary, over-redacting a legitimate token is the safe failure mode.
12
12
  const MAX_COMMAND_TOKEN_LENGTH = 40;
13
13
  const REDACTED_TOKEN = '…';
14
- function redactOverlongToken(token) {
14
+ export function redactOverlongToken(token) {
15
15
  return token.length > MAX_COMMAND_TOKEN_LENGTH ? REDACTED_TOKEN : token;
16
16
  }
17
17
  const ENV_ASSIGNMENT_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*=/;
@@ -1,2 +1,2 @@
1
- export declare function splitCommandSegments(command: string): string[][];
1
+ export { splitCommandSegments } from '../shell-parse/index.mts';
2
2
  export declare function isPackageRunner(word: string | undefined): boolean;
@@ -1,51 +1,6 @@
1
- // Commands are matched by command position, not by scanning for words anywhere in
2
- // the string. The string is split into segments on unquoted `;`, `&`, `|` and
3
- // newlines (so `git push;gh pr view` splits even with no surrounding whitespace).
4
- // Quoted spans, including any whitespace inside them, are grouped into a single
5
- // word, mirroring real shell tokenization.
6
- export function splitCommandSegments(command) {
7
- const segments = [];
8
- let current = [];
9
- let word = '';
10
- let quote = null;
11
- const flushWord = () => {
12
- if (word) {
13
- current.push(word);
14
- word = '';
15
- }
16
- };
17
- const flushSegment = () => {
18
- flushWord();
19
- if (current.length) {
20
- segments.push(current);
21
- current = [];
22
- }
23
- };
24
- for (const char of command) {
25
- if (quote) {
26
- if (char === quote)
27
- quote = null;
28
- else
29
- word += char;
30
- continue;
31
- }
32
- if (char === '"' || char === "'") {
33
- quote = char;
34
- continue;
35
- }
36
- if (char === ';' || char === '&' || char === '|' || char === '\n' || char === '\r') {
37
- flushSegment();
38
- continue;
39
- }
40
- if (/\s/.test(char)) {
41
- flushWord();
42
- continue;
43
- }
44
- word += char;
45
- }
46
- flushSegment();
47
- return segments;
48
- }
1
+ // Commands are matched by command position, not by scanning for words anywhere in the string.
2
+ // Segmenting and quote handling belong to shell-parse.
3
+ export { splitCommandSegments } from "../shell-parse/index.mjs";
49
4
  const PACKAGE_RUNNERS = ['npx', 'pnpm', 'pnpx', 'yarn'];
50
5
  export function isPackageRunner(word) {
51
6
  if (!word)
@@ -0,0 +1,6 @@
1
+ export type SandboxEscalation = {
2
+ commandPrefix: string;
3
+ justification?: string;
4
+ prefixRule?: string[];
5
+ };
6
+ export declare function escalationOf(payload: Record<string, unknown>): SandboxEscalation | undefined;
@@ -0,0 +1,34 @@
1
+ import { normalizeCommandPrefix, redactOverlongToken } from "./command-prefix.mjs";
2
+ import { asRecord } from "./shared.mjs";
3
+ const MAX_JUSTIFICATION_LENGTH = 240;
4
+ // Only a parsed `exec_command` function_call whose JSON arguments request
5
+ // `sandbox_permissions: "require_escalated"` counts. Text that merely quotes the field
6
+ // (for example an auto-review prompt) never reaches here because it is not a call.
7
+ // The approval outcome is not recorded in a stable shape, so it is intentionally omitted.
8
+ export function escalationOf(payload) {
9
+ if (payload.type !== 'function_call' || payload.name !== 'exec_command')
10
+ return undefined;
11
+ if (typeof payload.arguments !== 'string')
12
+ return undefined;
13
+ let args;
14
+ try {
15
+ args = asRecord(JSON.parse(payload.arguments));
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ if (args?.sandbox_permissions !== 'require_escalated')
21
+ return undefined;
22
+ const command = args.cmd ?? args.command;
23
+ const justification = typeof args.justification === 'string'
24
+ ? args.justification.replace(/\s+/g, ' ').trim().slice(0, MAX_JUSTIFICATION_LENGTH)
25
+ : '';
26
+ const rule = Array.isArray(args.prefix_rule)
27
+ ? args.prefix_rule.filter((token) => typeof token === 'string')
28
+ : [];
29
+ return {
30
+ commandPrefix: typeof command === 'string' ? normalizeCommandPrefix(command) : '',
31
+ ...(justification ? { justification } : {}),
32
+ ...(rule.length ? { prefixRule: rule.map(redactOverlongToken) } : {}),
33
+ };
34
+ }
@@ -16,7 +16,20 @@ export function formatTranscriptFacts(sessionId, facts) {
16
16
  `Tokens: input=${facts.tokens.input} output=${facts.tokens.output} cache_read=${facts.tokens.cacheRead} cache_creation=${facts.tokens.cacheCreation}`,
17
17
  `Subagent tool calls: ${facts.subagentToolCalls}`,
18
18
  `Subagent tokens: input=${facts.subagentTokens.input} output=${facts.subagentTokens.output} cache_read=${facts.subagentTokens.cacheRead} cache_creation=${facts.subagentTokens.cacheCreation}`,
19
+ ...escalationLines(facts),
19
20
  '',
20
21
  ].join('\n');
21
22
  }
23
+ function escalationLines(facts) {
24
+ if (!facts.escalations.length)
25
+ return [];
26
+ return [
27
+ `Sandbox escalations: ${facts.escalations.length}`,
28
+ ...facts.escalations.map((item) => {
29
+ const rule = item.prefixRule ? ` prefix_rule=${JSON.stringify(item.prefixRule)}` : '';
30
+ const why = item.justification ? ` justification=${JSON.stringify(item.justification)}` : '';
31
+ return `- ${item.commandPrefix || '(unknown)'}${rule}${why}`;
32
+ }),
33
+ ];
34
+ }
22
35
  export const formatUnavailable = (reason) => `=== Transcript Facts ===\nStatus: unavailable (${reason.replace(/\s+/g, ' ').slice(0, 240)})\n`;
@@ -7,7 +7,8 @@ import { segmentCodex } from "./codex-segment.mjs";
7
7
  import { computeClaude } from "./claude.mjs";
8
8
  import { formatTranscriptFacts, formatUnavailable } from "./format.mjs";
9
9
  import { globFrom, resolveTranscriptFile, SESSION_ID, } from "./resolve-transcript-file.mjs";
10
- import { emptyFacts, hasMalformedInteriorRecord, parseLines, } from "./shared.mjs";
10
+ import { hasMalformedInteriorRecord } from "./malformed-record.mjs";
11
+ import { emptyFacts, parseLines } from "./shared.mjs";
11
12
  export { codexChildren, codexIdentity } from "./codex.mjs";
12
13
  export { formatTranscriptFacts, formatUnavailable } from "./format.mjs";
13
14
  export { resolveTranscriptFile } from "./resolve-transcript-file.mjs";
@@ -0,0 +1 @@
1
+ export declare function hasMalformedInteriorRecord(lines: string[]): boolean;
@@ -0,0 +1,13 @@
1
+ import { asRecord } from "./shared.mjs";
2
+ export function hasMalformedInteriorRecord(lines) {
3
+ const nonblank = lines.filter((line) => line.trim());
4
+ const complete = lines.at(-1)?.trim() ? nonblank.slice(0, -1) : nonblank;
5
+ return complete.some((line) => {
6
+ try {
7
+ return !asRecord(JSON.parse(line));
8
+ }
9
+ catch {
10
+ return true;
11
+ }
12
+ });
13
+ }
@@ -1,3 +1,4 @@
1
+ import type { SandboxEscalation } from './escalations.mts';
1
2
  export type TokenTotals = {
2
3
  input: number;
3
4
  output: number;
@@ -16,6 +17,7 @@ export type TranscriptFacts = {
16
17
  tokens: TokenTotals;
17
18
  subagentToolCalls: number;
18
19
  subagentTokens: TokenTotals;
20
+ escalations: SandboxEscalation[];
19
21
  };
20
22
  export type ParsedLine = Record<string, unknown>;
21
23
  export type CodexSegment = {
@@ -27,5 +29,4 @@ export declare const emptyFacts: () => TranscriptFacts;
27
29
  export declare function asRecord(value: unknown): ParsedLine | undefined;
28
30
  export declare const asNumber: (value: unknown) => number;
29
31
  export declare function parseLines(lines: string[]): ParsedLine[];
30
- export declare function hasMalformedInteriorRecord(lines: string[]): boolean;
31
32
  export declare function applyCommand(command: string, facts: TranscriptFacts): void;