Skip to content

Commit dc671a7

Browse files
bradygasterCopilot
andauthored
fix(gh-aw): relay normalized squad commands through dispatch (#2136)
* fix(gh-aw): relay normalized squad commands through dispatch Fixes three command-routing defects reported against source SHA 261d140 (octodemo/zava-social-backend-20261001184422#1): 1. The lifecycle-repair fallback in the shared squad.md coordinator only recognized exact, /squad-prefixed issue-comment bodies. A command normalized and relayed by squad-command-router.md via workflow_dispatch (e.g. the bare "activate" dispatch input for a /squad activate comment) skipped repair entirely. Repair gating and the effective command are now derived identically for both the issue_comment and workflow_dispatch event paths (CANONICAL_BY_BARE_COMMAND normalization). 2. squad-command-router.md omitted `roles: all`, so gh-aw's default write-role activation gate blocked the router from running at all for non-write actors -- including modes the router intentionally allows anyone to invoke. Added `roles: all`; the router's own in-script, per-command authorization for mutating modes is unchanged. 3. The router's relayed dispatch dropped originating comment provenance, so an embedded /squad approve-improvement could never supply a real approval_comment_id and was rejected outright. The router now forwards an aw_context pointer (item type/number + originating comment id) through the dispatch, and squad-improvement-gate.mjs's validateApprovalDispatchRelay re-fetches and validates that live comment, binding permission to its own author -- never the dispatch actor -- so approval binding is not weakened. Package/lock/manifest regenerated via the standard `node workflows/shared/squad-install-verifier.mjs --write-source` pipeline; strict `gh aw compile --strict` passes with only the two documented warnings. Added test/gh-aw-command-router-relay.test.ts (true end-to-end router -> repair-job relay via real extracted step scripts, plus a normalization mutation-kill test), and extended test/gh-aw-command-parse.test.ts / test/gh-aw-improvement-worker.test.ts with regression coverage for all three findings. Local npm install is broken in this environment (missing transitive deps such as fdir), so vitest/eslint cannot run locally; every new/changed assertion was independently verified by direct Node/vm execution of the real production modules and scripts, and by compiled-lock diffing. Hosted CI at the PR head is the authoritative suite result. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(gh-aw): update compiled-digest golden hashes for relay fix The roles: all / aw_context changes to squad.md and squad-command-router.md legitimately alter the compiled squad.lock.yml content. Update the three hardcoded golden SHA-256 digests in test/gh-aw-quality.test.ts's canonical package integrity contract suite to match, following the same pattern as commit b545508. Independently recomputed via direct execution of the real compileWithPinnedActions/normalizeCompiledLock helpers (node --experimental-strip-types, bypassing the broken local vitest install) and confirmed to match hosted CI's reported values exactly. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(gh-aw): forward real item identity across the squad.md -> squad-improvement-worker relay hop Fixes a downstream defect in the command-routing relay chain (flagged by copilot-pull-request-reviewer[bot] against PR #2136, which fixed the three originally-scoped findings from source SHA 261d140, octodemo/zava-social-backend-20261001184422#1). Root cause: gh-aw's own dispatch_workflow safe-output engine unconditionally overwrites any agent-supplied aw_context input with its own buildAwContext() whenever a dispatch's target workflow declares an aw_context workflow_dispatch input. buildAwContext() derives item_type/item_number/comment_id solely from the CURRENT run's own event payload -- never inherited across a hop. When a relayed (workflow_dispatch -triggered) squad.md run dispatches to squad-improvement-worker via the squad-approve-improvement skill, that dispatch goes through gh-aw's real dispatch_workflow handler, so the engine always overwrites squad.md's aw_context with its own context -- which, because squad.md's own run is a workflow_dispatch event with no issue/comment payload, always carries empty item_type/item_number/comment_id. collectImprovementContext's existing strict exact-match check (correct for the native direct-comment path, where the engine's own context genuinely is accurate) therefore always rejected every relayed /squad approve-improvement, independent of any event_type widening. Fix (no gh-aw change; pure squad.md-side plumbing): - squad-improvement-worker.md: declare a new, non-colliding squad_approval_relay workflow_dispatch input (distinct name from aw_context, so gh-aw's engine never auto-overwrites it) and wire a parallel SQUAD_IMPROVE_RELAY_CONTEXT env var at both existing call sites. - squad.md: the squad-approve-improvement skill now always forwards squad_approval_relay: {event_type, item_type, item_number, comment_id} alongside the existing issue_number/approval_comment_id inputs, reusing the same already-resolved values. - squad-improvement-gate.mjs: collectImprovementContext keeps the unconditional repo/workflow_id provenance check against the engine's own (always-accurate) context, then branches: native path (event_type === issue_comment) validates item identity against the engine context unchanged; relayed path (any other event_type) validates with identical exact-match strictness against the new SQUAD_IMPROVE_RELAY_CONTEXT instead. No approval-binding check is weakened on either path; all unconditional live re-verification (comment/permission/revocation/ revision/linked-PR checks) is untouched. Regenerated workflows/package/*.md and workflows/squad-workflows.manifest.json via `node workflows/shared/squad-install-verifier.mjs --write-source`. Tests (test/gh-aw-improvement-worker.test.ts): - Extends the skill-JSON-shape assertion for the new relay field. - New describe block covering: relayed-path authorization success, repo/ workflow_id forgery still rejected, mutation-kill coverage (tampered comment_id/item_number/item_type/event_type each independently rejected), malformed/missing relay context rejected (no silent fallback to the engine's empty item fields), native-path non-regression, source wiring assertions, and a compiled-artifact assertion (gh aw compile --strict) proving both the worker's lock.yml declares/wires the new input and squad.lock.yml's compiled dispatch step actually emits squad_approval_relay. Verified locally: standalone Node execution of collectImprovementContext's new branch logic (native path, relayed success, 4 mutation-kill cases, 3 malformed/missing-context cases, repo/workflow_id forgery); gh aw compile --strict across all 8 installed workflows produces exactly the two documented warnings (Compiled 8 workflows: 8 succeeded, 2 warnings); per-workflow strict compiles of squad and squad-improvement-worker confirm the new input/env/dispatch-field wiring in the generated lock.yml files. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * test(gh-aw): update stale compiled-lock golden digests after relay-context fix Updating workflows/squad.md's squad-approve-improvement dispatch payload (and squad-improvement-worker.md's new input/env wiring) changes the compiled squad.lock.yml / squad-improvement-worker.lock.yml content, which shifts the normalized SHA-256 digests asserted by the canonical package integrity contract tests in test/gh-aw-quality.test.ts (tamper-mutation fixtures recomputed over the new baseline compiled output). Re-derived both digest pairs from the actual compiled output (workflow and package source bindings) and updated the three assertions that pinned the stale values. No test logic changed; this is a golden-value refresh consistent with the same pattern applied for the three originally-scoped fixes earlier in this PR. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 3ee53b2 commit dc671a7

17 files changed

Lines changed: 916 additions & 162 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
"@bradygaster/squad-cli": patch
3+
"@bradygaster/squad-sdk": patch
4+
---
5+
6+
Fixed three command-routing defects where a `/squad` command relayed by `squad-command-router.md` via `workflow_dispatch` (instead of arriving as a direct issue comment) could be silently dropped or mis-authorized:
7+
8+
- The lifecycle-repair fallback in the shared `squad.md` coordinator only recognized exact, `/squad`-prefixed issue-comment bodies. A command normalized and relayed by the router (e.g. the bare `activate` dispatch input for a `/squad activate` comment) no longer matched, so terminal activation states went unrepaired. Repair gating and the effective command are now derived the same way for both the `issue_comment` and `workflow_dispatch` event paths.
9+
- `squad-command-router.md` was missing `roles: all`, so gh-aw's default write-role activation gate blocked the router from even running for non-write actors — including modes the router intentionally allows anyone to invoke (e.g. `status`). The router now declares `roles: all` and continues to enforce its own in-script, per-command authorization for mutating modes.
10+
- The router's relayed dispatch dropped the originating issue/comment context, so an embedded `/squad approve-improvement` command could never supply a real `approval_comment_id` and was rejected outright. The router now forwards an `aw_context` pointer (item type/number and originating comment id) through the dispatch, and the improvement-approval gate validates permission against that comment's own live author — never the dispatch actor — so approval binding is unchanged, not weakened.

‎test/gh-aw-command-parse.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,16 @@ describe('gh-aw: shared /squad command contract (#1824)', () => {
203203
expect(WORKFLOW).not.toContain('### Step PC-1: Extract the command argument');
204204
});
205205

206+
it('declares roles: all so write-role gating does not block modes open to everyone (#2)', () => {
207+
expect(DISCOVERY_WORKFLOW).toMatch(/^on:\n\s+roles:\s*all\n/m);
208+
});
209+
210+
it('forwards originating comment provenance via aw_context on the relayed dispatch (#3)', () => {
211+
expect(DISCOVERY_WORKFLOW).toContain('comment_id: context.payload.comment?.id ?? null');
212+
expect(DISCOVERY_WORKFLOW).toContain('aw_context: awContext');
213+
expect(DISCOVERY_WORKFLOW).toContain("inputs: {");
214+
});
215+
206216
it('routes commands outside gh-aw start-only activation through the same contract', () => {
207217
expect(DISCOVERY_WORKFLOW).toContain("contains(github.event.issue.body, '/squad')");
208218
expect(DISCOVERY_WORKFLOW).toContain("contains(github.event.comment.body, '/squad')");
Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,257 @@
1+
import { describe, expect, it } from 'vitest';
2+
import { readFileSync } from 'node:fs';
3+
import { join } from 'node:path';
4+
import { createRequire } from 'node:module';
5+
import { compileFunction, constants as vmConstants } from 'node:vm';
6+
import {
7+
classifySquadCommand,
8+
commandRequiresAuthorization,
9+
isAuthorizedPermission,
10+
} from '../workflows/shared/squad-command-contract.mjs';
11+
12+
const nodeRequire = createRequire(import.meta.url);
13+
14+
// Regression coverage for the three command-routing defects reported against
15+
// bradygaster/squad source SHA 261d140679b158888f1a3c4d9a5a3e74eb55b633
16+
// (octodemo/zava-social-backend-20261001184422#1):
17+
//
18+
// #1 lifecycle-repair fallback only recognized exact issue-comment bodies,
19+
// so a normalized command relayed via workflow_dispatch skipped repair;
20+
// #2 the router omitted `roles: all`, so gh-aw's default write-role
21+
// activation gate blocked non-write actors from modes meant to be open
22+
// to all (open modes still require no mutating permission once past
23+
// that gate -- the router's own in-script authorization is unchanged);
24+
// #3 the router dropped originating comment provenance, so a relayed
25+
// `/squad approve-improvement` could never supply a real
26+
// `approval_comment_id`.
27+
//
28+
// These tests execute the real extracted step scripts the same way
29+
// `actions/github-script` does (compile the body as an async function and
30+
// invoke it -- see test/scripts/repo-health-comment-transport.test.ts for the
31+
// established pattern in this repo), so they exercise production source, not
32+
// a reimplementation of it.
33+
34+
const ROOT = process.cwd();
35+
const ROUTER = readFileSync(join(ROOT, 'workflows/squad-command-router.md'), 'utf8');
36+
const SHARED_SQUAD = readFileSync(join(ROOT, 'workflows/shared/squad.md'), 'utf8');
37+
38+
/** Read a `script: |` literal block starting at `marker`, dedented. */
39+
function extractScript(source: string, marker: string): string {
40+
const markerIndex = source.indexOf(marker);
41+
expect(markerIndex, `marker not found: ${marker}`).toBeGreaterThanOrEqual(0);
42+
const scriptIndex = source.indexOf('script: |', markerIndex);
43+
expect(scriptIndex, `no script block after marker: ${marker}`).toBeGreaterThanOrEqual(0);
44+
const lineStart = source.lastIndexOf('\n', scriptIndex) + 1;
45+
const indent = scriptIndex - lineStart;
46+
const lines: string[] = [];
47+
let cursor = source.indexOf('\n', scriptIndex) + 1;
48+
while (cursor > 0 && cursor < source.length) {
49+
const nextNewline = source.indexOf('\n', cursor);
50+
const line = nextNewline >= 0 ? source.slice(cursor, nextNewline) : source.slice(cursor);
51+
if (line.trim() !== '') {
52+
const lineIndent = line.match(/^\s*/)![0].length;
53+
if (lineIndent <= indent) break;
54+
lines.push(line.slice(indent + 2));
55+
} else {
56+
lines.push('');
57+
}
58+
if (nextNewline < 0) break;
59+
cursor = nextNewline + 1;
60+
}
61+
return lines.join('\n');
62+
}
63+
64+
function compileScript(script: string) {
65+
return compileFunction(
66+
`return (async () => {\n${script}\n})();`,
67+
['github', 'context', 'core', 'process', 'require'],
68+
{ importModuleDynamically: vmConstants.USE_MAIN_CONTEXT_DEFAULT_LOADER },
69+
) as (...args: unknown[]) => Promise<unknown>;
70+
}
71+
72+
describe('gh-aw: router-to-repair workflow_dispatch relay (#2, #3 findings)', () => {
73+
it('declares roles: all so the activation gate does not block non-write actors (#2)', () => {
74+
expect(ROUTER).toMatch(/^on:\n\s+roles:\s*all\n/m);
75+
});
76+
77+
it('preserves the router-level mutating-mode authorization that remains the real gate', () => {
78+
// roles: all only removes gh-aw's blanket write-role activation gate; the
79+
// router's own in-script permission check for mutating modes must be the
80+
// thing still enforcing authorization afterward.
81+
expect(ROUTER).toContain('contract.commandRequiresAuthorization(result)');
82+
expect(ROUTER).toContain('contract.isAuthorizedPermission(permission)');
83+
expect(ROUTER).toContain('getCollaboratorPermissionLevel');
84+
expect(commandRequiresAuthorization({ status: 'accepted', mode: 'cast' })).toBe(true);
85+
expect(commandRequiresAuthorization({ status: 'accepted', mode: 'status' })).toBe(false);
86+
expect(isAuthorizedPermission('read')).toBe(false);
87+
expect(isAuthorizedPermission('write')).toBe(true);
88+
});
89+
90+
it('forwards an aw_context comment pointer alongside the bare relayed command (#3)', () => {
91+
expect(ROUTER).toContain("comment_id: context.payload.comment?.id ?? null");
92+
expect(ROUTER).toContain('aw_context: awContext');
93+
expect(ROUTER).toContain("command: result.argumentText || 'cast'");
94+
});
95+
96+
it(
97+
'relays a normalized issue-comment activation command through the router script to the ' +
98+
'exact dispatch inputs it emits, end to end',
99+
async () => {
100+
const routerScript = extractScript(ROUTER, 'Route or reject discovered command');
101+
expect(routerScript).not.toContain('${{');
102+
103+
// An ordinary issue comment -- not a synthetic bare workflow_dispatch
104+
// input -- posted by an authorized (write-permission) human.
105+
const commentBody = '/squad activate';
106+
const context = {
107+
repo: { owner: 'bradygaster', repo: 'squad' },
108+
actor: 'maintainer',
109+
payload: {
110+
issue: { number: 4242 },
111+
comment: { id: 55001, body: commentBody },
112+
repository: { default_branch: 'dev' },
113+
},
114+
};
115+
116+
// classifySquadCommand must accept this as the 'activate' mode with a
117+
// bare argumentText -- this bare form is exactly what the pre-fix
118+
// repair job's exact-body-only `includes(command)` check could never
119+
// match once relayed through workflow_dispatch.
120+
const classified = classifySquadCommand({ comment: context.payload.comment, issue: context.payload.issue }, 'issue_comment');
121+
expect(classified).toMatchObject({ status: 'accepted', mode: 'activate', argumentText: 'activate' });
122+
123+
let dispatchedInputs: Record<string, string> | null = null;
124+
const github = {
125+
rest: {
126+
issues: { createComment: async () => undefined },
127+
repos: { getCollaboratorPermissionLevel: async () => ({ data: { permission: 'write' } }) },
128+
actions: {
129+
createWorkflowDispatch: async (params: { inputs: Record<string, string> }) => {
130+
dispatchedInputs = params.inputs;
131+
},
132+
},
133+
},
134+
};
135+
const core = { setFailed: (msg: string) => { throw new Error(`core.setFailed: ${msg}`); }, info: () => undefined, warning: () => undefined };
136+
137+
// The real router script resolves the command contract off a checked-out
138+
// trusted-base clone (`<workspace>/.squad-command-trusted-base/.github/...`);
139+
// point that one import *target path* at this repo's own working copy
140+
// of the real module instead of re-implementing the router's logic.
141+
// Every other line -- including the `require('node:path')` /
142+
// `require('node:url')` preamble -- is the real, unmodified extracted
143+
// script text, executed via the injected real `require`.
144+
const importStatement =
145+
'const contract = await import(pathToFileURL(nodePath.join(\n' +
146+
' trustedRoot,\n' +
147+
" '.github/workflows/shared/squad-command-contract.mjs',\n" +
148+
')).href);';
149+
expect(routerScript).toContain(importStatement);
150+
const inlined = routerScript.replace(
151+
importStatement,
152+
`const contract = await import(pathToFileURL(nodePath.join(process.cwd(), 'workflows/shared/squad-command-contract.mjs')).href);`,
153+
);
154+
expect(inlined).not.toBe(routerScript);
155+
156+
const previousWorkspace = process.env.GITHUB_WORKSPACE;
157+
process.env.GITHUB_WORKSPACE = ROOT;
158+
try {
159+
await compileScript(inlined)(github, context, core, process, nodeRequire);
160+
} finally {
161+
if (previousWorkspace === undefined) delete process.env.GITHUB_WORKSPACE;
162+
else process.env.GITHUB_WORKSPACE = previousWorkspace;
163+
}
164+
165+
expect(dispatchedInputs).not.toBeNull();
166+
expect(dispatchedInputs).toMatchObject({
167+
command: 'activate',
168+
issue_number: '4242',
169+
});
170+
const awContext = JSON.parse(dispatchedInputs!.aw_context);
171+
expect(awContext).toEqual({ item_type: 'issue', item_number: 4242, comment_id: 55001 });
172+
173+
// Now feed the router's exact emitted dispatch inputs into the real
174+
// repair job script as a workflow_dispatch event would, and confirm the
175+
// normalized, relayed command actually reaches and passes the repair
176+
// job's acceptance + authorization gates (not merely that the router
177+
// produced the right-looking payload).
178+
const repairScript = extractScript(SHARED_SQUAD, 'Repair terminal lifecycle after idempotent activation');
179+
expect(repairScript).not.toContain('${{');
180+
181+
const repairContext = {
182+
repo: { owner: 'bradygaster', repo: 'squad' },
183+
payload: { inputs: dispatchedInputs },
184+
};
185+
const paginateCalls: unknown[] = [];
186+
const repairGithub = {
187+
paginate: async (_fn: unknown, params: unknown) => {
188+
paginateCalls.push(params);
189+
return [];
190+
},
191+
rest: { issues: { listComments: () => undefined, updateComment: async () => undefined, createComment: async () => undefined }, repos: {} },
192+
};
193+
const infoMessages: string[] = [];
194+
const repairCore = {
195+
setFailed: (msg: string) => { throw new Error(`core.setFailed: ${msg}`); },
196+
info: (msg: string) => { infoMessages.push(msg); },
197+
};
198+
const previousEnv: Record<string, string | undefined> = {};
199+
const applied = {
200+
ISSUE_NUMBER: dispatchedInputs!.issue_number,
201+
SQUAD_EVENT_NAME: 'workflow_dispatch',
202+
SQUAD_COMMAND: dispatchedInputs!.command,
203+
};
204+
for (const [key, value] of Object.entries(applied)) {
205+
previousEnv[key] = process.env[key];
206+
process.env[key] = value;
207+
}
208+
try {
209+
await compileScript(repairScript)(repairGithub, repairContext, repairCore, process);
210+
} finally {
211+
for (const [key, value] of Object.entries(previousEnv)) {
212+
if (value === undefined) delete process.env[key];
213+
else process.env[key] = value;
214+
}
215+
}
216+
217+
// It must have reached the trusted-artifact lookup (proving the
218+
// normalized "activate" command and the workflow_dispatch pre-authorized
219+
// branch were both accepted) rather than failing the whole-plan command
220+
// validation the way the pre-fix exact-body-only check would have.
221+
expect(paginateCalls).toHaveLength(1);
222+
expect(infoMessages.some(m => m.includes('authorized via workflow_dispatch'))).toBe(true);
223+
},
224+
);
225+
226+
it('kills the normalization mutation: an un-normalized bare command is rejected again', async () => {
227+
const repairScript = extractScript(SHARED_SQUAD, 'Repair terminal lifecycle after idempotent activation');
228+
const mutated = repairScript.replace(
229+
'command = CANONICAL_BY_BARE_COMMAND[bare] || command;',
230+
'// normalization removed by mutation',
231+
);
232+
expect(mutated).not.toBe(repairScript);
233+
234+
const context = { repo: { owner: 'bradygaster', repo: 'squad' }, payload: { inputs: { issue_number: '4242', command: 'activate' } } };
235+
const paginateCalls: unknown[] = [];
236+
const github = { paginate: async (_fn: unknown, params: unknown) => { paginateCalls.push(params); return []; }, rest: { issues: {}, repos: {} } };
237+
let failedWith: string | null = null;
238+
const core = { setFailed: (msg: string) => { failedWith = msg; }, info: () => undefined };
239+
const previousEnv: Record<string, string | undefined> = {};
240+
const applied = { ISSUE_NUMBER: '4242', SQUAD_EVENT_NAME: 'workflow_dispatch', SQUAD_COMMAND: 'activate' };
241+
for (const [key, value] of Object.entries(applied)) {
242+
previousEnv[key] = process.env[key];
243+
process.env[key] = value;
244+
}
245+
try {
246+
await compileScript(mutated)(github, context, core, process);
247+
} finally {
248+
for (const [key, value] of Object.entries(previousEnv)) {
249+
if (value === undefined) delete process.env[key];
250+
else process.env[key] = value;
251+
}
252+
}
253+
254+
expect(failedWith).toContain('A valid whole-plan activation command and issue number are required.');
255+
expect(paginateCalls).toHaveLength(0);
256+
});
257+
});

0 commit comments

Comments
 (0)