Skip to content

Commit de1c4e6

Browse files
tamirdresherGeordi (Squad)
andauthored
fix(cli): resolvable squad_state bridge spec, doctor bridge probe, versioned health, state-mcp lifecycle (2.0.0-preview.2) (#2301)
* fix(cli): harden squad state bridge Fixes #2296 and #2300. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 995eea17-c356-4912-90ea-5e5b144e7ba9 * fix(sdk): guard state backend root operations Accept state-root aliases only for list-shaped operations and reject file or destructive root access before it reaches the backend. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 995eea17-c356-4912-90ea-5e5b144e7ba9 * fix(cli): probe the local built bridge in source checkouts Use packages/squad-cli/dist/cli-entry.js when init and doctor run from source, avoiding an npx registry fetch in CI and contributor environments. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 995eea17-c356-4912-90ea-5e5b144e7ba9 * fix(cli): reconcile historical state MCP keys Include the raw resolved-path hash and the original SHA-256 key format when removing legacy user-level squad_state entries. Add independent Windows and POSIX regression coverage that preserves unrelated registrations. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 995eea17-c356-4912-90ea-5e5b144e7ba9 * test(cli): assert direct source MCP launch Update upgrade portability coverage for the direct Node source entry while retaining an exact-version npx fallback assertion for installed deployments. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 995eea17-c356-4912-90ea-5e5b144e7ba9 * fix(cli): harden bridge config reliability Write reconciled user MCP config through a flushed sibling and atomic rename, with fault-injection coverage that preserves the original. Give the real cold two-layer health integration a documented bounded Windows budget. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 995eea17-c356-4912-90ea-5e5b144e7ba9 --------- Co-authored-by: Geordi (Squad) <geordi@squad.local> Co-authored-by: B'Elanna (Squad) <tamirdresher@users.noreply.github.com> Copilot-Session: 995eea17-c356-4912-90ea-5e5b144e7ba9
1 parent 73c4e64 commit de1c4e6

23 files changed

Lines changed: 1416 additions & 262 deletions

‎.changeset/calm-bridges-exit.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@bradygaster/squad-cli": patch
3+
"@bradygaster/squad-sdk": patch
4+
---
5+
6+
Generate resolvable versioned state bridge declarations, probe them in `squad doctor`, report bridge identity in health output, and terminate stdio servers when their host transport closes.

‎.changeset/safe-state-root.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@bradygaster/squad-sdk": patch
3+
---
4+
5+
Allow backend root aliases only for list-shaped operations and reject file or destructive operations before they can access or erase the entire state tree.

‎docs/src/content/docs/scenarios/troubleshooting.md‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,43 @@ If below v22.5, upgrade to the latest LTS:
117117

118118
---
119119

120+
## `state-mcp` processes remain after Copilot sessions close
121+
122+
**Problem:** Many `state-mcp` processes remain on a long-running development
123+
machine.
124+
125+
**Cause:** Copilot host sessions can remain alive after their visible UI session
126+
closes. Every live host keeps its stdio MCP children alive. Older Squad
127+
installations also used `npx`/shell wrapper chains and duplicate hashed user
128+
declarations, which multiplied the process count.
129+
130+
**Fix:**
131+
132+
1. Run `squad upgrade --force`. The repository `.mcp.json` declaration takes
133+
precedence, uses the installed CLI entry directly when available, and removes
134+
only the matching legacy `squad_state_<hash>` user declaration after backing
135+
up `~/.copilot/mcp-config.json`.
136+
2. Restart the affected Copilot sessions so they load the new declaration.
137+
3. If cleanup is still required, stop only confirmed parent-gone bridge PIDs.
138+
Never kill processes by image/name:
139+
140+
```powershell
141+
$all = Get-CimInstance Win32_Process
142+
$byPid = @{}
143+
$all | ForEach-Object { $byPid[[int]$_.ProcessId] = $_ }
144+
$orphans = $all | Where-Object {
145+
$_.CommandLine -match 'state-mcp' -and
146+
-not $byPid.ContainsKey([int]$_.ParentProcessId)
147+
}
148+
$orphans | Select-Object ProcessId, ParentProcessId, CommandLine
149+
$orphans | ForEach-Object { Stop-Process -Id ([int]$_.ProcessId) }
150+
```
151+
152+
If the list is empty, do not kill anything. The live Copilot parent owns
153+
those processes; close or restart that specific session instead.
154+
155+
---
156+
120157
## Upgrade doesn't change anything
121158

122159
**Problem:** Running `squad upgrade` completes but nothing changes.

‎packages/squad-cli/src/cli/commands/doctor.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ import { fatalNoSquad } from '../core/errors.js';
1919
import { isMutableStateKey, MUTABLE_STATE_PATHS } from '@bradygaster/squad-sdk/tools';
2020
import { resolveUpstreams } from '@bradygaster/squad-sdk/upstream';
2121
import { effectiveSquadDir } from '../core/effective-squad-dir.js';
22+
import { getPackageVersion } from '../core/version.js';
23+
import {
24+
probeSquadStateBridge,
25+
resolveConfiguredSquadStateMcp,
26+
} from '../core/mcp-probe.js';
2227

2328
const storage = new FSStorageProvider();
2429

@@ -595,6 +600,80 @@ function checkCopilotCli(): Promise<DoctorCheck> {
595600
});
596601
}
597602

