create-command-center 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE.agent-skills +21 -0
  3. package/README.md +62 -2
  4. package/RELEASING.md +29 -0
  5. package/UPSTREAM.md +13 -0
  6. package/bin/create-command-center.mjs +34 -0
  7. package/installer/build-parsers.mjs +21 -0
  8. package/installer/install.mjs +103 -0
  9. package/installer/template/AGENTS.md +9 -0
  10. package/installer/template/README.md +13 -0
  11. package/installer/template/gitignore +5 -0
  12. package/installer/template/repos/index.md +5 -0
  13. package/package.json +41 -4
  14. package/references/accessibility-checklist.md +160 -0
  15. package/references/definition-of-done.md +67 -0
  16. package/references/observability-checklist.md +92 -0
  17. package/references/orchestration-patterns.md +370 -0
  18. package/references/performance-checklist.md +239 -0
  19. package/references/security-checklist.md +250 -0
  20. package/references/testing-patterns.md +236 -0
  21. package/skills/accessibility-engineering/SKILL.md +133 -0
  22. package/skills/accessibility-engineering/scripts/audit-a11y.sh +233 -0
  23. package/skills/api-and-interface-design/SKILL.md +369 -0
  24. package/skills/browser-testing-with-devtools/SKILL.md +319 -0
  25. package/skills/cc/SKILL.md +26 -0
  26. package/skills/cc/assets/config.md +28 -0
  27. package/skills/cc/assets/progress.md +23 -0
  28. package/skills/cc/references/jobs.md +30 -0
  29. package/skills/cc/references/registration.md +63 -0
  30. package/skills/cc/scripts/checks.mjs +109 -0
  31. package/skills/cc/scripts/errors.mjs +3 -0
  32. package/skills/cc/scripts/home.mjs +60 -0
  33. package/skills/cc/scripts/init.mjs +499 -0
  34. package/skills/cc/scripts/inspection.mjs +315 -0
  35. package/skills/cc/scripts/vendor/LICENSE.parsers.txt +70 -0
  36. package/skills/cc/scripts/vendor/parsers.mjs +9951 -0
  37. package/skills/ci-cd-and-automation/SKILL.md +395 -0
  38. package/skills/code-review-and-quality/SKILL.md +402 -0
  39. package/skills/code-simplification/SKILL.md +331 -0
  40. package/skills/constraint-driven-development/SKILL.md +319 -0
  41. package/skills/constraint-driven-development/references/floor-guard.md +182 -0
  42. package/skills/constraint-driven-development/scripts/quality-gate.mjs +45 -0
  43. package/skills/context-engineering/SKILL.md +353 -0
  44. package/skills/debugging-and-error-recovery/SKILL.md +300 -0
  45. package/skills/deprecation-and-migration/SKILL.md +252 -0
  46. package/skills/documentation-and-adrs/SKILL.md +320 -0
  47. package/skills/doubt-driven-development/SKILL.md +245 -0
  48. package/skills/frontend-ui-engineering/SKILL.md +346 -0
  49. package/skills/git-workflow-and-versioning/SKILL.md +355 -0
  50. package/skills/idea-refine/SKILL.md +195 -0
  51. package/skills/idea-refine/examples.md +238 -0
  52. package/skills/idea-refine/frameworks.md +99 -0
  53. package/skills/idea-refine/refinement-criteria.md +113 -0
  54. package/skills/idea-refine/scripts/idea-refine.sh +15 -0
  55. package/skills/incremental-implementation/SKILL.md +249 -0
  56. package/skills/interview-me/SKILL.md +235 -0
  57. package/skills/observability-and-instrumentation/SKILL.md +238 -0
  58. package/skills/performance-optimization/SKILL.md +267 -0
  59. package/skills/performance-optimization/references/optimization-patterns.md +250 -0
  60. package/skills/planning-and-task-breakdown/SKILL.md +259 -0
  61. package/skills/security-and-hardening/SKILL.md +216 -0
  62. package/skills/security-and-hardening/references/hardening-patterns.md +333 -0
  63. package/skills/shipping-and-launch/SKILL.md +336 -0
  64. package/skills/source-driven-development/SKILL.md +217 -0
  65. package/skills/spec-driven-development/SKILL.md +307 -0
  66. package/skills/test-driven-development/SKILL.md +400 -0
  67. package/skills/using-agent-skills/SKILL.md +194 -0
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: cc
3
+ description: Initialize and operate a software factory home repo. Register project checkouts, maintain central configuration, and start, inspect, resume, or provide feedback on saved engineering jobs using the shared agent-skills workflows.
4
+ ---
5
+
6
+ # Command Center
7
+
8
+ Interpret `cc` operations in chat using the host agent's normal tools. For init, the bundled helper discovers and validates the home marker from its location and the invocation directory. Use the returned home path for subsequent operations. If it reports ambiguous or missing homes, resolve that choice before proceeding. For copied plugins or legacy unmarked homes, select an explicit valid home through `--home`. Product changes belong in the target checkout's Git history.
9
+
10
+ | Request | Action |
11
+ | --- | --- |
12
+ | `cc init [repo-link-or-path]` | Clone and register a remote, or register a local checkout |
13
+ | `cc repos` | List registered repos, paths, and setup gaps |
14
+ | `cc config <repo> [change]` | Read configuration, or apply the requested change |
15
+ | `cc start <repo> <task>` | Save the request and carry the job through the engineering workflow |
16
+ | `cc status [repo] [job]` | Read saved stages, evidence, blockers, and PR links |
17
+ | `cc resume <repo> <job>` | Reconcile and continue the saved job |
18
+ | `cc feedback <repo> <job> <text>` | Save the person's answer and continue the affected stage |
19
+
20
+ Read [registration](references/registration.md) for init, repos, and config. Read [jobs](references/jobs.md) for start, status, resume, and feedback. A bare invocation describes operations without writing records.
21
+
22
+ For `cc init`, use the bundled Node helper at `scripts/init.mjs` for preparation and registration. Follow the helper contract in the registration reference. Inspect reported facts and scoped instructions, propose checks from project evidence, and select skills from its canonical home catalog. Use its completion status, effective settings, setup gaps, and validation limits when reporting the result.
23
+
24
+ Load relevant engineering skills from the home root's `skills/` on demand. Shared checklists live in the root `references/`. Read project instructions before operating there. User authorization takes precedence over skill defaults. Report conflicts that materially affect scope or checks.
25
+
26
+ Verify saved claims against files, commits, check results, and PR state. Resolve review findings and check failures before delivery. Preserve human decisions for merge and deployment.
@@ -0,0 +1,28 @@
1
+ # <repo-id>
2
+
3
+ ## Repository
4
+
5
+ - Purpose — <purpose>
6
+ - Checkout — <path relative to home root>
7
+ - Remote — <credential-free remote and GitHub owner/repo when applicable>
8
+ - Repository identity — <normalized github.com/owner/repo, or local-only when no remote exists>
9
+ - Base branch — <confirmed default branch>
10
+ - Instructions — <project instruction paths>
11
+
12
+ ## Validation
13
+
14
+ List each required command, its working directory relative to the checkout, and its purpose. Record the source of the command. List unresolved setup items explicitly.
15
+
16
+ ## Setup gaps
17
+
18
+ List unresolved essentials explicitly. The init helper records unavailable default-branch evidence and missing validation commands here.
19
+
20
+ ## Engineering skills
21
+
22
+ Record project-specific additions or exclusions. Default to relevant shared lifecycle skills and specialists warranted by the work.
23
+
24
+ ## Delivery
25
+
26
+ - Start authorizes commits, pushing the job branch, and creating or updating a ready GitHub PR after checks and review pass.
27
+ - Merge and deployment require the person's decision.
28
+ - Record project-specific delivery preferences here.
@@ -0,0 +1,23 @@
1
+ # <job-id>
2
+
3
+ - Repo — <repo-id>
4
+ - Updated — <UTC timestamp>
5
+ - Stage — <stage>
6
+ - Interrupted stage — <when blocked>
7
+ - Checkout/worktree — <absolute path>
8
+ - Branch — <job branch>
9
+ - Base commit — <commit>
10
+ - Current commit — <commit>
11
+ - PR — <URL when available>
12
+
13
+ ## Artifacts
14
+
15
+ Link the exact request, frozen config, spec, plan, authoritative task list, verification results, review, and feedback history. Record skills used and approval evidence.
16
+
17
+ ## Blocker
18
+
19
+ Record the failure or missing decision and input needed to continue. Clear the active blocker when resolved while preserving its history.
20
+
21
+ ## History
22
+
23
+ Append timestamped stages, attempts, command results, commits, findings, and feedback. Record process identifiers if execution continues beyond the current session.
@@ -0,0 +1,30 @@
1
+ # Jobs and recovery
2
+
3
+ ## Create and preserve context
4
+
5
+ Resolve the registered checkout and confirm its Git identity. Report missing checkouts or mismatched remotes as blockers. Read central configuration and current project instructions. Preserve user edits. Use a dedicated branch or isolated worktree per job and record its exact path and base commit.
6
+
7
+ Use the config's generated Instruction scope data when present. Root rules apply across the checkout, while nested rules apply only within their directory. Legacy flat instruction lists retain each file's directory scope. Read the Check validation limits and setup gaps before treating the saved checks as ready for a job.
8
+
9
+ Create a unique UTC timestamp plus short random suffix under `jobs/<repo-id>/<job-id>/`. Save the exact request, a configuration snapshot as `config.md`, and `progress.md` based on [the progress template](../assets/progress.md). Freeze selected validation commands and delivery preferences. Configure skill output destinations in the job context to use this job's spec, plan, and task list. If project instructions require their own artifact locations, record those pointers and keep one authoritative task list.
10
+
11
+ Stages are `spec`, `plan`, `build`, `verify`, `review`, `deliver`, `ready`, `blocked`, and `rejected`. A blocked record includes the interrupted stage, actual reason, and input or recovery needed. Save evidence before marking stages complete. Preserve feedback, failures, and review rounds chronologically.
12
+
13
+ ## Execute
14
+
15
+ 1. **Spec.** Apply `spec-driven-development`. Use `interview-me` or `idea-refine` when clarification is needed. Save scope and acceptance criteria. Obtain approvals required by applicable skills, counting explicit approvals already provided.
16
+ 2. **Plan.** Apply `planning-and-task-breakdown`. Save dependencies, tasks, verification steps, and checkpoints. Use `constraint-driven-development` when the project needs an agreed quality bar. Resolve material open decisions before implementation.
17
+ 3. **Build.** Apply `incremental-implementation`, `test-driven-development`, and `git-workflow-and-versioning`. Load relevant frontend, API, security, accessibility, or other specialists. Record completed tasks and commit IDs after each slice.
18
+ 4. **Verify.** Run frozen checks in their recorded working directories and verify acceptance criteria. Save commands, exit results, commit, and relevant output. Apply `debugging-and-error-recovery` to failures, returning to build or recording a blocker. Missing tools and skipped checks cannot count as passes.
19
+ 5. **Review.** Apply `code-review-and-quality` to the actual diff plus specialist reviews warranted by the changes. Save findings and resolutions. Code changes require affected checks and review to be refreshed for the new commit. Use the shared Definition of Done as the completion bar.
20
+ 6. **Deliver.** Reconfirm remote identity, base branch, reviewed commit, checks, and delivery authorization. Push only the job branch and create or update its matching GitHub PR through the host's tools. Inspect existing branch PRs before creating another. Save its URL and head commit. Mark ready only when the PR head matches the checked and reviewed commit. Publication failures block at deliver with local evidence preserved. Report the ready PR for human review.
21
+
22
+ Apply `shipping-and-launch` when release preparation is requested. A normal job ends at its ready PR. Repeated recovery without new evidence stops with the actual blocker. Keep accepted scope through rework.
23
+
24
+ ## Status, resume, and feedback
25
+
26
+ Status reads records, reports their timestamps and stages, links evidence and PRs, and flags absent checkouts. Repo-only status lists its jobs. Omitted repo lists all jobs. An ambiguous job ID requires its repo ID. Status starts no work and writes no records.
27
+
28
+ Resume reads the request, saved config, tasks, feedback, checks, and reviews. Reconcile checkout identity, branch/worktree, current HEAD, dirty files, recorded processes, and PR state. A live recorded process must finish before another attempt starts. Preserve unexpected edits and resolve ownership before continuing. Evidence for another commit is stale. Record discrepancies and refresh affected verification and review before delivery. Report manually merged PRs from actual GitHub evidence.
29
+
30
+ Feedback saves the person's exact words, timestamp, and blocked stage. Apply only what the answer resolves, then reconcile and resume. Configuration changes after creation affect the job only through an explicitly requested amendment saved in history.
@@ -0,0 +1,63 @@
1
+ # Registration and central configuration
2
+
3
+ Run the bundled helper with Node.js 22 or newer and Git available. It discovers the home from canonical ancestors of the invocation directory and helper location. Explicit `--home` selects a home directly. Multiple candidates require a choice. Plugin caches are excluded from automatic discovery. Use the original valid home explicitly for a copied plugin. Existing bootstrap markers are accepted. Unmarked homes need a valid marker before discovery can use them.
4
+
5
+ ## `cc init` procedure
6
+
7
+ 1. Call `node <skill>/scripts/init.mjs prepare --cwd <invocation-directory> --source <repo-link-or-path>` with separate, quoted arguments. Use `--home` when selecting a specific home. Omit `--source` when the user omitted it. At the home root, an omitted source produces `SOURCE_REQUIRED`.
8
+ 2. Read the returned home, version-2 report, structured facts, catalog, and inspection paths. Instruction scopes identify root and nested governing directories. Read only the instructions applicable to the work's directory, in ancestor order. A template instruction file governs its template directory. Keep the preparation report path.
9
+ 3. Choose checks using explicit project instructions first, then CI commands, then documented manifest scripts. Record each command's working directory and exact source file. List unresolved conflicts and missing essentials as setup gaps. Registration does not execute checks.
10
+ 4. Save a UTF-8 details JSON file in the home `.cc/` directory using the shape below. Populate purpose, relevant skill names, check proposals, and gaps from inspection. Existing chosen settings survive repeats.
11
+ 5. Call `node <skill>/scripts/init.mjs register --home <returned-home> --report <report-path> --details <details-file>`. Read its exit code and JSON response. Report its `status`, identifiers, exact `changes`, effective `settings`, `setupGaps`, and `validationLimits` after success. Preparation changes and registration changes describe their respective operations.
12
+
13
+ ```json
14
+ {
15
+ "purpose": "Project purpose supported by its documentation",
16
+ "checks": [
17
+ { "command": "npm test", "workingDirectory": ".", "source": "AGENTS.md" }
18
+ ],
19
+ "skills": ["test-driven-development"],
20
+ "setupGaps": []
21
+ }
22
+ ```
23
+
24
+ Every check source must be in the inspection report. Working directories are relative to the checkout and must stay inside it. Supply empty arrays and explicit gaps when no checks or specialist skills are known. A missing purpose, missing checks, or unavailable default branch automatically creates a setup gap for a new record. The agent resolves command meaning and conflicts from project evidence. The helper validates structure and saves the result.
25
+
26
+ ## Facts and validation
27
+
28
+ The helper reads data formats without executing project code. Structured facts cover Node package manifests and npm/pnpm/Yarn/Bun evidence, Python pyproject/Pipfile/requirements and uv/Poetry/Pipenv evidence, Go module/workspace declarations, and Rust package/workspace manifests. Workspace patterns are expanded against discovered projects with exclusions and repository boundaries. Each fact carries source evidence. Lockfiles marked `presence_only` establish their tool's presence without claiming their dependency contents were parsed. Unsupported or malformed manifests produce diagnostics and setup gaps.
29
+
30
+ Supported check structures include explicit Node script runners (`npm run`, `npm run-script`, `pnpm run`, `yarn run`, `bun run`), declared lifecycle aliases, Python declared entry points through `uv run`, `poetry run`, or `pipenv run`, basic `go test`, and Cargo check commands with the documented flags in the helper. Package scripts and Cargo package selections must exist in the relevant project/workspace. The selected manager must agree with confirmed declaration/lockfile evidence.
31
+
32
+ Successful structural resolution returns `verified_structure`. Custom commands, unsupported flags, external Python tools, and compound shell expressions return `unresolved_structure` with explicit limits and setup gaps. This status covers the command's declared structure. Check adequacy and runtime success require the job's actual verification stage.
33
+
34
+ Select skills from `catalog.skills`. Names must resolve to one valid canonical `home/skills/` entry. Discovery copies and user/project libraries do not add catalog entries. Missing or ambiguous selected skills produce `SKILL_INVALID`. Unselected malformed entries are returned as catalog diagnostics.
35
+
36
+ ## Freshness and saved records
37
+
38
+ Preparation fingerprints instruction files, manifests, lockfiles, CI, documentation, and home skill entry points. Registration compares content and membership, then rederives facts from the current files. `INSPECTION_STALE` identifies changed paths and requires another preparation and agent inspection. Version-1 reports also require preparation again. Resolve parse, catalog, or command validation errors before retrying registration.
39
+
40
+ Configs retain editable Markdown settings and user notes. Generated Project facts, Instruction scope, and Check validation sections have `cc-init` ownership markers. The helper refreshes those sections and missing factual metadata while preserving existing chosen settings. Use `cc config` to amend those settings. Do not edit the preparation report to override facts.
41
+
42
+ Completion status is `created` for a new config, `repaired` for a changed existing config/index, and `reused` when both are unchanged. The compatibility `reused` boolean indicates that a config previously existed. Repeat-run results reflect saved settings and identify legacy validation prose that needs review.
43
+
44
+ ## Fixed helper behavior
45
+
46
+ - Existing local paths take precedence over `owner/repo` shorthand. Remote inputs accept GitHub HTTPS root links, `git@github.com:owner/repo[.git]`, `ssh://git@github.com/owner/repo[.git]`, and `owner/repo`. Terminal `.git` and trailing slashes are removed for identity. Extra path segments, queries, fragments, other hosts, traversal, and credential-bearing URLs are rejected. The SSH user `git` is permitted.
47
+ - GitHub identities are lowercase `github.com/owner/repo`. New remote IDs are lowercase `owner--repo`, with `projects/<owner>/<repo>` checkouts. HTTPS links and shorthand clone through canonical HTTPS. SSH inputs clone through canonical SCP-style SSH. Git receives the argument array `clone`, `--`, URL, destination. Existing Git authentication applies.
48
+ - All central configs are searched before cloning. Missing identity metadata is derived from supported remote fields. Duplicate identities, malformed configs, and ID collisions stop the operation. Existing IDs, paths, and chosen settings are retained. Missing recorded checkouts require recovery.
49
+ - An existing destination must be its own Git top-level with a matching origin. A conflicting directory or origin is preserved and reported. Linked paths inside home cannot redirect a clone or registry write outside it.
50
+ - The helper ensures `/projects/` and `/.cc/` ignore rules are effective before cloning. Failed clones remain unregistered. Inspect any partial destination before retrying. Cleanup and relocation require an explicit recovery decision.
51
+ - Inspection resolves the primary checkout and common Git directory, origin, current branch, and default-branch evidence from `refs/remotes/origin/HEAD`. It lists project instructions, manifests, lockfiles, CI, and documentation in sorted order, skipping dependency and generated directories. It reads filenames and Git metadata. The agent reads the selected files to derive project meaning.
52
+ - New local registrations use lowercase checkout basenames with spaces replaced by hyphens. Local-only and non-GitHub-origin repositories match by their canonical primary checkout. Earlier local IDs for a GitHub identity are retained.
53
+ - Preparation reports live in `.cc/init/`. Registration rechecks checkout identity and scans configs again under an exclusive `.cc/init.lock`. It atomically writes config first, then adds one stable relative index link. Repeats repair missing factual metadata and missing links, preserving saved settings and index organization. An interrupted index write is repaired by repeating registration.
54
+
55
+ Both helper operations return JSON with `ok: true` on success. Errors return nonzero with `ok: false` and a redacted error. Stop at a helper refusal. A lock records its PID and start time. Inspect the owner and any Git child processes before recovering a stale lock. Never remove a lock owned by a live operation.
56
+
57
+ ## Repos and config
58
+
59
+ `cc repos` reads the index and configs and reports paths and setup gaps. Inspection writes nothing. Above about 20 repos, group index links by purpose while retaining stable IDs.
60
+
61
+ `cc config <repo>` displays settings. A requested change updates only those settings. Commands resolve relative to the checkout, and skills relative to home. Changes affect future jobs. Existing jobs retain their saved config.
62
+
63
+ Central configuration owns factory settings. Project instructions apply in their repository. Inspect and report disagreements with central commands before claiming verification. Ask only for material choices that project evidence cannot settle.
@@ -0,0 +1,109 @@
1
+ import { posix } from 'node:path';
2
+ import { applicableInstructions } from './inspection.mjs';
3
+ import { failure } from './errors.mjs';
4
+
5
+ function projectAt(facts, cwd, ecosystem) {
6
+ return facts.projects.filter(item => item.ecosystem === ecosystem && (item.path === '.' || item.path === cwd || cwd.startsWith(`${item.path}/`)))
7
+ .sort((a, b) => b.path.length - a.path.length)[0];
8
+ }
9
+
10
+ function invalid(message) { throw failure('CHECK_INVALID', message); }
11
+
12
+ export function validateSkills(names, catalog) {
13
+ for (const name of names) {
14
+ const matches = catalog.skills.filter(skill => skill.name === name);
15
+ if (matches.length !== 1 || !matches[0].valid) throw failure('SKILL_INVALID', `Skill ${name} does not resolve to one valid canonical home entry.`, { paths: matches.map(skill => skill.path) });
16
+ }
17
+ return names.map(name => catalog.skills.find(skill => skill.name === name));
18
+ }
19
+
20
+ function validateManager(project, selected) {
21
+ if (project.manager.status === 'conflicting') invalid(`Package-manager evidence conflicts for ${project.path}.`);
22
+ if (project.manager.name && project.manager.name !== selected) invalid(`Selected manager ${selected} contradicts ${project.manager.name} for ${project.path}.`);
23
+ return project.manager.name ? [] : ['Package-manager selection has no confirmed declaration or lockfile evidence.'];
24
+ }
25
+
26
+ export function validateChecks(checks, facts, scopes) {
27
+ return checks.map(check => {
28
+ const cwd = posix.normalize(check.workingDirectory.replaceAll('\\', '/'));
29
+ const result = { command: check.command, workingDirectory: check.workingDirectory, source: check.source,
30
+ applicableInstructions: applicableInstructions(scopes, cwd).map(item => item.path), validationStatus: 'unresolved_structure', limits: [], evidence: [] };
31
+ if (/\r|\n|\0/.test(check.command)) invalid('Check command must be a single line.');
32
+ if (/[;&|<>`$]|\$\(/.test(check.command)) {
33
+ result.limits.push('Custom or compound command requires project-specific interpretation.');
34
+ return result;
35
+ }
36
+ // Recognize a deliberately small command grammar. Shell expansion remains opaque.
37
+ const tokens = check.command.trim().split(/\s+/);
38
+ const runner = tokens[0];
39
+ for (let index = 1; index < tokens.length; index++) {
40
+ const match = /^(--prefix|--cwd|--dir|-C|--manifest-path)(?:=(.*))?$/.exec(tokens[index]);
41
+ if (match) {
42
+ const target = match[2] ?? tokens[index + 1];
43
+ if (!target) invalid('Check path override is missing its target.');
44
+ const path = posix.normalize(posix.join(cwd, target.replaceAll('\\', '/')));
45
+ if (posix.isAbsolute(target) || /^[a-z]:/i.test(target) || path === '..' || path.startsWith('../')) invalid('Check target escapes the checkout.');
46
+ }
47
+ }
48
+ const node = projectAt(facts, cwd, 'node');
49
+ if (['npm', 'pnpm', 'yarn', 'bun'].includes(runner)) {
50
+ if (node) result.limits.push(...validateManager(node, runner));
51
+ let script;
52
+ let argsStart;
53
+ if (tokens[1] === 'run' || runner === 'npm' && tokens[1] === 'run-script') { script = tokens[2]; argsStart = 3; }
54
+ else if (['test', 'start', 'stop', 'restart'].includes(tokens[1]) && runner !== 'bun') { script = tokens[1]; argsStart = 2; }
55
+ if (!script || !/^[a-z0-9:._-]+$/i.test(script) || tokens.length > argsStart && tokens[argsStart] !== '--') {
56
+ result.limits.push('Package-manager command is outside the supported script-invocation grammar.'); return result;
57
+ }
58
+ if (!node || node.path !== cwd) invalid('Package script must run from the directory containing its package.json.');
59
+ if (!Object.hasOwn(node.scripts, script)) invalid(`Package script ${script} does not exist in ${node.manifest}.`);
60
+ result.evidence.push(node.scripts[script].evidence, ...node.manager.evidence);
61
+ } else if (runner === 'go' && tokens[1] === 'test') {
62
+ const project = projectAt(facts, cwd, 'go');
63
+ if (!project) invalid('go test requires a discovered Go module or workspace.');
64
+ if (tokens.slice(2).some(token => !['.', './...', '-race', '-v', '-cover', '-short'].includes(token) && !/^-count=\d+$/.test(token))) {
65
+ result.limits.push('Go flags or targets require project-specific interpretation.'); return result;
66
+ }
67
+ result.evidence.push(project.evidence.path);
68
+ } else if (runner === 'cargo' && ['test', 'check', 'clippy', 'fmt'].includes(tokens[1])) {
69
+ const project = projectAt(facts, cwd, 'rust');
70
+ if (!project) invalid('Cargo checks require a discovered Cargo project or workspace.');
71
+ const workspace = facts.projects.filter(item => item.ecosystem === 'rust' && item.workspace?.status === 'resolved' && item.workspace.members.includes(project.path)).sort((a, b) => b.path.length - a.path.length)[0] || project;
72
+ for (let index = 2; index < tokens.length; index++) {
73
+ if (tokens[index] !== '-p' && tokens[index] !== '--package') continue;
74
+ const name = tokens[index + 1];
75
+ if (!facts.projects.some(item => item.ecosystem === 'rust' && item.name === name && (item.path === workspace.path || workspace.workspace?.members.includes(item.path)))) invalid('Cargo package is outside the discovered workspace.');
76
+ }
77
+ if (tokens.some(token => /^--(?:manifest-path|config|target-dir)/.test(token))) {
78
+ result.limits.push('Cargo path/config overrides require project-specific interpretation.'); return result;
79
+ }
80
+ const supported = new Set(['--workspace', '--all-targets', '--all-features', '--no-default-features', '--locked', '--offline', '--quiet', '--verbose', '-q', '-v']);
81
+ const options = tokens.slice(2).filter((token, index, list) => token !== '-p' && token !== '--package' && list[index - 1] !== '-p' && list[index - 1] !== '--package');
82
+ if (options.some(token => !supported.has(token))) {
83
+ result.limits.push('Cargo flags or targets require project-specific interpretation.'); return result;
84
+ }
85
+ result.evidence.push(project.evidence.path, ...(workspace.workspace?.evidence || []));
86
+ } else {
87
+ let python = projectAt(facts, cwd, 'python');
88
+ let script;
89
+ if (['uv', 'poetry', 'pipenv'].includes(runner) && tokens[1] === 'run') script = tokens[2];
90
+ if (python && script) {
91
+ const candidates = facts.projects.filter(item => item.ecosystem === 'python' && item.path === python.path && Object.hasOwn(item.scripts, script));
92
+ if (new Set(candidates.map(item => item.scripts[script].command)).size > 1) invalid('Python entry point has conflicting declarations.');
93
+ python = candidates[0] || python;
94
+ result.limits.push(...validateManager(python, runner));
95
+ }
96
+ if (python && script && Object.hasOwn(python.scripts, script) && tokens.length === 3) {
97
+ result.evidence.push(python.scripts[script].evidence, ...python.manager.evidence);
98
+ } else {
99
+ result.limits.push('Custom command or external Python tool cannot be resolved from declared entry points.'); return result;
100
+ }
101
+ }
102
+ result.validationStatus = result.limits.length ? 'unresolved_structure' : 'verified_structure';
103
+ return result;
104
+ });
105
+ }
106
+
107
+ export function checkGaps(checks) {
108
+ return checks.filter(check => check.validationStatus !== 'verified_structure').map(check => `Check ${check.command} requires confirmation. ${check.limits.join(' ')}`);
109
+ }
@@ -0,0 +1,3 @@
1
+ export function failure(code, message, context = {}) {
2
+ return Object.assign(new Error(message), { code, ...context });
3
+ }
@@ -0,0 +1,60 @@
1
+ import { lstat, readFile, realpath } from 'node:fs/promises';
2
+ import { resolve, dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { failure } from './errors.mjs';
5
+
6
+ async function info(path) {
7
+ try { return await lstat(path); }
8
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
9
+ }
10
+
11
+ export async function validateHome(path) {
12
+ try {
13
+ const home = await realpath(resolve(path));
14
+ const markerPath = join(home, '.command-center.json');
15
+ const markerInfo = await info(markerPath);
16
+ if (!markerInfo?.isFile() || markerInfo.isSymbolicLink()) throw new Error('Home marker is missing or linked.');
17
+ const marker = JSON.parse(await readFile(markerPath, 'utf8'));
18
+ if (marker.kind !== 'command-center-home' || (marker.schemaVersion !== undefined && marker.schemaVersion !== 1) ||
19
+ typeof marker.templateVersion !== 'string' || !/^\d+\.\d+\.\d+(?:[-+][a-z0-9.-]+)?$/i.test(marker.templateVersion) ||
20
+ !Array.isArray(marker.agents) || marker.agents.some(agent => !['codex', 'claude'].includes(agent)) ||
21
+ new Set(marker.agents).size !== marker.agents.length) throw new Error('Unsupported home marker.');
22
+ for (const name of ['repos', 'skills', 'skills/cc']) {
23
+ const entry = await info(join(home, name));
24
+ if (!entry?.isDirectory() || entry.isSymbolicLink()) throw new Error(`Required home directory is missing or linked: ${name}`);
25
+ }
26
+ for (const name of ['AGENTS.md', 'skills/cc/SKILL.md']) {
27
+ const entry = await info(join(home, name));
28
+ if (!entry?.isFile() || entry.isSymbolicLink()) throw new Error(`Required home file is missing or linked: ${name}`);
29
+ }
30
+ return { home, marker };
31
+ } catch (error) {
32
+ throw failure('HOME_INVALID', `Invalid home at ${resolve(path)}. ${error.message}`);
33
+ }
34
+ }
35
+
36
+ function pluginCache(path) {
37
+ return /\/(?:\.codex|\.claude)\/plugins\/cache(?:\/|$)/i.test(path.replaceAll('\\', '/'));
38
+ }
39
+
40
+ export async function discoverHome({ home, cwd = process.cwd(), helperDirectory = dirname(fileURLToPath(import.meta.url)) } = {}) {
41
+ if (home) return { ...await validateHome(home), selectedBy: 'explicit' };
42
+ const candidates = new Map();
43
+ for (const start of [cwd, helperDirectory]) {
44
+ let current = await realpath(resolve(start));
45
+ if (pluginCache(current)) continue;
46
+ while (true) {
47
+ if (await info(join(current, '.command-center.json'))) {
48
+ const candidate = await validateHome(current);
49
+ const key = process.platform === 'win32' ? candidate.home.toLowerCase() : candidate.home;
50
+ candidates.set(key, candidate);
51
+ }
52
+ const parent = dirname(current);
53
+ if (parent === current) break;
54
+ current = parent;
55
+ }
56
+ }
57
+ if (!candidates.size) throw failure('HOME_NOT_FOUND', 'No home marker found. Supply --home with a valid Command Center home.');
58
+ if (candidates.size > 1) throw failure('HOME_AMBIGUOUS', 'Multiple homes found. Select one with --home.', { candidates: [...candidates.values()].map(item => item.home).sort() });
59
+ return { ...candidates.values().next().value, selectedBy: 'discovered' };
60
+ }