diff --git a/.changeset/secure-release-paths.md b/.changeset/secure-release-paths.md new file mode 100644 index 000000000..ccdf07845 --- /dev/null +++ b/.changeset/secure-release-paths.md @@ -0,0 +1,8 @@ +--- +"@bradygaster/squad-cli": patch +"@bradygaster/squad-sdk": patch +--- + +Harden generated configuration, remote detection, input parsing, and self-upgrade commands against unsafe or pathological inputs. + +Avoid probing retired profile squads while resolving legacy team roots. diff --git a/packages/squad-cli/src/cli/commands/doctor.ts b/packages/squad-cli/src/cli/commands/doctor.ts index 8df11ad03..9a1d14e21 100644 --- a/packages/squad-cli/src/cli/commands/doctor.ts +++ b/packages/squad-cli/src/cli/commands/doctor.ts @@ -101,7 +101,7 @@ function detectMode(cwd: string): ModeInfo { export function teamRootIsThisProject(cwd: string, teamRoot: string): boolean { const resolved = path.resolve(cwd, teamRoot); const normalize = (p: string) => { - const n = path.resolve(p).replace(/[\\/]+$/, ''); + const n = path.resolve(p).replace(/[\\/]$/, ''); return process.platform === 'win32' ? n.toLowerCase() : n; }; const target = normalize(resolved); diff --git a/packages/squad-cli/src/cli/commands/migrate.ts b/packages/squad-cli/src/cli/commands/migrate.ts index 952a4689d..49eea6607 100644 --- a/packages/squad-cli/src/cli/commands/migrate.ts +++ b/packages/squad-cli/src/cli/commands/migrate.ts @@ -320,7 +320,7 @@ function generateSquadConfig( }); } } - lines.push(` members: [${team.members.map(m => `'${m}'`).join(', ')}],`); + lines.push(` members: [${team.members.map(m => `'${escapeString(m)}'`).join(', ')}],`); lines.push(" }),"); lines.push(""); @@ -328,7 +328,7 @@ function generateSquadConfig( lines.push(" agents: ["); agents.forEach((agent, idx) => { const isLast = idx === agents.length - 1; - lines.push(` defineAgent({ name: '${agent.name}', role: '${escapeString(agent.role)}', charter: '${agent.charter}', status: '${agent.status}' })${isLast ? '' : ','}`); + lines.push(` defineAgent({ name: '${escapeString(agent.name)}', role: '${escapeString(agent.role)}', charter: '${escapeString(agent.charter)}', status: '${agent.status}' })${isLast ? '' : ','}`); }); lines.push(" ],"); lines.push(""); @@ -339,12 +339,12 @@ function generateSquadConfig( lines.push(" rules: ["); routing.rules.forEach((rule, idx) => { const isLast = idx === routing.rules.length - 1; - const agentsStr = `[${rule.agents.map(a => `'${a}'`).join(', ')}]`; + const agentsStr = `[${rule.agents.map(a => `'${escapeString(a)}'`).join(', ')}]`; const desc = rule.description ? `, description: '${escapeString(rule.description)}'` : ''; - lines.push(` { pattern: '${rule.pattern}', agents: ${agentsStr}${desc} }${isLast ? '' : ','}`); + lines.push(` { pattern: '${escapeString(rule.pattern)}', agents: ${agentsStr}${desc} }${isLast ? '' : ','}`); }); lines.push(" ],"); - lines.push(` defaultAgent: '${routing.defaultAgent}',`); + lines.push(` defaultAgent: '${escapeString(routing.defaultAgent)}',`); lines.push(" fallback: 'coordinator',"); lines.push(" }),"); lines.push(""); @@ -359,6 +359,9 @@ function generateSquadConfig( lines.push(" capacity: {"); Object.entries(casting.capacity).forEach(([universe, count], idx, arr) => { const isLast = idx === arr.length - 1; + if (!Number.isFinite(count)) { + throw new Error(`Casting capacity for '${universe}' must be a finite number`); + } lines.push(` '${escapeString(universe)}': ${count}${isLast ? '' : ','}`); }); lines.push(" },"); @@ -373,10 +376,12 @@ function generateSquadConfig( } /** - * Escape single quotes in string literals + * Escape content for a single-quoted JavaScript string literal. */ function escapeString(str: string): string { - return str.replace(/'/g, "\\'").replace(/\n/g, '\\n'); + return str.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + .replace(/\r/g, '\\r').replace(/\n/g, '\\n') + .replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); } /** diff --git a/packages/squad-cli/src/cli/core/team-md.ts b/packages/squad-cli/src/cli/core/team-md.ts index 5eff469c8..d61d49673 100644 --- a/packages/squad-cli/src/cli/core/team-md.ts +++ b/packages/squad-cli/src/cli/core/team-md.ts @@ -90,7 +90,14 @@ export function insertCopilotSection(content: string, autoAssign: boolean = fals * Remove @copilot section from team.md */ export function removeCopilotSection(content: string): string { - return content.replace(/\n## Coding Agent\n[\s\S]*?(?=\n## |\n*$)/, ''); + const heading = '\n## Coding Agent\n'; + const start = content.indexOf(heading); + if (start === -1) return content; + const nextSection = content.indexOf('\n## ', start + heading.length); + if (nextSection !== -1) return content.slice(0, start) + content.slice(nextSection); + let end = content.length; + while (end > start + heading.length && content[end - 1] === '\n') end--; + return content.slice(0, start) + content.slice(end); } /** diff --git a/packages/squad-cli/src/cli/core/upgrade.ts b/packages/squad-cli/src/cli/core/upgrade.ts index 4b336c62c..7e7101a64 100644 --- a/packages/squad-cli/src/cli/core/upgrade.ts +++ b/packages/squad-cli/src/cli/core/upgrade.ts @@ -10,6 +10,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; import { FSStorageProvider, stripTeamCapabilitiesBlock, syncTeamCapabilities } from '@bradygaster/squad-sdk'; import { clearResolveSquadCache, isRetiredProfileTeamRoot } from '@bradygaster/squad-sdk/resolution'; import { squadRepoLauncherScript } from '@bradygaster/squad-sdk/client'; +import { detectPlatformFromUrl } from '@bradygaster/squad-sdk/platform'; import { backfillCastingRegistryFromTeam, detectHistoricalCastingSchema, @@ -271,8 +272,7 @@ function detectIsGitHubForMcp(dest: string, config: Record): bo try { const remoteUrl = execFileSync('git', ['remote', 'get-url', 'origin'], { cwd: dest, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim(); - const remoteUrlLower = remoteUrl.toLowerCase(); - if (remoteUrlLower.includes('dev.azure.com') || remoteUrlLower.includes('visualstudio.com') || remoteUrlLower.includes('ssh.dev.azure.com')) { + if (detectPlatformFromUrl(remoteUrl) === 'azure-devops') { return false; } } catch { @@ -332,7 +332,7 @@ function stripRetiredProfileTeamRoot(squadDir: string, dest: string, dryRun: boo */ export function stripAgentStamps(s: string): string { return s - .replace(/\n?/g, '') + .replace(/\n?/g, '') .replace(//g, '') .replace(/- \*\*Version:\*\* \S+/g, '- **Version:** X') .replace(/`Squad v[^`]+`/g, '`Squad vX`') @@ -1893,11 +1893,12 @@ export function detectSelfUpgradeTag(currentVersion: string): SelfUpgradeTag { /** The exact command `selfUpgradeCli` runs for a package manager and dist-tag. */ export function selfUpgradeCommand(packageManager: SelfUpgradePackageManager, insiderOrTag: boolean | SelfUpgradeTag): string { const tag: SelfUpgradeTag = typeof insiderOrTag === 'boolean' ? (insiderOrTag ? 'insider' : 'latest') : insiderOrTag; - const pkg = `@bradygaster/squad-cli@${tag}`; + if (tag !== 'latest' && tag !== 'insider') throw new Error('Invalid self-upgrade tag'); switch (packageManager) { - case 'pnpm': return `pnpm add -g ${pkg}`; - case 'yarn': return `yarn global add ${pkg}`; - default: return `npm install -g ${pkg}`; + case 'pnpm': return tag === 'insider' ? 'pnpm add -g @bradygaster/squad-cli@insider' : 'pnpm add -g @bradygaster/squad-cli@latest'; + case 'yarn': return tag === 'insider' ? 'yarn global add @bradygaster/squad-cli@insider' : 'yarn global add @bradygaster/squad-cli@latest'; + case 'npm': return tag === 'insider' ? 'npm install -g @bradygaster/squad-cli@insider' : 'npm install -g @bradygaster/squad-cli@latest'; + default: throw new Error('Invalid self-upgrade package manager'); } } diff --git a/packages/squad-cli/src/cli/shell/index.ts b/packages/squad-cli/src/cli/shell/index.ts index 7c87f1946..1ce5621d7 100644 --- a/packages/squad-cli/src/cli/shell/index.ts +++ b/packages/squad-cli/src/cli/shell/index.ts @@ -1275,9 +1275,14 @@ export async function runShell(): Promise { recordShellError('dispatch', err instanceof Error ? err.constructor.name : 'unknown'); const errorMsg = err instanceof Error ? err.message : String(err); if (shellApi) { + const quotaExceeded = errorMsg.toLowerCase().split(/[\r\n\u2028\u2029]/).some((line) => { + const quota = line.indexOf('quota'); + return quota !== -1 && line.indexOf('exceed', quota + 5) !== -1; + }); const isRateLimit = err instanceof RateLimitError || - /rate.?limit|quota.*exceed|429/i.test(errorMsg); + /rate.?limit|429/i.test(errorMsg) || + quotaExceeded; let guidance; if (isRateLimit) { const retryAfter = diff --git a/packages/squad-sdk/src/agents/onboarding.ts b/packages/squad-sdk/src/agents/onboarding.ts index fe4433c6d..30d476c18 100644 --- a/packages/squad-sdk/src/agents/onboarding.ts +++ b/packages/squad-sdk/src/agents/onboarding.ts @@ -444,6 +444,24 @@ export async function onboardAgent( * @param role - Agent role * @returns True if config was updated, false if not found or JSON format */ +function findRulesArray(content: string): { start: number; end: number; entries: string } | undefined { + const start = /rules:\s*\[/.exec(content); + if (!start) return undefined; + const entriesStart = start.index + start[0].length; + let cursor = entriesStart; + while (cursor < content.length) { + const close = content.indexOf(']', cursor); + if (close === -1) return undefined; + let after = close + 1; + while (after < content.length && /\s/.test(content[after]!)) after++; + if (after < content.length && ',})'.includes(content[after]!)) { + return { start: start.index, end: close + 1, entries: content.slice(entriesStart, close) }; + } + cursor = close + 1; + } + return undefined; +} + export async function addAgentToConfig( teamRoot: string, agentName: string, @@ -527,21 +545,18 @@ export async function addAgentToConfig( if (workType) { const workTypePattern = new RegExp(`workType:\\s*['"]${workType}['"]`); if (!workTypePattern.test(updatedContent)) { - const rulesPattern = /rules:\s*\[([\s\S]*?)\](?=\s*[,}\)])/; - const rulesMatch = updatedContent.match(rulesPattern); + const rulesMatch = findRulesArray(updatedContent); if (rulesMatch) { const newRule = ` { workType: '${workType}', agents: ['@${agentName}'], confidence: 'high' }`; - const existingRules = rulesMatch[1]!.trimEnd(); + const existingRules = rulesMatch.entries.trimEnd(); const separator = existingRules.trim() ? ',\n' : '\n'; const updatedRules = existingRules + separator + newRule; - updatedContent = updatedContent.replace( - rulesPattern, - `rules: [${updatedRules}\n ]` - ); + updatedContent = updatedContent.slice(0, rulesMatch.start) + + `rules: [${updatedRules}\n ]` + updatedContent.slice(rulesMatch.end); modified = true; } } diff --git a/packages/squad-sdk/src/backend/durable-http-backend.ts b/packages/squad-sdk/src/backend/durable-http-backend.ts index 97bd878db..154c93588 100644 --- a/packages/squad-sdk/src/backend/durable-http-backend.ts +++ b/packages/squad-sdk/src/backend/durable-http-backend.ts @@ -232,7 +232,9 @@ export function validateBaseUrl(baseUrl: string | undefined): string { `baseUrl must use https:// (plain http:// is allowed only for localhost / 127.0.0.1 / ::1); got '${url.protocol}//${url.host}'`, 400); } if (url.username || url.password) throw new BackendError('invalid-request', 'baseUrl must not embed credentials', 400); - return baseUrl.replace(/\/+$/, ''); + let end = baseUrl.length; + while (end > 0 && baseUrl[end - 1] === '/') end--; + return baseUrl.slice(0, end); } function toError(res: Response, text: string): BackendError { diff --git a/packages/squad-sdk/src/casting/handwritten-registry.ts b/packages/squad-sdk/src/casting/handwritten-registry.ts index 98dcaf319..03a83efe9 100644 --- a/packages/squad-sdk/src/casting/handwritten-registry.ts +++ b/packages/squad-sdk/src/casting/handwritten-registry.ts @@ -66,7 +66,7 @@ export function toAgentId(value: string): string { .replace(/[\u0300-\u036f]/g, '') .toLowerCase() .replace(/[^a-z0-9]+/g, '-') - .replace(/^-+|-+$/g, ''); + .replace(/^-|-$/g, ''); } export interface DroppedRecord { name: string; reason: string } @@ -757,13 +757,24 @@ export interface TeamRosterMember { charterId?: string; } -const UNIVERSE_LINE = /^\s*(?:[-*]\s+)?\*{0,2}universe\*{0,2}\s*:\s*\*{0,2}\s*([^\n|*]+?)\s*$/im; -const UNIVERSE_CELL = /^\s*\|\s*\*{0,2}universe\*{0,2}\s*\|\s*([^|\n]+?)\s*\|/im; +const UNIVERSE_LINE = /^(?:[-*]\s+)?\*{0,2}universe\*{0,2}\s*:(.*)$/i; +const UNIVERSE_CELL = /^\|\s*\*{0,2}universe\*{0,2}\s*\|([^|]+)\|/i; /** Parse specialist rows from `team.md` (`## Members` table, else the first Name/Role table). */ export function parseTeamRoster(teamMd: string): { members: TeamRosterMember[]; universe?: string } { - const universe = (UNIVERSE_LINE.exec(teamMd)?.[1] ?? UNIVERSE_CELL.exec(teamMd)?.[1])?.replace(/[*_`]/g, '').trim(); const lines = teamMd.split(/\r?\n/); + let universeLine: string | undefined; + let universeCell: string | undefined; + for (const line of lines) { + const text = line.trim(); + const lineMatch = UNIVERSE_LINE.exec(text); + if (universeLine === undefined && lineMatch) { + const candidate = lineMatch[1]!.trimStart().replace(/^\*{0,2}/, '').trimStart(); + if (candidate && !/[*|]/.test(candidate)) universeLine = candidate; + } + if (universeCell === undefined) universeCell = UNIVERSE_CELL.exec(text)?.[1]; + } + const universe = (universeLine ?? universeCell)?.replace(/[*_`]/g, '').trim(); const membersHeading = lines.findIndex((l) => /^##\s+members\b/i.test(l.trim())); const scope = membersHeading === -1 ? lines diff --git a/packages/squad-sdk/src/client/adapters/apply.ts b/packages/squad-sdk/src/client/adapters/apply.ts index cea7e096c..eacbb6910 100644 --- a/packages/squad-sdk/src/client/adapters/apply.ts +++ b/packages/squad-sdk/src/client/adapters/apply.ts @@ -73,7 +73,16 @@ export function removeLines(existing: string, lines: readonly string[], id: stri return rows.join('\n'); } -const SECTION_RE = /^\s*(\[\[?)\s*([^\]\r\n]+?)\s*(\]\]?)\s*(?:#.*)?$/; +const SECTION_RE = /^\s*(\[\[?)([^\]\r\n]+)(\]\]?)\s*(?:#.*)?$/; + +function withoutTrailingLineBreaks(value: string): string { + let end = value.length; + while (end > 0 && value[end - 1] === '\n') { + end--; + if (end > 0 && value[end - 1] === '\r') end--; + } + return value.slice(0, end); +} function segmentsEqual(a: readonly string[], b: readonly string[]): boolean { return a.length === b.length && a.every((s, idx) => s === b[idx]); @@ -471,7 +480,7 @@ export function upsertTomlTable( if (!(k in merged)) merged[k] = v; } const body = Object.entries(merged).map(([k, v]) => `${k} = ${v}`); - const cleanedExisting = lines.join(nl).replace(/(\r?\n)*$/, ''); + const cleanedExisting = withoutTrailingLineBreaks(lines.join(nl)); const prefix = cleanedExisting === '' ? '' : cleanedExisting + nl + nl; return `${prefix}${[header, ...body].join(nl)}${nl}`; } @@ -798,7 +807,7 @@ export function removeTomlTable(existing: string, table: string): string { } if (!changed) return existing; const joined = lines.join(nl); - return joined.trim() === '' ? '' : joined.replace(/(\r?\n)*$/, nl); + return joined.trim() === '' ? '' : withoutTrailingLineBreaks(joined) + nl; } const MCP_CONTAINERS = ['mcpServers', 'mcp', 'servers']; diff --git a/packages/squad-sdk/src/client/adapters/coordinator.ts b/packages/squad-sdk/src/client/adapters/coordinator.ts index 3db15aa4c..818c0bdaf 100644 --- a/packages/squad-sdk/src/client/adapters/coordinator.ts +++ b/packages/squad-sdk/src/client/adapters/coordinator.ts @@ -62,8 +62,11 @@ export const CANONICAL_COORDINATOR_HEADINGS = [ export function extractCanonicalCoordinatorHeadings(markdown: string): string[] { const headings: string[] = []; for (const line of markdown.split(/\r?\n/)) { - const m = /^#{2,3}\s+(.+?)\s*$/.exec(line); - if (m) headings.push(m[1]!); + const count = line.startsWith('###') ? 3 : line.startsWith('##') ? 2 : 0; + if (count && /\s/.test(line.charAt(count))) { + const heading = line.slice(count).trim(); + if (heading) headings.push(heading); + } } return headings; } diff --git a/packages/squad-sdk/src/config/init.ts b/packages/squad-sdk/src/config/init.ts index 417a2d5e4..395f01995 100644 --- a/packages/squad-sdk/src/config/init.ts +++ b/packages/squad-sdk/src/config/init.ts @@ -22,6 +22,7 @@ import { ensureMemoryGovernanceDefaults } from '../memory/index.js'; import { addSquadStateGitignoreBlock, removeSquadStateGitignoreBlock } from './gitignore-state.js'; import { syncTeamCapabilities } from './team-capabilities.js'; import { ensureCastingRegistryPair } from '../casting/durable-registry.js'; +import { detectPlatformFromUrl } from '../platform/detect.js'; // ============================================================================ // Manifest-Curated Skills (must stay in sync with TEMPLATE_MANIFEST in CLI) @@ -259,6 +260,20 @@ function formatModelArray(chain: readonly string[]): string { return `[${chain.map(m => `'${m}'`).join(', ')}]`; } +function escapeSingleQuotedString(value: string): string { + return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + .replace(/\r/g, '\\r').replace(/\n/g, '\\n') + .replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); +} + +function agentVariableName(name: string, index: number): string { + return `agent${index + 1}_${name.replace(/[^A-Za-z0-9_$]/g, '_')}`; +} + +function docCommentText(value: string): string { + return value.replace(/\*\//g, '* /').replace(/\r\n?|\n/g, '\n * '); +} + /** * Generate TypeScript config file content. */ @@ -268,8 +283,8 @@ function generateTypeScriptConfig(options: InitOptions): string { return `import type { SquadConfig } from '@bradygaster/squad'; /** - * Squad Configuration for ${projectName} - * ${projectDescription ? `\n * ${projectDescription}` : ''} + * Squad Configuration for ${docCommentText(projectName)} + * ${projectDescription ? `\n * ${docCommentText(projectDescription)}` : ''} */ const config: SquadConfig = { version: '1.0.0', @@ -295,22 +310,22 @@ const config: SquadConfig = { rules: [ { workType: 'feature-dev', - agents: ['@${agents[0]?.name || 'coordinator'}'], + agents: ['@${escapeSingleQuotedString(agents[0]?.name || 'coordinator')}'], confidence: 'high' }, { workType: 'bug-fix', - agents: ['@${agents.find(a => a.role === 'developer')?.name || agents[0]?.name || 'coordinator'}'], + agents: ['@${escapeSingleQuotedString(agents.find(a => a.role === 'developer')?.name || agents[0]?.name || 'coordinator')}'], confidence: 'high' }, { workType: 'testing', - agents: ['@${agents.find(a => a.role === 'tester')?.name || agents[0]?.name || 'coordinator'}'], + agents: ['@${escapeSingleQuotedString(agents.find(a => a.role === 'tester')?.name || agents[0]?.name || 'coordinator')}'], confidence: 'high' }, { workType: 'documentation', - agents: ['@${agents.find(a => a.role === 'scribe')?.name || agents[0]?.name || 'coordinator'}'], + agents: ['@${escapeSingleQuotedString(agents.find(a => a.role === 'scribe')?.name || agents[0]?.name || 'coordinator')}'], confidence: 'high' } ], @@ -423,23 +438,24 @@ function generateJsonConfig(options: InitOptions): string { */ function generateSDKBuilderConfig(options: InitOptions): string { const { projectName, projectDescription, agents } = options; + const definitions = agents.map((agent, index) => ({ agent, variableName: agentVariableName(agent.name, index) })); // Generate imports let code = `import {\n defineSquad,\n defineTeam,\n defineAgent,\n} from '@bradygaster/squad-sdk';\n\n`; - code += `/**\n * Squad Configuration — ${projectName}\n`; + code += `/**\n * Squad Configuration — ${docCommentText(projectName)}\n`; if (projectDescription) { - code += ` *\n * ${projectDescription}\n`; + code += ` *\n * ${docCommentText(projectDescription)}\n`; } code += ` */\n`; // Generate agent definitions - for (const agent of agents) { + for (const { agent, variableName } of definitions) { const displayName = agent.displayName || titleCase(agent.name); - code += `const ${agent.name} = defineAgent({\n`; - code += ` name: '${agent.name}',\n`; - code += ` role: '${agent.role}',\n`; - code += ` description: '${displayName}',\n`; + code += `const ${variableName} = defineAgent({\n`; + code += ` name: '${escapeSingleQuotedString(agent.name)}',\n`; + code += ` role: '${escapeSingleQuotedString(agent.role)}',\n`; + code += ` description: '${escapeSingleQuotedString(displayName)}',\n`; code += ` status: 'active',\n`; code += `});\n\n`; } @@ -448,13 +464,13 @@ function generateSDKBuilderConfig(options: InitOptions): string { code += `export default defineSquad({\n`; code += ` version: '1.0.0',\n\n`; code += ` team: defineTeam({\n`; - code += ` name: '${projectName}',\n`; + code += ` name: '${escapeSingleQuotedString(projectName)}',\n`; if (projectDescription) { - code += ` description: '${projectDescription.replace(/'/g, "\\'")}',\n`; + code += ` description: '${escapeSingleQuotedString(projectDescription)}',\n`; } - code += ` members: [${agents.map(a => `'${a.name}'`).join(', ')}],\n`; + code += ` members: [${agents.map(a => `'${escapeSingleQuotedString(a.name)}'`).join(', ')}],\n`; code += ` }),\n\n`; - code += ` agents: [${agents.map(a => a.name).join(', ')}],\n`; + code += ` agents: [${definitions.map(a => a.variableName).join(', ')}],\n`; code += `});\n`; return code; @@ -485,6 +501,8 @@ function generateSDKBuilderConfigWithRoles(options: InitOptions): string { const role = getRoleById(id)!; return { name: id, role: id, displayName: role.title }; }); + const roleDefinitions = effectiveRoleAgents.map((agent, index) => ({ agent, variableName: agentVariableName(agent.name, index) })); + const plainDefinitions = plainAgents.map((agent, index) => ({ agent, variableName: agentVariableName(agent.name, index + roleDefinitions.length) })); const needsDefineAgent = plainAgents.length > 0; const needsUseRole = effectiveRoleAgents.length > 0; @@ -496,49 +514,43 @@ function generateSDKBuilderConfigWithRoles(options: InitOptions): string { let code = `import {\n${imports.map(i => ` ${i},`).join('\n')}\n} from '@bradygaster/squad-sdk';\n\n`; - code += `/**\n * Squad Configuration — ${projectName}\n`; + code += `/**\n * Squad Configuration — ${docCommentText(projectName)}\n`; if (projectDescription) { - code += ` *\n * ${projectDescription}\n`; + code += ` *\n * ${docCommentText(projectDescription)}\n`; } code += ` *\n * Uses built-in base roles from the role catalog.\n`; code += ` * Customize names and overrides for your project.\n`; code += ` */\n\n`; // Generate useRole() definitions - for (const agent of effectiveRoleAgents) { - const varName = agent.name.replace(/-/g, '_'); - code += `const ${varName} = useRole('${agent.role}', {\n`; - code += ` name: '${agent.name}',\n`; + for (const { agent, variableName } of roleDefinitions) { + code += `const ${variableName} = useRole('${escapeSingleQuotedString(agent.role)}', {\n`; + code += ` name: '${escapeSingleQuotedString(agent.name)}',\n`; code += `});\n\n`; } // Generate plain defineAgent() definitions (for system agents like scribe/ralph) - for (const agent of plainAgents) { + for (const { agent, variableName } of plainDefinitions) { const displayName = agent.displayName || titleCase(agent.name); - code += `const ${agent.name} = defineAgent({\n`; - code += ` name: '${agent.name}',\n`; - code += ` role: '${agent.role}',\n`; - code += ` description: '${displayName}',\n`; + code += `const ${variableName} = defineAgent({\n`; + code += ` name: '${escapeSingleQuotedString(agent.name)}',\n`; + code += ` role: '${escapeSingleQuotedString(agent.role)}',\n`; + code += ` description: '${escapeSingleQuotedString(displayName)}',\n`; code += ` status: 'active',\n`; code += `});\n\n`; } // All agent variable names in order - const allVarNames = [ - ...effectiveRoleAgents.map(a => a.name.replace(/-/g, '_')), - ...plainAgents.map(a => a.name), - ]; - const allNames = [ - ...effectiveRoleAgents.map(a => `'${a.name}'`), - ...plainAgents.map(a => `'${a.name}'`), - ]; + const definitions = [...roleDefinitions, ...plainDefinitions]; + const allVarNames = definitions.map(({ variableName }) => variableName); + const allNames = definitions.map(({ agent }) => `'${escapeSingleQuotedString(agent.name)}'`); code += `export default defineSquad({\n`; code += ` version: '1.0.0',\n\n`; code += ` team: defineTeam({\n`; - code += ` name: '${projectName}',\n`; + code += ` name: '${escapeSingleQuotedString(projectName)}',\n`; if (projectDescription) { - code += ` description: '${projectDescription.replace(/'/g, "\\'")}',\n`; + code += ` description: '${escapeSingleQuotedString(projectDescription)}',\n`; } code += ` members: [${allNames.join(', ')}],\n`; code += ` }),\n\n`; @@ -632,6 +644,23 @@ function titleCase(str: string): string { * Stamp version into squad.agent.md content. * Replaces three locations: HTML comment, Identity Version line, and {version} placeholder. */ +function isSemVer(value: string): boolean { + const [withoutBuild, build, ...extraBuild] = value.split('+'); + if (extraBuild.length > 0) return false; + const validIdentifiers = (text: string, prerelease: boolean): boolean => + text.split('.').every((part) => + /^[0-9A-Za-z-]+$/.test(part) && + !(prerelease && /^\d+$/.test(part) && part.length > 1 && part.startsWith('0')) + ); + if (build !== undefined && !validIdentifiers(build, false)) return false; + const dash = withoutBuild!.indexOf('-'); + const core = dash === -1 ? withoutBuild! : withoutBuild!.slice(0, dash); + const prerelease = dash === -1 ? undefined : withoutBuild!.slice(dash + 1); + if (prerelease !== undefined && !validIdentifiers(prerelease, true)) return false; + const numbers = core.split('.'); + return numbers.length === 3 && numbers.every((part) => /^(?:0|[1-9]\d*)$/.test(part)); +} + function stampVersionInContent(content: string, version: string): string { // HTML comment: content = content.replace( @@ -645,8 +674,10 @@ function stampVersionInContent(content: string, version: string): string { ); // Greeting placeholder or an already-resolved valid SemVer literal. content = content.replace( - /`Squad v(?:\{version\}|(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)`/g, - `\`Squad v${version}\``, + /`Squad v(\{version\}|[0-9A-Za-z.+-]+)`/g, + (match, existing: string) => existing === '{version}' || isSemVer(existing) + ? `\`Squad v${version}\`` + : match, ); return content; } @@ -1065,8 +1096,7 @@ All findings logged to \`.squad/fact-checker/audit-trail.md\` (append-only, succ let detectedPlatform: string | undefined; try { const remoteUrl = execFileSync('git', ['remote', 'get-url', 'origin'], { cwd: teamRoot, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim(); - const remoteUrlLower = remoteUrl.toLowerCase(); - if (remoteUrlLower.includes('dev.azure.com') || remoteUrlLower.includes('visualstudio.com') || remoteUrlLower.includes('ssh.dev.azure.com')) { + if (detectPlatformFromUrl(remoteUrl) === 'azure-devops') { detectedPlatform = 'azure-devops'; } } catch { @@ -1463,8 +1493,7 @@ ${projectDescription ? `- **Description:** ${projectDescription}\n` : ''}- **Cre let isGitHub = true; try { const remoteUrl = execFileSync('git', ['remote', 'get-url', 'origin'], { cwd: teamRoot, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }).trim(); - const remoteUrlLower = remoteUrl.toLowerCase(); - if (remoteUrlLower.includes('dev.azure.com') || remoteUrlLower.includes('visualstudio.com') || remoteUrlLower.includes('ssh.dev.azure.com')) { + if (detectPlatformFromUrl(remoteUrl) === 'azure-devops') { isGitHub = false; } } catch { diff --git a/packages/squad-sdk/src/config/team-capabilities.ts b/packages/squad-sdk/src/config/team-capabilities.ts index 4050672fb..b6e3a31c8 100644 --- a/packages/squad-sdk/src/config/team-capabilities.ts +++ b/packages/squad-sdk/src/config/team-capabilities.ts @@ -170,6 +170,26 @@ const INJECTION_PATTERNS: readonly RegExp[] = [ * @param maxLength - Maximum rendered length (ellipsis added when clamped). * @returns A single-line, structure-safe string. */ +function withoutHtmlComments(value: string): string { + const parts: string[] = []; + let cursor = 0; + while (cursor < value.length) { + const open = value.indexOf('', close)) { close += 3; break; } + if (value.startsWith('--!>', close)) { close += 4; break; } + close++; + } + if (close === -1) return parts.join(''); + cursor = close; + } + parts.push(value.slice(cursor)); + return parts.join(''); +} + export function sanitizeMetadataText(raw: unknown, maxLength: number = MAX_SUMMARY_LENGTH): string { if (typeof raw !== 'string' || raw.length === 0) return ''; @@ -181,8 +201,8 @@ export function sanitizeMetadataText(raw: unknown, maxLength: number = MAX_SUMMA text = text.replace(CONTROL_CHARS, ' '); // HTML comments can smuggle markers, canaries, or directives. - text = text.replace(//g, ' '); - text = text.replace(//g, ' '); + text = withoutHtmlComments(text); + text = text.replaceAll('', ' ').replaceAll('--!>', ' '); // Then remove tag-shaped content and escape residual opening brackets. text = text.replace(/<[^<>\n]{0,200}>/g, ' '); text = text.replace(/#*+=~-]+/, ''); text = text.replace(/\s+/g, ' ').trim(); @@ -205,7 +225,9 @@ export function sanitizeMetadataText(raw: unknown, maxLength: number = MAX_SUMMA if (text.length > limit) { text = text.slice(0, Math.max(1, limit - 1)).trimEnd(); // Never leave a dangling escape from a clipped `\|`. - text = text.replace(/\\+$/, '').trimEnd(); + let end = text.length; + while (end > 0 && text[end - 1] === '\\') end--; + text = text.slice(0, end).trimEnd(); text += '…'; } return text; diff --git a/packages/squad-sdk/src/platform/comms-teams.ts b/packages/squad-sdk/src/platform/comms-teams.ts index c364cf52a..796be2d9b 100644 --- a/packages/squad-sdk/src/platform/comms-teams.ts +++ b/packages/squad-sdk/src/platform/comms-teams.ts @@ -778,7 +778,25 @@ function escapeHtml(s: string): string { } function stripHtml(html: string): string { - return html.replace(/<[^>]+>/g, '').replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').trim(); + const parts: string[] = []; + let cursor = 0; + while (cursor < html.length) { + const open = html.indexOf('<', cursor); + if (open === -1) break; + const close = html.indexOf('>', open + 1); + if (close === -1) break; + if (close === open + 1) { + parts.push(html.slice(cursor, close + 1)); + } else { + parts.push(html.slice(cursor, open)); + } + cursor = close + 1; + } + parts.push(html.slice(cursor)); + const entities: Record = { + ' ': ' ', '&': '&', '<': '<', '>': '>', '"': '"', + }; + return parts.join('').replace(/&(?:nbsp|amp|lt|gt|quot);/g, (entity) => entities[entity]!).trim(); } export { diff --git a/packages/squad-sdk/src/platform/detect.ts b/packages/squad-sdk/src/platform/detect.ts index 9620574c4..335f2aa1a 100644 --- a/packages/squad-sdk/src/platform/detect.ts +++ b/packages/squad-sdk/src/platform/detect.ts @@ -20,6 +20,10 @@ export interface AzureDevOpsRemoteInfo { repo: string; } +function stripGitSuffix(repo: string): string { + return repo.length > 4 && repo.toLowerCase().endsWith('.git') ? repo.slice(0, -4) : repo; +} + /** * Parse a GitHub remote URL into owner/repo. * Supports HTTPS and SSH formats: @@ -37,9 +41,9 @@ export function parseGitHubRemote(url: string): GitHubRemoteInfo | null { } // SSH: git@github.com:owner/repo.git - const sshMatch = url.match(/github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/i); + const sshMatch = url.match(/^(?:[^@\s/:]+@)?github\.com:([^/]+)\/([^/]+)$/i); if (sshMatch) { - return { owner: sshMatch[1]!, repo: sshMatch[2]! }; + return { owner: sshMatch[1]!, repo: stripGitSuffix(sshMatch[2]!) }; } return null; @@ -66,6 +70,8 @@ function decodeSegment(value: string): string { * https://org.visualstudio.com/project/_git/repo */ export function parseAzureDevOpsRemote(url: string): AzureDevOpsRemoteInfo | null { + if (detectPlatformFromUrl(url) !== 'azure-devops') return null; + // Repo capture allows dots in repo names; the literal `/_git/` segment keeps // the match anchored unambiguously. // HTTPS dev.azure.com: https://dev.azure.com/org/project/_git/repo @@ -89,10 +95,10 @@ export function parseAzureDevOpsRemote(url: string): AzureDevOpsRemoteInfo | nul // (Org subdomain keeps the no-dot constraint — the `.visualstudio.com` anchor // requires it. Only the repo capture is widened.) const vsMatch = url.match( - /([^/.]+)\.visualstudio\.com\/([^/]+)\/_git\/([^/]+?)(?:\.git)?$/i, + /^(?:https?|ssh|git):\/\/([^/.]+)\.visualstudio\.com\/([^/]+)\/_git\/([^/]+)$/i, ); if (vsMatch) { - return { org: decodeSegment(vsMatch[1]!), project: decodeSegment(vsMatch[2]!), repo: decodeSegment(vsMatch[3]!) }; + return { org: decodeSegment(vsMatch[1]!), project: decodeSegment(vsMatch[2]!), repo: decodeSegment(stripGitSuffix(vsMatch[3]!)) }; } return null; @@ -104,8 +110,21 @@ export function parseAzureDevOpsRemote(url: string): AzureDevOpsRemoteInfo | nul * Defaults to 'github' if unrecognized. */ export function detectPlatformFromUrl(url: string): PlatformType { - if (/github\.com/i.test(url)) return 'github'; - if (/dev\.azure\.com/i.test(url) || /\.visualstudio\.com/i.test(url) || /ssh\.dev\.azure\.com/i.test(url)) { + const scpRemote = url.match(/^(?:[^@\s/:]+@)?([^:/\s]+):(?=[^/])/); + let hostname: string; + if (scpRemote) { + hostname = scpRemote[1]!.toLowerCase(); + } else { + try { + const parsed = new URL(url); + if (!['http:', 'https:', 'ssh:', 'git:'].includes(parsed.protocol)) return 'github'; + hostname = parsed.hostname.toLowerCase(); + } catch { + return 'github'; + } + } + if (hostname === 'dev.azure.com' || hostname === 'ssh.dev.azure.com' || + (hostname.endsWith('.visualstudio.com') && hostname.length > '.visualstudio.com'.length)) { return 'azure-devops'; } return 'github'; diff --git a/packages/squad-sdk/src/ralph/triage.ts b/packages/squad-sdk/src/ralph/triage.ts index d1fa71df1..615a2d46c 100644 --- a/packages/squad-sdk/src/ralph/triage.ts +++ b/packages/squad-sdk/src/ralph/triage.ts @@ -283,11 +283,30 @@ function findColumnIndex(headers: string[], candidates: string[]): number { return -1; } +function stripMarkdownLinks(value: string): string { + const parts: string[] = []; + let cursor = 0; + while (cursor < value.length) { + const open = value.indexOf('[', cursor); + if (open === -1) break; + const close = value.indexOf(']', open + 1); + if (close === -1) break; + if (close === open + 1 || value[close + 1] !== '(' || value[close + 2] === ')') { + parts.push(value.slice(cursor, close + 1)); + cursor = close + 1; + continue; + } + const end = value.indexOf(')', close + 2); + if (end === -1) break; + parts.push(value.slice(cursor, open), value.slice(open + 1, close)); + cursor = end + 1; + } + parts.push(value.slice(cursor)); + return parts.join(''); +} + function cleanCell(value: string): string { - return value - .replace(/`/g, '') - .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') - .trim(); + return stripMarkdownLinks(value.replace(/`/g, '')).trim(); } function splitKeywords(examplesCell: string | undefined): string[] { @@ -321,8 +340,7 @@ function normalizeName(value: string): string { } function normalizeRouteDestination(value: string): string { - return value - .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') + return stripMarkdownLinks(value) .replace(/[*_`]/g, '') .replace(/\p{Extended_Pictographic}/gu, '') .replace(/[\u200d\ufe0f]/g, '') @@ -388,8 +406,26 @@ function routeMatch( 'agent', 'engineer', 'engineering', 'management', 'owner', 'specialist', 'system', 'work', ]); - const tokens = (value: string): string[] => - value.toLowerCase().match(/[a-z0-9]+(?:[+#.][a-z0-9+#.]*)?(? { + const text = value.toLowerCase(); + const result: string[] = []; + const isAlphanumeric = (code: number) => + (code >= 48 && code <= 57) || (code >= 97 && code <= 122); + let cursor = 0; + while (cursor < text.length) { + if (!isAlphanumeric(text.charCodeAt(cursor))) { + cursor++; + continue; + } + const start = cursor++; + while (cursor < text.length && + (isAlphanumeric(text.charCodeAt(cursor)) || '+#.'.includes(text[cursor]!))) cursor++; + let end = cursor; + while (end > start && text[end - 1] === '.') end--; + result.push(text.slice(start, end)); + } + return result; + }; const containsPhrase = (haystack: string[], needle: string[]): boolean => needle.length > 0 && needle.length <= haystack.length && diff --git a/packages/squad-sdk/src/resolution.ts b/packages/squad-sdk/src/resolution.ts index 0e3e5f16d..05ef428d8 100644 --- a/packages/squad-sdk/src/resolution.ts +++ b/packages/squad-sdk/src/resolution.ts @@ -211,7 +211,7 @@ export function resolveSquad(startDir?: string): string | null { /** * Platform config directory for Squad WITHOUT creating it (see {@link resolveGlobalSquadPath}). */ -function platformSquadConfigDir(): string | null { +function platformSquadConfigDir(canonicalize = true): string | null { try { const platform = process.platform; let base: string; @@ -222,10 +222,10 @@ function platformSquadConfigDir(): string | null { } else { base = process.env['XDG_CONFIG_HOME'] ?? path.join(os.homedir(), '.config'); } - // Canonicalize the PARENT only and append `squad` lexically: establishing the boundary must + // Resolve the PARENT only and append `squad` lexically: establishing the boundary must // never stat/read the retired profile directory itself. - const canonicalBase = canonicalDir(base); - return canonicalBase === null ? null : path.join(canonicalBase, 'squad'); + const resolvedBase = canonicalize ? canonicalDir(base) : path.resolve(base); + return resolvedBase === null ? null : path.join(resolvedBase, 'squad'); } catch { return null; } @@ -239,12 +239,15 @@ function platformSquadConfigDir(): string | null { * removes the key. */ export function isRetiredProfileTeamRoot(teamDir: string): boolean { - const target = canonicalDir(teamDir); + const resolved = path.resolve(teamDir); + const lexical = profileBoundary(false); + // Reject known profile paths before canonicalizing the target, which would probe the retired tree. + if (!lexical.homeDir || isRetiredProfilePath(resolved, lexical)) return true; const b = profileBoundary(); // Fail closed: an unresolvable target or an unknown boundary is treated as retired (never followed). - if (target === null || !b.homeDir) return true; - if (isProfileOwned(target, b)) return true; - return isAncestorOf(path.join(b.homeDir, '.squad'), target) || samePath(target, path.join(b.homeDir, '.squad')); + if (!b.homeDir || isRetiredProfilePath(resolved, b)) return true; + const target = canonicalTeamDirOutsideProfile(resolved, b); + return target === null || isRetiredProfilePath(target, b); } /** Directories that are never project squads: the home dir and the roaming SQUAD_HOME root. */ @@ -257,16 +260,17 @@ interface ProfileBoundary { configDir: string | null; } -function profileBoundary(): ProfileBoundary { +function profileBoundary(canonicalize = true): ProfileBoundary { + const resolveBoundary = canonicalize ? canonicalDir : (p: string) => path.resolve(p); let homeDir: string | null = null; - try { homeDir = canonicalDir(os.homedir()); } catch { homeDir = null; } + try { homeDir = resolveBoundary(os.homedir()); } catch { homeDir = null; } const envHome = process.env['SQUAD_HOME']; // SQUAD_HOME: canonicalize its parent and append the leaf lexically, so the boundary is // established without touching the roaming directory itself. const squadHome = envHome - ? (() => { const parent = canonicalDir(path.dirname(path.resolve(envHome))); return parent === null ? null : path.join(parent, path.basename(path.resolve(envHome))); })() + ? (() => { const parent = resolveBoundary(path.dirname(path.resolve(envHome))); return parent === null ? null : path.join(parent, path.basename(path.resolve(envHome))); })() : (homeDir ? path.join(homeDir, '.squad') : null); - return { homeDir, squadHome, configDir: platformSquadConfigDir() }; + return { homeDir, squadHome, configDir: platformSquadConfigDir(canonicalize) }; } /** A canonical path is "profile-owned" when it is the home dir itself, SQUAD_HOME (or below), or the platform config dir (or below). */ @@ -276,6 +280,67 @@ function isProfileOwned(canonical: string, b: ProfileBoundary): boolean { return under(b.squadHome) || under(b.configDir); } +function isRetiredProfilePath(target: string, b: ProfileBoundary): boolean { + return (b.homeDir !== null && samePath(target, b.homeDir)) || isRetiredProfileTree(target, b); +} + +function isRetiredProfileTree(target: string, b: ProfileBoundary): boolean { + const under = (root: string | null) => root !== null && (samePath(target, root) || isAncestorOf(root, target)); + return under(b.squadHome) || under(b.configDir) || under(b.homeDir && path.join(b.homeDir, '.squad')); +} + +/** Resolve aliases one component at a time, stopping before entering a retired profile tree. */ +function canonicalTeamDirOutsideProfile(dir: string, b: ProfileBoundary): string | null { + const absolute = path.resolve(dir); + const root = path.parse(absolute).root; + const pending = absolute.slice(root.length).split(path.sep).filter(Boolean) + .map(name => ({ name, required: false })).reverse(); + let current = root; + let linkCount = 0; + while (pending.length) { + const { name, required } = pending.pop()!; + if (name === '.') continue; + if (name === '..') { + current = path.dirname(current); + if (isRetiredProfileTree(current, b)) return null; + continue; + } + const candidate = path.join(current, name); + if (isRetiredProfileTree(candidate, b)) return null; + let candidateExists = false; + try { + const entry = fs.lstatSync(candidate); + candidateExists = true; + if (entry.isSymbolicLink()) { + if (++linkCount > 40) return null; + let target = fs.readlinkSync(candidate); + if (process.platform === 'win32') { + if (target.slice(0, 8).toLowerCase() === '\\\\?\\unc\\') target = `\\\\${target.slice(8)}`; + else if (target.startsWith('\\\\?\\')) target = target.slice(4); + } + const targetRoot = path.parse(target).root; + if (path.isAbsolute(target)) current = targetRoot; + else if (targetRoot) return null; + const parts = target.slice(targetRoot.length).split(process.platform === 'win32' ? /[\\/]+/ : /\/+/).filter(Boolean); + for (let i = parts.length - 1; i >= 0; i--) { + pending.push({ name: parts[i]!, required: true }); + } + continue; + } + current = fs.realpathSync.native(candidate); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (!candidateExists && (code === 'ENOENT' || code === 'ENOTDIR') && !required) { + const unresolved = path.join(candidate, ...pending.reverse().map(part => part.name)); + return isRetiredProfilePath(unresolved, b) ? null : unresolved; + } + return null; + } + if (isRetiredProfileTree(current, b)) return null; + } + return current; +} + /** * Canonical absolute form of a directory for boundary comparisons: resolves 8.3 short * names on Windows (`C:\PROGRA~1` vs `C:\Program Files`) and symlinked homes. @@ -772,15 +837,22 @@ export function scratchFile(squadRoot: string, prefix: string, ext: string = '.t * @param projectDir - Absolute path to the project root. * @returns A sanitized, lowercase project key suitable for use as a directory name. */ +function withoutEdgeHyphens(value: string): string { + let start = 0; + let end = value.length; + while (start < end && value[start] === '-') start++; + while (end > start && value[end - 1] === '-') end--; + return value.slice(start, end); +} + export function deriveProjectKey(projectDir: string): string { const normalized = projectDir.replace(/\\/g, '/'); const base = path.basename(normalized); if (!base) return 'unknown-project'; - const sanitized = base + const sanitized = withoutEdgeHyphens(base .toLowerCase() - .replace(/[^a-z0-9._-]/g, '-') - .replace(/^-+|-+$/g, ''); + .replace(/[^a-z0-9._-]/g, '-')); return sanitized || 'unknown-project'; } @@ -807,10 +879,9 @@ export function resolveExternalStateDir(projectKey: string, create: boolean = tr } // Sanitize: replace path separators and unsafe chars with dashes - const sanitized = projectKey + const sanitized = withoutEdgeHyphens(projectKey .replace(/[/\\]/g, '-') - .replace(/[^a-zA-Z0-9._-]/g, '-') - .replace(/^-+|-+$/g, ''); + .replace(/[^a-zA-Z0-9._-]/g, '-')); if (!sanitized) { throw new Error('Invalid project key'); diff --git a/packages/squad-sdk/src/state-backend.ts b/packages/squad-sdk/src/state-backend.ts index 228c4bc48..a8f312154 100644 --- a/packages/squad-sdk/src/state-backend.ts +++ b/packages/squad-sdk/src/state-backend.ts @@ -502,8 +502,14 @@ export function validateStateKey(key: string): void { } +function withoutTrailingSlashes(value: string): string { + let end = value.length; + while (end > 0 && value[end - 1] === '/') end--; + return value.slice(0, end); +} + function normalizeKey(relativePath: string): string { - const normalized = relativePath.replace(/\\/g, '/').replace(/^\/+/, '').replace(/\/+$/, ''); + const normalized = withoutTrailingSlashes(relativePath.replace(/\\/g, '/').replace(/^\/+/, '')); // Empty string after normalization means "root" — valid for list() operations if (normalized.length > 0) { validateStateKey(normalized); @@ -1225,9 +1231,7 @@ export class StateBackendStorageAdapter implements StorageProvider { } if (!path.isAbsolute(filePath)) { - const relative = slashPath - .replace(/^(?:\.\/)+/, '') - .replace(/\/+$/, ''); + const relative = withoutTrailingSlashes(slashPath.replace(/^(?:\.\/)+/, '')); return relative.length === 0 ? this.resolveRoot(options) : relative; } diff --git a/packages/squad-sdk/src/storage/in-memory-storage-provider.ts b/packages/squad-sdk/src/storage/in-memory-storage-provider.ts index 0053249cb..cd66e1efe 100644 --- a/packages/squad-sdk/src/storage/in-memory-storage-provider.ts +++ b/packages/squad-sdk/src/storage/in-memory-storage-provider.ts @@ -16,7 +16,8 @@ export class InMemoryStorageProvider implements StorageProvider { private norm(p: string): string { // Convert Windows backslashes to forward slashes before POSIX normalization // so that paths from path.join() on Windows match stored POSIX keys. - return posix.normalize(p.replace(/\\/g, '/')).replace(/\/+$/, ''); + const normalized = posix.normalize(p.replace(/\\/g, '/')); + return normalized.endsWith('/') ? normalized.slice(0, -1) : normalized; } async createIfAbsent(filePath: string, data: string): Promise { diff --git a/test/clients.test.ts b/test/clients.test.ts index baf01571f..d09b0fce7 100644 --- a/test/clients.test.ts +++ b/test/clients.test.ts @@ -216,7 +216,7 @@ describe('shared files and TOML helper', () => { it('upsertTomlTable creates, updates and keeps neighbors', () => { expect(upsertTomlTable('', 't.x', { a: '"1"' })).toBe('[t.x]\na = "1"\n'); const out = upsertTomlTable('k = 1\n[t.x]\na = "0"\nz = 2\n[t.y]\nq = 3\n', 't.x', { a: '"1"', b: '[]' }); - expect(out).toBe('k = 1\n[t.x]\na = "1"\nz = 2\nb = []\n[t.y]\nq = 3\n'.replace(/\n$/, '\n')); + expect(out).toBe('k = 1\n[t.x]\na = "1"\nz = 2\nb = []\n[t.y]\nq = 3\n'); }); it('all expands to every client including codex and antigravity', () => { expect(parseClients('all')).toEqual(expect.arrayContaining(['codex', 'antigravity'])); diff --git a/test/comms-teams.test.ts b/test/comms-teams.test.ts index 5dd427f73..e754ae7cc 100644 --- a/test/comms-teams.test.ts +++ b/test/comms-teams.test.ts @@ -81,6 +81,11 @@ describe('stripHtml', () => { it('handles combined tags and entities', () => { expect(stripHtml('

Tom & Jerry <3

')).toBe('Tom & Jerry <3'); }); + + it('decodes entities once and does not assemble a tag when stripping nested markup', () => { + expect(stripHtml('&lt;script&gt;')).toBe('<script>'); + expect(stripHtml('hello <script>')).toBe('hello script>'); + }); }); // ─── formatTeamsMessage ────────────────────────────────────────────── diff --git a/test/init-scaffolding.test.ts b/test/init-scaffolding.test.ts index 97d84aefc..1775086be 100644 --- a/test/init-scaffolding.test.ts +++ b/test/init-scaffolding.test.ts @@ -427,6 +427,8 @@ describe('squad.agent.md template handling (#730)', () => { '`Squad velocity`', '`Squad v1.2`', '`Squad v01.2.3`', + '`Squad v1.2.3-01`', + '`Squad v1.2.3+build..7`', ]; const templateStorage = new Proxy(realStorage, { diff --git a/test/init-sdk.test.ts b/test/init-sdk.test.ts index 1aa57e4ee..8c97cccc1 100644 --- a/test/init-sdk.test.ts +++ b/test/init-sdk.test.ts @@ -14,6 +14,8 @@ import { mkdtemp, rm, readFile, readdir, access } from 'fs/promises'; import { join } from 'path'; import { tmpdir } from 'os'; import { existsSync } from 'fs'; +import { runInNewContext } from 'node:vm'; +import ts from 'typescript'; // Import initSquad from SDK // Note: initSquad lives at packages/squad-sdk/src/config/init.ts @@ -256,6 +258,102 @@ describe('squad init --sdk flag', () => { expect(configContent).toContain('Test Squad'); }); + it.each([false, true])('escapes project metadata in SDK config (roles=%s)', async (roles) => { + const projectName = "Team\\'name"; + const projectDescription = "Line \\'one\n*/ globalThis.injected = true; /*\u2028next"; + await initSquad({ + teamRoot: tempDir, + projectName, + projectDescription, + agents: [{ name: 'edie', role: 'Engineer' }], + configFormat: 'sdk', + roles, + }); + + const content = await readFile(join(tempDir, 'squad.config.ts'), 'utf-8'); + const parsed = ts.createSourceFile('squad.config.ts', content, ts.ScriptTarget.Latest, true); + const literals: string[] = []; + const visit = (node: ts.Node) => { + if (ts.isStringLiteral(node)) literals.push(node.text); + ts.forEachChild(node, visit); + }; + visit(parsed); + expect(ts.transpileModule(content, { reportDiagnostics: true }).diagnostics).toEqual([]); + expect(literals).toContain(projectName); + expect(literals).toContain(projectDescription); + expect(content).toContain('* / globalThis.injected'); + }); + + it.each([false, true])('generates safe SDK configs for arbitrary agent fields (roles=%s)', async (roles) => { + const agents = [ + { name: 'lead-agent', role: 'lead' }, + { name: "name'; globalThis.injected = true; //", role: "role\\'name\nnext", displayName: "Display\\'name\u2028next" }, + { name: 'class', role: 'worker' }, + { name: 'defineSquad', role: 'worker' }, + { name: 'a-b', role: 'worker' }, + { name: 'a_b', role: 'worker' }, + { name: 'class', role: 'worker' }, + ]; + await initSquad({ + teamRoot: tempDir, + projectName: 'test-squad', + agents, + configFormat: 'sdk', + roles, + linkedTeam: true, + }); + + const content = await readFile(join(tempDir, 'squad.config.ts'), 'utf-8'); + const compiled = ts.transpileModule(content, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, + reportDiagnostics: true, + }); + expect(compiled.diagnostics?.map(d => ts.flattenDiagnosticMessageText(d.messageText, '\n'))).toEqual([]); + const sdk = { + defineSquad: (value: unknown) => value, + defineTeam: (value: unknown) => value, + defineAgent: (value: unknown) => value, + useRole: (role: string, value: object) => ({ role, ...value }), + }; + const sandbox: { exports: Record; require: () => typeof sdk; injected?: boolean } = { + exports: {}, + require: () => sdk, + }; + runInNewContext(compiled.outputText, sandbox); + expect(sandbox.injected).toBeUndefined(); + const result = sandbox.exports.default as { + team: { members: string[] }; + agents: Array<{ name: string; role: string; description?: string }>; + }; + expect(Array.from(result.team.members)).toEqual(agents.map(agent => agent.name)); + expect(Array.from(result.agents, agent => agent.name)).toEqual(agents.map(agent => agent.name)); + expect(Array.from(result.agents, agent => agent.role)).toEqual(agents.map(agent => agent.role)); + expect(result.agents[1]?.description).toBe(agents[1]?.displayName); + }); + + it('escapes agent names in legacy TypeScript routing config', async () => { + const name = "agent\\'; globalThis.injected = true; //"; + await initSquad({ + teamRoot: tempDir, + projectName: 'test-squad', + agents: [{ name, role: 'developer' }], + configFormat: 'typescript', + linkedTeam: true, + }); + + const content = await readFile(join(tempDir, 'squad.config.ts'), 'utf-8'); + const compiled = ts.transpileModule(content, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, + reportDiagnostics: true, + }); + expect(compiled.diagnostics?.map(d => ts.flattenDiagnosticMessageText(d.messageText, '\n'))).toEqual([]); + const sandbox: { exports: Record; injected?: boolean } = { exports: {} }; + runInNewContext(compiled.outputText, sandbox); + expect(sandbox.injected).toBeUndefined(); + const result = sandbox.exports.default as { routing: { rules: Array<{ agents: string[] }> } }; + expect(Array.from(result.routing.rules, rule => rule.agents[0])).toEqual(Array(4).fill(`@${name}`)); + }); + // ── --sdk --roles integration (#378) ──────────────────────────────── it('init --sdk --roles uses useRole() instead of defineAgent()', async () => { diff --git a/test/migrate.test.ts b/test/migrate.test.ts index 6ce425dc4..6f67642fc 100644 --- a/test/migrate.test.ts +++ b/test/migrate.test.ts @@ -14,6 +14,8 @@ import { mkdtemp, rm, readFile, writeFile, mkdir } from 'fs/promises'; import { join } from 'path'; import { tmpdir } from 'os'; import { existsSync } from 'fs'; +import { Script } from 'node:vm'; +import { runMigrate } from '../packages/squad-cli/src/cli/commands/migrate.js'; // Note: migrate function location TBD - adjust import when implementation lands // Expected at packages/squad-sdk/src/config/migration.ts or cli command @@ -126,6 +128,80 @@ export default defineSquad({ */ }); + it('preserves quotes and backslashes in generated member, charter, and routing strings', async () => { + await createMarkdownSquad(tempDir); + const member = String.raw`o'brien\agent`; + const universe = String.raw`space's\stories`; + await writeFile(join(tempDir, '.squad', 'team.md'), [ + '# Squad Team — Test', + '## Members', + '| Name | Role | Assignment | Status |', + '| --- | --- | --- | --- |', + `| ${member} | Developer | Project | Active |`, + ].join('\n'), 'utf-8'); + await writeFile(join(tempDir, '.squad', 'routing.md'), [ + '## Work Type', + '| Work Type | Agent | Example |', + '| --- | --- | --- |', + String.raw`| Owner's \project | Edie | Owner's \files |`, + ].join('\n'), 'utf-8'); + await mkdir(join(tempDir, '.squad', 'casting')); + await writeFile(join(tempDir, '.squad', 'casting', 'policy.json'), JSON.stringify({ + allowlist_universes: [universe], + universe_capacity: { [universe]: 3 }, + }), 'utf-8'); + + await runMigrate(tempDir, { to: 'sdk' }); + const config = await readFile(join(tempDir, 'squad.config.ts'), 'utf-8'); + const body = config.slice(config.indexOf("} from '@bradygaster/squad-sdk';") + "} from '@bradygaster/squad-sdk';".length) + .replace('export default ', 'globalThis.result = '); + interface GeneratedConfig { + team: { members: string[] }; + agents: Array<{ name: string; charter: string }>; + routing: { rules: Array<{ pattern: string; description: string }> }; + casting: { allowlistUniverses: string[]; capacity: Record }; + } + const identity = (value: T): T => value; + const context: { + result?: GeneratedConfig; + defineSquad: typeof identity; + defineTeam: typeof identity; + defineAgent: typeof identity; + defineRouting: typeof identity; + defineCasting: typeof identity; + } = { + defineSquad: identity, defineTeam: identity, defineAgent: identity, + defineRouting: identity, defineCasting: identity, + }; + new Script(body).runInNewContext(context, { timeout: 1000 }); + + expect(context.result?.team.members).toEqual([member]); + expect(context.result?.agents[0]).toMatchObject({ + name: member, + charter: `.squad/agents/${member}/charter.md`, + }); + expect(context.result?.routing.rules[0]).toMatchObject({ + pattern: String.raw`owner's-\project`, + description: String.raw`Owner's \files`, + }); + expect(context.result?.casting).toMatchObject({ + allowlistUniverses: [universe], + capacity: { [universe]: 3 }, + }); + }); + + it('rejects nonnumeric casting capacities instead of generating executable input', async () => { + await createMarkdownSquad(tempDir); + await mkdir(join(tempDir, '.squad', 'casting')); + await writeFile(join(tempDir, '.squad', 'casting', 'policy.json'), JSON.stringify({ + allowlist_universes: ['example'], + universe_capacity: { example: '0}; globalThis.compromised = true; //' }, + }), 'utf-8'); + + await expect(runMigrate(tempDir, { to: 'sdk' })).rejects.toThrow("Casting capacity for 'example' must be a finite number"); + expect(existsSync(join(tempDir, 'squad.config.ts'))).toBe(false); + }); + it('--to sdk --dry-run prints preview without writing', async () => { await createMarkdownSquad(tempDir); diff --git a/test/platform-adapter.test.ts b/test/platform-adapter.test.ts index 1deec6678..b8744ca15 100644 --- a/test/platform-adapter.test.ts +++ b/test/platform-adapter.test.ts @@ -44,6 +44,23 @@ describe('detectPlatformFromUrl', () => { expect(detectPlatformFromUrl('https://myorg.visualstudio.com/myproject/_git/myrepo')).toBe('azure-devops'); }); + it.each([ + 'https://dev.azure.com.attacker.example/org/project/_git/repo', + 'https://attacker.example/dev.azure.com/org/project/_git/repo', + 'https://dev.azure.com@attacker.example/org/project/_git/repo', + 'git@ssh.dev.azure.com.attacker.example:v3/org/project/repo', + 'https://attacker-visualstudio.com/project/_git/repo', + 'file://dev.azure.com/org/project/_git/repo', + ])('does not trust Azure-looking text outside the remote host: %s', (url) => { + expect(detectPlatformFromUrl(url)).toBe('github'); + expect(parseAzureDevOpsRemote(url)).toBeNull(); + }); + + it('detects an SSH URL with a port and a GitHub-looking path on Azure', () => { + expect(detectPlatformFromUrl('ssh://git@ssh.dev.azure.com:22/v3/org/project/repo')).toBe('azure-devops'); + expect(detectPlatformFromUrl('https://dev.azure.com/org/github.com/_git/repo')).toBe('azure-devops'); + }); + it('defaults to github for unknown remotes', () => { expect(detectPlatformFromUrl('https://gitlab.com/owner/repo.git')).toBe('github'); }); @@ -80,6 +97,10 @@ describe('parseGitHubRemote', () => { expect(result).toEqual({ owner: 'owner', repo: 'repo' }); }); + it('does not parse an SSH host that merely ends with github.com', () => { + expect(parseGitHubRemote('git@notgithub.com:owner/repo.git')).toBeNull(); + }); + it('returns null for non-GitHub URLs', () => { expect(parseGitHubRemote('https://dev.azure.com/org/project/_git/repo')).toBeNull(); }); @@ -151,6 +172,12 @@ describe('parseAzureDevOpsRemote', () => { expect(result).toEqual({ org: 'contoso', project: 'WebApp', repo: 'frontend' }); }); + it('parses a long legacy organization without backtracking', () => { + const org = 'a'.repeat(10_000); + const result = parseAzureDevOpsRemote(`https://${org}.visualstudio.com/WebApp/_git/frontend.git`); + expect(result).toEqual({ org, project: 'WebApp', repo: 'frontend' }); + }); + it('returns null for GitHub URLs', () => { expect(parseAzureDevOpsRemote('https://github.com/owner/repo.git')).toBeNull(); }); diff --git a/test/profile-boundary.test.ts b/test/profile-boundary.test.ts index 8d1f2e9fa..24382ea28 100644 --- a/test/profile-boundary.test.ts +++ b/test/profile-boundary.test.ts @@ -176,15 +176,81 @@ describe('profile boundary: only the profile itself is rejected', () => { expect(resolveSquad(path.dirname(neighbour))).toBe(neighbour); }); + it('rejects legacy profile team roots without probing the profile tree', () => { + const configHome = path.join(tmp, 'profile-config'); + const profileRoot = path.join(configHome, 'squad'); + fs.mkdirSync(path.join(profileRoot, '.squad'), { recursive: true }); + const neighbour = path.join(configHome, 'neighbour'); + fs.mkdirSync(neighbour); + + const alias = path.join(tmp, 'profile-config-link'); + const configuredHome = tryLink(configHome, alias) ? alias : configHome; + vi.stubEnv('APPDATA', configuredHome); + vi.stubEnv('LOCALAPPDATA', configuredHome); + vi.stubEnv('XDG_CONFIG_HOME', configuredHome); + const configuredRoot = path.join(configuredHome, 'squad'); + const homeSquad = mkSquad(fakeHome); + const roaming = path.join(tmp, 'roaming'); + fs.mkdirSync(roaming); + vi.stubEnv('SQUAD_HOME', roaming); + const roots = [profileRoot, configuredRoot, homeSquad, roaming]; + const linkedProfile = path.join(tmp, 'linked-profile'); + const profileLinkAvailable = tryLink(profileRoot, linkedProfile); + const chainedProfile = path.join(tmp, 'chained-profile'); + const profileChainAvailable = profileLinkAvailable && tryLink(linkedProfile, chainedProfile); + const spellings = (p: string) => [p, path.join(fs.realpathSync.native(path.dirname(p)), path.basename(p))]; + const probeRoots = roots.flatMap(spellings); + const profileLinks = (profileLinkAvailable ? [linkedProfile, ...(profileChainAvailable ? [chainedProfile] : [])] : []) + .flatMap(spellings); + const homeProject = path.join(fakeHome, 'src', 'project'); + fs.mkdirSync(homeProject, { recursive: true }); + const linkedProject = path.join(tmp, 'linked-project'); + const projectLinkAvailable = tryLink(homeProject, linkedProject); + const lstat = vi.spyOn(fs, 'lstatSync'); + const realpath = vi.spyOn(fs.realpathSync, 'native'); + try { + for (const root of roots) { + expect(isRetiredProfileTeamRoot(root)).toBe(true); + expect(isRetiredProfileTeamRoot(path.join(root, '.squad'))).toBe(true); + } + expect(isRetiredProfileTeamRoot(neighbour)).toBe(false); + expect(isRetiredProfileTeamRoot(homeProject)).toBe(false); + if (projectLinkAvailable) { + expect(isRetiredProfileTeamRoot(linkedProject)).toBe(false); + expect(isRetiredProfileTeamRoot(path.join(linkedProject, 'future-team'))).toBe(false); + } + if (profileLinkAvailable) { + expect(isRetiredProfileTeamRoot(linkedProfile)).toBe(true); + expect(isRetiredProfileTeamRoot(path.join(linkedProfile, '.squad'))).toBe(true); + if (profileChainAvailable) expect(isRetiredProfileTeamRoot(chainedProfile)).toBe(true); + expect(realpath.mock.calls.map(([p]) => String(p)).filter(p => profileLinks.includes(p))).toEqual([]); + } + const probes = [...lstat.mock.calls, ...realpath.mock.calls] + .map(([p]) => String(p)) + .filter((p) => probeRoots.some((root) => { + const rel = path.relative(root, p); + return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)); + })); + expect(probes).toEqual([]); + } finally { + lstat.mockRestore(); + realpath.mockRestore(); + } + }); + it('canonicalization failure is fail-closed: the resolver refuses instead of comparing lexically (LC-12)', () => { const proj = path.join(fakeHome, 'src', 'proj'); const projSquad = mkSquad(proj); + const canonicalProj = fs.realpathSync.native(proj); clearResolveSquadCache(); expect(resolveSquad(proj)).toBe(projSquad); // Make canonicalization of this project fail (broken reparse point / EACCES on a parent in real life). const native = fs.realpathSync.native; + let errorCode = 'EACCES'; const spy = vi.spyOn(fs.realpathSync, 'native').mockImplementation(((p: fs.PathLike, ...rest: unknown[]) => { - if (String(p).toLowerCase().startsWith(proj.toLowerCase())) throw Object.assign(new Error('EACCES: cannot canonicalize'), { code: 'EACCES' }); + if ([proj, canonicalProj].some(root => String(p).toLowerCase().startsWith(root.toLowerCase()))) { + throw Object.assign(new Error(`${errorCode}: cannot canonicalize`), { code: errorCode }); + } return (native as (...a: unknown[]) => string)(p, ...rest); }) as typeof fs.realpathSync.native); try { @@ -192,6 +258,8 @@ describe('profile boundary: only the profile itself is rejected', () => { expect(resolveSquad(proj), 'unresolvable path must not be admitted lexically').toBeNull(); expect(resolveSquadPaths(proj)).toBeNull(); expect(isRetiredProfileTeamRoot(proj), 'an unresolvable teamRoot is never followed').toBe(true); + errorCode = 'ENOENT'; + expect(isRetiredProfileTeamRoot(proj), 'a disappeared existing path is never followed').toBe(true); } finally { spy.mockRestore(); } @@ -199,6 +267,20 @@ describe('profile boundary: only the profile itself is rejected', () => { expect(resolveSquad(proj), 'back to normal once canonicalization works').toBe(projSquad); }); + it('refuses broken and cyclic team-root links', (ctx) => { + const broken = path.join(tmp, 'broken-team'); + const first = path.join(tmp, 'first-link'); + const second = path.join(tmp, 'second-link'); + if (!tryLink(path.join(tmp, 'missing-target'), broken) + || !tryLink(second, first) + || !tryLink(first, second)) { + ctx.skip(); + return; + } + expect(isRetiredProfileTeamRoot(broken)).toBe(true); + expect(isRetiredProfileTeamRoot(first)).toBe(true); + }); + it('USERPROFILE/HOME pointing at a different directory moves the boundary with it', () => { const otherHome = path.join(tmp, 'other-home'); fs.mkdirSync(path.join(otherHome, 'work'), { recursive: true }); diff --git a/test/ralph-triage.test.ts b/test/ralph-triage.test.ts index c7efb3f76..e7490ba70 100644 --- a/test/ralph-triage.test.ts +++ b/test/ralph-triage.test.ts @@ -368,6 +368,15 @@ describe('triageIssue()', () => { expect(decision?.source).toBe('routing-rule'); }); + it.each(['C++', 'C#', 'Node.js'])('matches punctuated technology keywords: %s', (keyword) => { + const technologyRule: RoutingRule[] = [ + { workType: 'Technology', agentName: 'Runtime Engineer', keywords: [keyword] }, + ]; + const decision = triageIssue(issue(`Investigate ${keyword}...`), technologyRule, [], roster); + expect(decision?.source).toBe('routing-rule'); + expect(decision?.agent.name).toBe('Runtime Engineer'); + }); + it('prefers longer module path match (src/ralph/ over src/)', () => { const customModules: ModuleOwnership[] = [ { modulePath: 'src/', primary: 'Team Lead', secondary: null }, diff --git a/test/team-capabilities.test.ts b/test/team-capabilities.test.ts index 0bc242abc..1b58d4313 100644 --- a/test/team-capabilities.test.ts +++ b/test/team-capabilities.test.ts @@ -517,6 +517,7 @@ describe('#1608 — malformed, empty and unknown metadata', () => { describe('#1608 — sanitization of untrusted metadata', () => { it('escapes table pipes so a hostile value cannot forge columns', () => { expect(sanitizeMetadataText('a | b')).toBe('a \\| b'); + expect(sanitizeMetadataText('a\\|b')).toBe('a\\\\\\|b'); }); it('strips HTML comments, tags, and canary/marker tokens', () => { @@ -526,6 +527,9 @@ describe('#1608 — sanitization of untrusted metadata', () => { // Tags are removed; any inert inner text survives as plain prose. expect(sanitizeMetadataText('done')).toBe('x done'); expect(sanitizeMetadataText('SQUAD:TEAM-CAPABILITIES:END')).toBe('[redacted]'); + expect(sanitizeMetadataText('safe tail')).toBe('safe tail'); + expect(sanitizeMetadataText('safe tail')).toBe('safe tail'); + expect(sanitizeMetadataText('safe