603+
export async function checkSquadStateBridge(cwd: string): Promise<DoctorCheck> {
604+
const name = 'squad_state bridge';
605+
const expectedVersion = getPackageVersion();
606+
const configured = resolveConfiguredSquadStateMcp(cwd);
607+
const fix = "Run 'squad upgrade --force' to rewrite the bridge declaration.";
608+
if (!configured) {
609+
return {
610+
name,
611+
status: 'warn',
612+
message: `no squad_state declaration found in .mcp.json or the project-scoped user config. ${fix}`,
613+
};
614+
}
615+
616+
try {
617+
const probe = await probeSquadStateBridge(cwd, configured);
618+
if (probe.version !== expectedVersion) {
619+
return {
620+
name,
621+
status: 'fail',
622+
message: `version mismatch: configured bridge reports ${probe.version || 'unknown'}, running CLI is ${expectedVersion}. ${fix}`,
623+
};
624+
}
625+
if (!probe.tools.includes('squad_state_health')) {
626+
return {
627+
name,
628+
status: 'fail',
629+
message: `bridge ${expectedVersion} exposes ${probe.tools.length} tool(s) but not squad_state_health. ${fix}`,
630+
};
631+
}
632+
633+
const expectedTeamDir = path.resolve(effectiveSquadDir(cwd).stateDir);
634+
const healthVersion = `squad-state ${expectedVersion}`;
635+
const teamLine = probe.healthText.match(/^Team squad dir:\s*(.+)$/m)?.[1]?.trim();
636+
if (!probe.healthText.includes(healthVersion) || !teamLine) {
637+
return {
638+
name,
639+
status: 'fail',
640+
message: `bridge health is missing "${healthVersion}" or the resolved team directory. ${fix}`,
641+
};
642+
}
643+
const reportedTeamDir = path.resolve(teamLine);
644+
const sameTeamDir = process.platform === 'win32'
645+
? reportedTeamDir.toLowerCase() === expectedTeamDir.toLowerCase()
646+
: reportedTeamDir === expectedTeamDir;
647+
if (!sameTeamDir) {
648+
return {
649+
name,
650+
status: 'fail',
651+
message: `bridge resolved ${reportedTeamDir}, expected ${expectedTeamDir}. ${fix}`,
652+
};
653+
}
654+
655+
return {
656+
name,
657+
status: 'pass',
658+
message: `${probe.version}; ${probe.tools.length} tools; ${configured.precedence} config ${configured.configPath}`,
659+
};
660+
} catch (error) {
661+
const detail = error instanceof Error ? error.message : String(error);
662+
if (/ETARGET|No matching version found/i.test(detail)) {
663+
return {
664+
name,
665+
status: 'fail',
666+
message: `registry mirror cannot resolve the configured dist-tag. Pin @bradygaster/squad-cli@${expectedVersion} exactly, or ${fix.toLowerCase()}`,
667+
};
668+
}
669+
return {
670+
name,
671+
status: 'fail',
672+
message: `unreachable: ${detail}. ${fix}`,
673+
};
674+
}
675+
}
676+
598677
// ── git sync hooks check ─────────────────────────────────────────────
599678

