* test(#3897): failing-first coverage for §8.3 rungs 2-4 ADR-3473 §8.3 has four rungs; #3883/PR #3896 shipped the first. This pins the other three RED before any fix. Rung 2 — the install marker has four readers and resolveRuntime is not one. resolveRuntime resolves GSD_RUNTIME > config.runtime > 'claude' and reads no marker at all, while bin/install.js writes one (#2297) and FOUR hand-rolled readInstallRuntimeMarker copies exist: src/model-resolver.cts:65 (cached, with test seams), hooks/gsd-agent-isolation-guard.js:112, and TWICE in hooks/gsd-cursor-subagent-start.js at :346 and :355. Four copies of one rule. Fixtures and seam names mined from PR #3382 rather than re-derived; it implemented this rung and was closed "not on the merits". Rung 3 — the sandbox map, and the fallback that was the real defect. Measured across all 35 files in agents/, deriving workspace-write iff tools: declares Write or Edit: - all 11 CODEX_AGENT_SANDBOX entries derive to their mapped value exactly, zero disagreements — the map carries nothing the contract does not - 24 roles fall through `|| 'read-only'`, of which 16 declare Write or Edit So the map is redundant and the silent fallback is the defect. The maintainer chose to derive but hold those 16 at read-only pending the question of whether Codex enforces sandbox_mode or merely advises; HALT.md records it. T20 asserts the emitted sandbox_mode PER ROLE against a captured baseline, not in aggregate — an aggregate passes while one role silently widens, which is the proxy-instead-of-identity shape this repo names. T24 and T25 fail on a stale hold, so the hold list cannot rot into the subset map being deleted. Rung 4 — shortFormToId, recovered rather than invented. I nearly reported this as another wrong §8.3 claim: `git log -S shortFormToId` returns only documentation commits. That was the wrong instrument. Direct inspection of sdk/src/query/phase.ts at 11918dcc3^ shows five occurrences, and the tests match that code rather than a guess at its semantics — including first-write-wins on a duplicate short form. T43 asserts at the consumer's output: the emitted `waves` map from the real CLI, which pre-fix collapses to {"1":[...]} because every short-form edge is dropped. A unit assertion on resolveDependencyId would have passed throughout this defect's life. Observed RED, this tree: rung 2 11/11 fail — no marker rung, no seams rung 3 T23,T24,T25,T26,T30 fail; T28 fails (validate agents passes a TOML whose sandbox_mode disagrees — it checks presence only) rung 4 T42,T44 fail; T43,T49 fail with waves collapsed to a single wave 1 Green and staying green: T20/T21/T22/T27 as captured baselines, #3885's unresolvable-token warning and wave-verdict suppression, and #3785's display-mapping passthrough. If the third tier over-reaches, those go red — that is their job. Disclosed weakness: T45 (a canonical id with no dash is not short-form indexed) cannot be isolated behaviorally, because planMap always masks it. It is a non-crash boundary pin, weaker than the other rows, and is recorded as such rather than presented as equivalent. Design: .gsd/phase/feat-3897-adr3473-83-rungs/40-design.md Test matrix: .gsd/phase/feat-3897-adr3473-83-rungs/50-test-matrix.md Decision: .gsd/phase/feat-3897-adr3473-83-rungs/HALT.md Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * enhance(#3897): §8.3 rungs 2-4 — one marker reader, a derived sandbox, the third depends_on tier ADR-3473 §8.3 has four rungs. #3883/PR #3896 shipped the first. These are the other three. Rung 2 — the install marker had four readers, and resolveRuntime was not one. resolveRuntime resolved GSD_RUNTIME > config.runtime > 'claude' and read no marker, while bin/install.js writes one (#2297) and four hand-rolled readInstallRuntimeMarker copies existed: src/model-resolver.cts (cached, with seams), hooks/gsd-agent-isolation-guard.js, and twice in hooks/gsd-cursor-subagent-start.js. model-resolver's was already the house idiom, so it was promoted rather than replaced: src/runtime-slash.cts now owns it, and model-resolver plus both hooks delegate. The hooks reach it through ensureRuntimeBuild(), the seam lint-hooks-runtime-build-seam enforces. No import cycle existed - checked both directions before moving anything. The marker is the THIRD rung: env > project config > marker > 'claude'. N1 was checked rather than assumed, and my first reading of it was wrong. A marker holding an unknown name comes back essentially verbatim, which looked like a validation gap. Measured against the env rung with the same inputs - including "../../etc/passwd" and "claude;rm -rf /" - the two are identical, because they share resolveRuntimeNameFromCandidates. N1 asks for exactly that, and it is met. The residual (the shared normalizer normalizes shape, it does not validate against the known-runtime set) is pre-existing on the env rung and plausibly deliberate, since a new runtime should not need a code change. The marker also does not widen the trust boundary in any real sense: it lives inside the install tree beside the code, so anyone who can write it can write runtime-slash.cjs itself. Rung 3 — the map was redundant; the silent fallback was the defect. Measured across all 35 files in agents/, deriving workspace-write iff tools: declares Write or Edit: all 11 CODEX_AGENT_SANDBOX entries derive to their mapped value exactly, zero disagreements. The map carried nothing the contract did not already have, so it is DELETED rather than reconciled. What was actually broken is `|| 'read-only'`, which silently under-granted 24 of 35 roles. 16 of those 24 declare Write or Edit and would widen under derivation. Per the maintainer's decision (HALT.md), they are held at read-only pending the question of whether Codex enforces sandbox_mode or merely advises. Emitted TOML is therefore byte-identical for all 35 roles - asserted per role, not in aggregate, because an aggregate passes while one role silently widens. The hold list self-invalidates. A hold whose role no longer derives broader fails, and so does a hold naming a role with no agents/<name>.md. Without that it would rot into exactly the hand-maintained subset map being deleted, and this commit's own ledger claim would become false over time. Both cases were proved by injecting them and watching them throw. Two committed tests asserted the deleted map's existence and contents. They were pinning the thing being removed, so the tests moved rather than the production code: the 11 role-value pairs survive as a test-local PRE_3897_CODEX_AGENT_SANDBOX baseline, and the assertions now drive the real derivation against real agents/*.md. The coverage is preserved; only its source moved out of production code. validate agents gains checkCodexSandboxPosture, mirroring the existing checkCodexModelPosture: each installed TOML's sandbox_mode must equal the role's expected value, failing with role, expected and found. It previously checked file presence and manifest completeness only, so a TOML whose sandbox_mode disagreed passed. Rung 4 — shortFormToId, recovered rather than invented. I nearly reported this as another wrong §8.3 claim: git log -S returns only documentation commits. Wrong instrument. sdk/src/query/phase.ts at 11918dcc3^ carries five occurrences, and the implementation here matches that code rather than a guess at its semantics - including first-write-wins on a duplicate short form, deterministic from the sorted plan order. It resolves the bare plan number: depends_on: ["01"] now reaches 26-01-auth-hardening. That is a control-flow change, not a diagnostic one - plans that silently collapsed into a single wave 1 now execute in their declared waves, and execute-phase.md consumes those wave values. In-phase only, by construction: the map is built from this phase's rawPlans, so a same-named short form in another phase does not resolve. #3785's display-mapping passthrough and #3885's unresolvable-token warning and wave-verdict suppression are untouched and stay green. If the third tier had over-reached, those are what would have caught it. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3897): close a fail-open I introduced, and wire the posture check to its command Two blockers from review. Both are mine, and one is a security regression my own change created. 1. A held role could escape its hold by editing its own frontmatter. The Codex install loop set the sandbox identity from the agent's frontmatter `name:` field rather than from its filename, so the hold lookup keyed off a value the file itself declares: deriveCodexSandboxMode('gsd-doc-writer', <real file>) -> read-only deriveCodexSandboxMode('gsd-doc-writer-x', <same file, name: edited>) -> workspace-write deriveCodexSandboxMode('GSD-Doc-Writer', <same file, name: recased>) -> workspace-write What makes this a blocker rather than a nit is the DIRECTION. The deleted CODEX_AGENT_SANDBOX map had the identical lookup-key quirk, but it was an allowlist: an unmatched key fell back to read-only, which is safe. The new scheme derives workspace-write from the tool contract and uses the hold as a subtraction, so the same mismatch fails OPEN. I converted a fail-closed quirk into a fail-open one and did not notice; the isolated reviewer proved it by execution. Neither safety net caught it. validateCodexSandboxHolds only checks that <key>.md exists, never that a file's derived identity matches its key. checkCodexSandboxPosture looks the canonical source up by the installed TOML's filename, finds nothing for a renamed agent, and treats it as a custom non-roster agent — silently no violation. The identity is now the FILENAME STEM, which is what validateCodexSandboxHolds already validates and what an attacker editing frontmatter cannot change without renaming the file — at which point the existing validator catches it. The lookup is case-insensitive so a recase does not slip past either. The frontmatter name still drives the TOML body and filename, unchanged; only the sandbox identity moved. All 35 roster files were checked: name matches filename stem everywhere, so a stricter "they must agree or throw" invariant would have been safe against real content. It is deliberately NOT added — it would abort an install on a tampered file where emitting a correctly-derived read-only TOML is the safer outcome. Recorded as a fork rather than decided silently. 2. checkCodexSandboxPosture was exported and never called. cmdValidateAgents (src/verify.cts) called checkAgentsInstalled and checkCodexModelPosture only; grep for the sandbox check in that file returned nothing. So criterion 3 — "validate agents fails on semantic drift, not only on missing files" — was unmet, and `validate agents` behaved exactly as before. That is ADR-3473 Decision 2's named shape: a declared policy with no executor. It also meant the T28 test asserted at the helper's return value while the COMMAND stayed broken — the ADR-3180 Decision 4(b) failure this epic exists to close, committed by me while enforcing it elsewhere in the same epic. Now wired as an additive `sandbox_posture` field beside `codex_posture`, following the sibling precedent exactly. Drift is report-only, not a non-zero exit, because that is what checkCodexModelPosture does — two sibling posture checks disagreeing about whether a violation is fatal would be its own defect. The choice is recorded in a comment rather than left implicit. A consumer-output test now drives the real CLI and asserts on the emitted JSON, and was shown failing before the wiring and passing after. Also corrected a stale artifact: the design's Known limit L1 still claimed rung 3 was not in this deliverable, written while it was halted and false once the maintainer unblocked it. Verified after both fixes: the three bypass probes all return read-only, the per-role table is 35/35 byte-identical, and both hold self-invalidation cases still throw. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(#3897): the marker rung, the derived sandbox, and the bare plan-number depends_on Reference: the runtime precedence ladder in docs/CLI-TOOLS.md gains the install marker rung; docs/COMMANDS.md documents validate agents' new sandbox_posture field; docs/reference/plan-md.md documents that depends_on accepts the bare plan number. Explanation: a docs/features fragment keyed id 3897, so it cannot collide with a concurrent PR hand-allocating a section number, regenerated into FEATURES.md. ADR-3473 §8.3 gains an ANSWER blockquote in the document's own correction style, recording what was measured and built against the section's 2026-08-26 correction - including the qualification that checkAgentsInstalled itself still checks presence only, and the semantic assertion lives in a sibling wired into validate agents rather than folded into it. No how-to. Both user-visible changes are zero-step: a non-Claude install resolving its own runtime, and plans executing in their declared waves, both happen without the user doing anything. docs/how-to/control-the-reported-host-runtime.md covers a DIFFERENT ladder (resolveReportedRuntime / agent_runtime) that this change does not touch, and was deliberately left alone rather than edited by association. No tutorial - nothing multi-step to walk through. docs/AGENTS.md unchanged: it documents Claude-side tools frontmatter, never Codex sandbox_mode, and the emitted tools contract did not change. The prompt layer documents depends_on only by example, not by schema, so nothing there needed editing - and few-shot-examples/plan-checker.md already showed depends_on: ['01'], which now actually resolves. Translated copies of plan-md.md are untouched; the project treats translations as community-maintained. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3897): move the sandbox derivation out of the installer, off the install path, and off a third parser The full suite came back with 26 failures across four files. Three distinct causes, mapped individually rather than assuming the first explained the rest. A. Requiring bin/install.js printed the GSD banner to stdout and corrupted `validate agents` JSON. Unexpected token '', "[36m ██"... is not valid JSON checkCodexSandboxPosture reached deriveCodexSandboxMode by lazily requiring bin/install.js, whose module load prints the ASCII banner. So the command emitted banner bytes before its JSON and every JSON consumer broke, including ten tests that predate this branch. src/ reaching into bin/ was backwards layering that happened to also be loud. The derivation now lives in src/codex-agent-toml.cts - the existing Codex TOML domain module, no new module and no six-gate ripple - and both bin/install.js and src/agent-install-check.cts import it. One owner, which is §8.3's rule applied to the fix for §8.3. B. The stale-hold throw fired on a legitimate partial source dir, and masked a security assertion. validateCodexSandboxHolds treated "this hold's .md is absent from the install SOURCE dir" as a stale hold and threw. A test fixture, or any partial install source, legitimately contains a couple of agents. Worse, it threw BEFORE the path-escape check, so a test asserting that a `../../evil` frontmatter name is rejected got my unrelated error instead of the traversal rejection it was written for. A fail-closed check of mine was hiding a real security check. The "no stale holds, shrink-only" invariant is a property of the repo's canonical agents/ roster, not of whatever directory an install happens to read. It is off the runtime path and enforced where it belongs, in the tests that already existed for it. A partial source dir now installs cleanly, and the evil-name case throws with its own escapes-configHome message again. C. T8 depended on ambient process.env state. The marker/env parity assertion round-tripped through live process.env. It now compares against resolveExplicitRuntime's already-exported dependency-injection parameter - deterministic and hermetic, same claim. Proven still falsifiable rather than assumed: with the marker rung's normalization temporarily bypassed the two rungs diverge ("codex\n../../etc/passwd" vs "codex-../../etc/passwd") and the assertion fails, then passes again once reverted. One correction folded in along the way. The first version of the move added private _extractFrontmatterAndBody/_extractFrontmatterField helpers to codex-agent-toml.cts - a THIRD copy of frontmatter extraction, where the graph already shows two (bin/install.js:2348, runtime-artifact-conversion.cts:893). Adding a third inside the epic whose thesis is one implementation per rule is not defensible. deriveCodexSandboxMode no longer parses anything: it takes (identity, toolsValue) and each caller supplies the tools value using the extractor it already has. Both helpers are deleted. The identity argument is still the filename stem, so the fail-open fix is untouched. Verified after all three: `validate agents --raw` emits parseable JSON with no banner and both posture fields; the four hold-bypass probes still return read-only; the per-role table is 35/35 byte-identical at 26 read-only / 9 workspace-write; the hold list is still 16. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3897): drop a dev-only transitive dep, make the derivation total, retire a stale fallback test Suite down to 7 failures from 26. Three more causes, mapped individually. A. My extractor import dragged in a script that does not exist in an installed tree. Cannot find module '../../../scripts/fix-slash-commands.cjs' Chain: src/agent-install-check.cts imported runtime-artifact-conversion.cjs, which requires command-roster.cjs, whose line 36 requires ../../../scripts/fix-slash-commands.cjs. That path exists in the repo and not in an install, so every test exercising a synthetic install dir died at module load. I picked that extractor for convenience without checking what it pulls in - the same mistake that produced the banner bug, one layer further out. agent-install-check now uses a single-purpose extractToolsLine on codex-agent-toml.cts. That is deliberately NOT a general frontmatter parser: we deleted those helpers a commit ago for good reason, and this reads one line. Verified from outside the repo root that requiring either module prints nothing and does not throw. B. A test pinned the deleted name-based fallback. 'defaults unknown agents to read-only' called generateCodexAgentToml with a fixture declaring tools: Read, Write, Edit. Under derivation an unknown agent with a writing contract correctly derives workspace-write - design row S6, a new writing role gets the contract, not the pin. The behavior it asserted was the silent fallback this rung deleted; identity no longer decides the sandbox. Replaced with two rows rather than a flipped string: no tools declared -> read-only (absence is not a grant), and Write/Edit declared -> workspace-write. Strictly more coverage than the row it replaces. C. The stale-hold check still threw per derivation call. Last commit took the roster-existence check off the install path, but deriveCodexSandboxMode itself still threw when a hold's role did not derive broader FOR THE CONTENT IT WAS HANDED - so it fired on any synthetic fixture for a held role. The throw is gone, and it cost nothing: if a held role's content does not derive broader, the hold pins read-only and derivation returns read-only anyway, so the hold is a no-op and there is nothing to fail about. The staleness invariant is a property of the real agents/ roster, and validateCodexSandboxHolds still enforces it there - confirmed against the real roster after the change, not assumed. deriveCodexSandboxMode is now total: every (identity, toolsValue) including undefined and null returns read-only or workspace-write, never throws. Verified: validate agents emits parseable JSON; the four hold-bypass probes return read-only; the per-role table is 35/35 at 26 read-only / 9 workspace-write. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(#3897): put the rung-3 decision in the shipped docs instead of pointing at an ignored path The ADR entry and the feature fragment both ended their rung-3 explanation with "see .gsd/phase/feat-3897-adr3473-83-rungs/45-decision-rung3-sandbox.md". That directory is gitignored (.gitignore:55), so the rationale for holding 16 roles at read-only was reachable only from the machine that produced it. A reader of the ADR got a pointer to nothing. Both now carry the reasoning inline: the criterion asks both that the sandbox derive from the declared tool contract and that no role gain a broader sandbox, and those cannot both hold, because a faithful derivation widens 16 roles the deleted map never listed and that fell through its silent read-only default. The resolution is derive-and-hold - the derivation owns the rule now, each hold is released as its enforcement question is answered, and a hold is reversible where a widened sandbox that turns out to be enforced is not. Checked before assuming this was a defect class: CONTEXT.md cites .gsd/phase/<slug>/40-design.md as its standard Design: provenance line in eight module entries, and four other shipped docs do the same. Citing a phase artifact is an established convention here, so those are left alone. What was wrong was specific to these two: they put load-bearing rationale behind the pointer instead of provenance. docs/FEATURES.md regenerated from the fragment via scripts/gen-features.cjs rather than hand-edited. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3897): close a fail-open, stop a silent mis-resolution, and read a declaration as a declaration Two orthogonal reviews on the shipped sha. Three of the findings are the same failure class this epic exists to close, committed inside it. 1. BLOCKER - the sandbox was decided for one identity and applied to another. bin/install.js derived sandbox_mode for the filename stem and then wrote the result to `${name}.toml`, where name comes from the file's own frontmatter. Make the two disagree and a HELD role's artifact goes wide: rename gsd-doc-writer.md -> gsd-doc-writer-v2.md, keep name: gsd-doc-writer -> stem is unheld, derives workspace-write, lands on gsd-doc-writer.toml add any gsd-*.md whose frontmatter name: is a held role -> clobbers that role's toml with workspace-write Both emit read-only on origin/next, because the deleted map was an allowlist and a miss fell back safe. This is a regression my change introduced. The previous review round moved the HOLD KEY off frontmatter to the filename stem and left the OUTPUT PATH on frontmatter; my own comment at install.js:6985 calls that value attacker-editable, four lines above the line that uses it as the filename. The decision is now made over BOTH candidate identities, most-restrictive wins: if either the stem or the emitted name is held, the mode is read-only. 2. MAJOR - hold matching was toLowerCase() only, so confusables escaped. Turkish dotted/dotless i, fullwidth, NFD, trailing space/NBSP/dot/newline, ./ and ../agents/ all slipped the hold and emitted workspace-write. Identities are now basenamed, trimmed of NBSP/zero-width/control characters, NFKC-normalized and lowercased - and anything still carrying a character outside [a-z0-9._-] is treated as suspicious and derives read-only. We do not enumerate confusables; every shipped roster file is ASCII, so refusing to widen on an identity we cannot recognize is fail-closed with no false positives on real content. 3. MAJOR - the short-form depends_on tier mis-resolved SILENTLY. shortFormToId keyed on the last dash-segment of any canonical id with no constraint that it is a plan number, so a phase holding 09-FIX-auth-PLAN.md made depends_on: ["auth"] bind at wave 2 with zero warnings. This is the worst shape in the epic: the unresolvable-token warning fires on a DROPPED token, so a MIS-RESOLVED one is invisible and the tool reports a confident wave assignment built from a wrong edge. A wrong edge is worse than a missing one. The segment must now match /^\d+$/, which is exactly the contract docs/reference/plan-md.md already documents. This tier was recovered verbatim from the retired SDK lineage, which carried the same defect; we are deliberately NOT preserving it bug-for-bug, and the comment says so, so the next reader does not "restore" it. 4. MAJOR - the derivation was reading a declaration as an absence. extractToolsLine read one line, so a YAML list-form tools: block returned only its first item. Two roster files use list form, and gsd-nyquist-auditor declares Write and Edit there - parsed as "- Read", found no write tool, and emitted read-only. Rung 3's headline claim is that sandbox_mode derives from the declared tool contract; that claim was false for 2 of 35 roles and materially wrong for 1. Reading a declaration as an absence is the silent-drop class this epic exists to close. Renamed extractToolsValue and taught it both shapes. gsd-nyquist-auditor now derives workspace-write and joins CODEX_SANDBOX_HOLDS as its 17th entry, per the standing derive-and-hold decision - so emitted TOML stays byte-identical at 26 read-only / 9 workspace-write while the hold list finally records every role that would widen. A previous pass declined this fix because it moved the count; that inverts the priority. Byte-identity is preserved THROUGH the hold, not by leaving a parser broken. Divergence check, because this is where that bug hides: both paths feeding sandbox derivation - install.js's emitter and checkCodexSandboxPosture - now route through the one extractor. The tools readers in runtime-artifact-conversion and install.js's other frontmatter call sites serve Claude-side emission and do not feed sandbox derivation. Also fixed, each real: the posture check's `found` used a naive whole-file regex where its own sibling uses the block-aware scanner, so prose inside developer_instructions produced a false violation; `found` skipped truncatePostureValue and leaked a 300-char value into validate agents output; deriveCodexSandboxMode's absolute never-throws claim was false for an object with a throwing toString; T49 could not falsify cross-phase leakage (its target phase had its own 01, so a globally-scoped map passed too); T20/N6 iterated a hardcoded table and pinned the FIXTURE size, so a 36th agent would be silently unchecked; three tests reimplemented the code they were testing instead of importing it; and T2-T4 deleted GSD_RUNTIME without restoring it. Verified: hold list 17, gsd-nyquist-auditor derives workspace-write unheld and emits read-only held, roster 35/35 at 26/9, depends_on ["auth"] no longer resolves while ["01"] still does, both identity-bypass cases and every confusable vector emit read-only. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(#3897): the hold list is 17, and the reason the 17th was missing The count read 16 because the derivation could not read the declaration it claimed to derive from: the tools reader was single-line, so a YAML list-form tools: block returned only its first item and gsd-nyquist-auditor's declared Write and Edit were read as an absence. Both the ADR entry and the feature fragment now carry the corrected count and the reason for it, rather than a silently updated number. Deriving from a declaration you cannot parse is not deriving, and a flattering count is worse than a wrong one because it looks settled. docs/FEATURES.md regenerated from the fragment. Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(#3897): backfill changeset pr number Refs #3897 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: sim <sim@local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
800 lines
32 KiB
JavaScript
800 lines
32 KiB
JavaScript
/**
|
|
* GSD Agent Installation Validation Tests (#1371)
|
|
*
|
|
* Validates that GSD detects missing or incomplete agent installations and
|
|
* surfaces warnings through init commands and health checks. When agents are
|
|
* not installed, Task(subagent_type="gsd-*") silently falls back to
|
|
* general-purpose, losing specialized instructions.
|
|
*/
|
|
|
|
const { test, describe, beforeEach, afterEach } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('fs');
|
|
const os = require('os');
|
|
const path = require('path');
|
|
const { runNode } = require('./helpers/process-seam.cjs');
|
|
const { runGsdTools, createTempProject, cleanup } = require('./helpers.cjs');
|
|
const { installerEnv } = require('./helpers/install-shared.cjs');
|
|
|
|
// #3145: class-norm timeout, not a per-suite value — see helpers/timeouts.cjs.
|
|
const { INSTALL_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
|
|
const AGENTS_DIR_NAME = 'agents';
|
|
const MODEL_PROFILES = require('../gsd-core/bin/lib/model-profiles.cjs').MODEL_PROFILES;
|
|
const EXPECTED_AGENTS = Object.keys(MODEL_PROFILES);
|
|
const ROOT = path.join(__dirname, '..');
|
|
const INSTALL_SCRIPT = path.join(ROOT, 'bin', 'install.js');
|
|
|
|
/**
|
|
* Create a fake GSD install directory structure that mirrors what the installer
|
|
* produces. gsd-tools.cjs lives at <configDir>/gsd-core/bin/gsd-tools.cjs,
|
|
* so the agents dir is at <configDir>/agents/.
|
|
*
|
|
* We use --cwd to point at the project, and GSD_INSTALL_DIR env to override
|
|
* the agents directory location for testing.
|
|
*/
|
|
function _createAgentsDir(configDir, agentNames = []) {
|
|
const agentsDir = path.join(configDir, AGENTS_DIR_NAME);
|
|
fs.mkdirSync(agentsDir, { recursive: true });
|
|
for (const name of agentNames) {
|
|
fs.writeFileSync(
|
|
path.join(agentsDir, `${name}.md`),
|
|
`---\nname: ${name}\ndescription: Test agent\ntools: Read, Bash\ncolor: cyan\n---\nAgent content.\n`
|
|
);
|
|
}
|
|
return agentsDir;
|
|
}
|
|
|
|
function createCompleteCodexAgents(configDir) {
|
|
const agentsDir = path.join(configDir, '.codex', AGENTS_DIR_NAME);
|
|
fs.mkdirSync(agentsDir, { recursive: true });
|
|
const files = {};
|
|
for (const name of EXPECTED_AGENTS) {
|
|
fs.writeFileSync(path.join(agentsDir, `${name}.md`), `# ${name}\n`);
|
|
fs.writeFileSync(path.join(agentsDir, `${name}.toml`), `name = "${name}"\n`);
|
|
files[`agents/${name}.md`] = {};
|
|
files[`agents/${name}.toml`] = {};
|
|
}
|
|
fs.writeFileSync(
|
|
path.join(configDir, '.codex', 'gsd-file-manifest.json'),
|
|
JSON.stringify({ files }),
|
|
);
|
|
return agentsDir;
|
|
}
|
|
|
|
// ─── Init command agent validation ──────────────────────────────────────────
|
|
|
|
describe('init commands: agents_installed field (#1371)', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
// Point the SDK at the repo's agents/ dir (sibling of gsd-core/) via the
|
|
// GSD_AGENTS_DIR override. The SDK side of init resolves agents from
|
|
// GSD_AGENTS_DIR or the runtime config dir (~/.claude/agents for Claude); it
|
|
// does NOT walk up from cwd like the CJS-era code did. Without this override
|
|
// these tests would only pass on a dev machine with ~/.claude/agents/
|
|
// populated — which masked the divergence on Linux CI where that path is
|
|
// absent. See sdk/src/query/QUERY-HANDLERS.md ("subprocess vs in-process
|
|
// path resolution") and sdk/src/query/helpers.ts:resolveAgentsDir.
|
|
const REPO_AGENTS_DIR = path.resolve(__dirname, '..', 'agents');
|
|
|
|
test('init execute-phase includes agents_installed=true when agents exist', () => {
|
|
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-setup');
|
|
fs.mkdirSync(phaseDir, { recursive: true });
|
|
|
|
const result = runGsdTools('init execute-phase 1 --raw', tmpDir, { GSD_AGENTS_DIR: REPO_AGENTS_DIR });
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(typeof output.agents_installed, 'boolean',
|
|
'init execute-phase must include agents_installed field');
|
|
assert.strictEqual(output.agents_installed, true,
|
|
'agents_installed should be true when GSD_AGENTS_DIR has gsd-*.md files');
|
|
});
|
|
|
|
test('init plan-phase includes agents_installed=true when agents exist', () => {
|
|
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-setup');
|
|
fs.mkdirSync(phaseDir, { recursive: true });
|
|
|
|
const result = runGsdTools('init plan-phase 1 --raw', tmpDir, { GSD_AGENTS_DIR: REPO_AGENTS_DIR });
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(typeof output.agents_installed, 'boolean',
|
|
'init plan-phase must include agents_installed field');
|
|
assert.strictEqual(output.agents_installed, true);
|
|
});
|
|
|
|
test('init plan-phase reports the complete project-local Codex installation', () => {
|
|
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-setup');
|
|
const globalHome = path.join(tmpDir, 'global-codex');
|
|
fs.mkdirSync(phaseDir, { recursive: true });
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'config.json'),
|
|
JSON.stringify({ runtime: 'codex' }),
|
|
);
|
|
createCompleteCodexAgents(tmpDir);
|
|
const canonicalRoot = fs.realpathSync(tmpDir);
|
|
const localAgentsDir = path.join(canonicalRoot, '.codex', AGENTS_DIR_NAME);
|
|
_createAgentsDir(globalHome, EXPECTED_AGENTS);
|
|
|
|
const result = runGsdTools('init plan-phase 1 --raw', tmpDir, { CODEX_HOME: globalHome });
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.project_root, canonicalRoot);
|
|
assert.strictEqual(output.agent_runtime, 'codex');
|
|
assert.strictEqual(output.agents_dir, localAgentsDir);
|
|
assert.strictEqual(output.agents_installed, true);
|
|
assert.deepStrictEqual(output.missing_agents, []);
|
|
});
|
|
|
|
test('init reports codex when the session signal is present', () => {
|
|
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-setup');
|
|
fs.mkdirSync(phaseDir, { recursive: true });
|
|
|
|
const result = runGsdTools('init plan-phase 1 --raw', tmpDir, { CODEX_SANDBOX: 'seatbelt' });
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.agent_runtime, 'codex');
|
|
});
|
|
|
|
test('init honors explicit config runtime over detection', () => {
|
|
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-setup');
|
|
fs.mkdirSync(phaseDir, { recursive: true });
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'config.json'),
|
|
JSON.stringify({ runtime: 'claude' }),
|
|
);
|
|
|
|
const result = runGsdTools('init plan-phase 1 --raw', tmpDir, { CODEX_SANDBOX: 'seatbelt' });
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.agent_runtime, 'claude');
|
|
});
|
|
|
|
test('init is unaffected in a non-codex session', () => {
|
|
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-setup');
|
|
fs.mkdirSync(phaseDir, { recursive: true });
|
|
|
|
const result = runGsdTools('init plan-phase 1 --raw', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.agent_runtime, 'claude');
|
|
});
|
|
|
|
test('init honors GSD_RUNTIME over detection', () => {
|
|
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-setup');
|
|
fs.mkdirSync(phaseDir, { recursive: true });
|
|
|
|
const result = runGsdTools('init plan-phase 1 --raw', tmpDir, {
|
|
GSD_RUNTIME: 'opencode',
|
|
CODEX_SANDBOX: 'seatbelt',
|
|
});
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.agent_runtime, 'opencode');
|
|
});
|
|
|
|
test('init execute-phase includes missing_agents list when agents are missing', () => {
|
|
const phaseDir = path.join(tmpDir, '.planning', 'phases', '01-setup');
|
|
fs.mkdirSync(phaseDir, { recursive: true });
|
|
|
|
const result = runGsdTools('init execute-phase 1 --raw', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.ok(Array.isArray(output.missing_agents),
|
|
'init execute-phase must include missing_agents array');
|
|
});
|
|
|
|
test('init quick includes agents_installed field', () => {
|
|
const result = runGsdTools(['init', 'quick', 'test description', '--raw'], tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(typeof output.agents_installed, 'boolean',
|
|
'init quick must include agents_installed field');
|
|
});
|
|
});
|
|
|
|
// ─── Health check: agent installation ───────────────────────────────────────
|
|
|
|
describe('validate health: agent installation check W010 (#1371)', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
// Write minimal project files so health check doesn't fail on E001-E005
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'PROJECT.md'),
|
|
'# Project\n\n## What This Is\nTest\n\n## Core Value\nTest\n\n## Requirements\nTest\n'
|
|
);
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'ROADMAP.md'),
|
|
'# Roadmap\n\n### Phase 1: Setup\n'
|
|
);
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'STATE.md'),
|
|
'# Session State\n\n## Current Position\n\nPhase: 1\n'
|
|
);
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'config.json'),
|
|
JSON.stringify({
|
|
model_profile: 'balanced',
|
|
commit_docs: true,
|
|
workflow: { nyquist_validation: true },
|
|
}, null, 2)
|
|
);
|
|
fs.mkdirSync(path.join(tmpDir, '.planning', 'phases', '01-setup'), { recursive: true });
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('health check reports healthy when agents are installed (repo layout)', () => {
|
|
// In the repo, agents/ exists as a sibling of gsd-core/, so the
|
|
// health check should find them via the gsd-tools.cjs path resolution
|
|
const result = runGsdTools('validate health --raw', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
// Should not have W010 warning about missing agents
|
|
const w010 = (output.warnings || []).find(w => w.code === 'W010');
|
|
assert.ok(!w010, 'Should not warn about missing agents when agents/ dir exists with files');
|
|
});
|
|
});
|
|
|
|
// ─── Codex project-local validation status ──────────────────────────────────
|
|
|
|
describe('Codex project-local validation status', () => {
|
|
let tmpDir;
|
|
let globalHome;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
globalHome = path.join(tmpDir, 'global-codex');
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'config.json'),
|
|
JSON.stringify({ runtime: 'codex' }),
|
|
);
|
|
_createAgentsDir(globalHome, EXPECTED_AGENTS);
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('validate agents and health use a complete project-local Codex installation', () => {
|
|
createCompleteCodexAgents(tmpDir);
|
|
const localAgentsDir = path.join(fs.realpathSync(tmpDir), '.codex', AGENTS_DIR_NAME);
|
|
const env = { CODEX_HOME: globalHome };
|
|
|
|
const validateResult = runGsdTools('validate agents --raw', tmpDir, env);
|
|
assert.ok(validateResult.success, `validate agents failed: ${validateResult.error}`);
|
|
const validateOutput = JSON.parse(validateResult.output);
|
|
assert.strictEqual(validateOutput.agents_dir, localAgentsDir);
|
|
assert.strictEqual(validateOutput.agents_found, true);
|
|
assert.deepStrictEqual(validateOutput.missing, []);
|
|
assert.deepStrictEqual(validateOutput.incomplete, []);
|
|
|
|
const healthResult = runGsdTools('validate health --raw', tmpDir, env);
|
|
assert.ok(healthResult.success, `validate health failed: ${healthResult.error}`);
|
|
const healthOutput = JSON.parse(healthResult.output);
|
|
assert.ok(!(healthOutput.warnings || []).some(warning => warning.code === 'W010'));
|
|
});
|
|
|
|
test('an empty project-local Codex directory remains authoritative for validate agents and health', () => {
|
|
fs.mkdirSync(path.join(tmpDir, '.codex', AGENTS_DIR_NAME), { recursive: true });
|
|
fs.writeFileSync(path.join(tmpDir, '.codex', 'gsd-file-manifest.json'), JSON.stringify({ files: {} }));
|
|
const localAgentsDir = path.join(fs.realpathSync(tmpDir), '.codex', AGENTS_DIR_NAME);
|
|
const env = { CODEX_HOME: globalHome };
|
|
|
|
const validateResult = runGsdTools('validate agents --raw', tmpDir, env);
|
|
assert.ok(validateResult.success, `validate agents failed: ${validateResult.error}`);
|
|
const validateOutput = JSON.parse(validateResult.output);
|
|
assert.strictEqual(validateOutput.agents_dir, localAgentsDir);
|
|
assert.strictEqual(validateOutput.agents_found, false);
|
|
assert.deepStrictEqual(validateOutput.installed, []);
|
|
assert.deepStrictEqual(validateOutput.incomplete, []);
|
|
assert.deepStrictEqual(validateOutput.missing, EXPECTED_AGENTS);
|
|
|
|
const healthResult = runGsdTools('validate health --raw', tmpDir, env);
|
|
assert.ok(healthResult.success, `validate health failed: ${healthResult.error}`);
|
|
const healthOutput = JSON.parse(healthResult.output);
|
|
assert.ok((healthOutput.warnings || []).some(warning => warning.code === 'W010'));
|
|
});
|
|
});
|
|
|
|
// ─── Copilot .agent.md detection (#1512) ────────────────────────────────────
|
|
|
|
describe('checkAgentsInstalled: Copilot .agent.md format (#1512)', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('agents_installed=true when agents exist as .agent.md (Copilot format)', () => {
|
|
// Simulate a Copilot install: agents are named gsd-*.agent.md, not gsd-*.md
|
|
// Use GSD_AGENTS_DIR to point at an isolated dir with ONLY .agent.md files,
|
|
// so the test does not accidentally pass via the repo's own agents/ dir.
|
|
const agentsDir = path.join(tmpDir, 'copilot-agents');
|
|
fs.mkdirSync(agentsDir, { recursive: true });
|
|
for (const name of EXPECTED_AGENTS) {
|
|
fs.writeFileSync(
|
|
path.join(agentsDir, `${name}.agent.md`),
|
|
`---\nname: ${name}\ndescription: Test agent\n---\nAgent content.\n`
|
|
);
|
|
}
|
|
|
|
const result = runGsdTools('validate agents --raw', tmpDir, { GSD_AGENTS_DIR: agentsDir });
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
// Must report the custom dir, not the default repo agents dir
|
|
assert.strictEqual(output.agents_dir, agentsDir,
|
|
'agents_dir must be the GSD_AGENTS_DIR override, not the repo default');
|
|
assert.strictEqual(output.agents_found, true,
|
|
'agents_found must be true when agents exist as .agent.md (Copilot format)');
|
|
assert.deepStrictEqual(output.missing, [],
|
|
'missing must be empty when all agents exist as .agent.md');
|
|
});
|
|
|
|
test('agents_installed=false when .agent.md files exist for only some agents', () => {
|
|
const agentsDir = path.join(tmpDir, 'agents');
|
|
fs.mkdirSync(agentsDir, { recursive: true });
|
|
// Only install the first agent
|
|
const firstAgent = EXPECTED_AGENTS[0];
|
|
fs.writeFileSync(
|
|
path.join(agentsDir, `${firstAgent}.agent.md`),
|
|
`---\nname: ${firstAgent}\ndescription: Test agent\n---\nAgent content.\n`
|
|
);
|
|
|
|
const result = runGsdTools('validate agents --raw', tmpDir, { GSD_AGENTS_DIR: agentsDir });
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.agents_found, false,
|
|
'agents_found must be false when only some agents exist');
|
|
assert.ok(output.missing.length > 0, 'missing must be non-empty when some agents are absent');
|
|
});
|
|
|
|
test('init new-workspace includes agents_installed=true with Copilot .agent.md files', () => {
|
|
// Use an isolated dir with ONLY .agent.md files (no .md fallback)
|
|
const agentsDir = path.join(tmpDir, 'copilot-agents');
|
|
fs.mkdirSync(agentsDir, { recursive: true });
|
|
for (const name of EXPECTED_AGENTS) {
|
|
fs.writeFileSync(
|
|
path.join(agentsDir, `${name}.agent.md`),
|
|
`---\nname: ${name}\ndescription: Test agent\n---\nAgent content.\n`
|
|
);
|
|
}
|
|
|
|
const result = runGsdTools('init new-workspace --raw', tmpDir, { GSD_AGENTS_DIR: agentsDir });
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.agents_installed, true,
|
|
'agents_installed must be true when Copilot .agent.md files are present');
|
|
assert.deepStrictEqual(output.missing_agents, [],
|
|
'missing_agents must be empty when all .agent.md files are present');
|
|
});
|
|
|
|
test('agents_installed=true when agents exist as .toml (Codex format) (#278)', () => {
|
|
const agentsDir = path.join(tmpDir, 'codex-agents');
|
|
fs.mkdirSync(agentsDir, { recursive: true });
|
|
for (const name of EXPECTED_AGENTS) {
|
|
fs.writeFileSync(
|
|
path.join(agentsDir, `${name}.toml`),
|
|
`name = "${name}"\ndescription = "Test agent"\n`
|
|
);
|
|
}
|
|
|
|
const result = runGsdTools('validate agents --raw', tmpDir, { GSD_AGENTS_DIR: agentsDir });
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.strictEqual(output.agents_found, true,
|
|
'agents_found must be true when agents exist as .toml (Codex format)');
|
|
assert.deepStrictEqual(output.missing, [],
|
|
'missing must be empty when all agents exist as .toml');
|
|
});
|
|
|
|
test('GSD_AGENTS_DIR env var overrides default agents directory', () => {
|
|
// Create a custom agents dir in a subdirectory
|
|
const customAgentsDir = path.join(tmpDir, 'custom-agents');
|
|
fs.mkdirSync(customAgentsDir, { recursive: true });
|
|
// Put one agent there as .md (standard format)
|
|
fs.writeFileSync(
|
|
path.join(customAgentsDir, `${EXPECTED_AGENTS[0]}.md`),
|
|
`---\nname: ${EXPECTED_AGENTS[0]}\ndescription: Test agent\n---\nAgent content.\n`
|
|
);
|
|
|
|
const result = runGsdTools('validate agents --raw', tmpDir, { GSD_AGENTS_DIR: customAgentsDir });
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
// The custom dir path should be reported
|
|
assert.strictEqual(output.agents_dir, customAgentsDir,
|
|
'agents_dir must reflect GSD_AGENTS_DIR override');
|
|
});
|
|
});
|
|
|
|
// ─── Kimi agents/subagents detection (#743 review) ─────────────────────────
|
|
|
|
describe('checkAgentsInstalled: Kimi agents/subagents layout', () => {
|
|
test('Kimi install is detected by init, validate agents, and health checks', () => {
|
|
const tmpDir = createTempProject('gsd-kimi-agent-status-project-');
|
|
const tmpConfig = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-kimi-agent-status-config-'));
|
|
const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-kimi-agent-status-home-'));
|
|
const env = installerEnv({
|
|
HOME: tmpHome,
|
|
USERPROFILE: tmpHome,
|
|
KIMI_CONFIG_DIR: tmpConfig,
|
|
});
|
|
|
|
try {
|
|
const installResult = runNode(
|
|
[INSTALL_SCRIPT, '--kimi', '--global', '--config-dir', tmpConfig, '--no-sdk'],
|
|
{
|
|
cwd: tmpDir,
|
|
env,
|
|
timeoutMs: INSTALL_TIMEOUT_MS,
|
|
},
|
|
);
|
|
assert.strictEqual(
|
|
installResult.exitCode,
|
|
0,
|
|
`Kimi install failed\nstdout: ${installResult.stdout}\nstderr: ${installResult.stderr}`,
|
|
);
|
|
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, '.planning', 'config.json'),
|
|
JSON.stringify({ runtime: 'kimi', model_profile: 'balanced' }, null, 2),
|
|
);
|
|
|
|
const initResult = runGsdTools('init new-workspace --raw', tmpDir, env);
|
|
assert.ok(initResult.success, `init failed: ${initResult.error}`);
|
|
const initOutput = JSON.parse(initResult.output);
|
|
assert.strictEqual(initOutput.agent_runtime, 'kimi');
|
|
assert.strictEqual(initOutput.agents_dir, path.join(tmpConfig, 'agents'));
|
|
assert.strictEqual(initOutput.agents_installed, true);
|
|
assert.deepStrictEqual(initOutput.missing_agents, []);
|
|
|
|
const validateResult = runGsdTools('validate agents --raw', tmpDir, {
|
|
...env,
|
|
GSD_RUNTIME: 'kimi',
|
|
});
|
|
assert.ok(validateResult.success, `validate agents failed: ${validateResult.error}`);
|
|
const validateOutput = JSON.parse(validateResult.output);
|
|
assert.strictEqual(validateOutput.agents_dir, path.join(tmpConfig, 'agents'));
|
|
assert.strictEqual(validateOutput.agents_found, true);
|
|
assert.deepStrictEqual(validateOutput.missing, []);
|
|
|
|
const healthResult = runGsdTools('validate health --raw', tmpDir, {
|
|
...env,
|
|
GSD_RUNTIME: 'kimi',
|
|
});
|
|
assert.ok(healthResult.success, `validate health failed: ${healthResult.error}`);
|
|
const healthOutput = JSON.parse(healthResult.output);
|
|
const agentWarnings = (healthOutput.warnings || []).filter(
|
|
(warning) => warning.code === 'W010' || /GSD agents/i.test(warning.message || ''),
|
|
);
|
|
assert.deepStrictEqual(agentWarnings, []);
|
|
} finally {
|
|
cleanup(tmpDir);
|
|
cleanup(tmpConfig);
|
|
cleanup(tmpHome);
|
|
}
|
|
});
|
|
});
|
|
|
|
// ─── validate agents subcommand ─────────────────────────────────────────────
|
|
|
|
describe('validate agents subcommand (#1371)', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('validate agents returns status with agent list', () => {
|
|
const result = runGsdTools('validate agents --raw', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.ok('agents_dir' in output, 'Must include agents_dir path');
|
|
assert.ok('installed' in output, 'Must include installed array');
|
|
assert.ok('missing' in output, 'Must include missing array');
|
|
assert.ok('agents_found' in output, 'Must include agents_found boolean');
|
|
});
|
|
|
|
test('validate agents lists all expected agent types', () => {
|
|
const result = runGsdTools('validate agents --raw', tmpDir);
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
|
|
const output = JSON.parse(result.output);
|
|
// The expected agents come from MODEL_PROFILES keys
|
|
assert.ok(output.expected.length > 0, 'Must have expected agents');
|
|
});
|
|
});
|
|
|
|
// ─── Sandbox posture drift, at the COMMAND (#3897 rung 3, ADR-3473 §8.3) ─────
|
|
//
|
|
// tests/agent-install-check.test.cjs's T28 already proves checkCodexSandboxPosture
|
|
// itself detects a drifted sandbox_mode. That is a UNIT row — it drives the
|
|
// helper directly. Before verify.cts wired the helper into cmdValidateAgents,
|
|
// T28 stayed green while `gsd-tools validate agents` (the actual command a
|
|
// user/CI runs) never surfaced the drift at all — the ADR-3180 Decision 4(b)
|
|
// failure shape ("asserting at a helper's return, not at the consumer's
|
|
// output"). This row drives the real CLI end to end and asserts on ITS JSON,
|
|
// so a future regression that leaves the helper correct but un-wired from the
|
|
// command fails here even if T28 stays green.
|
|
describe('validate agents surfaces sandbox posture drift at the command (#3897 rung 3)', () => {
|
|
let tmpDir;
|
|
let agentsDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempProject();
|
|
agentsDir = path.join(tmpDir, 'codex-agents');
|
|
fs.mkdirSync(agentsDir, { recursive: true });
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('validateAgentsSurfacesSandboxDriftAtTheCommand_3897: `validate agents` reports the drifted agent/expected/found via sandbox_posture', () => {
|
|
// agents/gsd-executor.md (the real repo role source — checkCodexSandboxPosture
|
|
// reads it directly, it is not fixture-overridable) declares tools that derive
|
|
// workspace-write. Install a drifted TOML claiming read-only instead.
|
|
fs.writeFileSync(
|
|
path.join(agentsDir, 'gsd-executor.toml'),
|
|
'name = "gsd-executor"\ndescription = "Executes plans"\nsandbox_mode = "read-only"\n'
|
|
+ "developer_instructions = '''\nExecute.\n'''\n",
|
|
);
|
|
|
|
const env = { GSD_AGENTS_DIR: agentsDir, GSD_RUNTIME: 'codex' };
|
|
const result = runGsdTools('validate agents --raw', tmpDir, env);
|
|
assert.ok(result.success, `validate agents failed: ${result.error}`);
|
|
assert.strictEqual(result.exitCode, 0, 'model-posture drift is report-only, not fatal — sandbox posture must match that precedent');
|
|
|
|
const output = JSON.parse(result.output);
|
|
assert.ok(
|
|
output.sandbox_posture,
|
|
`expected \`validate agents\` output to carry a sandbox_posture key, got keys: ${Object.keys(output).join(', ')}`,
|
|
);
|
|
assert.strictEqual(output.sandbox_posture.ok, false);
|
|
const violation = output.sandbox_posture.violations.find((v) => v.agent === 'gsd-executor');
|
|
assert.ok(violation, 'the command output must name the drifted agent');
|
|
assert.strictEqual(violation.expected, 'workspace-write');
|
|
assert.strictEqual(violation.found, 'read-only');
|
|
});
|
|
});
|
|
|
|
// ─── Bug #1058: validate agents detects manifest-backed .md/.toml pair drift ──
|
|
|
|
describe('bug #1058: validate agents detects manifest-backed .md/.toml pair drift', () => {
|
|
// All real agents/gsd-*.md files in the repo (used to populate fixtures)
|
|
const REPO_AGENTS_DIR_1058 = path.resolve(__dirname, '..', 'agents');
|
|
|
|
/**
|
|
* Copy all gsd-*.md files from the repo agents dir into destDir.
|
|
*/
|
|
function copyAgentMdFiles(destDir) {
|
|
const files = fs.readdirSync(REPO_AGENTS_DIR_1058).filter(f => /^gsd-.*\.md$/.test(f));
|
|
for (const file of files) {
|
|
const src = path.join(REPO_AGENTS_DIR_1058, file);
|
|
const dst = path.join(destDir, file);
|
|
fs.copyFileSync(src, dst);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Build a gsd-file-manifest.json whose files map includes both .md and .toml
|
|
* entries for every EXPECTED_AGENTS entry.
|
|
*/
|
|
function buildManifestBothPairs(agents) {
|
|
const files = {};
|
|
for (const name of agents) {
|
|
files[`agents/${name}.md`] = 'deadbeef';
|
|
files[`agents/${name}.toml`] = 'deadbeef';
|
|
}
|
|
return { version: '1.0.0', files };
|
|
}
|
|
|
|
let tmpDir;
|
|
|
|
afterEach(() => {
|
|
if (tmpDir) {
|
|
cleanup(tmpDir);
|
|
tmpDir = null;
|
|
}
|
|
});
|
|
|
|
test('agents_found=false and incomplete non-empty when .toml files are absent but manifest expects them', () => {
|
|
// Arrange: all .md files present, manifest says both .md and .toml are expected,
|
|
// but NO .toml files are created on disk.
|
|
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-bug-1058-missing-toml-'));
|
|
const agentsDir = path.join(tmpDir, 'agents');
|
|
fs.mkdirSync(agentsDir, { recursive: true });
|
|
|
|
// Copy real .md files
|
|
copyAgentMdFiles(agentsDir);
|
|
|
|
// Write manifest with both .md and .toml entries but no .toml files on disk
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, 'gsd-file-manifest.json'),
|
|
JSON.stringify(buildManifestBothPairs(EXPECTED_AGENTS), null, 2),
|
|
);
|
|
|
|
// Act
|
|
const result = runGsdTools('validate agents --raw', tmpDir, {
|
|
GSD_RUNTIME: 'codex',
|
|
GSD_AGENTS_DIR: agentsDir,
|
|
});
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
const output = JSON.parse(result.output);
|
|
|
|
// Assert: the completeness check must catch the missing .toml files
|
|
assert.strictEqual(
|
|
output.agents_found,
|
|
false,
|
|
`Expected agents_found=false when manifest-tracked .toml files are absent, got agents_found=${output.agents_found}`,
|
|
);
|
|
assert.ok(
|
|
Array.isArray(output.incomplete),
|
|
'Expected output.incomplete to be an array',
|
|
);
|
|
// Every agent whose .toml is absent must appear in incomplete (sorted deep-equal)
|
|
assert.deepStrictEqual(
|
|
[...output.incomplete].sort(),
|
|
[...EXPECTED_AGENTS].sort(),
|
|
`Expected incomplete to equal full EXPECTED_AGENTS set; got ${JSON.stringify(output.incomplete)}`,
|
|
);
|
|
// missing (entirely-absent .md) must be empty — these agents are not missing, only incomplete
|
|
assert.deepStrictEqual(
|
|
output.missing,
|
|
[],
|
|
`Expected missing=[] when all .md files are present; got ${JSON.stringify(output.missing)}`,
|
|
);
|
|
});
|
|
|
|
test('agents_found=false and incomplete non-empty when .md files are absent but manifest expects them', () => {
|
|
// Arrange: only .toml files present on disk, manifest says both .md and .toml are expected,
|
|
// but NO .md files exist. This is the opposite-side pair-drift case.
|
|
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-bug-1058-missing-md-'));
|
|
const agentsDir = path.join(tmpDir, 'agents');
|
|
fs.mkdirSync(agentsDir, { recursive: true });
|
|
|
|
// Create ONLY .toml files — deliberately skip .md files
|
|
for (const name of EXPECTED_AGENTS) {
|
|
fs.writeFileSync(path.join(agentsDir, `${name}.toml`), `name = "${name}"
|
|
`);
|
|
}
|
|
|
|
// Write manifest with both .md and .toml entries
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, 'gsd-file-manifest.json'),
|
|
JSON.stringify(buildManifestBothPairs(EXPECTED_AGENTS), null, 2),
|
|
);
|
|
|
|
// Act
|
|
const result = runGsdTools('validate agents --raw', tmpDir, {
|
|
GSD_RUNTIME: 'codex',
|
|
GSD_AGENTS_DIR: agentsDir,
|
|
});
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
const output = JSON.parse(result.output);
|
|
|
|
// Assert: missing .md files must surface as incomplete (pair-drift detected symmetrically)
|
|
assert.strictEqual(
|
|
output.agents_found,
|
|
false,
|
|
`Expected agents_found=false when manifest-tracked .md files are absent, got agents_found=${output.agents_found}`,
|
|
);
|
|
assert.ok(
|
|
Array.isArray(output.incomplete),
|
|
'Expected output.incomplete to be an array',
|
|
);
|
|
assert.ok(
|
|
output.incomplete.length > 0,
|
|
`Expected incomplete to be non-empty when .md files are absent; got ${JSON.stringify(output.incomplete)}`,
|
|
);
|
|
});
|
|
|
|
test('agents_found=true and incomplete=[] when both .md and .toml files are present', () => {
|
|
// Arrange: all .md AND .toml present, manifest says both expected
|
|
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-bug-1058-complete-pair-'));
|
|
const agentsDir = path.join(tmpDir, 'agents');
|
|
fs.mkdirSync(agentsDir, { recursive: true });
|
|
|
|
// Copy real .md files
|
|
copyAgentMdFiles(agentsDir);
|
|
|
|
// Create .toml files for each expected agent
|
|
for (const name of EXPECTED_AGENTS) {
|
|
fs.writeFileSync(path.join(agentsDir, `${name}.toml`), `name = "${name}"\n`);
|
|
}
|
|
|
|
// Write manifest with both .md and .toml entries
|
|
fs.writeFileSync(
|
|
path.join(tmpDir, 'gsd-file-manifest.json'),
|
|
JSON.stringify(buildManifestBothPairs(EXPECTED_AGENTS), null, 2),
|
|
);
|
|
|
|
// Act
|
|
const result = runGsdTools('validate agents --raw', tmpDir, {
|
|
GSD_RUNTIME: 'codex',
|
|
GSD_AGENTS_DIR: agentsDir,
|
|
});
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
const output = JSON.parse(result.output);
|
|
|
|
// Assert: complete pair => no false positive
|
|
assert.strictEqual(
|
|
output.agents_found,
|
|
true,
|
|
`Expected agents_found=true when both .md and .toml files are present; got ${output.agents_found}`,
|
|
);
|
|
assert.deepStrictEqual(
|
|
output.incomplete,
|
|
[],
|
|
`Expected incomplete=[] when all manifest-tracked files are present; got ${JSON.stringify(output.incomplete)}`,
|
|
);
|
|
});
|
|
|
|
test('no spurious incomplete flags when no manifest is present (protects claude/bundled installs)', () => {
|
|
// Arrange: all .md files present, NO manifest file at all
|
|
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-bug-1058-no-manifest-'));
|
|
const agentsDir = path.join(tmpDir, 'agents');
|
|
fs.mkdirSync(agentsDir, { recursive: true });
|
|
|
|
// Copy real .md files
|
|
copyAgentMdFiles(agentsDir);
|
|
|
|
// Explicitly do NOT write gsd-file-manifest.json
|
|
|
|
// Act
|
|
const result = runGsdTools('validate agents --raw', tmpDir, {
|
|
GSD_RUNTIME: 'codex',
|
|
GSD_AGENTS_DIR: agentsDir,
|
|
});
|
|
assert.ok(result.success, `Command failed: ${result.error}`);
|
|
const output = JSON.parse(result.output);
|
|
|
|
// Assert: without a manifest, completeness check must no-op (incomplete empty)
|
|
assert.deepStrictEqual(
|
|
output.incomplete,
|
|
[],
|
|
`Expected incomplete=[] when no manifest present; got ${JSON.stringify(output.incomplete)}`,
|
|
);
|
|
// agents_found should reflect plain file presence (all .md files copied => true)
|
|
assert.strictEqual(
|
|
output.agents_found,
|
|
true,
|
|
`Expected agents_found=true when all .md files are present and no manifest; got ${output.agents_found}`,
|
|
);
|
|
});
|
|
});
|