600679
const SQUAD_SYNC_HOOK_MARKER = '# --- squad-sync-hook ---';
@@ -842,6 +921,7 @@ export async function runDoctor(cwd?: string): Promise<DoctorCheck[]> {
842921
const upstreamCheck = checkUpstreams(squadDir);
843922
if (upstreamCheck) checks.push(upstreamCheck);
844923

924+
checks.push(await checkSquadStateBridge(resolvedCwd));
845925

846926
// Hook presence check (only for two-layer / orphan backends)
847927
const hookCheck = checkGitSyncHooks(resolvedCwd, squadDir);

‎packages/squad-cli/src/cli/commands/state-mcp.ts‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ export function createStateMcpToolRegistry(startDir: string): ToolRegistry {
8383
return new ToolRegistry(context.paths.teamSquadDir, undefined, context.storage, undefined, undefined, undefined, {
8484
backendName: context.backend.name,
8585
upstreamDir: context.paths.projectDir,
86+
runtimeVersion: SERVER_INFO.version,
8687
});
8788
}
8889

@@ -265,7 +266,44 @@ export async function runStateMcp(startDir = process.cwd(), options: StateMcpOpt
265266
return normalizeToolResult(result);
266267
});
267268

268-
await server.connect(new StdioServerTransport());
269+
const transport = new StdioServerTransport();
270+
let stopping = false;
271+
let forceExit: NodeJS.Timeout | undefined;
272+
273+
const stop = async (): Promise<void> => {
274+
if (stopping) return;
275+
stopping = true;
276+
forceExit = setTimeout(() => process.exit(0), 500);
277+
try {
278+
await server.close();
279+
} catch {
280+
// Transport teardown is best-effort; the grace timer guarantees exit.
281+
}
282+
};
283+
284+
const onStdinEnd = (): void => { void stop(); };
285+
const onDisconnect = (): void => { void stop(); };
286+
const onSigpipe = (): void => { void stop(); };
287+
const onStdoutError = (error: NodeJS.ErrnoException): void => {
288+
if (error.code === 'EPIPE') void stop();
289+
};
290+
291+
process.stdin.once('end', onStdinEnd);
292+
process.stdin.once('close', onStdinEnd);
293+
process.once('disconnect', onDisconnect);
294+
process.once('SIGPIPE', onSigpipe);
295+
process.stdout.on('error', onStdoutError);
296+
297+
try {
298+
await server.connect(transport);
299+
} finally {
300+
process.stdin.off('end', onStdinEnd);
301+
process.stdin.off('close', onStdinEnd);
302+
process.off('disconnect', onDisconnect);
303+
process.off('SIGPIPE', onSigpipe);
304+
process.stdout.off('error', onStdoutError);
305+
if (forceExit && !stopping) clearTimeout(forceExit);
306+
}
269307
}
270308

271309
export function printStateMcpHelp(): void {

‎packages/squad-cli/src/cli/core/init.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,11 @@ import { projectSquadStateMcpSpec, resolveSquadStateMcpSpec } from './mcp-spec.j
1818
import { describeMcpSpec, ensureUserOwnedTemplates } from './upgrade.js';
1919
import { syncCopilotInstructionsFile } from './managed-file.js';
2020
import { getTemplatesDir } from './templates.js';
21-
import { ensureSquadStateMcpInRoot, tombstoneStaleSquadStateInProjectMcp } from './mcp-root.js';
21+
import {
22+
ensureSquadStateMcpInRoot,
23+
reconcileSquadStateUserConfig,
24+
tombstoneStaleSquadStateInProjectMcp,
25+
} from './mcp-root.js';
2226
import { applyClientProjectionsForInit, reportClientResults, type ClientId } from './clients.js';
2327
import {
2428
readTeamMd,
@@ -454,6 +458,11 @@ export async function runInit(dest: string, options: RunInitOptions = {}): Promi
454458
if (tomb.removed) {
455459
success(`removed stale squad_state from ${tomb.path} (now lives in .mcp.json)`);
456460
}
461+
const userConfig = reconcileSquadStateUserConfig(dest);
462+
if (userConfig.action === 'removed') {
463+
success(`removed duplicate ${(userConfig.keys ?? [userConfig.key]).join(', ')} from ${userConfig.path} (.mcp.json takes precedence)`);
464+
console.log(`${DIM} backup: ${userConfig.backupPath}${RESET}`);
465+
}
457466
} catch (err) {
458467
console.warn(`${YELLOW}⚠ Could not install squad_state MCP entry in .mcp.json: ${err instanceof Error ? err.message : err}${RESET}`);
459468
}
@@ -483,6 +492,11 @@ export async function runInit(dest: string, options: RunInitOptions = {}): Promi
483492
if (tomb.removed) {
484493
success(`removed stale squad_state from ${tomb.path} (now lives in .mcp.json)`);
485494
}
495+
const userConfig = reconcileSquadStateUserConfig(dest);
496+
if (userConfig.action === 'removed') {
497+
success(`removed duplicate ${(userConfig.keys ?? [userConfig.key]).join(', ')} from ${userConfig.path} (.mcp.json takes precedence)`);
498+
console.log(`${DIM} backup: ${userConfig.backupPath}${RESET}`);
499+
}
486500
} catch {
487501
// best-effort: .mcp.json write failure does not block init
488502
}

‎packages/squad-cli/src/cli/core/managed-file.ts‎

Lines changed: 35 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { readFileSync, writeFileSync, existsSync, copyFileSync } from 'node:fs';
1+
import fs, { readFileSync, writeFileSync, existsSync, copyFileSync } from 'node:fs';
2+
import { randomUUID } from 'node:crypto';
23
import { extname } from 'node:path';
34

45
export const COPILOT_INSTRUCTIONS_START = '<!-- squad:copilot-instructions:start -->';
@@ -20,17 +21,46 @@ function readExisting(filePath: string): string | undefined {
2021
}
2122
}
2223

24+
function managedTextUpdate(existing: string | undefined, content: string): string | undefined {
25+
const normalize = (text: string) => text.replace(/\r\n?|\n/g, '\n');
26+
if (existing !== undefined && normalize(existing) === normalize(content)) return undefined;
27+
const eol = existing?.match(/\r\n|\n|\r/)?.[0];
28+
return eol ? normalize(content).replace(/\n/g, eol) : content;
29+
}
30+
2331
/** Keep destination newlines, and avoid rewriting a newline-only difference. */
2432
export function writeManagedText(filePath: string, content: string): boolean {
2533
const existing = readExisting(filePath);
26-
const normalize = (text: string) => text.replace(/\r\n?|\n/g, '\n');
27-
if (existing !== undefined && normalize(existing) === normalize(content)) return false;
28-
const eol = existing?.match(/\r\n|\n|\r/)?.[0];
29-
const next = eol ? normalize(content).replace(/\n/g, eol) : content;
34+
const next = managedTextUpdate(existing, content);
35+
if (next === undefined) return false;
3036
writeFileSync(filePath, next, 'utf8');
3137
return true;
3238
}
3339

40+
/** Write through a flushed sibling file, then atomically replace the destination. */
41+
export function writeManagedTextAtomic(filePath: string, content: string): boolean {
42+
const existing = readExisting(filePath);
43+
const next = managedTextUpdate(existing, content);
44+
if (next === undefined) return false;
45+
46+
const tempPath = `${filePath}.squad-tmp-${process.pid}-${randomUUID()}`;
47+
const mode = fs.existsSync(filePath) ? fs.statSync(filePath).mode : 0o666;
48+
try {
49+
const descriptor = fs.openSync(tempPath, 'wx', mode);
50+
try {
51+
fs.writeFileSync(descriptor, next, 'utf8');
52+
fs.fsyncSync(descriptor);
53+
} finally {
54+
fs.closeSync(descriptor);
55+
}
56+
fs.renameSync(tempPath, filePath);
57+
} catch (error) {
58+
fs.rmSync(tempPath, { force: true });
59+
throw error;
60+
}
61+
return true;
62+
}
63+
3464
export function copyManagedFile(source: string, destination: string): void {
3565
if (!MANAGED_TEXT_EXTENSIONS.has(extname(source).toLowerCase()) || !existsSync(destination)) {
3666
copyFileSync(source, destination);
@@ -149,4 +179,3 @@ export function syncCopilotInstructionsFile(sourceTemplatePath: string, destinat
149179
}
150180
return writeManagedText(destinationPath, nextContent);
151181
}
152-

0 commit comments

Comments
 (0)