diff --git a/.changeset/remove-unused-internal-code.md b/.changeset/remove-unused-internal-code.md
new file mode 100644
index 00000000..d2fc0cc9
--- /dev/null
+++ b/.changeset/remove-unused-internal-code.md
@@ -0,0 +1,5 @@
+---
+'@tanstack/intent': patch
+---
+
+Remove unused internal helpers, duplicate path and type guards, and dead branches. Move workspace resolution into `core` and split shared utilities by job. Exports and behavior do not change.
diff --git a/.changeset/shorten-meta-skill-wording.md b/.changeset/shorten-meta-skill-wording.md
new file mode 100644
index 00000000..bdbe21ab
--- /dev/null
+++ b/.changeset/shorten-meta-skill-wording.md
@@ -0,0 +1,5 @@
+---
+'@tanstack/intent': patch
+---
+
+Shorten the wording of the bundled `domain-discovery`, `generate-skill`, `tree-generator`, and `skill-staleness-check` skills. Instructions do not change.
diff --git a/README.md b/README.md
index f62b7d98..1a394c3d 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,7 @@
--
+
@@ -72,14 +72,14 @@ A CLI for library maintainers to generate, validate, and ship [Agent Skills](htt
-
+
-
+
diff --git a/docs/cli/intent-maintainer.md b/docs/cli/intent-maintainer.md
index 44e1c3e5..c8d69590 100644
--- a/docs/cli/intent-maintainer.md
+++ b/docs/cli/intent-maintainer.md
@@ -123,7 +123,7 @@ Generated commands do not pin a revision or match the application's installed de
Intent preserves existing plugin version fields. Claude uses an explicit plugin version to decide whether an update is available: bump the authoritative plugin version when releasing changed content. Without a version in either the plugin or its marketplace entry, Git-based Claude installs use the source commit. Updating an npm package version alone does not update plugin metadata.
-Publish through the library's normal release process. Repository exports do not submit marketplace listings, publish releases, or update consumer installations. State the supported package versions in implementation skills and check them against the consumer's dependencies. Consumers manage updates and removal through their chosen installer.
+Repository exports do not submit marketplace listings, publish releases, or update consumer installations. State the supported package versions in implementation skills and check them against the consumer's dependencies. Consumers manage updates and removal through their chosen installer.
## Maintain and check
@@ -135,7 +135,7 @@ Publish through the library's normal release process. Repository exports do not
-Status accepts `--json` and an actual Git comparison base with `--base [`. Sync copies descriptions, purpose, sources, and prerequisites from the registered skills into the tree. It also adds the package discovery keyword and includes each skill directory in existing `files` allowlists. An absent allowlist stays absent, preserving npm's default contents. Sync prints each path it synchronized, or `Nothing to synchronize.` when every file is current, and labels the consumer install commands when repository distribution is selected. Inspect the actual packed archive in the library's release checks.
+Status accepts `--json` and a Git comparison base with `--base ][`. Sync copies descriptions, purpose, sources, and prerequisites from the registered skills into the tree. It also adds the package discovery keyword and includes each skill directory in existing `files` allowlists. An absent allowlist stays absent, preserving npm's default contents. Sync prints each path it synchronized, or `Nothing to synchronize.` when every file is current, and labels the consumer install commands when repository distribution is selected. Inspect the packed archive in the library's release checks.
`maintainer review --interactive` is the human path. It walks each pending item in the terminal, shows the current guidance and changed files, and records the chosen outcomes with reason and evidence. It requires a terminal outside CI.
diff --git a/docs/cli/intent-review.md b/docs/cli/intent-review.md
index ab3db2e5..88da317d 100644
--- a/docs/cli/intent-review.md
+++ b/docs/cli/intent-review.md
@@ -33,7 +33,7 @@ A justified no-op is a completed review. Missing evidence remains pending.
| Option | Behavior |
| --- | --- |
| `[dir]` | Locate the Git working tree. The review covers that repository, including its packages. |
-| `--base ][` | Compare against an available Git commit or ref, such as the actual PR base. |
+| `--base ][` | Compare against an available Git commit or ref, such as the PR base. |
| `--json` | Print the complete structured report for an agent or script. |
| `--check` | Exit nonzero when review items remain. |
@@ -159,7 +159,7 @@ For a human terminal, run the interactive command from the library repository:
-Inspect each item's current guidance and changed files, choose an outcome, and supply the reason and actual evidence. The changes view compares tracked files with the displayed Git base and includes untracked content. Use `--base ` for a specific comparison. Edit and test guidance before starting; changes during review invalidate the affected outcomes.
+Inspect each item's current guidance and changed files, choose an outcome, and supply the reason and evidence. The changes view compares tracked files with the displayed Git base and includes untracked content. Use `--base ` for a specific comparison. Edit and test guidance before starting; changes during review invalidate the affected outcomes.
Choose **Leave pending** when more work is needed. Items with unresolved source mappings or planning problems cannot be completed. The final preview lists the proposed outcomes and evidence. Confirmation records through the same fingerprint checks as `--record`; cancellation records nothing. Evidence text is stored, not executed or independently verified.
diff --git a/docs/cli/intent-stale.md b/docs/cli/intent-stale.md
index 9047f847..8c4963c2 100644
--- a/docs/cli/intent-stale.md
+++ b/docs/cli/intent-stale.md
@@ -121,7 +121,7 @@ Reason generation:
The existing `--github-review` workflow mode writes `review-items.json` and, when there are items, `pr-body.md`. Its Agent Review instructions route to `generate-skill` and its conditional review-signals reference. The command itself does not create a remote PR or edit skills; the installed GitHub workflow handles the review reminder.
-Version drift and missing stored source SHAs do not prove that guidance is wrong. Review actual source changes before editing. Missing evidence stays unresolved, and an evidence-backed no-op may leave a signal flagged. Failed checks require logs; workflow advisories are separate maintenance items. Neither is a reason to rewrite skills.
+Version drift and missing stored source SHAs do not prove that guidance is wrong. Review the source changes before editing. Missing evidence stays unresolved, and an evidence-backed no-op may leave a signal flagged. Failed checks require logs; workflow advisories are separate maintenance items. Neither is a reason to rewrite skills.
### `stale` and `review` serve different checks
diff --git a/docs/concepts/trust-model.md b/docs/concepts/trust-model.md
index 48bed8f5..b2bbe6a2 100644
--- a/docs/concepts/trust-model.md
+++ b/docs/concepts/trust-model.md
@@ -37,9 +37,9 @@ Workspace discovery checks ancestors up to the first workspace declaration or Gi
When no effective policy exists, `intent install` follows this flow:
-1. **Discover:** summarize npm and workspace skill counts. Descriptions and exclusions are available through optional inspection.
-2. **Choose:** enable all sources, choose packages or scopes, or select individual skills. Package and scope selections stay compact and include future matching skills. A whole scope requires an explicit selection.
-3. **Confirm once:** show the current skill count, saved rules, and destination file. Optional individual review opens skill lists only for the selected packages you choose to inspect. It can add exclusions while retaining broad rules; unreviewed packages keep their selection. Only affirmative confirmation saves permissions and exclusions atomically, then installs guidance. An empty selection explicitly confirms disabling all skills.
+1. Summarize npm and workspace skill counts. Descriptions and exclusions are available through optional inspection.
+2. Enable all sources, choose packages or scopes, or select individual skills. Package and scope selections stay compact and include future matching skills. A whole scope requires an explicit selection.
+3. Confirm the current skill count, saved rules, and destination file. Optional individual review opens skill lists only for the selected packages you choose to inspect. It can add exclusions while retaining broad rules; unreviewed packages keep their selection. Only affirmative confirmation saves permissions and exclusions atomically, then installs guidance. An empty selection explicitly confirms disabling all skills.
| Outcome | Files changed |
| --- | --- |
diff --git a/docs/getting-started/quick-start-consumers.md b/docs/getting-started/quick-start-consumers.md
index b759bfda..61459344 100644
--- a/docs/getting-started/quick-start-consumers.md
+++ b/docs/getting-started/quick-start-consumers.md
@@ -57,13 +57,7 @@ Project-scoped hooks are installed for Claude Code and Codex. `intent install` c
Cursor and generic `AGENTS.md` agents use the guidance block only.
-Hooks return the available Intent skill catalog as context for supported agent sessions and keep the edit gate active until they observe a supported `intent load` command.
-
-Hooks do not verify that:
-
-- The command succeeded.
-- The skill matched the task.
-- The agent applied the guidance.
+Hooks return the available Intent skill catalog as context for supported agent sessions and keep the edit gate active until they observe a supported `intent load` command. See [intent hooks](../cli/intent-hooks) for what hooks do not verify.
To control what appears in the session catalog, configure `intent.skills` and `intent.exclude` in `package.json`.
diff --git a/docs/getting-started/quick-start-maintainers.md b/docs/getting-started/quick-start-maintainers.md
index b613eaf7..25f88d96 100644
--- a/docs/getting-started/quick-start-maintainers.md
+++ b/docs/getting-started/quick-start-maintainers.md
@@ -102,7 +102,7 @@ Selecting skills for repository distribution requires registered, authored skill
-Use the actual registered names; each must be a tree entry whose `SKILL.md` exists. When the repository, plugin name, or selection cannot be resolved, setup reports every missing input in one error. This records the selection in the skill tree. `maintainer sync` generates plugin metadata pointing to the existing package directories and prints consumer commands for `npx skills add` and `gh skill add`. Consumers can also use the native Claude or Cursor plugin flow. No second copy of the skill text is created, and later skills are not added automatically.
+Use the registered names; each must be a tree entry whose `SKILL.md` exists. When the repository, plugin name, or selection cannot be resolved, setup reports every missing input in one error. This records the selection in the skill tree. `maintainer sync` generates plugin metadata pointing to the existing package directories and prints consumer commands for `npx skills add` and `gh skill add`. Consumers can also use the native Claude or Cursor plugin flow. No second copy of the skill text is created, and later skills are not added automatically.
To explicitly record package-only distribution or turn off earlier repository exports:
diff --git a/docs/overview.md b/docs/overview.md
index d80492c8..d6b0806d 100644
--- a/docs/overview.md
+++ b/docs/overview.md
@@ -28,7 +28,7 @@ Intent provides tooling for two workflows:
- Ship skills in the same release pipeline as code
- Review version, source, artifact, and package coverage signals
-## Keep the workflow boundaries clear
+## Workflow stages
| Stage | Who runs it | Result |
| --- | --- | --- |
diff --git a/docs/registry.md b/docs/registry.md
index 0a686d42..ab76fbe9 100644
--- a/docs/registry.md
+++ b/docs/registry.md
@@ -50,7 +50,7 @@ This adds the `tanstack-intent` keyword and registered skill directories to exis
-Save the report under `.intent/`, assess the pending items, and annotate completed outcomes with their reasons and actual evidence. Record the report with `intent maintainer review --record `, then run `intent maintainer check`. This checks skill structure, registration, generated files, and pending reviews together. See the [source-review reference](./cli/intent-review) for report fields and recording.
+Save the report under `.intent/`, assess the pending items, and annotate completed outcomes with their reasons and evidence. Record the report with `intent maintainer review --record `, then run `intent maintainer check`. This checks skill structure, registration, generated files, and pending reviews together. See the [source-review reference](./cli/intent-review) for report fields and recording.
### 4. Publish
diff --git a/packages/intent/meta/domain-discovery/SKILL.md b/packages/intent/meta/domain-discovery/SKILL.md
index 8f237f5b..ff91d776 100644
--- a/packages/intent/meta/domain-discovery/SKILL.md
+++ b/packages/intent/meta/domain-discovery/SKILL.md
@@ -40,14 +40,14 @@ The lightweight path produces identical output artifacts (domain_map.yaml and sk
These rules override any other reasoning. No exceptions.
-1. **Phases 2 and 4 are interactive interviews conducted with the maintainer.** You must ask the questions specified in each sub-section and wait for the maintainer's response before continuing. Documentation, source code, and other automated analysis are NOT substitutes for the maintainer's answers.
-2. **Every question in Phases 2 and 4 must be asked as an open-ended question and sent as a message to the maintainer.** You must then STOP and WAIT for their reply. Do not answer your own questions. Do not infer answers from documentation. Do not skip questions because you believe you already know the answer.
-3. **Never ask factual questions you can answer by searching the codebase.** Before asking any question, determine whether the answer is a deterministic fact (how many X exist, what versions are supported, which files implement Y) or a judgment call (which ones matter, what should we prioritize, what do developers struggle with). Factual questions must be answered by searching the code — grep, glob, read files. Only ask the maintainer for priorities, opinions, trade-offs, and implicit knowledge that cannot be found in code or docs. Asking the maintainer a question whose answer is sitting in the codebase wastes their time and erodes trust in the process.
+1. **Phases 2 and 4 are interactive interviews conducted with the maintainer.** You must ask the questions specified in each sub-section and wait for the maintainer's response before continuing. Documentation, source code, and other automated analysis are not substitutes for the maintainer's answers.
+2. **Every question in Phases 2 and 4 must be asked as an open-ended question and sent as a message to the maintainer.** You must then stop and wait for their reply. Do not answer your own questions. Do not infer answers from documentation. Do not skip questions because you believe you already know the answer.
+3. **Never ask factual questions you can answer by searching the codebase.** Before asking any question, determine whether the answer is a deterministic fact (how many X exist, what versions are supported, which files implement Y) or a judgment call (which ones matter, what should we prioritize, what do developers struggle with). Factual questions must be answered by searching the code — grep, glob, read files. Only ask the maintainer for priorities, opinions, trade-offs, and implicit knowledge that cannot be found in code or docs.
4. **Do not convert open-ended questions into multiple-choice, yes/no, or confirmation prompts.** The question templates in each sub-section are open-ended by design. Present them as open-ended questions. The maintainer's unprompted answers surface knowledge that pre-structured options suppress.
5. **Minimum question counts are enforced.** Each sub-section specifies a question count range (e.g. "2–4 questions"). You must ask at least the minimum number. Asking zero questions in any sub-section is a protocol violation.
6. **STOP gates are mandatory.** At the boundaries marked `── STOP ──` below, you must halt execution and wait for the maintainer's response or acknowledgment before proceeding. Do not continue past a STOP gate in the same message.
7. **If the maintainer asks to skip an interview phase**, explain the value of the phase and what will be lost. Proceed with skipping only if they confirm a second time.
-8. **Rich documentation makes interviews MORE valuable, not less.** When docs are comprehensive, the interview surfaces what docs miss: implicit knowledge, AI-specific failure modes, undocumented tradeoffs, and the maintainer's prioritization of what matters most. Never rationalize skipping interviews because documentation is thorough.
+8. **Rich documentation makes interviews more valuable, not less.** When docs are comprehensive, the interview surfaces what docs miss: implicit knowledge, AI-specific failure modes, undocumented tradeoffs, and the maintainer's prioritization of what matters most. Never rationalize skipping interviews because documentation is thorough.
---
@@ -202,7 +202,7 @@ Adapt from this bank of gap-targeted question templates:
### 4c — AI-agent-specific failure modes (2–4 questions)
-These target mistakes that AI coding agents make but human developers typically don't. Agent-specific failures are often the highest-value findings — in testing, maintainer answers to these questions produced the most critical failure modes.
+These target mistakes that AI coding agents make but human developers typically don't. Agent-specific failures are often the highest-value findings.
- "What mistakes would an AI coding agent make that a human developer wouldn't? Think about: hallucinating APIs that don't exist, defaulting to language primitives instead of library abstractions, choosing the wrong adapter or integration path."
- "When an agent generates code using your library, what's the first thing you'd check? What pattern would make you immediately say 'an AI wrote this'?"
diff --git a/packages/intent/meta/generate-skill/SKILL.md b/packages/intent/meta/generate-skill/SKILL.md
index 8ac783d7..af4844c0 100644
--- a/packages/intent/meta/generate-skill/SKILL.md
+++ b/packages/intent/meta/generate-skill/SKILL.md
@@ -23,7 +23,7 @@ Check repository instructions and Git status before edits; preserve unrelated ch
Before choosing or changing repository exports, follow [repository distribution](references/distribution.md). For an export-only change, complete that procedure against existing skill records; use the authoring steps below only if guidance must change.
-For an initial skill set or a request spanning several developer tasks, read [initial batches](references/initial-batches.md). Reuse scope already approved in the conversation. For one concrete task, proceed directly below. During ordinary library work, keep the code change as the primary task. Read [source review](references/source-review.md) to identify affected guidance from actual changes and record completed reviews before handing off any of these workflows.
+For an initial skill set or a request spanning several developer tasks, read [initial batches](references/initial-batches.md). Reuse scope already approved in the conversation. For one concrete task, proceed directly below. During ordinary library work, keep the code change as the primary task. Read [source review](references/source-review.md) to identify affected guidance from the changes and record completed reviews before handing off any of these workflows.
For every authoring batch or update, read [the planning record procedure](references/planning-records.md) and create or incrementally maintain `domain_map.yaml`, `skill_spec.md`, and `skill_tree.yaml`. Read existing records first and preserve prior scope and decisions. These records grow with the batches; maintaining them does not require a full-library interview or generating every planned skill.
@@ -31,7 +31,7 @@ When the input is an `intent stale` report or generated review PR, read [review-
## 2. Read the evidence and choose the owner
-Read the relevant source, types, tests, docs, examples, and existing skills with their required references. Follow imports or related guidance where they affect the task. Record the source revision or package version used. For an update, inspect the supplied change and the existing skill's claims; use an actual diff or documented before/after behavior when available. A version change alone does not establish changed behavior or a baseline.
+Read the relevant source, types, tests, docs, examples, and existing skills with their required references. Follow imports or related guidance where they affect the task. Record the source revision or package version used. For an update, inspect the supplied change and the existing skill's claims; use a diff or documented before/after behavior when available. A version change alone does not establish changed behavior or a baseline.
Prefer updating guidance that already owns the task. Create one new skill only when developers would benefit from discovering that task independently. Clarify an ambiguous boundary with a concrete example: would a developer trying this task need the same guidance, or a different prerequisite or workflow? Keep the library's established names and terminology.
@@ -49,7 +49,7 @@ No fixed interview or review-preference question is needed for one task.
Apply the writing rules below to each task in the agreed batch. For a **new skill**, read [the skill format](references/skill-format.md) for frontmatter, body, and prerequisite conventions. Source documentation can establish the batch’s evidence; create or extend its required planning record alongside the skills.
-For an **update**, preserve established names, layout, terminology, and scope unless the actual change requires otherwise. Edit only affected sections and references. Add a sourced old/new example when a changed pattern would otherwise mislead users. Reconcile all three planning documents with the change using the planning record procedure; update affected entries and preserve accurate, unrelated decisions. Change `metadata.library_version` only when the revised guidance is verified for that version; do not fabricate historical versions or rewrite unrelated metadata to clear a staleness signal.
+For an **update**, preserve established names, layout, terminology, and scope unless the change requires otherwise. Edit only affected sections and references. Add a sourced old/new example when a changed pattern would otherwise mislead users. Reconcile all three planning documents with the change using the planning record procedure; update affected entries and preserve accurate, unrelated decisions. Change `metadata.library_version` only when the revised guidance is verified for that version; do not fabricate historical versions or rewrite unrelated metadata to clear a staleness signal.
### Writing rules
@@ -72,11 +72,11 @@ For new guidance and updates that change a recommended behavior, follow [task qu
For new or changed descriptions, also follow [discovery checks](references/task-quality.md#check-discovery-separately). Keep activation evidence separate from task correctness.
-Run `npm exec --no -- intent validate ` with the actual owning package's skill directory (or the repository's installed `intent`). Fix errors without weakening validation. Keep every SKILL.md within the 500-line limit. Review packaging warnings separately; they do not require installing dependencies or changing publishing configuration during authoring.
+Run `npm exec --no -- intent validate ` with the owning package's skill directory (or the repository's installed `intent`). Fix errors without weakening validation. Keep every SKILL.md within the 500-line limit. Review packaging warnings separately; they do not require installing dependencies or changing publishing configuration during authoring.
-Check that every reference and prerequisite resolves, every changed claim matches the cited source/version, and examples use actual supported APIs. Exercise the relevant example or package check where available. Intent's structural validation does not prove semantic correctness or agent behavior. If a check cannot run, report it as not verified with the reason.
+Check that every reference and prerequisite resolves, every changed claim matches the cited source/version, and examples use supported APIs. Exercise the relevant example or package check where available. Intent's structural validation does not prove semantic correctness or agent behavior. If a check cannot run, report it as not verified with the reason.
-Inspect the actual `SKILL.md` output and matching tree entry before handoff: the description makes the use conditions clear, purpose explains the skill, and both stay within supported behavior. Check migrated purpose text against the pre-edit description and preserve established purpose on later updates. Do not imply stronger guarantees to attract more requests. Check that references have reading conditions and independently discoverable tasks justify any new skills.
+Inspect the `SKILL.md` output and matching tree entry before handoff: the description makes the use conditions clear, purpose explains the skill, and both stay within supported behavior. Check migrated purpose text against the pre-edit description and preserve established purpose on later updates. Do not imply stronger guarantees to attract more requests. Check that references have reading conditions and independently discoverable tasks justify any new skills.
Verify all three planning documents against the resulting skills and prior record, then record completed skill and planning outcomes using the [source review procedure](references/source-review.md), then inspect the final diff for unrelated edits and run `git diff --check` for touched files. Return the changed library behavior, affected skill/reference paths, all three planning document paths and their changes or justified no-op, source/version evidence, structural and task-check results, and any remaining maintainer decision. Distinguish updated guidance, verified no change, and missing evidence for each reviewed task. Report whether a fresh consumer session completed the representative task; if that check could not run, mark it unverified rather than treating the authoring session as independent evidence. The result is ready for maintainer review when the task is usable end to end and those checks pass.
diff --git a/packages/intent/meta/generate-skill/references/distribution.md b/packages/intent/meta/generate-skill/references/distribution.md
index d0ca8db6..b54ced4a 100644
--- a/packages/intent/meta/generate-skill/references/distribution.md
+++ b/packages/intent/meta/generate-skill/references/distribution.md
@@ -10,7 +10,7 @@ Package-only distribution is the default; `intent maintainer setup` mentions rep
intent maintainer setup --distribution repo --skill discover-library --skill query
```
-Use the actual registered skill names. The repository is read from package metadata; supply `--repository owner/repo` when it cannot be established. `--plugin-name` chooses an initial plugin name when the default is unsuitable. To record the package-only default explicitly, so later sessions do not raise the option again, run:
+Use the registered skill names. The repository is read from package metadata; supply `--repository owner/repo` when it cannot be established. `--plugin-name` chooses an initial plugin name when the default is unsuitable. To record the package-only default explicitly, so later sessions do not raise the option again, run:
```sh
intent maintainer setup --distribution none
@@ -31,9 +31,9 @@ Run `intent maintainer sync` after authoring. Inspect `skills` paths in `.claude
- **GitHub skill installers:** use the generated `npx skills add owner/repo --full-depth --skill ` or `gh skill add owner/repo ` commands. `--full-depth` finds package skills even when root or agent-directory skills exist; `--skill` still limits the selection. Their default installation scope is the project. User scope is a separate consumer choice (`--global` for skills, `--scope user` for gh). Repository source location and installation scope are separate concepts.
- **Plugins:** use the generated marketplace metadata with Claude Code or Cursor's native plugin installation. The plugin references the selected package directories; it does not require Intent to invoke those skills.
-The generated selection controls Intent's exported metadata and suggested install commands. Third-party installers retain their own discovery rules; a full repository scan or explicit `--all` can expose other public skills. Use the named selection or exact paths when distributing a curated subset. Check references from the installed skill directory and test the actual consumer task separately: copying a skill does not prove that all its links or recommendations are portable.
+The generated selection controls Intent's exported metadata and suggested install commands. Third-party installers retain their own discovery rules; a full repository scan or explicit `--all` can expose other public skills. Use the named selection or exact paths when distributing a curated subset. Check references from the installed skill directory and test the consumer task separately: copying a skill does not prove that all its links or recommendations are portable.
-Publish through the library's normal npm/GitHub release process. `gh skill publish --dry-run` can validate a GitHub skill release without publishing it; actual releases remain a maintainer action. skills.sh indexes public GitHub skills through real installation usage; there is no submission API used by Intent. Do not simulate installations to create a listing.
+Publish through the library's normal npm/GitHub release process. `gh skill publish --dry-run` can validate a GitHub skill release without publishing it; releases remain a maintainer action. skills.sh indexes public GitHub skills through real installation usage; there is no submission API used by Intent. Do not simulate installations to create a listing.
## Versions and updates
@@ -48,7 +48,7 @@ Publish through the library's normal npm/GitHub release process. `gh skill publi
1. Install the selected skills in disposable consumer projects through each advertised installer and host. Check selected names and exclusion of unselected skills. For plugins, inspect all loaded components: the repository root is the plugin root, so preserved or automatically discovered commands, agents, hooks, and MCP configuration are not limited by the skill selection.
2. Resolve required references from the installed skill directory and execute bundled helpers with valid and invalid inputs. Check runtime requirements against the consumer environment. Proceed when the required files and tools work outside the source checkout.
3. Test updates and removal through the chosen installer. Use the native [Claude](https://code.claude.com/docs/en/plugin-marketplaces#validation-and-testing) or [Cursor](https://cursor.com/docs/reference/plugins) flow to check plugin activation and changed versions. Verify that source opt-out clears generated exports without removing existing consumer copies.
-4. Run an actual consumer task against the supported package version using the [task quality checks](task-quality.md). File copying and valid manifests establish packaging, not task correctness.
+4. Run a consumer task against the supported package version using the [task quality checks](task-quality.md). File copying and valid manifests establish packaging, not task correctness.
5. After the final sync, record supported outcomes through [source review](source-review.md) and run `intent maintainer check`. Report paths, revisions, host versions, check results, and missing evidence. The diff is ready for review when these checks pass; mark unavailable hosts or task evidence as incomplete. Publishing and commits require the maintainer's request.
For changed installer syntax or host formats, verify matching versions against the [skills CLI](https://github.com/vercel-labs/skills), [GitHub skill install](https://cli.github.com/manual/gh_skill_install), [Claude plugin paths](https://code.claude.com/docs/en/plugins-reference#path-behavior-rules), and [Cursor plugins](https://cursor.com/docs/reference/plugins) before changing consumer instructions.
diff --git a/packages/intent/meta/generate-skill/references/maintainer-commands.md b/packages/intent/meta/generate-skill/references/maintainer-commands.md
index a494cb3e..1e7107d3 100644
--- a/packages/intent/meta/generate-skill/references/maintainer-commands.md
+++ b/packages/intent/meta/generate-skill/references/maintainer-commands.md
@@ -6,8 +6,8 @@ Use the repository's installed Intent command for these actions, such as `pnpm e
2. For a new task, run `intent maintainer add --domain --description --source --task `. Repeat `--source`, `--requires`, and `--task` for multiple entries; each `--task` becomes an assessed developer task in the domain map. In a monorepo, run the command from the owning package directory or pass `--package packages/` relative to the repository root. Source paths are relative to the owning package; `owner/repo:path` is relative to the repository. Use `--path /SKILL.md` for an established custom layout. To register an existing skill, supply its name, domain, package, and path; its frontmatter supplies the other fields. The command prints every file it wrote.
3. Author the skill and reconcile all three records using the procedures in this skill. The command creates a skeleton and a domain-map entry; add any tasks not supplied on the command line. Write the spec's decisions/history. Remove `` only after authoring the corresponding document. Do not remove it simply to make a check pass. To retire a registered skill, run `intent maintainer remove `; it marks the tree entry `retired` and notes it in the spec without deleting the file, and refuses while the skill is selected for distribution or required by another skill.
4. Run `intent maintainer status` to see missing work, stale metadata, and pending reviews. `--json` includes the full source-review report. For a supplied PR base, use `--base ][`.
-5. Run `intent repair --json` when mechanical validation failures are present. Use `intent repair --write` for unambiguous frontmatter migrations; resolve conflicting values from evidence. `intent repair --patch` proposes code-preserving splits for labeled before/after examples, but inspect whether they are alternatives before applying those suggestions. The repair command does not replace validation or establish that guidance is current. Run `intent maintainer sync` after edits. It copies descriptions, purpose, sources, and prerequisites from registered skills into the tree, repairs the tree's record links, and includes the skill directories in existing package `files` allowlists. It preserves authored map/spec content and other manifest fields. It does not change version claims or run a package release. An absent `files` allowlist stays absent so npm's default contents are preserved; check the actual packed archive as part of the package's release checks.
-6. Follow [source review](source-review.md) with `intent maintainer review --json`, supply justified outcomes, and record them with `intent maintainer review --record .intent/review.json`. A maintainer working in a terminal can do the same with `intent maintainer review --interactive`. The command retains the existing revision and content-fingerprint checks. Run `intent maintainer check` after recording; it exits nonzero for incomplete authoring, stale generated metadata, invalid skills, missing local prerequisites, or pending reviews. Use the same check in CI, passing the actual PR base and `--github-summary` so the reasons appear in the step summary; the workflow that `setup` copies does both.
+5. Run `intent repair --json` when mechanical validation failures are present. Use `intent repair --write` for unambiguous frontmatter migrations; resolve conflicting values from evidence. `intent repair --patch` proposes code-preserving splits for labeled before/after examples, but inspect whether they are alternatives before applying those suggestions. The repair command does not replace validation or establish that guidance is current. Run `intent maintainer sync` after edits. It copies descriptions, purpose, sources, and prerequisites from registered skills into the tree, repairs the tree's record links, and includes the skill directories in existing package `files` allowlists. It preserves authored map/spec content and other manifest fields. It does not change version claims or run a package release. An absent `files` allowlist stays absent so npm's default contents are preserved; check the packed archive as part of the package's release checks.
+6. Follow [source review](source-review.md) with `intent maintainer review --json`, supply justified outcomes, and record them with `intent maintainer review --record .intent/review.json`. A maintainer working in a terminal can do the same with `intent maintainer review --interactive`. The command retains the existing revision and content-fingerprint checks. Run `intent maintainer check` after recording; it exits nonzero for incomplete authoring, stale generated metadata, invalid skills, missing local prerequisites, or pending reviews. Use the same check in CI, passing the PR base and `--github-summary` so the reasons appear in the step summary; the workflow that `setup` copies does both.
Keep unimplemented future skills in the tree with `status: planned` and retired entries with `status: retired`. They remain part of the cumulative record but do not count as implemented skills or enter package publishing configuration. An active entry with a missing file is an error to resolve, not an invitation to delete the entry. Local prerequisite slugs are checked against implemented tree entries; verify external package prerequisites and the developer task through the task-quality procedure.
diff --git a/packages/intent/meta/generate-skill/references/planning-records.md b/packages/intent/meta/generate-skill/references/planning-records.md
index 2a6f8e12..0c2b78b6 100644
--- a/packages/intent/meta/generate-skill/references/planning-records.md
+++ b/packages/intent/meta/generate-skill/references/planning-records.md
@@ -40,7 +40,7 @@ skills:
- `domain_map.yaml` owns the domain/task relationships, supported failure modes, cross-references, tensions, and knowledge gaps. Keep task slugs and package ownership aligned with the skills.
- `skill_spec.md` is the human-readable coverage and decision record. Retain the existing inventories and add a **Coverage and batch history** section recording the assessed scope, each completed batch or behavior change, its source revision/version, consequential decisions and reasons, check outcomes, and remaining work. Keep entries concise; do not store transcripts. Distinguish implemented guidance from planned work and unassessed areas.
-- `skill_tree.yaml` owns skill identities, paths, prerequisites, source mappings, and package placement. Keep existing planned entries and their status or explanatory notes. Add each new skill, and update entries when their names, paths, dependencies, or sources change. Resolve `path` relative to the owning package when `package` is present; otherwise resolve it relative to the library root. Keep `generated_from` links accurate for the actual artifact location.
+- `skill_tree.yaml` owns skill identities, paths, prerequisites, source mappings, and package placement. Keep existing planned entries and their status or explanatory notes. Add each new skill, and update entries when their names, paths, dependencies, or sources change. Resolve `path` relative to the owning package when `package` is present; otherwise resolve it relative to the library root. Keep `generated_from` links accurate for the artifact location.
- `references` lists the `.md` files under the skill's `references/` directory. `intent validate` requires the key when the skill has reference files, and requires the list to match those files: each path has the form `references/.md`, is listed once, and exists, and no file is left out. Omit the key, or use an empty list, for a skill without reference files. `intent validate` also checks every reference file as described in [the skill format](skill-format.md).
Keep each tree entry's `description` aligned with its skill's activation description and its `purpose` aligned with `metadata.purpose`. Existing map/spec task explanations retain their meaning; do not replace them with trigger text. Record a purpose migration and its preserved source text in the batch review without discarding prior decisions.
@@ -60,7 +60,7 @@ Before handoff, reconcile the resulting diff with all three documents:
## Check and record completion
-Check that all three files exist and contain substantive content. Parse both YAML files with the repository’s available YAML parser, then compare the map, spec, tree, and actual skill files. Verify every implemented tree path and prerequisite, the selected batch’s coverage, and preservation of prior entries. Planned future entries are not passing implementations. Run skill validation and the task-quality checks for changed guidance.
+Check that all three files exist and contain substantive content. Parse both YAML files with the repository’s available YAML parser, then compare the map, spec, tree, and skill files. Verify every implemented tree path and prerequisite, the selected batch’s coverage, and preservation of prior entries. Planned future entries are not passing implementations. Run skill validation and the task-quality checks for changed guidance.
Follow [source review](source-review.md) after all skill and record edits. The default installed maintainer workflow reports a planning review item whose snapshot includes the three documents and the skill/source evidence. It stays unresolved when a required file is missing, empty, ignored, or invalid; later source or skill changes reopen its review even if the documents did not change. Record an `updated` outcome after changing the record or a `no-change` outcome with evidence covering all three documents when they remain accurate.
diff --git a/packages/intent/meta/generate-skill/references/review-signals.md b/packages/intent/meta/generate-skill/references/review-signals.md
index af2df731..02e2b854 100644
--- a/packages/intent/meta/generate-skill/references/review-signals.md
+++ b/packages/intent/meta/generate-skill/references/review-signals.md
@@ -10,7 +10,7 @@ Use the report and existing conversation to locate the owning package, skill, an
| Input | Evidence needed | Possible outcome |
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Stale skill or version drift | The current skill's claims and an actual source diff or documented before/after behavior for the target version. | Update affected guidance, or explain why it remains accurate. A version number alone proves neither outcome. |
+| Stale skill or version drift | The current skill's claims and a source diff or documented before/after behavior for the target version. | Update affected guidance, or explain why it remains accurate. A version number alone proves neither outcome. |
| Missing source SHA | The referenced source and a trustworthy revision or baseline. A missing stored SHA does not prove that the source changed. | Establish the evidence before deciding whether guidance needs an update. If unavailable, report uncertainty. |
| Missing package, artifact, or generated-skill coverage | Public tasks in the package, existing skill owners, and relevant artifact entries or exclusions. | Extend an existing owner, create one independently useful task, or retain a supported out-of-scope decision. Ask only if an unresolved scope choice changes the outcome. |
| Invalid or unreadable artifact | The reported parse/validation error and the relevant artifact content. | Report the affected coverage conclusion as unknown until the artifact can be read. Do not infer absent coverage from a failed read. |
diff --git a/packages/intent/meta/generate-skill/references/skill-format.md b/packages/intent/meta/generate-skill/references/skill-format.md
index 541828a7..685656db 100644
--- a/packages/intent/meta/generate-skill/references/skill-format.md
+++ b/packages/intent/meta/generate-skill/references/skill-format.md
@@ -22,13 +22,13 @@ sources:
Replace template values with evidence from the library. `name` uses only lowercase letters, numbers, and hyphens, matches its parent directory, and is at most 64 characters. `description` is at most 1024 characters. Intent-specific scalars belong under `metadata`, whose values are strings. Intent supports top-level `sources` and `requires` arrays. Source entries use `Owner/repo:relative-path`; globs are supported, but select paths relevant to the task. If the repository or target version cannot be established, report that uncertainty instead of inventing provenance.
-Follow [Agent Skills description guidance](https://agentskills.io/skill-creation/optimizing-descriptions). Keep library context and explicit use conditions in `description`; it must communicate the supported task without requiring custom metadata. Check actual discovery using [discovery checks](task-quality.md#check-discovery-separately).
+Follow [Agent Skills description guidance](https://agentskills.io/skill-creation/optimizing-descriptions). Keep library context and explicit use conditions in `description`; it must communicate the supported task without requiring custom metadata. Check discovery using [discovery checks](task-quality.md#check-discovery-separately).
### Purpose and activation
`description` is the standard agent-discovery field. Write concrete “Use when…” conditions that identify what the agent can accomplish and distinguish adjacent tasks. `metadata.purpose` is Intent's descriptive explanation of what the skill is for, stored as a string in the standard [metadata extension point](https://agentskills.io/specification#metadata-field).
-For a new skill, author both fields. For an existing skill without `metadata.purpose`, read its description before editing and preserve that text unchanged as purpose, then write the activation description. Use the actual pre-edit content, not a rewritten draft or a newly invented summary. If purpose already exists, preserve it; subsequent edits to activation conditions do not replace it. If the source proves that a preserved purpose is inaccurate, report the conflict and propose the smallest correction explicitly rather than silently changing its meaning during migration.
+For a new skill, author both fields. For an existing skill without `metadata.purpose`, read its description before editing and preserve that text unchanged as purpose, then write the activation description. Use the pre-edit content, not a rewritten draft or a newly invented summary. If purpose already exists, preserve it; subsequent edits to activation conditions do not replace it. If the source proves that a preserved purpose is inaccurate, report the conflict and propose the smallest correction explicitly rather than silently changing its meaning during migration.
Keep purpose and activation scope aligned when maintaining the skill. Existing third-party skills without purpose remain valid; the field is an Intent authoring convention, not a universal Agent Skills requirement. Structural validation checks its string type through the metadata contract, not the quality of the prose or a literal “Use when” prefix.
diff --git a/packages/intent/meta/generate-skill/references/source-review.md b/packages/intent/meta/generate-skill/references/source-review.md
index b391a9ab..12572c1b 100644
--- a/packages/intent/meta/generate-skill/references/source-review.md
+++ b/packages/intent/meta/generate-skill/references/source-review.md
@@ -4,13 +4,13 @@ Read this before handing off an initial skill batch, an ordinary library change,
## Inspect the current changes
-Run `intent maintainer review --json` using the repository's installed Intent command, or the package-manager command used to load this procedure. When the task supplies a PR base, pass `--base ][` with that actual revision. Do not invent a historical baseline. Without an explicit base, Intent compares against the first recorded review's baseline, or `HEAD` when no state exists. It also compares each skill's current source and guidance content with its last recorded review.
+Run `intent maintainer review --json` using the repository's installed Intent command, or the package-manager command used to load this procedure. When the task supplies a PR base, pass `--base ][` with that revision. Do not invent a historical baseline. Without an explicit base, Intent compares against the first recorded review's baseline, or `HEAD` when no state exists. It also compares each skill's current source and guidance content with its last recorded review.
If rewritten history makes the recorded baseline unavailable, do not guess a replacement. Fetch the missing history, or choose an available commit as a new coverage boundary from repository evidence. Generate the report with `intent maintainer review --base --json`, resolve every reported item, then record that report. A fully resolved explicit report adopts its base for later default reviews, including when the report has no items. An omitted, unresolved, or invalid item leaves the unavailable baseline unchanged.
For a new batch, review the selected skills. Other items remain pending unless the maintainer has included them in the task. For ordinary code changes, inspect affected skills and unmapped changes within the agreed change. An unmapped file is an investigation input, not a demand for a new skill or full taxonomy. Decide from the source and developer task whether existing guidance needs updating, a new independently useful skill is warranted, or no guidance change is needed.
-Read [the planning record procedure](planning-records.md), then review the actual diff, affected source, skill, references, relevant tests, and all three planning documents. Create missing records and reconcile changed coverage, recommendations, dependencies, and maintainer decisions before handoff. Preserve unrelated record entries and future work. An item with no recorded review compares its files with the commit that introduced its guidance, so `changedFiles` is empty for an initial review only when nothing changed since then. A recorded content snapshot detects edits even if the earlier review happened before a commit; it does not retain the earlier source text. Use an available Git diff or explain when historical text is unavailable. Missing sources, foreign repositories, conflicts, or unavailable history remain unknown until the evidence is resolved.
+Read [the planning record procedure](planning-records.md), then review the diff, affected source, skill, references, relevant tests, and all three planning documents. Create missing records and reconcile changed coverage, recommendations, dependencies, and maintainer decisions before handoff. Preserve unrelated record entries and future work. An item with no recorded review compares its files with the commit that introduced its guidance, so `changedFiles` is empty for an initial review only when nothing changed since then. A recorded content snapshot detects edits even if the earlier review happened before a commit; it does not retain the earlier source text. Use an available Git diff or explain when historical text is unavailable. Missing sources, foreign repositories, conflicts, or unavailable history remain unknown until the evidence is resolved.
Agent instruction files, generated plugin metadata, the generated CI workflow, `.intent/`, package manifests, and lockfiles are never reported as unmapped changes; a skill that lists one of them in `sources` still tracks it. Add repository-specific patterns under `review.ignore` in `skill_tree.yaml`. Plain `sources` paths are relative to the skill's nearest owning package, or the Git root when no package exists. `owner/repository:path` paths are relative to the Git root and must match the local repository's origin or root package repository metadata. Git glob syntax supports `*`, `?`, character classes and `**`; brace expansion and extglobs are unsupported. Keep evidence paths accurate. The command reviews Git-visible `SKILL.md` files under `skills/`, custom skill directories containing `_artifacts/`, and paths declared in an existing `skill_tree.yaml`. Previously recorded skills remain covered. Shared repository/package planning directories do not select every agent instruction in the package; list custom skill paths in the tree, using its `package` field for monorepo ownership. Installed dependencies under `node_modules` are excluded. Ignored files and external repositories still require explicit manual review.
@@ -20,7 +20,7 @@ After guidance edits and task checks, regenerate the JSON report. Save it outsid
- `outcome`: `updated`, `no-change`, `out-of-scope`, or `unresolved`.
- `reason`: the concrete behavior comparison and why that outcome follows.
-- `evidence`: source paths/revisions and actual check results. For behavior-changing guidance, include structural validation, executable task checks, and fresh-consumer evidence or its explicit limitation.
+- `evidence`: source paths/revisions and check results. For behavior-changing guidance, include structural validation, executable task checks, and fresh-consumer evidence or its explicit limitation.
When every pending item shares one outcome and one reason, run `intent maintainer review --unchanged ""` or `--updated ""`; the command records the reviewed revision and changed files as evidence. Otherwise preserve the report's identity, base and fingerprints and run `intent maintainer review --record .intent/review.json`. For planning items, use `updated` or an evidence-backed `no-change` covering all three documents. The command rejects a report that annotates nothing, stale fingerprints, and unresolved source mappings or planning files. It writes completed outcomes to `.intent/review-state.json`; unresolved or unannotated items stay pending. Do not invent passing checks, use a generic reason, or mark unrelated items complete just to empty the report.
diff --git a/packages/intent/meta/generate-skill/references/task-quality.md b/packages/intent/meta/generate-skill/references/task-quality.md
index 173a9a07..42869051 100644
--- a/packages/intent/meta/generate-skill/references/task-quality.md
+++ b/packages/intent/meta/generate-skill/references/task-quality.md
@@ -4,7 +4,7 @@ Read this for new skills and when a change affects the behavior a skill recommen
## Check discovery separately
-For new or changed descriptions, follow [Agent Skills description evaluation](https://agentskills.io/skill-creation/optimizing-descriptions). Save realistic should-load prompts and adjacent should-not-load prompts with the task cases. Include requests that omit the library's API vocabulary. Expose the skill through normal consumer setup and inspect whether the agent actually loads its `SKILL.md`; a skill name in the answer is insufficient.
+For new or changed descriptions, follow [Agent Skills description evaluation](https://agentskills.io/skill-creation/optimizing-descriptions). Save realistic should-load prompts and adjacent should-not-load prompts with the task cases. Include requests that omit the library's API vocabulary. Expose the skill through normal consumer setup and inspect whether the agent loads its `SKILL.md`; a skill name in the answer is insufficient.
Repeat ambiguous results and record observed activation separately from task success. When tuning a description, keep a fixed mix of positive and negative prompts held out from revision, then check fresh phrasings. Report the prompts, attempts, and observed loads; do not claim a reliability rate from one run. If the runtime cannot expose discovery, mark it unverified rather than substituting a keyword match or structural validation.
@@ -14,15 +14,15 @@ Use the library's existing examples and tests to choose a realistic developer re
Put the case in the repository's existing test or eval layout. When no layout exists, use `tests/skills//` with a `task.md`, a small starting fixture, and an executable check using the package's existing test runner. The task describes what the developer needs without supplying the solution. The checks assert externally observable behavior, including the relevant error path. Keep grading tests outside the files the consumer agent is asked to edit.
-Use real package APIs and the actual source version being reviewed. Execute the expected solution to validate the fixture and checker before using them to grade an agent. Apply the same behavioral assertions to a plausible incorrect solution, such as the specific mistake the skill warns about, and confirm those assertions fail. An assertion that merely says the bad solution is different does not establish that the grader rejects it. If the intended behavior is unresolved, get that decision before authoring dependent guidance or grading it.
+Use real package APIs and the source version being reviewed. Execute the expected solution to validate the fixture and checker before using them to grade an agent. Apply the same behavioral assertions to a plausible incorrect solution, such as the specific mistake the skill warns about, and confirm those assertions fail. An assertion that merely says the bad solution is different does not establish that the grader rejects it. If the intended behavior is unresolved, get that decision before authoring dependent guidance or grading it.
-Check precise claims in the description as well as the body and main happy path. For asynchronous APIs, distinguish synchronous throws from rejected promises, cancellation before a call from cancellation during one, and rejection from successful completion. Exercise the input and error shapes supported by the actual API before claiming errors are always preserved. A passing representative task does not validate every statement in a skill.
+Check precise claims in the description as well as the body and main happy path. For asynchronous APIs, distinguish synchronous throws from rejected promises, cancellation before a call from cancellation during one, and rejection from successful completion. Exercise the input and error shapes supported by the API before claiming errors are always preserved. A passing representative task does not validate every statement in a skill.
## Exercise a fresh consumer session
Use an available isolated agent session in a disposable copy of the fixture. Install or expose the candidate package and skill through the same Intent setup a consumer would use. Start from the plain developer task with no authoring conversation, personal memory, answer files, or extra hints. Keep the full authoring repository and the grader out of the consumer's context when the task does not require them.
-Let the consumer attempt the task, then run the unchanged grading checks against its output. Capture the skill and package revisions, setup used, agent/model when available, final diff, check results, and which guidance actually loaded. Failed or unavailable runs are not passing quality evidence. Do not install another agent, grant broader permissions, or expose credentials just to make the evaluation run.
+Let the consumer attempt the task, then run the unchanged grading checks against its output. Capture the skill and package revisions, setup used, agent/model when available, final diff, check results, and which guidance loaded. Failed or unavailable runs are not passing quality evidence. Do not install another agent, grant broader permissions, or expose credentials just to make the evaluation run.
Inspect the observable tool trace as well as the result: unnecessary reference loads, repeated command reconstruction, and ignored constraints identify where to refine the procedure. Review successful runs too; a passing result can hide avoidable work. Keep useful source-backed corrections and remove instructions the task does not need.
@@ -34,4 +34,4 @@ If no fresh-session capability is available, still create and run the determinis
Investigate whether a failure belongs to setup/discovery, an incorrect or incomplete skill, an unsupported API, or the fixture/checker. Repair the owning defect. Preserve the check's intended behavior; do not relax an assertion to make a generated solution pass. Repeat the affected check after a repair.
-When source behavior changes, update the expected outcome from the source evidence and rerun the affected case. Preserve unrelated cases. Report structural validation, executable task checks, and fresh-agent outcomes separately so the maintainer knows what was actually proved.
+When source behavior changes, update the expected outcome from the source evidence and rerun the affected case. Preserve unrelated cases. Report structural validation, executable task checks, and fresh-agent outcomes separately so the maintainer knows what was proved.
diff --git a/packages/intent/meta/skill-staleness-check/SKILL.md b/packages/intent/meta/skill-staleness-check/SKILL.md
index 26523712..68c3820f 100644
--- a/packages/intent/meta/skill-staleness-check/SKILL.md
+++ b/packages/intent/meta/skill-staleness-check/SKILL.md
@@ -53,9 +53,9 @@ If no skills match, exit silently.
### Using `intent stale`
-There is no separate sync script — `intent stale [dir] [--json]` is the real,
-existing staleness signal (see `docs/cli/intent-stale.md`). It is **read-only**:
-it reports drift, it does not write anything. For a given library:
+`intent stale [dir] [--json]` is the staleness signal (see
+`docs/cli/intent-stale.md`). It is **read-only**: it reports drift, it does
+not write anything. For a given library:
```bash
intent stale packages/query --json
@@ -67,11 +67,11 @@ This reports:
currently published version), classified `major`/`minor`/`patch`.
- Missing source SHAs recorded in that package's `skills/sync-state.json`
(a conservative signal — it flags gaps in the stored SHA record, not
- actual remote content differences; see the doc's Notes section).
+ remote content differences; see the doc's Notes section).
`intent stale` does not classify "needs regeneration" vs "version bump only"
the way a dedicated sync tool might — that classification is this skill's own
-job, done in Step 2 below using the actual source diff, not `intent stale`'s
+job, done in Step 2 below using the source diff, not `intent stale`'s
output alone.
---
@@ -119,10 +119,9 @@ For skills classified as needing content updates:
For version bump only:
-There is no write-capable script for this. Edit `library_version` directly
-in each affected skill's frontmatter, then update the recorded SHA(s) for
-that library in its `skills/sync-state.json` (see Step 5) to reflect the new
-synced state.
+Edit `library_version` directly in each affected skill's frontmatter, then
+update the recorded SHA(s) for that library in its `skills/sync-state.json`
+(see Step 5) to reflect the new synced state.
---
@@ -145,13 +144,10 @@ second-order dependency are not automatically re-checked.
## Step 5 — Mark skills as synced
-There is no write-capable script for this either. After updating a skill,
-edit that library's `skills/sync-state.json` directly: update
-`library_version` and the affected skill's `skills[skillName].sources_sha`
-map with the new source file SHA(s) from the commit that triggered this run.
-(That is the real current shape read by `intent stale` — it has no separate
-tree-generator SHA or sync-timestamp field, despite what an earlier version
-of this doc implied.)
+After updating a skill, edit that library's `skills/sync-state.json`
+directly: update `library_version` and the affected skill's
+`skills[skillName].sources_sha` map with the new source file SHA(s) from the
+commit that triggered this run.
---
@@ -219,9 +215,8 @@ Exit silently (no PR, no notification, no issue) when ANY of these are true:
### GitHub API usage
-This skill (not a separate script) uses the `gh` CLI directly for GitHub API
-access — fetching source diffs in Step 2 and opening PRs in Step 6. It
-requires:
+This skill uses the `gh` CLI directly for GitHub API access — fetching
+source diffs in Step 2 and opening PRs in Step 6. It requires:
- `gh` CLI installed and authenticated
- Read access to upstream TanStack package repos (query, router, db, form,
diff --git a/packages/intent/meta/tree-generator/SKILL.md b/packages/intent/meta/tree-generator/SKILL.md
index c0ea1f46..3bbb21ff 100644
--- a/packages/intent/meta/tree-generator/SKILL.md
+++ b/packages/intent/meta/tree-generator/SKILL.md
@@ -14,7 +14,7 @@ metadata:
# Skill Tree Generator
-You produce and maintain a tree of SKILL.md files for a library. Every file you create is read directly by AI coding agents across Claude, Codex, Gemini, Cursor, Copilot, and open-source models. Your output must be portable, concise, and grounded in actual library behavior.
+You produce and maintain a tree of SKILL.md files for a library. Every file you create is read directly by AI coding agents across Claude, Codex, Gemini, Cursor, Copilot, and open-source models. Your output must be portable, concise, and grounded in library behavior.
### Skill types
@@ -114,8 +114,6 @@ If tasks stand alone, there are no framework adapter packages, and a shared over
- Each skill is type `core` (not `sub-skill`) and stands alone without a parent registry
- Skip Step 2 (core overview) and Step 3 (sub-skills) — go directly to writing individual skills as standalone core skills using Step 3's body format
-This avoids unnecessary scaffolding for focused libraries where the overhead of a hierarchical skill tree exceeds the navigation benefit.
-
### Step 1 — Plan the file tree
From the domain map, each entry in the `skills` list becomes a SKILL.md file. The `type` field on each skill (`core`, `framework`, `lifecycle`, `composition`) determines where it goes. Determine the file tree:
@@ -296,8 +294,6 @@ When a library version, changelog, migration guide, or accuracy report requires
## Cross-model compatibility
-Output is consumed by all major AI coding agents. To ensure consistency:
-
- Markdown with YAML frontmatter — universally parsed
- No XML tags in generated skill content
- Code blocks use triple backticks with language annotation
diff --git a/packages/intent/meta/tree-generator/references/update-skills.md b/packages/intent/meta/tree-generator/references/update-skills.md
index 80091bcf..497bcfb6 100644
--- a/packages/intent/meta/tree-generator/references/update-skills.md
+++ b/packages/intent/meta/tree-generator/references/update-skills.md
@@ -2,4 +2,4 @@
For a current task, supplied diff, identified code/docs change, or accuracy report, follow [generate-skill](../../generate-skill/SKILL.md). It owns the source checks, questions, incremental edits, no-impact decision, validation, and review handoff for each affected task.
-For an explicitly requested full-library audit, first identify candidate skills from the supplied changes and their documented scope. A release number is a reason to investigate, not proof of changed behavior. Use actual source diffs, changelogs, and migration guides; leave missing evidence as uncertainty. Apply the focused procedure to each candidate without redesigning the tree. Keep any requested report in the repository's existing format; no new staleness report or changelog is required merely to update a skill.
+For an explicitly requested full-library audit, first identify candidate skills from the supplied changes and their documented scope. A release number is a reason to investigate, not proof of changed behavior. Use source diffs, changelogs, and migration guides; leave missing evidence as uncertainty. Apply the focused procedure to each candidate without redesigning the tree. Keep any requested report in the repository's existing format; no new staleness report or changelog is required merely to update a skill.
diff --git a/packages/intent/src/cli.ts b/packages/intent/src/cli.ts
index 9c52251f..a575b862 100644
--- a/packages/intent/src/cli.ts
+++ b/packages/intent/src/cli.ts
@@ -100,7 +100,7 @@ function createCli(
import('./commands/support.js'),
import('./commands/meta.js'),
])
- await runMetaCommand(name, getMetaDir())
+ runMetaCommand(name, getMetaDir())
})
cli
diff --git a/packages/intent/src/commands/exclude.ts b/packages/intent/src/commands/exclude.ts
index 503d573b..4c9caaf0 100644
--- a/packages/intent/src/commands/exclude.ts
+++ b/packages/intent/src/commands/exclude.ts
@@ -1,6 +1,7 @@
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { fail } from '../shared/cli-error.js'
+import { errorMessage } from '../shared/guards.js'
import { compileExcludePatterns } from '../core/excludes.js'
export interface ExcludeCommandOptions {
@@ -16,12 +17,8 @@ function normalizeAction(action: string | undefined): ExcludeAction {
fail(`Unknown exclude action: ${action}. Expected list, add, or remove.`)
}
-function getPackageJsonPath(cwd: string): string {
- return join(cwd, 'package.json')
-}
-
function readPackageJson(cwd: string): Record {
- const packageJsonPath = getPackageJsonPath(cwd)
+ const packageJsonPath = join(cwd, 'package.json')
if (!existsSync(packageJsonPath)) {
fail(`No package.json found in ${cwd}`)
}
@@ -32,9 +29,7 @@ function readPackageJson(cwd: string): Record {
unknown
>
} catch (err) {
- fail(
- `Failed to parse ${packageJsonPath}: ${err instanceof Error ? err.message : String(err)}`,
- )
+ fail(`Failed to parse ${packageJsonPath}: ${errorMessage(err)}`)
}
}
@@ -77,8 +72,11 @@ function setConfiguredExcludes(
}
function writePackageJson(cwd: string, pkg: Record): void {
- const packageJsonPath = getPackageJsonPath(cwd)
- writeFileSync(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8')
+ writeFileSync(
+ join(cwd, 'package.json'),
+ `${JSON.stringify(pkg, null, 2)}\n`,
+ 'utf8',
+ )
}
function normalizePattern(
@@ -103,9 +101,7 @@ function validatePattern(pattern: string): void {
try {
compileExcludePatterns([pattern])
} catch (err) {
- fail(
- `Invalid exclude pattern "${pattern}": ${err instanceof Error ? err.message : String(err)}`,
- )
+ fail(`Invalid exclude pattern "${pattern}": ${errorMessage(err)}`)
}
}
diff --git a/packages/intent/src/commands/install/command.ts b/packages/intent/src/commands/install/command.ts
index 2072c425..d69d0ff7 100644
--- a/packages/intent/src/commands/install/command.ts
+++ b/packages/intent/src/commands/install/command.ts
@@ -1,10 +1,8 @@
import { relative } from 'node:path'
import { readSkillSourcesConfig } from '../../core/source-policy.js'
import { fail } from '../../shared/cli-error.js'
-import {
- detectIntentCommandPackageManager,
- formatIntentCommand,
-} from '../../shared/command-runner.js'
+import { detectPackageManager } from '../../discovery/package-manager.js'
+import { formatIntentCommand } from '../../shared/command-runner.js'
import {
coreOptionsFromGlobalFlags,
noticeOptionsFromGlobalFlags,
@@ -23,7 +21,7 @@ import { setupInitialPermissions } from './permissions.js'
import type { GlobalScanFlags } from '../support.js'
import type { IntentCoreOptions } from '../../core/index.js'
import type { ScanResult } from '../../shared/types.js'
-import type { PermissionPrompts } from './permissions.js'
+import type { PermissionPrompts, PermissionSetupResult } from './permissions.js'
export const INSTALL_PROMPT = `You are an AI assistant helping a developer set up skill-to-task mappings for their project.
@@ -141,6 +139,12 @@ export interface InstallCommandRuntime {
permissionPrompts?: PermissionPrompts
}
+function thrownMessage(error: unknown): string {
+ return error && typeof error === 'object' && 'message' in error
+ ? String(error.message)
+ : String(error)
+}
+
function formatTargetPath(targetPath: string): string {
return relative(process.cwd(), targetPath) || targetPath
}
@@ -225,9 +229,7 @@ export async function runInstallCommand(
'--maintainer cannot be combined with --map, --review, --print-prompt, --global, or --global-only.',
)
}
- const generated = buildMaintainerGuidanceBlock(
- detectIntentCommandPackageManager(),
- )
+ const generated = buildMaintainerGuidanceBlock(detectPackageManager())
const namespace = 'intent-maintainer'
if (options.dryRun) {
const targetPath = resolveIntentSkillsBlockTargetPath(
@@ -289,9 +291,7 @@ export async function runInstallCommand(
if (!options.map) {
const policy = readSkillSourcesConfig(process.cwd())
- let permissions: Awaited<
- ReturnType
- > | null = null
+ let permissions: PermissionSetupResult | null = null
if (policy.mode === 'absent' || options.review) {
const isTTY = runtime.isTTY ?? process.stdin.isTTY === true
@@ -307,7 +307,6 @@ export async function runInstallCommand(
review: options.review,
root: process.cwd(),
runtime: {
- // Loaded on demand: @clack/prompts is only needed when prompting.
prompts:
runtime.permissionPrompts ??
(
@@ -316,11 +315,7 @@ export async function runInstallCommand(
},
})
} catch (error) {
- const message =
- error && typeof error === 'object' && 'message' in error
- ? String(error.message)
- : String(error)
- fail(`Permissions: failed: ${message}`)
+ fail(`Permissions: failed: ${thrownMessage(error)}`)
}
if (
permissions.status === 'canceled' ||
@@ -334,9 +329,8 @@ export async function runInstallCommand(
)
}
- const generated = buildIntentSkillGuidanceBlock(
- detectIntentCommandPackageManager(),
- )
+ const packageManager = detectPackageManager()
+ const generated = buildIntentSkillGuidanceBlock(packageManager)
if (options.dryRun) {
const targetPath = resolveIntentSkillsBlockTargetPath(process.cwd(), 1)
@@ -379,9 +373,8 @@ export async function runInstallCommand(
console.log(`Guidance: ${result.status} ${target}.`)
} else {
printWriteResult(result)
- }
- if (!permissions)
console.log('To change permissions, run intent install --review.')
+ }
printPlacementTip(result.targetPath)
if (permissions && (available || permissions.available)) {
const packages =
@@ -394,22 +387,14 @@ export async function runInstallCommand(
`Available: ${skillCount} ${skillCount === 1 ? 'skill' : 'skills'} from ${packageCount} ${packageCount === 1 ? 'package' : 'packages'}.`,
)
if (skillCount > 0) {
- console.log(
- `Next: ${formatIntentCommand(detectIntentCommandPackageManager(), 'list')}`,
- )
+ console.log(`Next: ${formatIntentCommand(packageManager, 'list')}`)
} else {
console.log('To change permissions, run intent install --review.')
}
}
return
} catch (error) {
- if (permissions) {
- const message =
- error && typeof error === 'object' && 'message' in error
- ? String(error.message)
- : String(error)
- fail(`Guidance: failed: ${message}`)
- }
+ if (permissions) fail(`Guidance: failed: ${thrownMessage(error)}`)
throw error
}
}
diff --git a/packages/intent/src/commands/install/guidance.ts b/packages/intent/src/commands/install/guidance.ts
index 7d4ff4cb..441b015b 100644
--- a/packages/intent/src/commands/install/guidance.ts
+++ b/packages/intent/src/commands/install/guidance.ts
@@ -3,6 +3,7 @@ import { join } from 'node:path'
import { parse as parseYaml } from 'yaml'
import { formatIntentCommand } from '../../shared/command-runner.js'
import { repositoryWritePath } from '../../shared/write-path.js'
+import { errorMessage } from '../../shared/guards.js'
import { writeChanges } from '../../maintainer/files.js'
import { parseIntentInvocation } from '../../hooks/policy.js'
import { isGeneratedMappingSkill } from '../../skills/categories.js'
@@ -128,9 +129,7 @@ function parseSkillsList(block: string): {
return { errors: [], mappings: parsed.tanstackIntent }
} catch (err) {
return {
- errors: [
- `Managed block contains invalid YAML: ${err instanceof Error ? err.message : String(err)}`,
- ],
+ errors: [`Managed block contains invalid YAML: ${errorMessage(err)}`],
mappings: [],
}
}
@@ -229,7 +228,7 @@ export function verifyIntentSkillsBlockFile({
try {
parsedId = parseSkillUse(mapping.id)
} catch (err) {
- errors.push(err instanceof Error ? err.message : String(err))
+ errors.push(errorMessage(err))
}
if (containsLocalPathValue(mapping.id)) {
@@ -464,7 +463,9 @@ export function planIntentSkillsBlock({
}
const existingTarget = findExistingConfigWithManagedBlock(root, namespace)
- const targetPath = resolveIntentSkillsBlockTargetPath(root, 1, namespace)!
+ const targetPath =
+ existingTarget?.filePath ??
+ resolveIntentSkillsBlockTargetPath(root, 1, namespace)!
if (existingTarget) {
const nextContent = replaceManagedBlock(
diff --git a/packages/intent/src/commands/install/permission-prompts.ts b/packages/intent/src/commands/install/permission-prompts.ts
index 2f7642ed..47edee37 100644
--- a/packages/intent/src/commands/install/permission-prompts.ts
+++ b/packages/intent/src/commands/install/permission-prompts.ts
@@ -36,7 +36,6 @@ export function createPermissionPrompts(
},
): PermissionPrompts {
const io = { input: stdin, output: stdout }
- // Let Clack own search, scrolling, terminal sizing, and keyboard controls.
const picker = { ...io, maxItems: 6 }
const searchablePicker = {
...picker,
@@ -215,8 +214,7 @@ export function createPermissionPrompts(
parsed.mode === 'allow-all' && !selection.skills.includes('*')
)
const source = parsed.sources[0]!
- if (source.kind === 'git' || 'pattern' in source)
- return !selection.skills.includes('*')
+ if ('pattern' in source) return !selection.skills.includes('*')
// A collection of exact skills does not grant future package skills.
return (
!policy.matchers.some(
@@ -421,7 +419,7 @@ export function createPermissionPrompts(
const config = parseSkillSources([rule])
if (config.mode !== 'explicit') return true
const source = config.sources[0]!
- if (source.kind === 'git' || 'pattern' in source) return true
+ if ('pattern' in source) return true
const id = `${source.kind === 'workspace' ? 'workspace:' : ''}${source.id}#${source.skill}`
// Keep undiscovered and excluded rules, and preserve unchanged raw entries.
if (reviewedIds.has(id) && !selected.has(id)) return false
diff --git a/packages/intent/src/commands/install/permissions.ts b/packages/intent/src/commands/install/permissions.ts
index 4637aff1..3602c601 100644
--- a/packages/intent/src/commands/install/permissions.ts
+++ b/packages/intent/src/commands/install/permissions.ts
@@ -130,7 +130,7 @@ function normalizePermissions(selected: Array): Array {
const config = parseSkillSources([value])
if (config.mode !== 'explicit') return true
const source = config.sources[0]!
- if (source.kind === 'git' || 'pattern' in source) return true
+ if ('pattern' in source) return true
const others = parseSkillSources(
values.filter(
(other) =>
@@ -340,9 +340,9 @@ export async function setupInitialPermissions({
status: unchanged
? 'unchanged'
: writePreparedPackageSkillsUpdate(update),
- ...(review
- ? { available: { skills: enabled.length, packages: packageCount } }
- : {}),
+ available: review
+ ? { skills: enabled.length, packages: packageCount }
+ : undefined,
}
}
}
diff --git a/packages/intent/src/commands/list.ts b/packages/intent/src/commands/list.ts
index f5d4201a..2a04ef87 100644
--- a/packages/intent/src/commands/list.ts
+++ b/packages/intent/src/commands/list.ts
@@ -9,12 +9,7 @@ import {
printWarnings,
} from './support.js'
import type { GlobalScanFlags } from './support.js'
-import type {
- IntentPackageSummary,
- IntentSkillList,
- IntentSkillSummary,
-} from '../core/index.js'
-import type { ScanResult } from '../shared/types.js'
+import type { IntentSkillList, IntentSkillSummary } from '../core/index.js'
export interface ListCommandOptions extends GlobalScanFlags {
json?: boolean
@@ -74,25 +69,6 @@ function groupSkillsByPackageRoot(
return grouped
}
-function getPackageSkills(
- pkg: IntentPackageSummary,
- skillsByPackageRoot: Map>,
-): Array {
- return skillsByPackageRoot.get(pkg.packageRoot) ?? []
-}
-
-function formatLoadCommand(
- skill: IntentSkillSummary,
- packageManager: ScanResult['packageManager'],
- scopeFlag: string,
-): string {
- return formatIntentCommand(packageManager, [
- 'load',
- `${skill.packageName}#${skill.skillName}`,
- ...(scopeFlag ? [scopeFlag.trim()] : []),
- ])
-}
-
function printHiddenSources(result: IntentSkillList, audience: string): void {
if (audience === 'agent') {
console.log(
@@ -168,7 +144,7 @@ export async function runListCommand(
const skillsByPackageRoot = groupSkillsByPackageRoot(result.skills)
const allSkills = result.packages.map((pkg) =>
- getPackageSkills(pkg, skillsByPackageRoot).map((skill) => ({
+ (skillsByPackageRoot.get(pkg.packageRoot) ?? []).map((skill) => ({
name: skill.skillName,
description: skill.description,
type: skill.type,
@@ -177,19 +153,23 @@ export async function runListCommand(
const nameWidth = computeSkillNameWidth(allSkills)
const showTypes = result.skills.some((skill) => skill.type)
const scopeFlag = options.globalOnly
- ? ' --global-only'
+ ? '--global-only'
: options.global
- ? ' --global'
- : ''
+ ? '--global'
+ : undefined
console.log(`\nSkills:\n`)
for (const pkg of result.packages) {
console.log(` ${pkg.name}`)
printSkillTree(
- getPackageSkills(pkg, skillsByPackageRoot).map((skill) => ({
+ (skillsByPackageRoot.get(pkg.packageRoot) ?? []).map((skill) => ({
name: skill.skillName,
description: skill.description,
- loadCommand: formatLoadCommand(skill, result.packageManager, scopeFlag),
+ loadCommand: formatIntentCommand(result.packageManager, [
+ 'load',
+ `${skill.packageName}#${skill.skillName}`,
+ ...(scopeFlag ? [scopeFlag] : []),
+ ]),
type: skill.type,
})),
{ nameWidth, packageName: pkg.name, showTypes },
diff --git a/packages/intent/src/commands/load.ts b/packages/intent/src/commands/load.ts
index a0160416..8991b1d6 100644
--- a/packages/intent/src/commands/load.ts
+++ b/packages/intent/src/commands/load.ts
@@ -32,6 +32,15 @@ function printLoadDebug(loaded: LoadedIntentSkill | ResolvedIntentSkill): void {
])
}
+function orFail(run: () => T): T {
+ try {
+ return run()
+ } catch (err) {
+ if (err instanceof IntentCoreError) fail(err.message)
+ throw err
+ }
+}
+
export function runLoadCommand(
use: string | undefined,
options: LoadCommandOptions,
@@ -47,15 +56,7 @@ export function runLoadCommand(
const coreOptions = coreOptionsFromGlobalFlags(options)
if (options.path) {
- let resolved: ResolvedIntentSkill
- try {
- resolved = resolveIntentSkill(use, coreOptions)
- } catch (err) {
- if (err instanceof IntentCoreError) {
- fail(err.message)
- }
- throw err
- }
+ const resolved = orFail(() => resolveIntentSkill(use, coreOptions))
printLoadDebug(resolved)
console.log(resolved.path)
@@ -65,15 +66,7 @@ export function runLoadCommand(
return
}
- let loaded: LoadedIntentSkill
- try {
- loaded = loadIntentSkill(use, coreOptions)
- } catch (err) {
- if (err instanceof IntentCoreError) {
- fail(err.message)
- }
- throw err
- }
+ const loaded = orFail(() => loadIntentSkill(use, coreOptions))
printLoadDebug(loaded)
if (options.json) {
diff --git a/packages/intent/src/commands/maintainer.ts b/packages/intent/src/commands/maintainer.ts
index 71370e5e..5b66fb20 100644
--- a/packages/intent/src/commands/maintainer.ts
+++ b/packages/intent/src/commands/maintainer.ts
@@ -4,6 +4,7 @@ import { isCI } from 'std-env'
import { resolveProjectContext } from '../core/project-context.js'
import { createIntentFsCache } from '../discovery/fs-cache.js'
import { fail } from '../shared/cli-error.js'
+import { errorMessage } from '../shared/guards.js'
import {
planSetupRecords,
readRecord,
@@ -20,7 +21,7 @@ import {
readDistribution,
} from '../maintainer/distribution.js'
import { planSetupGithubActions } from '../setup/index.js'
-import { detectIntentCommandPackageManager } from '../shared/command-runner.js'
+import { detectPackageManager } from '../discovery/package-manager.js'
import { getMetaDir } from './support.js'
import {
buildMaintainerGuidanceBlock,
@@ -35,14 +36,7 @@ export interface MaintainerCommandRuntime {
reviewPrompts?: ReviewPrompts
}
-interface MaintainerAction {
- usage: string
- summary: string
- writes: string
- options: Array<[flag: string, description: string]>
-}
-
-const optionHelp: Record = {
+const optionHelp = {
artifacts: [
'--artifacts ',
'Planning record directory, relative to the repository root',
@@ -86,6 +80,15 @@ const optionHelp: Record = {
'--github-summary',
'Write a GitHub Actions step summary when GITHUB_STEP_SUMMARY is set',
],
+} satisfies Record
+
+type MaintainerOption = keyof typeof optionHelp
+
+interface MaintainerAction {
+ usage: string
+ summary: string
+ writes: string
+ options: Array
}
// Ordered as a maintainer runs them. `maintainer --help` prints this table and
@@ -97,13 +100,7 @@ export const maintainerActions: Record = {
'Initialize planning records, register existing skills, install agent instructions and CI.',
writes:
'skill_tree.yaml, domain_map.yaml, skill_spec.md (registering any SKILL.md under skills/ that is not yet recorded), the intent-maintainer block in AGENTS.md (or the existing agent instruction file), and .github/workflows/check-skills.yml when it does not exist.',
- options: [
- 'artifacts',
- 'distribution',
- 'repository',
- 'pluginName',
- 'skill',
- ].map((key) => optionHelp[key]!),
+ options: ['artifacts', 'distribution', 'repository', 'pluginName', 'skill'],
},
add: {
usage:
@@ -120,20 +117,20 @@ export const maintainerActions: Record = {
'source',
'requires',
'task',
- ].map((key) => optionHelp[key]!),
+ ],
},
remove: {
usage: 'maintainer remove [--package ]',
summary: 'Retire a registered skill without deleting its guidance.',
writes:
'The entry status in skill_tree.yaml and a note in skill_spec.md. Delete the SKILL.md yourself once its guidance is no longer needed.',
- options: ['artifacts', 'package'].map((key) => optionHelp[key]!),
+ options: ['artifacts', 'package'],
},
status: {
usage: 'maintainer status [--json] [--base ][]',
summary: 'Report authoring gaps, files to sync, and pending reviews.',
writes: 'Nothing.',
- options: ['artifacts', 'base', 'json'].map((key) => optionHelp[key]!),
+ options: ['artifacts', 'base', 'json'],
},
sync: {
usage: 'maintainer sync',
@@ -141,30 +138,21 @@ export const maintainerActions: Record = {
'Align the skill tree and package metadata with SKILL.md frontmatter.',
writes:
'skill_tree.yaml, package.json keywords and files, and generated distribution files when repository distribution is selected.',
- options: ['artifacts'].map((key) => optionHelp[key]!),
+ options: ['artifacts'],
},
review: {
usage:
'maintainer review [--unchanged | --updated | --json | --interactive | --record ] [--base ][]',
summary: 'Find guidance affected by Git changes and record outcomes.',
writes: '.intent/review-state.json when recording; nothing otherwise.',
- options: [
- 'base',
- 'unchanged',
- 'updated',
- 'json',
- 'record',
- 'interactive',
- ].map((key) => optionHelp[key]!),
+ options: ['base', 'unchanged', 'updated', 'json', 'record', 'interactive'],
},
check: {
usage: 'maintainer check [--base ][] [--github-summary]',
summary:
'Fail when authoring issues, stale generated files, or pending reviews remain.',
writes: 'Nothing. Use it as the CI gate.',
- options: ['artifacts', 'base', 'githubSummary'].map(
- (key) => optionHelp[key]!,
- ),
+ options: ['artifacts', 'base', 'githubSummary'],
},
}
@@ -187,8 +175,10 @@ export function maintainerHelp(action?: string): string {
lines.push(` Writes: ${entry.writes}`)
if (action) {
lines.push('', 'Options:')
- for (const [flag, description] of entry.options)
+ for (const key of entry.options) {
+ const [flag, description] = optionHelp[key]
lines.push(` ${flag.padEnd(28)} ${description}`)
+ }
} else lines.push('')
}
if (!action)
@@ -241,32 +231,16 @@ export async function runMaintainerCommand(
options: MaintainerCommandOptions,
runtime: MaintainerCommandRuntime = {},
): Promise {
- const allowed: Record> = {
- setup: ['artifacts', 'distribution', 'repository', 'pluginName', 'skill'],
- add: [
- 'artifacts',
- 'package',
- 'path',
- 'domain',
- 'description',
- 'source',
- 'requires',
- 'task',
- ],
- remove: ['artifacts', 'package'],
- status: ['artifacts', 'base', 'json'],
- sync: ['artifacts'],
- review: ['base', 'json', 'record', 'interactive', 'unchanged', 'updated'],
- check: ['artifacts', 'base', 'githubSummary'],
- }
- if (!allowed[action])
+ const allowed: ReadonlyArray | undefined =
+ maintainerActions[action]?.options
+ if (!allowed)
fail(
`Unknown maintainer action: ${action}. Expected setup, add, remove, status, sync, review, or check.`,
)
if (name !== undefined && action !== 'add' && action !== 'remove')
fail(`maintainer ${action} does not take a skill name.`)
for (const key of Object.keys(options)) {
- if (key !== '--' && !allowed[action].includes(key))
+ if (key !== '--' && !allowed.includes(key))
fail(
`--${kebab(key)} is not supported by maintainer ${action}. Run intent maintainer ${action} --help for its options.`,
)
@@ -302,7 +276,7 @@ export async function runMaintainerCommand(
)
console.log(`Recorded ${count} review outcome(s) as ${oneShot}.`)
} catch (error) {
- fail(error instanceof Error ? error.message : String(error))
+ fail(errorMessage(error))
}
return
}
@@ -354,9 +328,7 @@ export async function runMaintainerCommand(
// setup has no --domain flag to point the maintainer at.
candidate.problems.push(
candidate.domain.trim()
- ? error instanceof Error
- ? error.message
- : String(error)
+ ? errorMessage(error)
: `Set a non-empty domain for ${candidate.name} in ${project.artifacts}/domain_map.yaml, then run intent maintainer setup again.`,
)
},
@@ -374,9 +346,7 @@ export async function runMaintainerCommand(
project.artifacts,
)
const guidance = planIntentSkillsBlock({
- ...buildMaintainerGuidanceBlock(
- detectIntentCommandPackageManager(project.root),
- ),
+ ...buildMaintainerGuidanceBlock(detectPackageManager(project.root)),
root: project.root,
namespace: 'intent-maintainer',
skipWhenEmpty: false,
diff --git a/packages/intent/src/commands/meta.ts b/packages/intent/src/commands/meta.ts
index 1090ef90..3a800821 100644
--- a/packages/intent/src/commands/meta.ts
+++ b/packages/intent/src/commands/meta.ts
@@ -1,12 +1,14 @@
import { existsSync, readFileSync, readdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fail } from '../shared/cli-error.js'
+import { errorMessage } from '../shared/guards.js'
+import { parseFrontmatter } from '../shared/frontmatter.js'
import { rewriteLoadedSkillMarkdownDestinations } from '../core/markdown.js'
-export async function runMetaCommand(
+export function runMetaCommand(
name: string | undefined,
metaDir: string,
-): Promise {
+): void {
if (!existsSync(metaDir)) {
fail('Meta-skills directory not found.')
}
@@ -33,17 +35,19 @@ export async function runMetaCommand(
}),
)
} catch (err) {
- const msg = err instanceof Error ? err.message : String(err)
- fail(`Failed to read meta-skill "${name}": ${msg}`)
+ fail(`Failed to read meta-skill "${name}": ${errorMessage(err)}`)
}
return
}
- const { parseFrontmatter } = await import('../shared/utils.js')
const entries = readdirSync(metaDir, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
- .filter((entry) => existsSync(join(metaDir, entry.name, 'SKILL.md')))
+ .map((entry) => ({
+ name: entry.name,
+ skillFile: join(metaDir, entry.name, 'SKILL.md'),
+ }))
+ .filter((entry) => existsSync(entry.skillFile))
if (entries.length === 0) {
console.log('No meta-skills found.')
@@ -53,8 +57,7 @@ export async function runMetaCommand(
console.log('Meta-skills (for library maintainers):\n')
for (const entry of entries) {
- const skillFile = join(metaDir, entry.name, 'SKILL.md')
- const fm = parseFrontmatter(skillFile)
+ const fm = parseFrontmatter(entry.skillFile)
let description = ''
if (typeof fm?.description === 'string') {
description = fm.description.replace(/\s+/g, ' ').trim()
diff --git a/packages/intent/src/commands/repair.ts b/packages/intent/src/commands/repair.ts
index 79a3db86..8551dbfb 100644
--- a/packages/intent/src/commands/repair.ts
+++ b/packages/intent/src/commands/repair.ts
@@ -1,5 +1,5 @@
import { existsSync, readFileSync } from 'node:fs'
-import { relative, resolve } from 'node:path'
+import { relative } from 'node:path'
import { resolveProjectContext } from '../core/project-context.js'
import { createIntentFsCache } from '../discovery/fs-cache.js'
import { writeChanges } from '../maintainer/files.js'
@@ -8,7 +8,7 @@ import { repositoryWritePath } from '../shared/write-path.js'
import { renderRepairPatch } from '../shared/patch.js'
import { planExampleRepairs } from '../validate/blocks.js'
import { planFrontmatterRepair } from '../validate/repairs.js'
-import { collectDefaultSkillsDirs } from './validate.js'
+import { collectDefaultSkillsDirs, resolveSkillsDir } from './validate.js'
import type { FileChange } from '../maintainer/files.js'
export interface RepairCommandOptions {
@@ -30,13 +30,7 @@ export async function runRepairCommand(
const directories =
dir === undefined
? collectDefaultSkillsDirs(context, findSkillFiles, fsCache)
- : [
- resolveProjectContext({
- cwd: process.cwd(),
- targetPath: dir,
- fsCache,
- }).targetSkillsDir ?? resolve(dir),
- ]
+ : [resolveSkillsDir(dir, fsCache)]
if (dir !== undefined && !existsSync(directories[0]!))
fail(`Skills directory not found: ${dir}`)
const paths = [...new Set(directories.flatMap(findSkillFiles))]
diff --git a/packages/intent/src/commands/review.ts b/packages/intent/src/commands/review.ts
index ed866e7e..250b2886 100644
--- a/packages/intent/src/commands/review.ts
+++ b/packages/intent/src/commands/review.ts
@@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { createReview, recordReview } from '../review/review.js'
import { fail, isCliFailure } from '../shared/cli-error.js'
+import { errorMessage, isRecord } from '../shared/guards.js'
import { writeStaleReviewWorkflowFiles } from '../staleness/workflow-review.js'
export interface ReviewCommandOptions {
@@ -34,12 +35,9 @@ export function runReviewCommand(
const input: unknown = JSON.parse(
readFileSync(resolve(options.record), 'utf8'),
)
- if (
- typeof input === 'object' &&
- input !== null &&
- Array.isArray((input as { items?: unknown }).items)
- ) {
- const items = (input as { items: Array }).items
+ const items: Array | null =
+ isRecord(input) && Array.isArray(input.items) ? input.items : null
+ if (items) {
const annotated = items.filter(
(item) =>
typeof item === 'object' &&
@@ -121,7 +119,7 @@ export function runReviewCommand(
type: 'review-check-failed',
library: options.packageLabel ?? 'workspace',
subject: 'intent review',
- reasons: [error instanceof Error ? error.message : String(error)],
+ reasons: [errorMessage(error)],
},
])
console.log(
@@ -129,6 +127,6 @@ export function runReviewCommand(
)
return
}
- fail(error instanceof Error ? error.message : String(error))
+ fail(errorMessage(error))
}
}
diff --git a/packages/intent/src/commands/stale.ts b/packages/intent/src/commands/stale.ts
index ccdb637a..b23b8167 100644
--- a/packages/intent/src/commands/stale.ts
+++ b/packages/intent/src/commands/stale.ts
@@ -10,11 +10,9 @@ import {
compileSkillSourcePolicy,
readSkillSourcesConfig,
} from '../core/source-policy.js'
-import { isCliFailure } from '../shared/cli-error.js'
-import {
- detectIntentCommandPackageManager,
- formatIntentCommand,
-} from '../shared/command-runner.js'
+import { detectPackageManager } from '../discovery/package-manager.js'
+import { formatIntentCommand } from '../shared/command-runner.js'
+import { failureMessage } from './support.js'
import type { IntentFsCache } from '../discovery/fs-cache.js'
import type { StalenessReport } from '../shared/types.js'
@@ -24,16 +22,18 @@ export interface StaleCommandOptions {
packageLabel?: string
}
+type StaleTargetResolver = (
+ targetDir?: string,
+ fsCache?: IntentFsCache,
+) => Promise<{
+ reports: Array
+ workflowAdvisories?: Array
+}>
+
export async function runStaleCommand(
targetDir: string | undefined,
options: StaleCommandOptions,
- resolveStaleTargets: (
- targetDir?: string,
- fsCache?: IntentFsCache,
- ) => Promise<{
- reports: Array
- workflowAdvisories?: Array
- }>,
+ resolveStaleTargets: StaleTargetResolver,
): Promise {
if (options.githubReview) {
await runGithubReview(targetDir, options, resolveStaleTargets)
@@ -62,6 +62,7 @@ export async function runStaleCommand(
return
}
+ let needsReview = false
for (const report of reports) {
const driftLabel = report.versionDrift
? ` [${report.versionDrift} drift]`
@@ -77,6 +78,7 @@ export async function runStaleCommand(
if (stale.length === 0 && signals.length === 0) {
console.log(' All skills up-to-date')
} else {
+ needsReview = true
for (const skill of stale) {
console.log(` ⚠ ${skill.name}: ${skill.reasons.join(', ')}`)
}
@@ -99,15 +101,9 @@ export async function runStaleCommand(
console.log()
}
- if (
- reports.some(
- (report) =>
- report.skills.some((skill) => skill.needsReview) ||
- report.signals.some((signal) => signal.needsReview),
- )
- ) {
+ if (needsReview) {
const command = formatIntentCommand(
- detectIntentCommandPackageManager(targetDir),
+ detectPackageManager(targetDir),
'meta generate-skill',
)
console.log(
@@ -119,13 +115,7 @@ export async function runStaleCommand(
async function runGithubReview(
targetDir: string | undefined,
options: StaleCommandOptions,
- resolveStaleTargets: (
- targetDir?: string,
- fsCache?: IntentFsCache,
- ) => Promise<{
- reports: Array
- workflowAdvisories?: Array
- }>,
+ resolveStaleTargets: StaleTargetResolver,
): Promise {
const {
collectStaleReviewItems,
@@ -157,12 +147,7 @@ async function runGithubReview(
} catch (err) {
const item = createFailedStaleReviewItem(packageLabel)
writeStaleReviewWorkflowFiles([item])
- const message = isCliFailure(err)
- ? err.message
- : err instanceof Error
- ? err.message
- : String(err)
- console.log(`Intent stale check failed: ${message}`)
+ console.log(`Intent stale check failed: ${failureMessage(err)}`)
console.log('Wrote a review PR body so maintainers can inspect the logs.')
}
}
diff --git a/packages/intent/src/commands/support.ts b/packages/intent/src/commands/support.ts
index 7500d747..ee1b42d2 100644
--- a/packages/intent/src/commands/support.ts
+++ b/packages/intent/src/commands/support.ts
@@ -1,13 +1,14 @@
import { existsSync, readFileSync, statSync } from 'node:fs'
import { dirname, join, relative, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
-import { fail } from '../shared/cli-error.js'
+import { fail, isCliFailure } from '../shared/cli-error.js'
+import { errorMessage } from '../shared/guards.js'
import { resolveProjectContext } from '../core/project-context.js'
import { createIntentFsCache } from '../discovery/fs-cache.js'
import {
findWorkspacePackages,
findWorkspaceRoot,
-} from '../setup/workspace-patterns.js'
+} from '../core/workspace-patterns.js'
import type { IntentCoreOptions } from '../core/index.js'
import type { IntentFsCache } from '../discovery/fs-cache.js'
import type {
@@ -23,7 +24,6 @@ export interface GlobalScanFlags {
global?: boolean
globalOnly?: boolean
notices?: boolean
- noNotices?: boolean
}
export interface StaleTargetResult {
@@ -33,30 +33,21 @@ export interface StaleTargetResult {
export const INTENT_CHECK_SKILLS_WORKFLOW_VERSION = 5
+// Startup keeps shared/cli-error.ts free of imports, so this lives with the commands.
+export function failureMessage(err: unknown): string {
+ return isCliFailure(err) ? err.message : errorMessage(err)
+}
+
export function getMetaDir(): string {
return findMetaDir(dirname(fileURLToPath(import.meta.url)))
}
-/**
- * Resolve the package `meta/` directory by walking up from `startDir`.
- *
- * The CLI module sits at `src/commands/` in source but is bundled flat into
- * `dist/` in the published package, so the depth from the module to the
- * package root differs between the two layouts. A hardcoded `..` count is
- * correct for only one of them and breaks `setup` / `meta` / `scaffold` in the
- * other. Walking up to the first `meta/` directory handles both layouts (and
- * symlinked installs such as pnpm) without depending on the build output
- * depth. Falls back to the historical `../../meta` resolution if no `meta/`
- * is found, so behaviour is never worse than before.
- */
+// Walks up to the first meta/ directory so the same code works from
+// src/commands/ and the flat bundled dist/. Falls back to ../../meta.
export function findMetaDir(startDir: string): string {
let dir = startDir
- // Sanity cap: a package is never this many dirs deep; the root check below
- // also stops the walk at the filesystem root.
for (let limit = 0; limit < 10; limit++) {
const candidate = join(dir, 'meta')
- // Check it's a directory, not just that something named `meta` exists — a
- // stray file named `meta` in an ancestor must not short-circuit the walk.
if (existsSync(candidate) && statSync(candidate).isDirectory())
return candidate
const parent = dirname(dir)
@@ -68,8 +59,6 @@ export function findMetaDir(startDir: string): string {
export function getCheckSkillsWorkflowAdvisories(root: string): Array {
const workflowPath = join(root, '.github', 'workflows', 'check-skills.yml')
- if (!existsSync(workflowPath)) return []
-
let content: string
try {
content = readFileSync(workflowPath, 'utf8')
@@ -101,15 +90,11 @@ export async function scanIntentsOrFail(
})
return scan
} catch (err) {
- fail(err instanceof Error ? err.message : String(err))
+ fail(errorMessage(err))
}
}
function scanOptionsFromGlobalFlags(options: GlobalScanFlags): ScanOptions {
- if (options.global && options.globalOnly) {
- fail('Use either --global or --global-only, not both.')
- }
-
if (options.globalOnly) {
return { scope: 'global' }
}
@@ -138,7 +123,7 @@ export function coreOptionsFromGlobalFlags(
export function noticeOptionsFromGlobalFlags(options: GlobalScanFlags): {
noNotices?: boolean
} {
- return { noNotices: options.noNotices || options.notices === false }
+ return { noNotices: options.notices === false }
}
function formatDebugValue(value: string | number | Array): string {
diff --git a/packages/intent/src/commands/validate.ts b/packages/intent/src/commands/validate.ts
index 14de2889..8f96818c 100644
--- a/packages/intent/src/commands/validate.ts
+++ b/packages/intent/src/commands/validate.ts
@@ -7,10 +7,11 @@ import {
} from 'node:fs'
import { basename, dirname, join, relative, resolve } from 'node:path'
import { parseDocument, parse as parseYaml } from 'yaml'
-import { fail, isCliFailure } from '../shared/cli-error.js'
-import { readScalarField } from '../shared/utils.js'
+import { fail } from '../shared/cli-error.js'
+import { errorMessage, isRecord } from '../shared/guards.js'
+import { readScalarField } from '../shared/frontmatter.js'
import { resolveProjectContext } from '../core/project-context.js'
-import { findWorkspacePackages } from '../setup/workspace-patterns.js'
+import { findWorkspacePackages } from '../core/workspace-patterns.js'
import { createIntentFsCache } from '../discovery/fs-cache.js'
import {
checkSkillBlocks,
@@ -24,19 +25,14 @@ import {
agentSkillNamePattern,
planFrontmatterRepair,
} from '../validate/repairs.js'
-import { printWarnings } from './support.js'
+import { failureMessage, printWarnings } from './support.js'
import type { SkillBlockCache } from '../validate/blocks.js'
import type { IntentFsCache } from '../discovery/fs-cache.js'
import type { FileChange } from '../maintainer/files.js'
import type { ProjectContext } from '../core/project-context.js'
import type { IntentArtifactSkill } from '../shared/types.js'
-interface ValidationError {
- file: string
- message: string
-}
-
-interface ValidationWarning {
+interface ValidationIssue {
file: string
message: string
}
@@ -81,7 +77,7 @@ function isScalarValue(value: unknown): boolean {
}
function buildValidationFailure(
- errors: Array,
+ errors: Array,
warnings: Array,
): string {
const lines = ['', `❌ Validation failed with ${errors.length} error(s):`, '']
@@ -130,11 +126,7 @@ function collectPackagingWarnings(
if (pkgResult.error) {
const code = (pkgResult.error as NodeJS.ErrnoException).code
if (code === 'ENOENT') return []
- const msg =
- pkgResult.error instanceof Error
- ? pkgResult.error.message
- : String(pkgResult.error)
- return [`Could not parse package.json: ${msg}`]
+ return [`Could not parse package.json: ${errorMessage(pkgResult.error)}`]
}
return []
}
@@ -150,11 +142,7 @@ function collectPackagingWarnings(
if (!wsResult.packageJson && wsResult.error) {
const code = (wsResult.error as NodeJS.ErrnoException).code
if (code !== 'ENOENT') {
- const msg =
- wsResult.error instanceof Error
- ? wsResult.error.message
- : String(wsResult.error)
- return [`Could not parse package.json: ${msg}`]
+ return [`Could not parse package.json: ${errorMessage(wsResult.error)}`]
}
}
if (wsResult.packageJson) {
@@ -267,14 +255,6 @@ function readTreeEntries(
return entries
}
-function formatWarning({ file, message }: ValidationWarning): string {
- return `${file}: ${message}`
-}
-
-function isRecord(value: unknown): value is Record {
- return !!value && typeof value === 'object' && !Array.isArray(value)
-}
-
function normalizeLineEndings(value: string, lineEnding: string): string {
return lineEnding === '\r\n' ? value.replace(/\r?\n/g, '\r\n') : value
}
@@ -286,7 +266,7 @@ function repairRoot(fsCache?: IntentFsCache): string {
function applyFrontmatterFixes(
plans: Array,
- root = repairRoot(),
+ root: string,
): void {
writeChanges(
root,
@@ -300,7 +280,7 @@ function applyFrontmatterFixes(
function applySetVersion(
plans: Array,
version: string,
- root = repairRoot(),
+ root: string,
): void {
const changes: Array = []
@@ -312,20 +292,14 @@ function applySetVersion(
)
if (!match) continue
- const openingLineEnding = match[1]
- const frontmatter = match[2]
- const closingLineEnding = match[3]
- const afterClose = match[4]
- const body = match[5]
- if (
- openingLineEnding === undefined ||
- frontmatter === undefined ||
- closingLineEnding === undefined ||
- afterClose === undefined ||
- body === undefined
- ) {
- continue
- }
+ const [
+ ,
+ openingLineEnding = '',
+ frontmatter = '',
+ closingLineEnding = '',
+ afterClose = '',
+ body = '',
+ ] = match
const doc = parseDocument(frontmatter)
if (doc.errors.length > 0) continue
@@ -348,8 +322,8 @@ function collectAgentSkillSpecWarnings({
}: {
fm: Record
rel: string
-}): Array {
- const warnings: Array = []
+}): Array {
+ const warnings: Array = []
if (
fm.license !== undefined &&
@@ -437,7 +411,7 @@ export async function runValidateCommand(
} catch (err) {
writeGithubValidationSummary({
ok: false,
- message: validationErrorMessage(err),
+ message: failureMessage(err),
})
throw err
}
@@ -455,11 +429,7 @@ async function runValidateCommandInternal(
// skills roots gets every error in one report and one summary.
const explicitDirs = [
...new Set([...(dir === undefined ? [] : [dir].flat()), ...additionalDirs]),
- ].map(
- (target) =>
- resolveProjectContext({ cwd: process.cwd(), targetPath: target, fsCache })
- .targetSkillsDir ?? resolve(process.cwd(), target),
- )
+ ].map((target) => resolveSkillsDir(target, fsCache))
const skillsDirs = [
...new Set([
...(dir === undefined
@@ -478,7 +448,7 @@ async function runValidateCommandInternal(
if (findSkillFiles(skillsDir).length === 0) fail('No SKILL.md files found')
}
- const errors: Array = []
+ const errors: Array = []
const warnings: Array = []
const skippedBlockChecks = new Set()
const blockCache: SkillBlockCache = {}
@@ -487,6 +457,7 @@ async function runValidateCommandInternal(
let validatedCount = 0
const validatedFiles = new Set()
const artifacts = new Map>()
+ const treeDeclarations = new Map()
if (skillsDirs.length === 0) {
console.log('No skills/ directory found — skipping validation.')
@@ -513,7 +484,15 @@ async function runValidateCommandInternal(
}> = []
let treeEntries: Map | undefined
const declaresReferences = [skillsDir, validateContext.workspaceRoot].some(
- (root) => root && treeDeclaresReferences(root),
+ (root) => {
+ if (!root) return false
+ let declares = treeDeclarations.get(root)
+ if (declares === undefined) {
+ declares = treeDeclaresReferences(root)
+ treeDeclarations.set(root, declares)
+ }
+ return declares
+ },
)
for (const filePath of skillFiles) {
const rel = relative(process.cwd(), filePath)
@@ -624,7 +603,9 @@ async function runValidateCommandInternal(
}
warnings.push(
- ...collectAgentSkillSpecWarnings({ fm, rel }).map(formatWarning),
+ ...collectAgentSkillSpecWarnings({ fm, rel }).map(
+ ({ file, message }) => `${file}: ${message}`,
+ ),
)
const skillDir = dirname(filePath)
@@ -760,6 +741,7 @@ async function runValidateCommandInternal(
skills,
references: skills.flatMap((skill) => skill.references),
cache: blockCache,
+ fsCache,
})
if (exampleSummaries)
for (const [file, summary] of summarizeSkillExamples(result, skills))
@@ -809,10 +791,9 @@ async function runValidateCommandInternal(
try {
parseYaml(content)
} catch (err) {
- const detail = err instanceof Error ? err.message : String(err)
errors.push({
file: relative(process.cwd(), artifactPath),
- message: `Invalid YAML in artifact file: ${detail}`,
+ message: `Invalid YAML in artifact file: ${errorMessage(err)}`,
})
}
}
@@ -886,12 +867,6 @@ async function runValidateCommandInternal(
printWarnings(warnings)
}
-function validationErrorMessage(err: unknown): string {
- if (isCliFailure(err)) return err.message
- if (err instanceof Error) return err.message
- return String(err)
-}
-
function writeGithubValidationSummary({
message,
ok,
@@ -932,6 +907,16 @@ function writeGithubValidationSummary({
appendFileSync(summaryPath, lines.join('\n'))
}
+export function resolveSkillsDir(
+ target: string,
+ fsCache: IntentFsCache,
+): string {
+ return (
+ resolveProjectContext({ cwd: process.cwd(), targetPath: target, fsCache })
+ .targetSkillsDir ?? resolve(process.cwd(), target)
+ )
+}
+
export function collectDefaultSkillsDirs(
context: ProjectContext,
findSkillFiles: (dir: string) => Array,
diff --git a/packages/intent/src/core/excludes.ts b/packages/intent/src/core/excludes.ts
index aaa74bf4..e14e3ce4 100644
--- a/packages/intent/src/core/excludes.ts
+++ b/packages/intent/src/core/excludes.ts
@@ -1,4 +1,7 @@
-import { dirname, isAbsolute, relative, resolve } from 'node:path'
+import { dirname, resolve } from 'node:path'
+import { isRecord } from '../shared/guards.js'
+import { isWithinOrEqual } from '../shared/paths.js'
+import { getPackageShortName } from '../skills/use.js'
import { resolveProjectContext } from './project-context.js'
import { readPackageJson } from './package-json.js'
import type { ProjectContext } from './project-context.js'
@@ -23,20 +26,12 @@ function normalizeExcludePatterns(value: unknown): Array {
.filter(Boolean)
}
-function isWithinOrEqual(path: string, parentDir: string): boolean {
- const rel = relative(parentDir, path)
- return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
-}
-
function readPackageExcludes(
dir: string,
fsCache?: IntentFsCache,
): Array {
- const pkg = readPackageJson(dir, fsCache)
- const intent = pkg?.intent
- if (!intent || typeof intent !== 'object') return []
-
- return normalizeExcludePatterns((intent as Record).exclude)
+ const intent = readPackageJson(dir, fsCache)?.intent
+ return isRecord(intent) ? normalizeExcludePatterns(intent.exclude) : []
}
export function getConfigDirs(
@@ -155,8 +150,7 @@ function skillNameVariants(
packageName: string,
skillName: string,
): Array {
- const shortName = packageName.split('/').pop() ?? packageName
- const prefix = `${shortName}/`
+ const prefix = `${getPackageShortName(packageName)}/`
if (skillName.startsWith(prefix)) {
return [skillName, skillName.slice(prefix.length)]
}
diff --git a/packages/intent/src/core/intent-core.ts b/packages/intent/src/core/intent-core.ts
index a84402c2..f20684bc 100644
--- a/packages/intent/src/core/intent-core.ts
+++ b/packages/intent/src/core/intent-core.ts
@@ -1,5 +1,7 @@
-import { isAbsolute, relative, resolve } from 'node:path'
+import { resolve } from 'node:path'
import { createIntentFsCache } from '../discovery/fs-cache.js'
+import { errorMessage } from '../shared/guards.js'
+import { isWithinOrEqual } from '../shared/paths.js'
import { ResolveSkillUseError, resolveSkillUse } from '../skills/resolver.js'
import { formatSkillUse, parseSkillUse } from '../skills/use.js'
import {
@@ -17,9 +19,8 @@ import {
scanForPolicedIntents,
} from './source-policy.js'
import type { ResolveSkillResult } from '../skills/resolver.js'
-import type { IntentFsCache } from '../discovery/fs-cache.js'
-import type { ReadFs } from '../shared/utils.js'
-import type { ScanOptions, ScanScope } from '../shared/types.js'
+import type { ReadFs } from '../shared/fs-identity.js'
+import type { ScanScope } from '../shared/types.js'
import type {
IntentCoreErrorCode,
IntentCoreOptions,
@@ -60,7 +61,7 @@ export class IntentCoreError extends Error {
}
}
-function toScanOptions(options: IntentCoreOptions): ScanOptions {
+function toScanScope(options: IntentCoreOptions): ScanScope {
if (options.global && options.globalOnly) {
throw new IntentCoreError(
'invalid-options',
@@ -68,26 +69,9 @@ function toScanOptions(options: IntentCoreOptions): ScanOptions {
)
}
- if (options.globalOnly) {
- return { scope: 'global' }
- }
-
- if (options.global) {
- return { scope: 'local-and-global' }
- }
-
- return { scope: 'local' }
-}
-
-function getScanScope(options: ScanOptions): ScanScope {
- return options.scope ?? (options.includeGlobal ? 'local-and-global' : 'local')
-}
-
-function withFsCache(
- options: ScanOptions,
- fsCache: IntentFsCache,
-): ScanOptions & { fsCache: IntentFsCache } {
- return { ...options, fsCache }
+ if (options.globalOnly) return 'global'
+ if (options.global) return 'local-and-global'
+ return 'local'
}
function resolveCoreCwd(options: IntentCoreOptions): string {
@@ -98,13 +82,13 @@ export function listIntentSkills(
options: IntentCoreOptions = {},
): IntentSkillList {
const cwd = resolveCoreCwd(options)
- const scanOptions = toScanOptions(options)
+ const scope = toScanScope(options)
const fsCache = createIntentFsCache()
const projectContext = resolveProjectContext({ cwd, fsCache })
const { hiddenSourceCount, hiddenSources, scan, excludePatterns } =
scanForPolicedIntents({
cwd,
- scanOptions: withFsCache(scanOptions, fsCache),
+ scanOptions: { scope, fsCache },
coreOptions: options,
context: projectContext,
})
@@ -146,7 +130,7 @@ export function listIntentSkills(
if (options.debug) {
result.debug = {
cwd,
- scope: getScanScope(scanOptions),
+ scope,
excludes: excludePatterns,
packageCount: result.packages.length,
skillCount: result.skills.length,
@@ -160,21 +144,6 @@ export function listIntentSkills(
return result
}
-function resolveFromCwd(cwd: string, path: string): string {
- return resolve(cwd, path)
-}
-
-function isResolvedPathInsidePackageRoot(
- path: string,
- packageRoot: string,
-): boolean {
- const relativePath = relative(packageRoot, path)
- return (
- relativePath === '' ||
- (!relativePath.startsWith('..') && !isAbsolute(relativePath))
- )
-}
-
function toResolvedIntentSkill(
cwd: string,
use: string,
@@ -189,9 +158,7 @@ function toResolvedIntentSkill(
} {
let realResolvedPath: string
try {
- realResolvedPath = readFs.realpathSync.native(
- resolveFromCwd(cwd, resolved.path),
- )
+ realResolvedPath = readFs.realpathSync.native(resolve(cwd, resolved.path))
} catch {
throw new IntentCoreError(
'skill-file-not-found',
@@ -199,10 +166,10 @@ function toResolvedIntentSkill(
)
}
const realPackageRoot = readFs.realpathSync.native(
- resolveFromCwd(cwd, resolved.packageRoot),
+ resolve(cwd, resolved.packageRoot),
)
- if (!isResolvedPathInsidePackageRoot(realResolvedPath, realPackageRoot)) {
+ if (!isWithinOrEqual(realResolvedPath, realPackageRoot)) {
throw new IntentCoreError(
'skill-path-outside-package',
`Resolved skill path for "${use}" is outside package root: ${resolved.path}`,
@@ -276,10 +243,7 @@ function resolveIntentSkillInCwd(
try {
parsedUse = parseSkillUse(use)
} catch (err) {
- throw new IntentCoreError(
- 'invalid-skill-use',
- err instanceof Error ? err.message : String(err),
- )
+ throw new IntentCoreError('invalid-skill-use', errorMessage(err))
}
const fsCache = createIntentFsCache()
@@ -297,8 +261,7 @@ function resolveIntentSkillInCwd(
throw new IntentCoreError(refusal.code, refusal.message)
}
- const scanOptions = toScanOptions(options)
- const scope = getScanScope(scanOptions)
+ const scope = toScanScope(options)
const fastPathResolved = resolveSkillUseFastPath(
parsedUse,
options,
@@ -338,9 +301,11 @@ function resolveIntentSkillInCwd(
const { scan: scanResult, droppedNames } = scanForPolicedIntents({
cwd,
- scanOptions: withFsCache(scanOptions, fsCache),
+ scanOptions: { scope, fsCache },
coreOptions: options,
context: projectContext,
+ config,
+ excludePatterns,
})
if (droppedNames.includes(parsedUse.packageName)) {
const lateRefusal = packageNotListedRefusal(use, parsedUse.packageName)
diff --git a/packages/intent/src/core/load-resolution.ts b/packages/intent/src/core/load-resolution.ts
index bed6a6c7..22c69c2a 100644
--- a/packages/intent/src/core/load-resolution.ts
+++ b/packages/intent/src/core/load-resolution.ts
@@ -1,12 +1,10 @@
import { existsSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
-import { createIntentFsCache } from '../discovery/fs-cache.js'
import { resolveSkillEntry } from '../skills/resolver.js'
import { scanIntentPackageAtRoot } from '../discovery/scanner.js'
-import { findWorkspacePackages } from '../setup/workspace-patterns.js'
-import { getDeps, resolveDepDir } from '../shared/utils.js'
+import { getDeps } from '../shared/node-modules.js'
+import { findWorkspacePackages } from './workspace-patterns.js'
import { warningMentionsPackage } from './excludes.js'
-import { resolveProjectContext } from './project-context.js'
import type { ResolveSkillResult } from '../skills/resolver.js'
import type { IntentFsCache } from '../discovery/fs-cache.js'
import type { ProjectContext } from './project-context.js'
@@ -83,23 +81,6 @@ function findVisibleDependencyDir(
return null
}
-function resolveDependencyPackageDir(
- packageName: string,
- fromDir: string,
-): string | null {
- return (
- findVisibleDependencyDir(packageName, fromDir) ??
- resolveDepDir(packageName, fromDir)
- )
-}
-
-function workspacePackageDeclaresDependency(
- packageJson: Record,
- packageName: string,
-): boolean {
- return getDeps(packageJson).includes(packageName)
-}
-
function hasYarnPnpFile(dir: string | null): boolean {
return (
dir !== null &&
@@ -107,13 +88,6 @@ function hasYarnPnpFile(dir: string | null): boolean {
)
}
-function shouldSkipFastPathForYarnPnp(
- context: ProjectContext,
- cwd: string,
-): boolean {
- return hasYarnPnpFile(cwd) || hasYarnPnpFile(context.workspaceRoot)
-}
-
function getDirectLoadFastPathCandidateDirs(
packageName: string,
context: ProjectContext,
@@ -126,7 +100,7 @@ function getDirectLoadFastPathCandidateDirs(
addCandidateDir(
candidates,
seen,
- resolveDependencyPackageDir(packageName, context.packageRoot ?? cwd),
+ findVisibleDependencyDir(packageName, context.packageRoot ?? cwd),
)
return candidates
}
@@ -134,17 +108,17 @@ function getDirectLoadFastPathCandidateDirs(
addCandidateDir(
candidates,
seen,
- resolveDependencyPackageDir(
+ findVisibleDependencyDir(
packageName,
context.packageRoot ?? context.workspaceRoot,
),
)
- if (context.workspaceRoot && context.workspaceRoot !== context.packageRoot) {
+ if (context.workspaceRoot !== context.packageRoot) {
addCandidateDir(
candidates,
seen,
- resolveDependencyPackageDir(packageName, context.workspaceRoot),
+ findVisibleDependencyDir(packageName, context.workspaceRoot),
)
}
@@ -167,14 +141,12 @@ function getWorkspaceLoadFastPathCandidateDirs(
}
for (const pkg of workspacePackages) {
- if (!workspacePackageDeclaresDependency(pkg.packageJson, packageName)) {
- continue
- }
+ if (!getDeps(pkg.packageJson).includes(packageName)) continue
addCandidateDir(
candidates,
seen,
- resolveDependencyPackageDir(packageName, pkg.dir),
+ findVisibleDependencyDir(packageName, pkg.dir),
)
}
@@ -251,12 +223,12 @@ function resolveFromPackageRoots(
export function resolveSkillUseFastPath(
parsedUse: SkillUse,
options: IntentCoreOptions,
- context = resolveProjectContext({ cwd: process.cwd() }),
- cwd = context.cwd,
- fsCache = createIntentFsCache(),
+ context: ProjectContext,
+ cwd: string,
+ fsCache: IntentFsCache,
): FastPathResolveResult | null {
if (options.globalOnly) return null
- if (shouldSkipFastPathForYarnPnp(context, cwd)) return null
+ if (hasYarnPnpFile(cwd) || hasYarnPnpFile(context.workspaceRoot)) return null
const directResolved = resolveFromPackageRoots(
getDirectLoadFastPathCandidateDirs(parsedUse.packageName, context, cwd),
diff --git a/packages/intent/src/core/markdown.ts b/packages/intent/src/core/markdown.ts
index cb9cb40b..29e4d3ea 100644
--- a/packages/intent/src/core/markdown.ts
+++ b/packages/intent/src/core/markdown.ts
@@ -1,5 +1,5 @@
import { dirname, isAbsolute, relative, resolve } from 'node:path'
-import { toPosixPath } from '../shared/utils.js'
+import { toPosixPath } from '../shared/paths.js'
/**
* A character that does not occur in `text`, taken from the Unicode private
@@ -13,10 +13,6 @@ function pickPlaceholder(text: string): string {
return String.fromCharCode(codePoint)
}
-function resolveFromCwd(path: string): string {
- return resolve(process.cwd(), path)
-}
-
function splitDestinationSuffix(destination: string): {
pathPart: string
suffix: string
@@ -305,7 +301,7 @@ export function rewriteLoadedSkillMarkdownDestinations({
}): string {
const context: MarkdownDestinationRewriteContext = {
cwd,
- resolvedPackageRoot: resolveFromCwd(packageRoot),
+ resolvedPackageRoot: resolve(cwd, packageRoot),
skillDir: dirname(skillFilePath),
rewrittenDestinations: new Map(),
}
diff --git a/packages/intent/src/core/package-json.ts b/packages/intent/src/core/package-json.ts
index 8be2e9f9..962438df 100644
--- a/packages/intent/src/core/package-json.ts
+++ b/packages/intent/src/core/package-json.ts
@@ -1,5 +1,6 @@
import { join } from 'node:path'
import { createIntentFsCache } from '../discovery/fs-cache.js'
+import { errorMessage } from '../shared/guards.js'
/**
* Reads a project policy manifest, returning null only when the file is absent.
@@ -24,7 +25,7 @@ export function readPackageJson(
return null
}
throw new Error(
- `Failed to read Intent policy from ${filePath}: ${error instanceof Error ? error.message : String(error)}`,
+ `Failed to read Intent policy from ${filePath}: ${errorMessage(error)}`,
)
}
diff --git a/packages/intent/src/core/project-context.ts b/packages/intent/src/core/project-context.ts
index d4c56878..70fd4e3e 100644
--- a/packages/intent/src/core/project-context.ts
+++ b/packages/intent/src/core/project-context.ts
@@ -1,10 +1,11 @@
import { existsSync, statSync } from 'node:fs'
-import { dirname, join, relative, resolve } from 'node:path'
+import { dirname, join, resolve } from 'node:path'
+import { isWithinOrEqual } from '../shared/paths.js'
import { createIntentFsCache } from '../discovery/fs-cache.js'
import {
findWorkspaceRoot,
readWorkspacePatterns,
-} from '../setup/workspace-patterns.js'
+} from './workspace-patterns.js'
import type { IntentFsCache } from '../discovery/fs-cache.js'
export type ProjectContext = {
@@ -64,14 +65,14 @@ export function resolveProjectContext({
function findOwningPackageRoot(
startPath: string,
- fsCache?: IntentFsCache,
+ fsCache: IntentFsCache,
): string | null {
- let cache = fsCache ? packageRootCaches.get(fsCache) : undefined
- if (fsCache && !cache) {
+ let cache = packageRootCaches.get(fsCache)
+ if (!cache) {
cache = new Map()
packageRootCaches.set(fsCache, cache)
}
- const cachedStart = cache?.get(startPath)
+ const cachedStart = cache.get(startPath)
if (cachedStart !== undefined) return cachedStart
let dir = toSearchDir(startPath)
@@ -79,14 +80,14 @@ function findOwningPackageRoot(
const visited: Array = [startPath]
while (dir !== prev) {
- const cached = cache?.get(dir)
+ const cached = cache.get(dir)
if (cached !== undefined) {
- for (const visitedDir of visited) cache?.set(visitedDir, cached)
+ for (const visitedDir of visited) cache.set(visitedDir, cached)
return cached
}
visited.push(dir)
if (existsSync(join(dir, 'package.json'))) {
- for (const visitedDir of visited) cache?.set(visitedDir, dir)
+ for (const visitedDir of visited) cache.set(visitedDir, dir)
return dir
}
@@ -96,7 +97,7 @@ function findOwningPackageRoot(
dir = dirname(dir)
}
- for (const visitedDir of visited) cache?.set(visitedDir, null)
+ for (const visitedDir of visited) cache.set(visitedDir, null)
return null
}
@@ -129,8 +130,3 @@ function resolveTargetSkillsDir(
return null
}
-
-function isWithinOrEqual(path: string, parentDir: string): boolean {
- const rel = relative(parentDir, path)
- return rel === '' || (!rel.startsWith('..') && !rel.startsWith('/'))
-}
diff --git a/packages/intent/src/core/skill-sources.ts b/packages/intent/src/core/skill-sources.ts
index 3a3dfeb6..c0e2f515 100644
--- a/packages/intent/src/core/skill-sources.ts
+++ b/packages/intent/src/core/skill-sources.ts
@@ -1,11 +1,9 @@
// Static-discovery invariant: this module only inspects strings. It never
// resolves, requires, or executes any discovered package.
-type SkillSource =
- | ({ raw: string; kind: 'npm' | 'workspace' } & (
- { id: string; skill?: string } | { pattern: string }
- ))
- | { raw: string; id: string; kind: 'git'; ref: string }
+type SkillSource = { raw: string; kind: 'npm' | 'workspace' } & (
+ { id: string; skill?: string } | { pattern: string }
+)
/**
* `absent` (key missing, v0 upgrade path) and `empty` (`[]`) are deliberately
@@ -32,12 +30,6 @@ export class SkillSourcesParseError extends Error {
}
}
-export function isSkillSourcesParseError(
- error: unknown,
-): error is SkillSourcesParseError {
- return error instanceof SkillSourcesParseError
-}
-
/**
* Strictness is fail-whole-list: every malformed entry is collected and
* reported together, and a single bad entry rejects the entire list rather
diff --git a/packages/intent/src/core/source-policy.ts b/packages/intent/src/core/source-policy.ts
index 5d565bd4..d65e3b2b 100644
--- a/packages/intent/src/core/source-policy.ts
+++ b/packages/intent/src/core/source-policy.ts
@@ -2,6 +2,7 @@ import { scanForIntents } from '../discovery/scanner.js'
import { createIntentFsCache } from '../discovery/fs-cache.js'
import { detectIntentAudience } from '../shared/environment.js'
import { ALLOW_ALL_NOTICE } from '../shared/cli-output.js'
+import { isRecord } from '../shared/guards.js'
import {
compileExcludePatterns,
compileWildcardPattern,
@@ -14,9 +15,10 @@ import {
import { readPackageJson } from './package-json.js'
import { parseSkillSources } from './skill-sources.js'
import { resolveProjectContext } from './project-context.js'
+import type { ScanOptionsWithFsCache } from '../discovery/scanner.js'
import type { IntentFsCache } from '../discovery/fs-cache.js'
import type { SkillUse } from '../skills/use.js'
-import type { IntentPackage, ScanOptions, ScanResult } from '../shared/types.js'
+import type { IntentPackage, ScanResult } from '../shared/types.js'
import type { ExcludeMatcher } from './excludes.js'
import type { ProjectContext } from './project-context.js'
import type { SkillSourcesConfig } from './skill-sources.js'
@@ -26,8 +28,6 @@ import type {
IntentHiddenSourceSummary,
} from './types.js'
-export { ALLOW_ALL_NOTICE }
-
export const MIGRATION_NOTICE =
'intent.skills is not set — all discovered skill sources are surfaced. A future version will require an explicit intent.skills allowlist; add one to opt in to specific sources.'
@@ -64,10 +64,6 @@ interface SkillSourceMatcher {
function compileSkillSourceMatcher(
source: ExplicitSkillSource,
): SkillSourceMatcher {
- if (source.kind === 'git') {
- return { source, matchesPackage: () => false }
- }
-
const matchesName =
'pattern' in source
? compileWildcardPattern(source.pattern)
@@ -205,15 +201,8 @@ export function applySourcePolicy(
const { config, excludeMatchers } = options
const audience = options.audience ?? 'human'
const sourcePolicy = compileSkillSourcePolicy(config)
- const seen = new Set()
const notices: Array = []
- const emit = (notice: string): void => {
- if (seen.has(notice)) return
- seen.add(notice)
- notices.push(notice)
- }
-
const packages: Array = []
const hiddenSources: Array = []
@@ -238,7 +227,7 @@ export function applySourcePolicy(
}
if (hiddenSources.length > 0) {
- emit(formatUnlistedNotice(hiddenSources, audience))
+ notices.push(formatUnlistedNotice(hiddenSources, audience))
}
if (config.mode === 'explicit') {
@@ -252,16 +241,16 @@ export function applySourcePolicy(
source.skill &&
!pkg.skills.some((skill) => skill.name === source.skill))
) {
- emit(
+ notices.push(
`"${source.raw}" is declared in intent.skills but was not discovered.`,
)
}
}
}
- if (config.mode === 'absent') emit(MIGRATION_NOTICE)
- else if (config.mode === 'allow-all') emit(ALLOW_ALL_NOTICE)
- else if (config.mode === 'empty') emit(EMPTY_NOTE)
+ if (config.mode === 'absent') notices.push(MIGRATION_NOTICE)
+ else if (config.mode === 'allow-all') notices.push(ALLOW_ALL_NOTICE)
+ else if (config.mode === 'empty') notices.push(EMPTY_NOTE)
return {
hiddenSourceCount: hiddenSources.length,
@@ -280,10 +269,10 @@ export function readSkillSourcesConfig(
): SkillSourcesConfig {
for (const dir of getConfigDirs(cwd, context)) {
const intent = readPackageJson(dir, fsCache)?.intent
- if (!intent || typeof intent !== 'object') continue
+ if (!isRecord(intent)) continue
if ('skills' in intent) {
- const skills = (intent as Record).skills
+ const skills = intent.skills
if (skills === null || skills === undefined) continue
return parseSkillSources(skills)
}
@@ -302,24 +291,22 @@ export interface PolicedScan {
export function scanForPolicedIntents(params: {
cwd: string
- scanOptions: ScanOptions
+ scanOptions: ScanOptionsWithFsCache
coreOptions: IntentCoreOptions
context?: ProjectContext
+ config?: SkillSourcesConfig
+ excludePatterns?: Array
}): PolicedScan {
const { cwd, scanOptions, coreOptions } = params
- const fsCache =
- (scanOptions as ScanOptions & { fsCache?: IntentFsCache }).fsCache ??
- createIntentFsCache()
+ const fsCache = scanOptions.fsCache ?? createIntentFsCache()
const context = params.context ?? resolveProjectContext({ cwd, fsCache })
const audience = detectIntentAudience(coreOptions.audience)
const cachedScanOptions = { ...scanOptions, fsCache }
const scanResult = scanForIntents(cwd, cachedScanOptions)
- const config = readSkillSourcesConfig(cwd, context, fsCache)
- const excludePatterns = getEffectiveExcludePatterns(
- coreOptions,
- context,
- fsCache,
- )
+ const config = params.config ?? readSkillSourcesConfig(cwd, context, fsCache)
+ const excludePatterns =
+ params.excludePatterns ??
+ getEffectiveExcludePatterns(coreOptions, context, fsCache)
const excludeMatchers = compileExcludePatterns(excludePatterns)
const policy = applySourcePolicy(scanResult, {
diff --git a/packages/intent/src/core/types.ts b/packages/intent/src/core/types.ts
index eb675b4c..6cf66fad 100644
--- a/packages/intent/src/core/types.ts
+++ b/packages/intent/src/core/types.ts
@@ -97,24 +97,6 @@ export interface LoadedIntentSkillDebug {
scan: ScanStats
}
-// `npm:foo` and `workspace:foo` are distinct sources; name-only comparison
-// would collapse them onto one lockfile entry/approval.
-export interface SourceIdentity {
- kind: 'npm' | 'workspace'
- id: string
-}
-
-export function sourceIdentityKey(s: SourceIdentity): string {
- return `${s.kind}\u0000${s.id}`
-}
-
-export function sourceIdentityEquals(
- a: SourceIdentity,
- b: SourceIdentity,
-): boolean {
- return a.kind === b.kind && a.id === b.id
-}
-
export type IntentCoreErrorCode =
| 'invalid-options'
| 'invalid-skill-use'
diff --git a/packages/intent/src/setup/workspace-patterns.ts b/packages/intent/src/core/workspace-patterns.ts
similarity index 89%
rename from packages/intent/src/setup/workspace-patterns.ts
rename to packages/intent/src/core/workspace-patterns.ts
index 2979f380..ebd3d725 100644
--- a/packages/intent/src/setup/workspace-patterns.ts
+++ b/packages/intent/src/core/workspace-patterns.ts
@@ -2,8 +2,9 @@ import { existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { parse as parseJsonc } from 'jsonc-parser/lib/esm/main.js'
import { parse as parseYaml } from 'yaml'
-import { hasAnySkillFile } from '../shared/utils.js'
-import { readPackageJson } from '../core/package-json.js'
+import { errorMessage, isRecord } from '../shared/guards.js'
+import { hasAnySkillFile } from '../shared/skill-files.js'
+import { readPackageJson } from './package-json.js'
import type { ParseError } from 'jsonc-parser/lib/esm/main.js'
import type { IntentFsCache } from '../discovery/fs-cache.js'
@@ -26,10 +27,6 @@ function normalizeWorkspacePatterns(patterns: Array): Array {
].sort(compareCodeUnits)
}
-function isRecord(value: unknown): value is Record {
- return typeof value === 'object' && value !== null && !Array.isArray(value)
-}
-
function parseWorkspacePatternList(
value: unknown,
fieldName: string,
@@ -108,9 +105,7 @@ function readJsoncFile(path: string): unknown {
function warnConfigError(path: string, err: unknown): void {
const verb = err instanceof SyntaxError ? 'parse' : 'read'
- console.error(
- `Warning: failed to ${verb} ${path}: ${err instanceof Error ? err.message : err}`,
- )
+ console.error(`Warning: failed to ${verb} ${path}: ${errorMessage(err)}`)
}
type WorkspacePatternSource = {
@@ -119,13 +114,6 @@ type WorkspacePatternSource = {
getPatterns: (config: unknown) => Array | null
}
-export type WorkspaceInfo = {
- root: string
- patterns: Array
- packageDirs: Array
- packageDirsWithSkills: Array
-}
-
const workspacePatternSources: Array = [
{
fileName: 'pnpm-workspace.yaml',
@@ -245,23 +233,6 @@ export function findWorkspacePackages(
return packageDirs
}
-export function getWorkspaceInfo(root: string): WorkspaceInfo | null {
- const patterns = readWorkspacePatterns(root)
- if (!patterns) return null
-
- const packageDirs = resolveWorkspacePackages(root, patterns)
- const packageDirsWithSkills = packageDirs.filter((dir) => {
- const skillsDir = join(dir, 'skills')
- return existsSync(skillsDir) && hasAnySkillFile(skillsDir)
- })
- return {
- root,
- patterns,
- packageDirs,
- packageDirsWithSkills,
- }
-}
-
export function resolveWorkspacePackages(
root: string,
patterns: Array,
@@ -338,7 +309,7 @@ function readChildDirectories(dir: string): Array {
.map((entry) => join(dir, entry.name))
} catch (err: unknown) {
console.error(
- `Warning: could not read directory ${dir}: ${err instanceof Error ? err.message : err}`,
+ `Warning: could not read directory ${dir}: ${errorMessage(err)}`,
)
return []
}
@@ -377,6 +348,12 @@ export function findWorkspaceRoot(
return null
}
-export function findPackagesWithSkills(root: string): Array {
- return getWorkspaceInfo(root)?.packageDirsWithSkills ?? []
+export function findPackagesWithSkills(
+ root: string,
+ fsCache?: IntentFsCache,
+): Array {
+ return findWorkspacePackages(root, fsCache).filter((dir) => {
+ const skillsDir = join(dir, 'skills')
+ return existsSync(skillsDir) && hasAnySkillFile(skillsDir)
+ })
}
diff --git a/packages/intent/src/discovery/fs-cache.ts b/packages/intent/src/discovery/fs-cache.ts
index 60981209..7fed1264 100644
--- a/packages/intent/src/discovery/fs-cache.ts
+++ b/packages/intent/src/discovery/fs-cache.ts
@@ -1,10 +1,8 @@
import { join } from 'node:path'
-import {
- createFsIdentityCache,
- findSkillFiles as findSkillFilesUncached,
- nodeReadFs,
-} from '../shared/utils.js'
-import type { ReadFs } from '../shared/utils.js'
+import { isRecord } from '../shared/guards.js'
+import { createFsIdentityCache, nodeReadFs } from '../shared/fs-identity.js'
+import { findSkillFiles as findSkillFilesUncached } from '../shared/skill-files.js'
+import type { ReadFs } from '../shared/fs-identity.js'
type PackageJsonReadResult = {
packageJson: Record | null
@@ -36,10 +34,6 @@ export type IntentFsCache = {
exists: (path: string) => boolean
}
-function isRecord(value: unknown): value is Record {
- return typeof value === 'object' && value !== null && !Array.isArray(value)
-}
-
export function createIntentFsCache(): IntentFsCache {
const packageJsonCache = new Map()
const skillFilesCache = new Map>()
diff --git a/packages/intent/src/discovery/index.ts b/packages/intent/src/discovery/index.ts
deleted file mode 100644
index 0e0e22d9..00000000
--- a/packages/intent/src/discovery/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { createPackageRegistrar } from './register.js'
-export { createDependencyWalker } from './walk.js'
diff --git a/packages/intent/src/discovery/package-manager.ts b/packages/intent/src/discovery/package-manager.ts
index 55c92089..6383f5bc 100644
--- a/packages/intent/src/discovery/package-manager.ts
+++ b/packages/intent/src/discovery/package-manager.ts
@@ -9,21 +9,13 @@ function readPackageManagerField(
fsCache: IntentFsCache,
): PackageManager | null {
if (!existsSync(join(dir, 'package.json'))) return null
- try {
- const parsed = fsCache.readPackageJson(dir)
- if (!parsed) return null
-
- const value = parsed.packageManager
- if (typeof value !== 'string') return null
-
- if (value.startsWith('pnpm@')) return 'pnpm'
- if (value.startsWith('yarn@')) return 'yarn'
- if (value.startsWith('bun@')) return 'bun'
- if (value.startsWith('npm@')) return 'npm'
- } catch {
- return null
- }
+ const value = fsCache.readPackageJson(dir)?.packageManager
+ if (typeof value !== 'string') return null
+ if (value.startsWith('pnpm@')) return 'pnpm'
+ if (value.startsWith('yarn@')) return 'yarn'
+ if (value.startsWith('bun@')) return 'bun'
+ if (value.startsWith('npm@')) return 'npm'
return null
}
diff --git a/packages/intent/src/discovery/register.ts b/packages/intent/src/discovery/register.ts
index 14807664..ed99842f 100644
--- a/packages/intent/src/discovery/register.ts
+++ b/packages/intent/src/discovery/register.ts
@@ -1,7 +1,6 @@
-import { existsSync } from 'node:fs'
import { join, sep } from 'node:path'
import { rewriteSkillLoadPaths } from '../skills/paths.js'
-import { listNodeModulesPackageDirs } from '../shared/utils.js'
+import { listNodeModulesPackageDirs } from '../shared/node-modules.js'
import type {
IntentConfig,
IntentPackage,
@@ -36,7 +35,7 @@ export interface CreatePackageRegistrarOptions {
*/
exists: (path: string) => boolean
rememberVariant: (pkg: IntentPackage) => void
- validateIntentField: (pkgName: string, intent: unknown) => IntentConfig | null
+ validateIntentField: (intent: unknown) => IntentConfig | null
warnings: Array
}
@@ -57,8 +56,6 @@ export function createPackageRegistrar(opts: CreatePackageRegistrarOptions) {
nodeModulesDir: string,
source: IntentPackage['source'] = 'local',
): void {
- if (!existsSync(nodeModulesDir)) return
-
const key = opts.getFsIdentity(nodeModulesDir)
if (scannedNodeModulesDirs.has(key)) return
scannedNodeModulesDirs.add(key)
@@ -100,7 +97,7 @@ export function createPackageRegistrar(opts: CreatePackageRegistrarOptions) {
const version =
typeof pkgJson.version === 'string' ? pkgJson.version : '0.0.0'
const intent =
- opts.validateIntentField(name, pkgJson.intent) ??
+ opts.validateIntentField(pkgJson.intent) ??
opts.deriveIntentConfig(pkgJson)
if (!intent) {
opts.warnings.push(
diff --git a/packages/intent/src/discovery/scanner.ts b/packages/intent/src/discovery/scanner.ts
index 93406be9..3f133a4b 100644
--- a/packages/intent/src/discovery/scanner.ts
+++ b/packages/intent/src/discovery/scanner.ts
@@ -13,24 +13,23 @@ import {
resolve,
sep,
} from 'node:path'
-import {
- detectGlobalNodeModules,
- nodeReadFs,
- parseFrontmatter,
- readScalarField,
- toPosixPath,
-} from '../shared/utils.js'
+import { errorMessage, isRecord } from '../shared/guards.js'
+import { isWithinOrEqual, toPosixPath } from '../shared/paths.js'
+import { detectGlobalNodeModules } from '../shared/node-modules.js'
+import { parseFrontmatter, readScalarField } from '../shared/frontmatter.js'
import {
findWorkspacePackages,
findWorkspaceRoot,
readWorkspacePatterns,
-} from '../setup/workspace-patterns.js'
+} from '../core/workspace-patterns.js'
import { compareVersions, normalizeVersion } from '../shared/version.js'
+import { getPackageShortName } from '../skills/use.js'
import { createIntentFsCache } from './fs-cache.js'
import { detectPackageManager } from './package-manager.js'
-import { createDependencyWalker, createPackageRegistrar } from './index.js'
+import { createPackageRegistrar } from './register.js'
+import { createDependencyWalker } from './walk.js'
import type { IntentFsCache } from './fs-cache.js'
-import type { ReadFs } from '../shared/utils.js'
+import type { ReadFs } from '../shared/fs-identity.js'
import type {
InstalledVariant,
IntentConfig,
@@ -42,7 +41,7 @@ import type {
VersionConflict,
} from '../shared/types.js'
-type ScanOptionsWithFsCache = ScanOptions & {
+export type ScanOptionsWithFsCache = ScanOptions & {
fsCache?: IntentFsCache
}
@@ -132,7 +131,7 @@ function loadPnpApi(root: string): LoadedPnp | null {
// reference becomes patched without routing a post-setup `require('node:fs')`
// through Yarn's resolver hook (which rejects the `node:fs` specifier under
// Yarn 1 PnP).
- const readFs = requireFromHere('node:fs') as unknown as ReadFs
+ const readFs: ReadFs = requireFromHere('node:fs')
try {
// eslint-disable-next-line no-restricted-syntax -- sanctioned PnP runtime load
@@ -168,9 +167,8 @@ function loadPnpApi(root: string): LoadedPnp | null {
// Ignore and report the project PnP load error below.
}
- const msg = err instanceof Error ? err.message : String(err)
throw new Error(
- `Yarn PnP project detected, but Intent could not load Yarn's PnP API from ${pnpPath}: ${msg}`,
+ `Yarn PnP project detected, but Intent could not load Yarn's PnP API from ${pnpPath}: ${errorMessage(err)}`,
)
}
}
@@ -190,14 +188,7 @@ function getPnpDependencyLocator(
return { name: dependencyName, reference: target }
}
-// ---------------------------------------------------------------------------
-// Intent field validation
-// ---------------------------------------------------------------------------
-
-function validateIntentField(
- _pkgName: string,
- intent: unknown,
-): IntentConfig | null {
+function validateIntentField(intent: unknown): IntentConfig | null {
if (!intent || typeof intent !== 'object') return null
const pb = intent as Record
@@ -226,35 +217,28 @@ function validateIntentField(
function deriveIntentConfig(
pkgJson: Record,
): IntentConfig | null {
- // Derive repo from repository field
+ const { repository } = pkgJson
let repo: string | null = null
- if (typeof pkgJson.repository === 'string') {
- repo = pkgJson.repository
- } else if (
- pkgJson.repository &&
- typeof pkgJson.repository === 'object' &&
- typeof (pkgJson.repository as Record).url === 'string'
- ) {
- repo = (pkgJson.repository as Record).url as string
+ if (typeof repository === 'string') {
+ repo = repository
+ } else if (isRecord(repository) && typeof repository.url === 'string') {
// Normalize git+https://github.com/foo/bar.git → foo/bar
- repo = repo
+ repo = repository.url
.replace(/^git\+/, '')
.replace(/\.git$/, '')
.replace(/^https?:\/\/github\.com\//, '')
}
- // Derive docs from homepage field
const docs =
typeof pkgJson.homepage === 'string' ? pkgJson.homepage : undefined
- // Need at least a repo to be useful
if (!repo) return null
- // Derive requires from intent.requires if partially present
- const intentPartial = pkgJson.intent as Record | undefined
const requires =
- intentPartial && Array.isArray(intentPartial.requires)
- ? intentPartial.requires.filter((r): r is string => typeof r === 'string')
+ isRecord(pkgJson.intent) && Array.isArray(pkgJson.intent.requires)
+ ? pkgJson.intent.requires.filter(
+ (r): r is string => typeof r === 'string',
+ )
: undefined
return {
@@ -265,14 +249,10 @@ function deriveIntentConfig(
}
}
-// ---------------------------------------------------------------------------
-// Skill discovery within a package
-// ---------------------------------------------------------------------------
-
/**
* Real path of the package root that owns `skillsDir`, or null when it cannot
* be resolved. Computed once per package: every skill entry is checked against
- * the same root, so resolving it per skill only repeated the same syscalls.
+ * the same root.
*/
function resolveRealPackageRoot(
skillsDir: string,
@@ -290,7 +270,7 @@ function readSkillEntry(
realPackageRoot: string | null,
childDir: string,
skillFile: string,
- readFs: ReadFs = nodeReadFs,
+ readFs: ReadFs,
): SkillEntry | null {
if (!readFs.openSync || !readFs.fstatSync || !readFs.closeSync) return null
if (realPackageRoot === null) return null
@@ -341,8 +321,8 @@ function discoverSkillByNameHint(
skillsDir: string,
packageName: string,
skillNameHint: string,
- readFs: ReadFs = nodeReadFs,
- includeMetadata = true,
+ readFs: ReadFs,
+ includeMetadata: boolean,
): Array {
const skills: Array = []
const seen = new Set()
@@ -413,15 +393,6 @@ function discoverSkills(
})
}
-function getPackageShortName(packageName: string): string {
- return packageName.split('/').pop() ?? packageName
-}
-
-function isWithinOrEqual(path: string, parentDir: string): boolean {
- const rel = relative(parentDir, path)
- return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
-}
-
function resolveSkillNameHintPath(
skillsDir: string,
hint: string,
@@ -460,10 +431,6 @@ function getSkillNameHints(
return [skillNameHint, `${packageShortName}/${skillNameHint}`]
}
-// ---------------------------------------------------------------------------
-// Topological sort on requires
-// ---------------------------------------------------------------------------
-
function topoSort(packages: Array): Array {
const byName = new Map(packages.map((p) => [p.name, p]))
const visited = new Set()
@@ -503,43 +470,6 @@ function comparePackageVersions(a: string, b: string): number {
return compareVersions(versionA, versionB)
}
-function formatVariantWarning(
- name: string,
- variants: Array,
- chosen: IntentPackage,
-): string | null {
- const uniqueVersions = new Set(variants.map((variant) => variant.version))
- if (uniqueVersions.size <= 1) return null
-
- const details = variants
- .map((variant) => `${variant.version} at ${variant.packageRoot}`)
- .join(', ')
-
- return `Found ${variants.length} installed variants of ${name} across ${uniqueVersions.size} versions (${details}). Using ${chosen.version} from ${chosen.packageRoot}.`
-}
-
-function toVersionConflict(
- packageName: string,
- variants: Array,
- chosen: IntentPackage,
-): VersionConflict | null {
- const uniqueVersions = new Set(variants.map((variant) => variant.version))
- if (uniqueVersions.size <= 1) return null
-
- return {
- packageName,
- chosen: {
- version: chosen.version,
- packageRoot: chosen.packageRoot,
- },
- variants,
- }
-}
-
-// ---------------------------------------------------------------------------
-// Main scanner
-// ---------------------------------------------------------------------------
-
function getScanScope(options: ScanOptions): ScanScope {
return options.scope ?? (options.includeGlobal ? 'local-and-global' : 'local')
}
@@ -675,12 +605,8 @@ export function scanForIntents(
: undefined,
},
}
- // Track registered package names to avoid duplicates across phases
const packageIndexes = new Map()
- const packageVariants = new Map<
- string,
- Map
- >()
+ const packageVariants = new Map>()
let pnpApi: PnpApi | null | undefined
const getPackageKind = createPackageKindResolver(
@@ -700,10 +626,6 @@ export function scanForIntents(
return pnpApi
}
- function getStats(): ScanResult['stats'] {
- return fsCache.getStats()
- }
-
function rememberVariant(pkg: IntentPackage): void {
let variants = packageVariants.get(pkg.name)
if (!variants) {
@@ -717,7 +639,7 @@ export function scanForIntents(
}
function ensureGlobalNodeModules(): void {
- if (!nodeModules.global.path && !explicitGlobalNodeModules) {
+ if (!nodeModules.global.path) {
const detected = detectGlobalNodeModules(packageManager)
nodeModules.global.path = detected.path
nodeModules.global.source = detected.source
@@ -728,10 +650,6 @@ export function scanForIntents(
}
}
- function readPkgJson(dirPath: string): Record | null {
- return fsCache.readPackageJson(dirPath)
- }
-
const { scanNodeModulesDir, scanTarget, tryRegister } =
createPackageRegistrar({
comparePackageVersions,
@@ -745,7 +663,7 @@ export function scanForIntents(
packageIndexes,
packages,
projectRoot,
- readPkgJson,
+ readPkgJson: fsCache.readPackageJson,
rememberVariant,
validateIntentField,
warnings,
@@ -762,7 +680,7 @@ export function scanForIntents(
primeFsIdentity: fsCache.primeFsIdentity,
packages,
projectRoot,
- readPkgJson,
+ readPkgJson: fsCache.readPackageJson,
scanNodeModulesDir,
tryRegister,
warnings,
@@ -867,36 +785,35 @@ export function scanForIntents(
notices: [],
conflicts,
nodeModules,
- stats: getStats(),
+ stats: fsCache.getStats(),
}
}
for (const pkg of packages) {
- const variants = packageVariants.get(pkg.name)
- if (!variants) continue
-
- const conflict = toVersionConflict(pkg.name, [...variants.values()], pkg)
- if (conflict) {
- conflicts.push(conflict)
- }
-
- const warning = formatVariantWarning(pkg.name, [...variants.values()], pkg)
- if (warning) {
- warnings.push(warning)
- }
+ const variants = [...(packageVariants.get(pkg.name)?.values() ?? [])]
+ const versions = new Set(variants.map((v) => v.version))
+ if (versions.size <= 1) continue
+ conflicts.push({
+ packageName: pkg.name,
+ chosen: { version: pkg.version, packageRoot: pkg.packageRoot },
+ variants,
+ })
+ const details = variants
+ .map((v) => `${v.version} at ${v.packageRoot}`)
+ .join(', ')
+ warnings.push(
+ `Found ${variants.length} installed variants of ${pkg.name} across ${versions.size} versions (${details}). Using ${pkg.version} from ${pkg.packageRoot}.`,
+ )
}
- // Sort by dependency order
- const sorted = topoSort(packages)
-
return {
packageManager,
- packages: sorted,
+ packages: topoSort(packages),
warnings,
notices: [],
conflicts,
nodeModules,
- stats: getStats(),
+ stats: fsCache.getStats(),
}
}
@@ -905,7 +822,6 @@ export interface ScanIntentPackageAtRootOptions {
fsCache?: IntentFsCache
includeSkillMetadata?: boolean
projectRoot?: string
- source?: IntentPackage['source']
skillNameHint?: string
}
@@ -932,10 +848,6 @@ export function scanIntentPackageAtRoot(
fsCache.getFsIdentity,
)
- function readPkgJson(dirPath: string): Record | null {
- return fsCache.readPackageJson(dirPath)
- }
-
const { tryRegister } = createPackageRegistrar({
comparePackageVersions,
deriveIntentConfig,
@@ -957,17 +869,13 @@ export function scanIntentPackageAtRoot(
packageIndexes,
packages,
projectRoot,
- readPkgJson,
+ readPkgJson: fsCache.readPackageJson,
rememberVariant() {},
validateIntentField,
warnings,
})
- tryRegister(
- packageRoot,
- options.fallbackName ?? 'unknown',
- options.source ?? 'local',
- )
+ tryRegister(packageRoot, options.fallbackName ?? 'unknown')
return {
package: packages[0] ?? null,
diff --git a/packages/intent/src/discovery/walk.ts b/packages/intent/src/discovery/walk.ts
index 626c46ea..56edc76b 100644
--- a/packages/intent/src/discovery/walk.ts
+++ b/packages/intent/src/discovery/walk.ts
@@ -4,8 +4,8 @@ import {
getDeps,
listNestedNodeModulesPackageDirs,
resolveDepDir,
-} from '../shared/utils.js'
-import { findWorkspacePackages } from '../setup/workspace-patterns.js'
+} from '../shared/node-modules.js'
+import { findWorkspacePackages } from '../core/workspace-patterns.js'
import type { IntentFsCache } from './fs-cache.js'
import type { IntentPackage } from '../shared/types.js'
@@ -17,7 +17,7 @@ export interface CreateDependencyWalkerOptions {
readPkgJson: (dirPath: string) => PackageJson | null
getFsIdentity: (path: string) => string
/** Marks a directory `resolveDepDir` returned as its own identity. */
- primeFsIdentity?: (realPath: string) => void
+ primeFsIdentity: (realPath: string) => void
scanNodeModulesDir: (nodeModulesDir: string) => void
tryRegister: (dirPath: string, fallbackName: string) => boolean
packages: Array
@@ -45,7 +45,7 @@ export function createDependencyWalker(opts: CreateDependencyWalkerOptions) {
depDir = resolveDepDir(depName, fromDir, depDirResolution)
byDepName.set(depName, depDir)
// The result is already a real directory, so its identity is itself.
- if (depDir) opts.primeFsIdentity?.(depDir)
+ if (depDir) opts.primeFsIdentity(depDir)
}
return depDir
diff --git a/packages/intent/src/hooks/agents/claude.ts b/packages/intent/src/hooks/agents/claude.ts
deleted file mode 100644
index 44bb71f1..00000000
--- a/packages/intent/src/hooks/agents/claude.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import type { HookDecision } from '../types.js'
-
-export type ClaudeHookOutput = {
- hookSpecificOutput: {
- hookEventName: 'PreToolUse'
- permissionDecision: 'deny'
- permissionDecisionReason: string
- }
-}
-
-export function formatClaudePreToolUseOutput(
- decision: HookDecision,
-): ClaudeHookOutput | undefined {
- if (decision.decision === 'allow') {
- return undefined
- }
-
- return {
- hookSpecificOutput: {
- hookEventName: 'PreToolUse',
- permissionDecision: 'deny',
- permissionDecisionReason: decision.reason,
- },
- }
-}
diff --git a/packages/intent/src/hooks/agents/codex.ts b/packages/intent/src/hooks/agents/codex.ts
deleted file mode 100644
index ccc13e87..00000000
--- a/packages/intent/src/hooks/agents/codex.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import type { HookDecision } from '../types.js'
-
-export type CodexHookOutput = {
- hookSpecificOutput: {
- hookEventName: 'PreToolUse'
- permissionDecision: 'deny'
- permissionDecisionReason: string
- }
-}
-
-export function formatCodexPreToolUseOutput(
- decision: HookDecision,
-): CodexHookOutput | undefined {
- if (decision.decision === 'allow') {
- return undefined
- }
-
- return {
- hookSpecificOutput: {
- hookEventName: 'PreToolUse',
- permissionDecision: 'deny',
- permissionDecisionReason: decision.reason,
- },
- }
-}
diff --git a/packages/intent/src/hooks/agents/copilot.ts b/packages/intent/src/hooks/agents/copilot.ts
deleted file mode 100644
index c2231075..00000000
--- a/packages/intent/src/hooks/agents/copilot.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import type { HookDecision } from '../types.js'
-
-export type CopilotHookOutput = {
- permissionDecision: 'deny'
- permissionDecisionReason: string
-}
-
-export function formatCopilotPreToolUseOutput(
- decision: HookDecision,
-): CopilotHookOutput | undefined {
- if (decision.decision === 'allow') {
- return undefined
- }
-
- return {
- permissionDecision: 'deny',
- permissionDecisionReason: decision.reason,
- }
-}
diff --git a/packages/intent/src/hooks/install.ts b/packages/intent/src/hooks/install.ts
index 49b9b2cb..bc174568 100644
--- a/packages/intent/src/hooks/install.ts
+++ b/packages/intent/src/hooks/install.ts
@@ -4,6 +4,7 @@ import { dirname, relative } from 'node:path'
import { detectPackageManager } from '../discovery/package-manager.js'
import { fail } from '../shared/cli-error.js'
import { formatIntentCommand } from '../shared/command-runner.js'
+import { errorMessage, isRecord } from '../shared/guards.js'
import { ALL_HOOK_AGENTS, HOOK_AGENT_ADAPTERS } from './adapters.js'
import {
EDIT_TOOLS_BY_AGENT,
@@ -65,15 +66,20 @@ export function validateHookInstallOptions({
export function buildHookRunnerScript(
agent: HookAgent,
- catalogCommand = formatIntentCommand(
- detectPackageManager(),
- 'list --json --no-notices',
- ),
- loadCommand = formatIntentCommand(
- detectPackageManager(),
- 'load #',
- ),
+ catalogCommand?: string,
+ loadCommand?: string,
): string {
+ if (catalogCommand === undefined || loadCommand === undefined) {
+ const packageManager = detectPackageManager()
+ catalogCommand ??= formatIntentCommand(
+ packageManager,
+ 'list --json --no-notices',
+ )
+ loadCommand ??= formatIntentCommand(
+ packageManager,
+ 'load #',
+ )
+ }
const editTools = [...EDIT_TOOLS_BY_AGENT[agent]].sort()
return `#!/usr/bin/env node
@@ -428,31 +434,6 @@ function installAgentHook({
}),
)
- return hookInstallResult({
- agent,
- configPath,
- scope,
- scriptPath,
- scriptStatus,
- configStatus,
- })
-}
-
-function hookInstallResult({
- agent,
- configPath,
- configStatus,
- scope,
- scriptPath,
- scriptStatus,
-}: {
- agent: HookAgent
- configPath: string
- configStatus: HookInstallStatus
- scope: HookInstallScope
- scriptPath: string
- scriptStatus: HookInstallStatus
-}): HookInstallResult {
return {
agent,
configPath,
@@ -480,24 +461,7 @@ function upsertAdapterHooks({
}): Record {
switch (configKind) {
case 'claude-settings':
- return upsertClaudeHooks(config, project, scriptPath)
- case 'codex-hooks':
- return upsertCodexHooks(config, project, scriptPath)
- case 'copilot-hooks':
- return upsertCopilotHooks(config, scriptPath)
- }
-}
-
-function upsertClaudeHooks(
- config: Record,
- project: boolean,
- scriptPath: string,
-): Record {
- const hooks = objectValue(config.hooks)
- hooks.SessionStart = upsertHookGroup(arrayValue(hooks.SessionStart), {
- matcher: 'startup|resume|clear|compact',
- hooks: [
- {
+ return upsertGateHooks(config, 'Bash|Write|Edit|MultiEdit|NotebookEdit', {
type: 'command',
command: 'node',
args: [
@@ -506,60 +470,33 @@ function upsertClaudeHooks(
: scriptPath,
],
timeout: 10,
- statusMessage: CATALOG_STATUS_MESSAGE,
- },
- ],
- })
- hooks.PreToolUse = upsertHookGroup(arrayValue(hooks.PreToolUse), {
- matcher: 'Bash|Write|Edit|MultiEdit|NotebookEdit',
- hooks: [
- {
+ })
+ case 'codex-hooks':
+ return upsertGateHooks(config, 'Bash|apply_patch|Edit|Write', {
type: 'command',
- command: 'node',
- args: [
- project
- ? '${CLAUDE_PROJECT_DIR}/.intent/hooks/intent-claude-gate.mjs'
- : scriptPath,
- ],
+ command: project
+ ? 'node "$(git rev-parse --show-toplevel)/.intent/hooks/intent-codex-gate.mjs"'
+ : `node ${quoteShell(scriptPath)}`,
timeout: 10,
- statusMessage: GATE_STATUS_MESSAGE,
- },
- ],
- })
- return { ...config, hooks }
+ })
+ case 'copilot-hooks':
+ return upsertCopilotHooks(config, scriptPath)
+ }
}
-function upsertCodexHooks(
+function upsertGateHooks(
config: Record,
- project: boolean,
- scriptPath: string,
+ matcher: string,
+ entry: Record,
): Record {
const hooks = objectValue(config.hooks)
hooks.SessionStart = upsertHookGroup(arrayValue(hooks.SessionStart), {
matcher: 'startup|resume|clear|compact',
- hooks: [
- {
- type: 'command',
- command: project
- ? 'node "$(git rev-parse --show-toplevel)/.intent/hooks/intent-codex-gate.mjs"'
- : `node ${quoteShell(scriptPath)}`,
- timeout: 10,
- statusMessage: CATALOG_STATUS_MESSAGE,
- },
- ],
+ hooks: [{ ...entry, statusMessage: CATALOG_STATUS_MESSAGE }],
})
hooks.PreToolUse = upsertHookGroup(arrayValue(hooks.PreToolUse), {
- matcher: 'Bash|apply_patch|Edit|Write',
- hooks: [
- {
- type: 'command',
- command: project
- ? 'node "$(git rev-parse --show-toplevel)/.intent/hooks/intent-codex-gate.mjs"'
- : `node ${quoteShell(scriptPath)}`,
- timeout: 10,
- statusMessage: GATE_STATUS_MESSAGE,
- },
- ],
+ matcher,
+ hooks: [{ ...entry, statusMessage: GATE_STATUS_MESSAGE }],
})
return { ...config, hooks }
}
@@ -677,23 +614,17 @@ function parseJsonObject(
content: string,
): Record {
try {
- const parsed = JSON.parse(content) as unknown
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
- return parsed as Record
- }
+ const parsed: unknown = JSON.parse(content)
+ if (isRecord(parsed)) return parsed
} catch (err) {
- fail(
- `Failed to parse ${formatPath(filePath)}: ${err instanceof Error ? err.message : String(err)}`,
- )
+ fail(`Failed to parse ${formatPath(filePath)}: ${errorMessage(err)}`)
}
fail(`Failed to parse ${formatPath(filePath)}: expected a JSON object.`)
}
function objectValue(value: unknown): Record {
- return value && typeof value === 'object' && !Array.isArray(value)
- ? { ...(value as Record) }
- : {}
+ return isRecord(value) ? { ...value } : {}
}
function arrayValue(value: unknown): Array {
diff --git a/packages/intent/src/hooks/policy.ts b/packages/intent/src/hooks/policy.ts
index c99fa013..082f4c43 100644
--- a/packages/intent/src/hooks/policy.ts
+++ b/packages/intent/src/hooks/policy.ts
@@ -1,10 +1,4 @@
-import type {
- HookAgent,
- HookDecision,
- IntentInvocation,
- IntentObservation,
- ToolEvent,
-} from './types.js'
+import type { HookAgent, IntentInvocation } from './types.js'
export const EDIT_TOOLS_BY_AGENT: Record> = {
claude: new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']),
@@ -48,71 +42,3 @@ export function parseIntentInvocation(
return action === 'load' ? { action, skillUse } : { action }
}
-
-export function observationFromEvent(
- event: ToolEvent | undefined,
-): IntentObservation | undefined {
- if (!event || typeof event !== 'object') {
- return undefined
- }
-
- const toolName = event.tool_name ?? event.toolName
- const toolInput = event.tool_input ?? event.toolArgs
-
- if (toolName !== 'Bash') {
- return undefined
- }
-
- const command =
- typeof toolInput === 'string'
- ? safeCommandFromString(toolInput)
- : commandFromObject(toolInput)
-
- const parsed = parseIntentInvocation(command)
-
- if (!parsed || typeof command !== 'string') {
- return undefined
- }
-
- return { action: parsed.action, skillUse: parsed.skillUse, raw: command }
-}
-
-export function gateDecision({
- agent,
- hasLoaded,
- toolName,
-}: {
- agent: HookAgent
- hasLoaded: boolean
- toolName: string
-}): HookDecision {
- if (EDIT_TOOLS_BY_AGENT[agent].has(toolName) && !hasLoaded) {
- return { decision: 'deny', reason: GATE_DENY_REASON }
- }
-
- return { decision: 'allow' }
-}
-
-export function hasIntentCheckFromObservations(
- observations: Array | undefined>,
-): boolean {
- return observations.some(
- (entry) => entry?.action === 'list' || entry?.action === 'load',
- )
-}
-
-function commandFromObject(value: unknown): unknown {
- return value && typeof value === 'object'
- ? (value as { command?: unknown }).command
- : undefined
-}
-
-function safeCommandFromString(value: string): string {
- try {
- const parsed = JSON.parse(value) as unknown
- const command = commandFromObject(parsed)
- return typeof command === 'string' ? command : value
- } catch {
- return value
- }
-}
diff --git a/packages/intent/src/hooks/types.ts b/packages/intent/src/hooks/types.ts
index cf2141d5..b6b284a7 100644
--- a/packages/intent/src/hooks/types.ts
+++ b/packages/intent/src/hooks/types.ts
@@ -6,17 +6,3 @@ export type IntentInvocation = {
action: 'list' | 'load'
skillUse?: string
}
-
-export type IntentObservation = IntentInvocation & {
- raw: string
-}
-
-export type HookDecision =
- { decision: 'allow' } | { decision: 'deny'; reason: string }
-
-export type ToolEvent = {
- tool_name?: unknown
- toolName?: unknown
- tool_input?: unknown
- toolArgs?: unknown
-}
diff --git a/packages/intent/src/index.ts b/packages/intent/src/index.ts
index dc71567d..cac09e65 100644
--- a/packages/intent/src/index.ts
+++ b/packages/intent/src/index.ts
@@ -1,3 +1,6 @@
+export { findSkillFiles } from './shared/skill-files.js'
+export { getDeps, resolveDepDir } from './shared/node-modules.js'
+export { parseFrontmatter } from './shared/frontmatter.js'
export { scanForIntents } from './discovery/scanner.js'
export { checkStaleness } from './staleness/index.js'
export { readIntentArtifacts } from './staleness/artifact-coverage.js'
@@ -7,12 +10,6 @@ export {
createFailedStaleReviewItem,
type StaleReviewItem,
} from './staleness/workflow-review.js'
-export {
- findSkillFiles,
- getDeps,
- parseFrontmatter,
- resolveDepDir,
-} from './shared/utils.js'
export {
formatSkillUse,
isSkillUseParseError,
diff --git a/packages/intent/src/maintainer/add.ts b/packages/intent/src/maintainer/add.ts
index 81eecf71..71525533 100644
--- a/packages/intent/src/maintainer/add.ts
+++ b/packages/intent/src/maintainer/add.ts
@@ -3,10 +3,10 @@ import { basename, dirname, join, relative } from 'node:path'
import { stringify } from 'yaml'
import { resolveProjectContext } from '../core/project-context.js'
import { createIntentFsCache } from '../discovery/fs-cache.js'
-import { parseFrontmatter } from '../shared/utils.js'
+import { isRecord } from '../shared/guards.js'
+import { parseFrontmatter } from '../shared/frontmatter.js'
import {
authoringMarker,
- isObject,
projectPath,
readRecord,
recordPath,
@@ -123,7 +123,7 @@ export function planAddSkills(
slug: name,
domain: options.domain,
description: entry.purpose ?? entry.description,
- ...(packageDir ? { packages: [manifestName] } : {}),
+ packages: packageDir ? [manifestName] : undefined,
tasks,
covers: [],
})
@@ -177,7 +177,7 @@ function prepareAddition(
name,
slug: name,
domain: options.domain,
- ...(packageDir ? { package: packageDir } : {}),
+ package: packageDir,
path: options.path ?? `skills/${name}/SKILL.md`,
}
const path = skillPath(project, entry, checked)
@@ -215,7 +215,7 @@ function prepareAddition(
'To register an existing skill, supply its --path and --domain; edit its frontmatter directly before running sync.',
)
const parsed = existingFrontmatter ?? parseFrontmatter(path)
- if (!isObject(parsed) || parsed.name !== name)
+ if (!isRecord(parsed) || parsed.name !== name)
throw new Error(
'Existing skill has invalid frontmatter or a different name.',
)
@@ -253,7 +253,7 @@ function prepareAddition(
entry.sources = stringList(frontmatter.sources ?? [], 'sources')
entry.requires = stringList(frontmatter.requires ?? [], 'requires')
if (
- isObject(frontmatter.metadata) &&
+ isRecord(frontmatter.metadata) &&
typeof frontmatter.metadata.purpose === 'string'
)
entry.purpose = frontmatter.metadata.purpose
diff --git a/packages/intent/src/maintainer/distribution.ts b/packages/intent/src/maintainer/distribution.ts
index 19f5da24..905c8f87 100644
--- a/packages/intent/src/maintainer/distribution.ts
+++ b/packages/intent/src/maintainer/distribution.ts
@@ -1,11 +1,11 @@
import { existsSync, readFileSync } from 'node:fs'
import { dirname, relative } from 'node:path'
import { applyEdits, modify } from 'jsonc-parser'
-import { parseFrontmatter } from '../shared/utils.js'
+import { isRecord } from '../shared/guards.js'
+import { parseFrontmatter } from '../shared/frontmatter.js'
import { stringList } from './add.js'
import {
authoringMarker,
- isObject,
projectPath,
readRecord,
skillEntries,
@@ -32,12 +32,8 @@ const repositoryPattern =
/^[a-zA-Z0-9][a-zA-Z0-9-]*\/[a-zA-Z0-9][a-zA-Z0-9_.-]*$/
const namePattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
-export function readDistribution(
- tree: ReturnType,
-): Distribution | undefined {
- const value: unknown = tree.document.toJS().distribution
- if (value === undefined) return undefined
- if (!isObject(value) || !['repo', 'none'].includes(String(value.mode)))
+function isDistribution(value: unknown): value is Distribution {
+ if (!isRecord(value) || !['repo', 'none'].includes(String(value.mode)))
throw new Error('skill_tree.yaml distribution.mode must be repo or none.')
if (value.mode === 'repo' || value.name !== undefined) {
if (
@@ -52,18 +48,26 @@ export function readDistribution(
if (!stringList(value.skills, 'distribution.skills').length)
throw new Error('Choose at least one distribution skill.')
}
- return value as unknown as Distribution
+ return true
+}
+
+export function readDistribution(
+ tree: ReturnType,
+): Distribution | undefined {
+ const value: unknown = tree.document.toJS().distribution
+ if (value === undefined || !isDistribution(value)) return undefined
+ return value
}
function readJson(path: string): Record {
const value: unknown = JSON.parse(readFileSync(path, 'utf8'))
- if (!isObject(value)) throw new Error(`Expected a JSON object: ${path}`)
+ if (!isRecord(value)) throw new Error(`Expected a JSON object: ${path}`)
return value
}
function inferDistributionRepository(project: MaintainerProject): string {
const manifest = readJson(projectPath(project.root, 'package.json'))
- const declared = isObject(manifest.repository)
+ const declared = isRecord(manifest.repository)
? manifest.repository.url
: manifest.repository
return typeof declared === 'string'
@@ -218,10 +222,9 @@ export function planDistribution(
// explicit opt-in through maintainer setup --distribution repo.
const config = readDistribution(tree) ?? { mode: 'none' as const }
const changes: Array = []
- const problems: Array = []
const commands: Array = []
if (config.mode === 'none' && !config.name)
- return { changes, problems, commands, mode: config.mode }
+ return { changes, commands, mode: config.mode }
const { name, repository } = config
const selected = config.mode === 'repo' ? config.skills! : []
const exported: Array<{ name: string; path: string }> = []
@@ -232,7 +235,7 @@ export function planDistribution(
const path = skillPath(project, entry)
const fm = parseFrontmatter(path)
if (
- !isObject(fm) ||
+ !isRecord(fm) ||
fm.name !== selectedName ||
!namePattern.test(selectedName)
)
@@ -288,7 +291,7 @@ export function planDistribution(
const change = jsonChange(project, marketplacePath, (current) => {
if (
current.metadata !== undefined &&
- (!isObject(current.metadata) ||
+ (!isRecord(current.metadata) ||
(current.metadata.pluginRoot !== undefined &&
!['', '.', './'].includes(String(current.metadata.pluginRoot))))
)
@@ -302,7 +305,7 @@ export function planDistribution(
throw new Error(`Invalid marketplace name in ${marketplacePath}.`)
if (
current.owner !== undefined &&
- (!isObject(current.owner) ||
+ (!isRecord(current.owner) ||
typeof current.owner.name !== 'string' ||
!current.owner.name.trim())
)
@@ -310,7 +313,7 @@ export function planDistribution(
if (
current.plugins !== undefined &&
(!Array.isArray(current.plugins) ||
- current.plugins.some((plugin) => !isObject(plugin)))
+ current.plugins.some((plugin) => !isRecord(plugin)))
)
throw new Error(`Invalid plugins array in ${marketplacePath}.`)
const plugins = (current.plugins ?? []) as Array<
@@ -396,5 +399,5 @@ export function planDistribution(
`/plugin install ${name}@${String(marketplaceName)}`,
)
}
- return { changes, problems, commands, mode: config.mode }
+ return { changes, commands, mode: config.mode }
}
diff --git a/packages/intent/src/maintainer/existing.ts b/packages/intent/src/maintainer/existing.ts
index 4f2087c2..c8c14bb3 100644
--- a/packages/intent/src/maintainer/existing.ts
+++ b/packages/intent/src/maintainer/existing.ts
@@ -4,11 +4,12 @@ import { basename, dirname, relative } from 'node:path'
import { resolveProjectContext } from '../core/project-context.js'
import { createIntentFsCache } from '../discovery/fs-cache.js'
import { reviewIgnorePatterns } from '../review/review.js'
-import { resolveWorkspacePackages } from '../setup/workspace-patterns.js'
-import { isDefaultSkillPath, parseFrontmatter } from '../shared/utils.js'
+import { resolveWorkspacePackages } from '../core/workspace-patterns.js'
+import { errorMessage, isRecord } from '../shared/guards.js'
+import { isDefaultSkillPath } from '../shared/paths.js'
+import { parseFrontmatter } from '../shared/frontmatter.js'
import { stringList } from './add.js'
import {
- isObject,
projectPath,
readRecord,
recordPath,
@@ -150,9 +151,7 @@ export function findExistingSkills(
skill.frontmatter = frontmatter
skill.domain = inferDomain(frontmatter, mapped, id)
} catch (error) {
- skill.problems.push(
- error instanceof Error ? error.message : String(error),
- )
+ skill.problems.push(errorMessage(error))
}
return [skill]
})
@@ -180,14 +179,14 @@ function inferDomain(
): string {
const metadata = frontmatter.metadata
if (
- isObject(metadata) &&
+ isRecord(metadata) &&
typeof metadata.domain === 'string' &&
metadata.domain.trim()
)
return metadata.domain.trim()
const name = basename(dirname(id))
- const mapping = mapped.find((value) => isObject(value) && value.slug === name)
- if (isObject(mapping) && typeof mapping.domain === 'string')
+ const mapping = mapped.find((value) => isRecord(value) && value.slug === name)
+ if (isRecord(mapping) && typeof mapping.domain === 'string')
return mapping.domain
const parent = basename(dirname(dirname(id)))
return parent === 'skills' ? defaultDomain : parent
diff --git a/packages/intent/src/maintainer/project.ts b/packages/intent/src/maintainer/project.ts
index 1e79702b..08749d30 100644
--- a/packages/intent/src/maintainer/project.ts
+++ b/packages/intent/src/maintainer/project.ts
@@ -2,6 +2,7 @@ import { execFileSync } from 'node:child_process'
import { existsSync, lstatSync, readFileSync } from 'node:fs'
import { basename, dirname, join, relative, resolve } from 'node:path'
import { parseDocument, stringify } from 'yaml'
+import { isRecord } from '../shared/guards.js'
import { resolveProjectContext } from '../core/project-context.js'
import { createIntentFsCache } from '../discovery/fs-cache.js'
import type { IntentFsCache } from '../discovery/fs-cache.js'
@@ -117,7 +118,7 @@ export function readRecord(
const parsed: unknown = document.toJS()
if (
document.errors.length ||
- !isObject(parsed) ||
+ !isRecord(parsed) ||
!Array.isArray(parsed.skills)
)
throw new Error(
@@ -126,10 +127,6 @@ export function readRecord(
return { path, source, document }
}
-export function isObject(value: unknown): value is Record {
- return typeof value === 'object' && value !== null && !Array.isArray(value)
-}
-
export interface SkillEntry extends Record {
name: string
path: string
@@ -146,7 +143,7 @@ export function skillEntries(
const paths = new Set()
return entries.map((entry) => {
if (
- !isObject(entry) ||
+ !isRecord(entry) ||
typeof entry.name !== 'string' ||
!entry.name ||
typeof entry.path !== 'string' ||
@@ -204,7 +201,7 @@ export function planSetupRecords(
throw error ?? new Error(`Invalid package.json: ${context.packageRoot}`)
const library = {
name: manifest.name ?? basename(root),
- ...(manifest.version ? { version: manifest.version } : {}),
+ version: manifest.version || undefined,
}
const defaults: Record = {
'domain_map.yaml': stringify({
diff --git a/packages/intent/src/maintainer/sync.ts b/packages/intent/src/maintainer/sync.ts
index 95bfc7de..1f0215b2 100644
--- a/packages/intent/src/maintainer/sync.ts
+++ b/packages/intent/src/maintainer/sync.ts
@@ -3,12 +3,12 @@ import { dirname, relative } from 'node:path'
import { applyEdits, modify, parse } from 'jsonc-parser'
import { resolveProjectContext } from '../core/project-context.js'
import { createIntentFsCache } from '../discovery/fs-cache.js'
-import { parseFrontmatter } from '../shared/utils.js'
+import { isRecord } from '../shared/guards.js'
+import { parseFrontmatter } from '../shared/frontmatter.js'
import { stringList } from './add.js'
import { planDistribution } from './distribution.js'
import {
authoringMarker,
- isObject,
projectPath,
readRecord,
recordPath,
@@ -71,7 +71,7 @@ export function planMaintainerSync(project: MaintainerProject) {
}
const fm = parseFrontmatter(path)
if (
- !isObject(fm) ||
+ !isRecord(fm) ||
typeof fm.description !== 'string' ||
!fm.description.trim()
)
@@ -100,7 +100,7 @@ export function planMaintainerSync(project: MaintainerProject) {
}
for (const [field, value] of Object.entries({
description: fm.description,
- purpose: isObject(fm.metadata) ? fm.metadata.purpose : undefined,
+ purpose: isRecord(fm.metadata) ? fm.metadata.purpose : undefined,
sources,
requires,
})) {
@@ -111,7 +111,7 @@ export function planMaintainerSync(project: MaintainerProject) {
if (readFileSync(path, 'utf8').includes(authoringMarker))
problems.push(`${name}: skill still needs authoring.`)
const candidates: Array> = map.skills.filter(
- (skill: unknown) => isObject(skill) && skill.slug === name,
+ (skill: unknown) => isRecord(skill) && skill.slug === name,
)
const mapped =
candidates.find((skill) => skill.domain === entry.domain) ?? candidates[0]
@@ -170,7 +170,7 @@ export function planMaintainerSync(project: MaintainerProject) {
const manifest: unknown = parse(source, errors, {
allowTrailingComma: true,
})
- if (errors.length || !isObject(manifest))
+ if (errors.length || !isRecord(manifest))
throw new Error(`Invalid package.json: ${path}`)
let content = source
const indent = source.match(/\n([\t ]+)"/)?.[1] ?? ' '
@@ -224,6 +224,5 @@ export function planMaintainerSync(project: MaintainerProject) {
problems.push('skill_spec.md still needs authored coverage and decisions.')
const distribution = planDistribution(project, tree, entries)
changes.push(...distribution.changes)
- problems.push(...distribution.problems)
return { changes, problems, skills, distribution }
}
diff --git a/packages/intent/src/review/review.ts b/packages/intent/src/review/review.ts
index 7d4a91a9..dcce2c57 100644
--- a/packages/intent/src/review/review.ts
+++ b/packages/intent/src/review/review.ts
@@ -14,7 +14,10 @@ import {
import { basename, dirname, join, relative, resolve } from 'node:path'
import { parse as parseYaml } from 'yaml'
import { resolveProjectContext } from '../core/project-context.js'
-import { isDefaultSkillPath, parseFrontmatter } from '../shared/utils.js'
+import { createIntentFsCache } from '../discovery/fs-cache.js'
+import { errorMessage, isRecord } from '../shared/guards.js'
+import { isDefaultSkillPath } from '../shared/paths.js'
+import { parseFrontmatter } from '../shared/frontmatter.js'
type Snapshot = Record
type Outcome = 'updated' | 'no-change' | 'out-of-scope' | 'unresolved'
@@ -208,10 +211,6 @@ function safePath(root: string, path: string): string {
return current
}
-function isObject(value: unknown): value is Record {
- return !!value && typeof value === 'object' && !Array.isArray(value)
-}
-
function isHash(value: unknown): value is string {
return typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)
}
@@ -235,6 +234,31 @@ function resolvedOutcome(value: unknown): value is ReviewRecord['outcome'] {
)
}
+function isReviewRecord(value: unknown): value is ReviewRecord {
+ return (
+ isRecord(value) &&
+ isHash(value.fingerprint) &&
+ isRecord(value.snapshot) &&
+ Object.values(value.snapshot).every(
+ (hash) => hash === null || isHash(hash),
+ ) &&
+ typeof value.head === 'string' &&
+ /^[a-f0-9]{40,64}$/.test(value.head) &&
+ resolvedOutcome(value.outcome) &&
+ hasEvidence(value)
+ )
+}
+
+function isReviewState(value: unknown): value is ReviewState {
+ return (
+ isRecord(value) &&
+ value.schemaVersion === 1 &&
+ typeof value.baseline === 'string' &&
+ /^[a-f0-9]{40,64}$/.test(value.baseline) &&
+ isRecord(value.items)
+ )
+}
+
function readState(root: string): {
state: ReviewState | null
content: string | null
@@ -244,37 +268,17 @@ function readState(root: string): {
const content = readFileSync(path, 'utf8')
try {
const value: unknown = JSON.parse(content)
- if (
- !isObject(value) ||
- value.schemaVersion !== 1 ||
- typeof value.baseline !== 'string' ||
- !/^[a-f0-9]{40,64}$/.test(value.baseline) ||
- !isObject(value.items)
- )
- throw new Error()
- for (const [id, item] of Object.entries(value.items)) {
- if (
- !isObject(item) ||
- !isHash(item.fingerprint) ||
- !isObject(item.snapshot) ||
- !Object.values(item.snapshot).every(
- (hash) => hash === null || isHash(hash),
- ) ||
- typeof item.head !== 'string' ||
- !/^[a-f0-9]{40,64}$/.test(item.head) ||
- !resolvedOutcome(item.outcome) ||
- !hasEvidence(item)
- )
- throw new Error()
- for (const path of Object.keys(item.snapshot)) validatePath(path)
- const record = item as unknown as ReviewRecord
+ if (!isReviewState(value)) throw new Error()
+ for (const [id, record] of Object.entries(value.items)) {
+ if (!isReviewRecord(record)) throw new Error()
+ for (const path of Object.keys(record.snapshot)) validatePath(path)
if (
record.fingerprint !== reviewFingerprint(id, record.snapshot, []) &&
record.fingerprint !== legacyReviewFingerprint(id, record.snapshot, [])
)
throw new Error()
}
- return { state: value as unknown as ReviewState, content }
+ return { state: value, content }
} catch {
throw new Error(
`Invalid review state at ${statePath}. Restore or repair it before recording another review.`,
@@ -283,7 +287,7 @@ function readState(root: string): {
}
function repositoryName(value: unknown): string | undefined {
- if (isObject(value)) return repositoryName(value.url)
+ if (isRecord(value)) return repositoryName(value.url)
if (typeof value !== 'string') return undefined
let path = value
if (value.startsWith('git@github.com:')) {
@@ -316,7 +320,7 @@ function repositoryNames(root: string): Set {
const manifest: unknown = JSON.parse(
readFileSync(safePath(root, 'package.json'), 'utf8'),
)
- const name = isObject(manifest)
+ const name = isRecord(manifest)
? repositoryName(manifest.repository)
: undefined
if (name) names.add(name)
@@ -367,9 +371,9 @@ export function reviewIgnorePatterns(
path: string,
) {
if (tree.review === undefined) return []
- const ignore = isObject(tree.review) ? tree.review.ignore : undefined
+ const ignore = isRecord(tree.review) ? tree.review.ignore : undefined
if (
- !isObject(tree.review) ||
+ !isRecord(tree.review) ||
(ignore !== undefined &&
(!Array.isArray(ignore) ||
ignore.some((entry) => typeof entry !== 'string' || !entry.trim())))
@@ -427,6 +431,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
]),
)
const files = sorted(list())
+ const fileSet = new Set(files)
const untracked = splitPaths(
git(root, [
'ls-files',
@@ -438,6 +443,8 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
]),
)
const changed = sorted([...diff(), ...untracked])
+ const changedSet = new Set(changed)
+ const fsCache = createIntentFsCache()
const names = repositoryNames(root)
const covered = new Set()
const items: Array = []
@@ -471,7 +478,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
try {
return [file, fileHash(file)]
} catch (error) {
- problems.push(error instanceof Error ? error.message : String(error))
+ problems.push(errorMessage(error))
return [file, null]
}
}),
@@ -508,7 +515,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
]).filter((file) =>
previous
? (current[file] ?? null) !== (previous.snapshot[file] ?? null)
- : (changedSinceIntroduced?.has(file) ?? changed.includes(file)),
+ : (changedSinceIntroduced?.has(file) ?? changedSet.has(file)),
)
items.push({
id,
@@ -532,7 +539,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
const customRoots = existingArtifactDirs
.filter((dir) => basename(dir) === '_artifacts')
.map((dir) => dirname(dir))
- .filter((dir) => dir !== '.' && !files.includes(`${dir}/package.json`))
+ .filter((dir) => dir !== '.' && !fileSet.has(`${dir}/package.json`))
const declaredSkills = new Set()
const treeIgnorePatterns: Array = []
for (const dir of existingArtifactDirs) {
@@ -544,11 +551,11 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
// Missing or invalid trees remain unresolved in planning validation below.
continue
}
- if (!isObject(tree)) continue
+ if (!isRecord(tree)) continue
treeIgnorePatterns.push(...reviewIgnorePatterns(tree, treePath))
if (Array.isArray(tree.skills)) {
for (const entry of tree.skills) {
- if (!isObject(entry) || typeof entry.path !== 'string') continue
+ if (!isRecord(entry) || typeof entry.path !== 'string') continue
declaredSkills.add(
typeof entry.package === 'string'
? `${entry.package}/${entry.path}`
@@ -596,12 +603,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
if (skillHash === null) continue
frontmatter = parseFrontmatter(safePath(root, file))
} catch (error) {
- add(
- 'skill',
- file,
- [file],
- [error instanceof Error ? error.message : String(error)],
- )
+ add('skill', file, [file], [errorMessage(error)])
continue
}
const sources = frontmatter?.sources
@@ -616,6 +618,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
const { packageRoot } = resolveProjectContext({
cwd: root,
targetPath: safePath(root, file),
+ fsCache,
})
const packageDir = relative(root, packageRoot ?? root).replaceAll(
'\\',
@@ -635,7 +638,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
throw new Error(`Source matched no available files: ${source}`)
sourceFiles.push(...matches)
} catch (error) {
- problems.push(error instanceof Error ? error.message : String(error))
+ problems.push(errorMessage(error))
}
}
}
@@ -649,7 +652,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
'.github/copilot-instructions.md',
].some(
(path) =>
- files.includes(path) &&
+ fileSet.has(path) &&
fileHash(path) !== null &&
readFileSync(safePath(root, path), 'utf8').includes(
'',
@@ -659,7 +662,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
const dirs = existingArtifactDirs.length
? existingArtifactDirs
: [
- resolveProjectContext({ cwd: root }).isMonorepo
+ resolveProjectContext({ cwd: root, fsCache }).isMonorepo
? '_artifacts'
: 'skills/_artifacts',
]
@@ -670,7 +673,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
const problems: Array = []
for (const path of paths) {
try {
- if (!files.includes(path)) {
+ if (!fileSet.has(path)) {
problems.push(
existsSync(safePath(root, path))
? `Planning record must be visible to Git: ${path}`
@@ -687,15 +690,13 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
problems.push(`Planning record is empty: ${path}`)
} else if (path.endsWith('.yaml')) {
const parsed: unknown = parseYaml(content)
- if (!isObject(parsed) || !Array.isArray(parsed.skills))
+ if (!isRecord(parsed) || !Array.isArray(parsed.skills))
problems.push(
`Planning record requires an object with a skills array: ${path}`,
)
}
} catch (error) {
- problems.push(
- `${path}: ${error instanceof Error ? error.message : String(error)}`,
- )
+ problems.push(`${path}: ${errorMessage(error)}`)
}
}
// The shared record must be reviewed again when its source or guidance changes.
@@ -705,7 +706,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
[
...covered,
...skillFiles,
- ...paths.filter((path) => files.includes(path)),
+ ...paths.filter((path) => fileSet.has(path)),
],
problems,
)
@@ -719,8 +720,8 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport {
for (const id of Object.keys(state?.items ?? {})) {
if (!id.startsWith('skill:')) continue
const path = id.slice('skill:'.length)
- if (files.includes(path)) continue
- if (fileHash(path) === null && !changed.includes(path)) {
+ if (fileSet.has(path)) continue
+ if (fileHash(path) === null && !changedSet.has(path)) {
add('source', path, [path], [])
}
}
@@ -751,7 +752,7 @@ export function recordPendingReview(
export function recordReview(cwd: string, input: unknown): number {
if (
- !isObject(input) ||
+ !isRecord(input) ||
input.schemaVersion !== 1 ||
typeof input.base !== 'string' ||
!Array.isArray(input.items)
@@ -769,7 +770,7 @@ export function recordReview(cwd: string, input: unknown): number {
const seen = new Set()
let count = 0
for (const value of input.items) {
- if (!isObject(value) || typeof value.id !== 'string' || seen.has(value.id))
+ if (!isRecord(value) || typeof value.id !== 'string' || seen.has(value.id))
throw new Error('Invalid or duplicate review item.')
seen.add(value.id)
if (value.outcome === undefined || value.outcome === 'unresolved') continue
diff --git a/packages/intent/src/setup/project-setup.ts b/packages/intent/src/setup/project-setup.ts
index c646dc49..1a5b041d 100644
--- a/packages/intent/src/setup/project-setup.ts
+++ b/packages/intent/src/setup/project-setup.ts
@@ -1,18 +1,17 @@
import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
import { basename, join, relative } from 'node:path'
import { repositoryWritePath } from '../shared/write-path.js'
+import { errorMessage, isRecord } from '../shared/guards.js'
import { writeChanges } from '../maintainer/files.js'
import { resolveProjectContext } from '../core/project-context.js'
+import { createIntentFsCache } from '../discovery/fs-cache.js'
import {
findPackagesWithSkills,
findWorkspaceRoot,
readWorkspacePatterns,
-} from './workspace-patterns.js'
+} from '../core/workspace-patterns.js'
import type { FileChange } from '../maintainer/files.js'
-
-// ---------------------------------------------------------------------------
-// Types
-// ---------------------------------------------------------------------------
+import type { IntentFsCache } from '../discovery/fs-cache.js'
export interface EditPackageJsonResult {
added: Array
@@ -102,10 +101,6 @@ function deriveWorkspacePackageName(
return repoName
}
-// ---------------------------------------------------------------------------
-// Variable detection from package.json
-// ---------------------------------------------------------------------------
-
function readPackageJson(root: string): Record {
const pkgPath = join(root, 'package.json')
try {
@@ -117,9 +112,7 @@ function readPackageJson(root: string): Record {
'code' in err &&
(err as NodeJS.ErrnoException).code === 'ENOENT'
if (!isNotFound) {
- console.error(
- `Warning: could not read ${pkgPath}: ${err instanceof Error ? err.message : err}`,
- )
+ console.error(`Warning: could not read ${pkgPath}: ${errorMessage(err)}`)
}
return {}
}
@@ -129,24 +122,15 @@ function detectRepo(
pkgJson: Record,
fallback: string,
): string {
- const intent = pkgJson.intent as Record | undefined
+ const intent = isRecord(pkgJson.intent) ? pkgJson.intent : undefined
if (typeof intent?.repo === 'string') {
return intent.repo
}
- if (typeof pkgJson.repository === 'string') {
- return pkgJson.repository
- .replace(/^git\+/, '')
- .replace(/\.git$/, '')
- .replace(/^https?:\/\/github\.com\//, '')
- }
-
- if (
- pkgJson.repository &&
- typeof pkgJson.repository === 'object' &&
- typeof (pkgJson.repository as Record).url === 'string'
- ) {
- return ((pkgJson.repository as Record).url as string)
+ const { repository } = pkgJson
+ const url = isRecord(repository) ? repository.url : repository
+ if (typeof url === 'string') {
+ return url
.replace(/^git\+/, '')
.replace(/\.git$/, '')
.replace(/^https?:\/\/github\.com\//, '')
@@ -180,9 +164,11 @@ function buildWatchPaths(root: string, packageDirs: Array): string {
paths.add(`${relDir}/src/**`)
}
- const pkgJson = readPackageJson(packageDir)
- const intent = pkgJson.intent as Record | undefined
- const docs = typeof intent?.docs === 'string' ? intent.docs : 'docs/'
+ const intent = readPackageJson(packageDir).intent
+ const docs =
+ isRecord(intent) && typeof intent.docs === 'string'
+ ? intent.docs
+ : 'docs/'
const docsPattern = localDocsPattern(docs)
if (docsPattern) {
paths.add(
@@ -205,11 +191,8 @@ function buildWatchPaths(root: string, packageDirs: Array): string {
function detectVars(root: string, packageDirs?: Array): TemplateVars {
const pkgJson = readPackageJson(root)
const rawName = typeof pkgJson.name === 'string' ? pkgJson.name : 'unknown'
- const docs =
- typeof (pkgJson.intent as Record | undefined)?.docs ===
- 'string'
- ? ((pkgJson.intent as Record).docs as string)
- : 'docs/'
+ const intent = isRecord(pkgJson.intent) ? pkgJson.intent : undefined
+ const docs = typeof intent?.docs === 'string' ? intent.docs : 'docs/'
const isMonorepo = packageDirs !== undefined
const monorepoFallbackPkg = packageDirs?.[0]
? readPackageJson(packageDirs[0])
@@ -224,7 +207,6 @@ function detectVars(root: string, packageDirs?: Array): TemplateVars {
packageName = deriveWorkspacePackageName(root, repo, packageDirs)
}
- // Derive srcPath: monorepos use a wildcard; single packages use the short name or fall back to root src/
const shortName = packageName.replace(/^@[^/]+\//, '')
let srcPath = isMonorepo
? 'packages/*/src/**'
@@ -254,11 +236,13 @@ function detectVars(root: string, packageDirs?: Array): TemplateVars {
}
}
-// ---------------------------------------------------------------------------
-// Template variable substitution
-// ---------------------------------------------------------------------------
-
-function applyVars(content: string, vars: TemplateVars): string {
+function applyTemplate(content: string, vars: TemplateVars): string {
+ if (vars.WATCH_PATHS) {
+ content = content.replace(
+ /\s+- '?\{\{DOCS_PATH\}\}'?\n\s+- '?\{\{SRC_PATH\}\}'?/,
+ vars.WATCH_PATHS,
+ )
+ }
return content
.replace(/\{\{PACKAGE_NAME\}\}/g, vars.PACKAGE_NAME)
.replace(/\{\{PACKAGE_LABEL\}\}/g, vars.PACKAGE_LABEL)
@@ -271,70 +255,16 @@ function applyVars(content: string, vars: TemplateVars): string {
.replace(/\{\{INTENT_ARTIFACTS\}\}/g, vars.INTENT_ARTIFACTS)
}
-// ---------------------------------------------------------------------------
-// Copy helpers
-// ---------------------------------------------------------------------------
-
-function templatesUse(
- srcDir: string,
- destDir: string,
- placeholder: string,
-): boolean {
- if (!existsSync(srcDir)) return false
- return readdirSync(srcDir).some(
- (entry) =>
- !existsSync(join(destDir, entry)) &&
- readFileSync(join(srcDir, entry), 'utf8').includes(placeholder),
- )
+export function runEditPackageJson(root: string): EditPackageJsonResult {
+ return editPackageJson(root, createIntentFsCache())
}
-function planTemplates(
- srcDir: string,
- destDir: string,
- vars: TemplateVars,
+function editPackageJson(
root: string,
-): {
- changes: Array
- copied: Array
- skipped: Array
-} {
- const copied: Array = []
- const skipped: Array = []
- const changes: Array = []
-
- if (!existsSync(srcDir)) return { changes, copied, skipped }
-
- for (const entry of readdirSync(srcDir)) {
- const srcPath = join(srcDir, entry)
- const destPath = repositoryWritePath(root, join(destDir, entry))
-
- if (existsSync(destPath)) {
- skipped.push(destPath)
- continue
- }
-
- let content = readFileSync(srcPath, 'utf8')
- if (vars.WATCH_PATHS) {
- content = content.replace(
- /\s+- '?\{\{DOCS_PATH\}\}'?\n\s+- '?\{\{SRC_PATH\}\}'?/,
- vars.WATCH_PATHS,
- )
- }
- const substituted = applyVars(content, vars)
- changes.push({ path: destPath, source: null, content: substituted })
- copied.push(destPath)
- }
-
- return { changes, copied, skipped }
-}
-
-// ---------------------------------------------------------------------------
-// Command: edit-package-json
-// ---------------------------------------------------------------------------
-
-export function runEditPackageJson(root: string): EditPackageJsonResult {
+ fsCache: IntentFsCache,
+): EditPackageJsonResult {
const result: EditPackageJsonResult = { added: [], alreadyPresent: [] }
- const context = resolveProjectContext({ cwd: root })
+ const context = resolveProjectContext({ cwd: root, fsCache })
const packageRoot = context.packageRoot ?? root
const pkgPath = join(packageRoot, 'package.json')
@@ -355,15 +285,13 @@ export function runEditPackageJson(root: string): EditPackageJsonResult {
return result
}
- // Detect indent size from existing file
const indentMatch = raw.match(/^(\s+)"/m)
const indentSize = indentMatch?.[1] ? indentMatch[1].length : 2
- // --- keywords array ---
- if (!Array.isArray(pkg.keywords)) {
- pkg.keywords = []
- }
- const keywords = pkg.keywords as Array
+ const keywords: Array = Array.isArray(pkg.keywords)
+ ? pkg.keywords
+ : []
+ pkg.keywords = keywords
if (keywords.includes('tanstack-intent')) {
result.alreadyPresent.push('keywords: "tanstack-intent"')
} else {
@@ -371,11 +299,8 @@ export function runEditPackageJson(root: string): EditPackageJsonResult {
result.added.push('keywords: "tanstack-intent"')
}
- // --- files array ---
- if (!Array.isArray(pkg.files)) {
- pkg.files = []
- }
- const files = pkg.files as Array
+ const files: Array = Array.isArray(pkg.files) ? pkg.files : []
+ pkg.files = files
// In monorepos, _artifacts lives at repo root, not under packages —
// the negation pattern is a no-op and shouldn't be added.
@@ -394,34 +319,21 @@ export function runEditPackageJson(root: string): EditPackageJsonResult {
writeFileSync(pkgPath, JSON.stringify(pkg, null, indentSize) + '\n')
- // Print results
for (const a of result.added) console.log(`✓ Added ${a}`)
for (const a of result.alreadyPresent) console.log(` Already present: ${a}`)
return result
}
-// ---------------------------------------------------------------------------
-// Monorepo-aware command runner
-// ---------------------------------------------------------------------------
-
-/**
- * When run from a monorepo root, finds all workspace packages with SKILL.md
- * files and runs the given command on each. Falls back to single-package
- * behavior only when no workspace config is detected. If workspace config
- * exists but no packages have skills, warns and returns empty.
- */
-function runForEachPackage(
+export function runEditPackageJsonAll(
root: string,
- runOne: (dir: string) => T,
-): Array> | T {
- const isMonorepo = readWorkspacePatterns(root) !== null
- const pkgsWithSkills = isMonorepo ? findPackagesWithSkills(root) : []
-
- if (!isMonorepo) {
- return runOne(root)
+): Array> | EditPackageJsonResult {
+ const fsCache = createIntentFsCache()
+ if (readWorkspacePatterns(root, fsCache) === null) {
+ return editPackageJson(root, fsCache)
}
+ const pkgsWithSkills = findPackagesWithSkills(root, fsCache)
if (pkgsWithSkills.length === 0) {
console.log('No workspace packages with skills found.')
return []
@@ -430,27 +342,18 @@ function runForEachPackage(
return pkgsWithSkills.map((pkgDir) => {
const rel = relative(root, pkgDir) || '.'
console.log(`\n── ${rel} ──`)
- return { package: rel, result: runOne(pkgDir) }
+ return { package: rel, result: editPackageJson(pkgDir, fsCache) }
})
}
-export function runEditPackageJsonAll(
- root: string,
-): Array> | EditPackageJsonResult {
- return runForEachPackage(root, runEditPackageJson)
-}
-
-// ---------------------------------------------------------------------------
-// Command: setup-github-actions
-// ---------------------------------------------------------------------------
-
export function planSetupGithubActions(
root: string,
metaDir: string,
artifacts = '',
) {
- const workspaceRoot = findWorkspaceRoot(root) ?? root
- const packageDirs = findPackagesWithSkills(workspaceRoot)
+ const fsCache = createIntentFsCache()
+ const workspaceRoot = findWorkspaceRoot(root, fsCache) ?? root
+ const packageDirs = findPackagesWithSkills(workspaceRoot, fsCache)
const vars = detectVars(
workspaceRoot,
packageDirs.length > 0 ? packageDirs : undefined,
@@ -466,20 +369,31 @@ export function planSetupGithubActions(
vars.INTENT_ARTIFACTS = artifacts
const srcDir = join(metaDir, 'templates', 'workflows')
const destDir = join(workspaceRoot, '.github', 'workflows')
- if (existsSync(srcDir))
- for (const entry of readdirSync(srcDir))
- repositoryWritePath(workspaceRoot, join(destDir, entry))
+ const skipped: Array = []
+ const templates: Array<{ path: string; content: string }> = []
+ for (const entry of existsSync(srcDir) ? readdirSync(srcDir) : []) {
+ const path = repositoryWritePath(workspaceRoot, join(destDir, entry))
+ if (existsSync(path)) skipped.push(path)
+ else
+ templates.push({
+ path,
+ content: readFileSync(join(srcDir, entry), 'utf8'),
+ })
+ }
// Existing workflows are preserved even in a development build with no pin.
- if (templatesUse(srcDir, destDir, '{{INTENT_WORKFLOW_REF}}'))
+ if (
+ templates.some(({ content }) => content.includes('{{INTENT_WORKFLOW_REF}}'))
+ )
vars.INTENT_WORKFLOW_REF =
(process.env.INTENT_WORKFLOW_REF
? validateWorkflowRef(process.env.INTENT_WORKFLOW_REF)
: undefined) || resolveIntentWorkflowRef(join(metaDir, '..'))
- const {
- changes,
- copied: workflows,
- skipped,
- } = planTemplates(srcDir, destDir, vars, workspaceRoot)
+ const changes: Array = templates.map(({ path, content }) => ({
+ path,
+ source: null,
+ content: applyTemplate(content, vars),
+ }))
+ const workflows = changes.map((change) => change.path)
const messages = [
...workflows.map((file) => `✓ Copied workflow: ${file}`),
...skipped.map((file) => ` Already exists: ${file}`),
diff --git a/packages/intent/src/shared/cli-output.ts b/packages/intent/src/shared/cli-output.ts
index f281d886..acdaac15 100644
--- a/packages/intent/src/shared/cli-output.ts
+++ b/packages/intent/src/shared/cli-output.ts
@@ -23,7 +23,7 @@ function envSuppressesNotices(): boolean {
return value ? TRUE_LIKE_VALUES.has(value) : false
}
-function shouldSuppressNotices(options: NoticeOutputOptions = {}): boolean {
+function shouldSuppressNotices(options: NoticeOutputOptions): boolean {
return options.noNotices === true || envSuppressesNotices()
}
diff --git a/packages/intent/src/shared/command-runner.ts b/packages/intent/src/shared/command-runner.ts
index 51eb4496..9efca107 100644
--- a/packages/intent/src/shared/command-runner.ts
+++ b/packages/intent/src/shared/command-runner.ts
@@ -1,8 +1,5 @@
-import { detectPackageManager } from '../discovery/package-manager.js'
import type { PackageManager } from './types.js'
-export { detectPackageManager as detectIntentCommandPackageManager }
-
const runnerByPackageManager: Record = {
bun: 'bunx --no-install --package @tanstack/intent intent',
npm: 'npm exec --no -- intent',
diff --git a/packages/intent/src/shared/display.ts b/packages/intent/src/shared/display.ts
index 1cf7be52..6d19a9d0 100644
--- a/packages/intent/src/shared/display.ts
+++ b/packages/intent/src/shared/display.ts
@@ -1,7 +1,3 @@
-// ---------------------------------------------------------------------------
-// Shared display helpers for CLI output
-// ---------------------------------------------------------------------------
-
import {
formatRuntimeSkillLookupHint,
isStableLoadPath,
@@ -15,10 +11,6 @@ export interface SkillDisplay {
path?: string
}
-function padColumn(text: string, width: number): string {
- return text.length >= width ? text + ' ' : text.padEnd(width)
-}
-
export function printTable(
headers: Array,
rows: Array>,
@@ -27,13 +19,13 @@ export function printTable(
(h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)) + 2,
)
- const headerLine = headers.map((h, i) => padColumn(h, widths[i]!)).join('')
+ const headerLine = headers.map((h, i) => h.padEnd(widths[i]!)).join('')
const separator = widths.map((w) => '─'.repeat(w)).join('')
console.log(headerLine)
console.log(separator)
for (const row of rows) {
- console.log(row.map((cell, i) => padColumn(cell, widths[i]!)).join(''))
+ console.log(row.map((cell, i) => cell.padEnd(widths[i]!)).join(''))
}
}
diff --git a/packages/intent/src/shared/frontmatter.ts b/packages/intent/src/shared/frontmatter.ts
new file mode 100644
index 00000000..08db583d
--- /dev/null
+++ b/packages/intent/src/shared/frontmatter.ts
@@ -0,0 +1,91 @@
+import { parse as parseYaml } from 'yaml'
+import { nodeReadFs } from './fs-identity.js'
+import type { ReadFs } from './fs-identity.js'
+
+/**
+ * Read a scalar string field from frontmatter, preferring `metadata.` over
+ * a top-level `` (#159 back-compat for the frontmatter migration).
+ */
+export function readScalarField(
+ fm: Record | null | undefined,
+ key: string,
+): string | undefined {
+ const metadata = fm?.metadata
+ if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {
+ const nested = (metadata as Record)[key]
+ if (typeof nested === 'string') return nested
+ }
+ const top = fm?.[key]
+ return typeof top === 'string' ? top : undefined
+}
+
+/**
+ * Parse YAML frontmatter from a path or caller-owned descriptor at offset zero.
+ * Returns null if no frontmatter or on error; caller-owned descriptors stay open.
+ */
+export function parseFrontmatter(
+ filePath: string | number,
+ fs: ReadFs = nodeReadFs,
+): Record | null {
+ const content = readFrontmatterRegion(filePath, fs)
+ if (content === null) return null
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/)
+ if (!match?.[1]) return null
+ try {
+ return parseYaml(match[1]) as Record
+ } catch {
+ return null
+ }
+}
+
+/** Max bytes read when probing a file's leading frontmatter region. */
+const FRONTMATTER_READ_LIMIT = 16 * 1024
+/** Reused across calls; safe because reads are synchronous and single-threaded. */
+const frontmatterBuffer = Buffer.allocUnsafe(FRONTMATTER_READ_LIMIT)
+
+/**
+ * Read just the leading region of a file, enough to cover its frontmatter,
+ * instead of its whole body. Falls back to a full read when the bounded read
+ * primitives are unavailable or the frontmatter exceeds the probe limit.
+ */
+function readFrontmatterRegion(
+ filePath: string | number,
+ fs: ReadFs,
+): string | null {
+ if (fs.openSync && fs.readSync && fs.closeSync) {
+ let fd: number
+ try {
+ fd = typeof filePath === 'number' ? filePath : fs.openSync(filePath, 'r')
+ } catch {
+ return null
+ }
+ try {
+ const bytesRead = fs.readSync(
+ fd,
+ frontmatterBuffer,
+ 0,
+ FRONTMATTER_READ_LIMIT,
+ 0,
+ )
+ const region = frontmatterBuffer.toString('utf8', 0, bytesRead)
+ // A full buffer means the file may extend past the probe window; only
+ // trust the bounded read when it captured the closing fence.
+ const truncated =
+ bytesRead === FRONTMATTER_READ_LIMIT &&
+ !/\r?\n---/.test(region.slice(3))
+ // The positional probe leaves the descriptor at offset zero. Keep the
+ // full-read fallback on that descriptor so replacement cannot redirect it.
+ return truncated ? fs.readFileSync(fd, 'utf8') : region
+ } catch {
+ return null
+ } finally {
+ if (typeof filePath !== 'number') fs.closeSync(fd)
+ }
+ }
+
+ try {
+ return fs.readFileSync(filePath, 'utf8')
+ } catch {
+ return null
+ }
+}
diff --git a/packages/intent/src/shared/fs-identity.ts b/packages/intent/src/shared/fs-identity.ts
new file mode 100644
index 00000000..7c9065ab
--- /dev/null
+++ b/packages/intent/src/shared/fs-identity.ts
@@ -0,0 +1,90 @@
+import {
+ closeSync,
+ existsSync,
+ fstatSync,
+ lstatSync,
+ openSync,
+ readFileSync,
+ readSync,
+ readdirSync,
+ realpathSync,
+} from 'node:fs'
+import { resolve } from 'node:path'
+
+/**
+ * The subset of `node:fs` the scanner reads through. Under Yarn PnP this is
+ * swapped for Yarn's libzip-patched `fs` so reads can reach files inside
+ * `.yarn/cache/*.zip` (see scanner `loadPnpApi`). The static `node:fs` named
+ * imports cannot be used directly for that, because their bindings are captured
+ * before Yarn's `setup()` patches the CommonJS `fs` module.
+ */
+export interface ReadFs {
+ existsSync: typeof existsSync
+ lstatSync: typeof lstatSync
+ readFileSync: typeof readFileSync
+ readdirSync: typeof readdirSync
+ realpathSync: typeof realpathSync
+ /**
+ * Optional low-level read primitives. When present (always on `node:fs` and
+ * Yarn's libzip-patched module) `parseFrontmatter` reads only the leading
+ * region of a file instead of its whole body.
+ */
+ openSync?: typeof openSync
+ readSync?: typeof readSync
+ closeSync?: typeof closeSync
+ fstatSync?: typeof fstatSync
+}
+
+export const nodeReadFs: ReadFs = {
+ existsSync,
+ lstatSync,
+ readFileSync,
+ readdirSync,
+ realpathSync,
+ openSync,
+ readSync,
+ closeSync,
+ fstatSync,
+}
+
+export interface FsIdentityResolver {
+ (path: string): string
+ /**
+ * Record that `realPath` is already an identity (not a symlink), so a later
+ * lookup returns it without an `lstat`. Callers use this for directories
+ * they have just resolved through `resolveDepDir`.
+ */
+ prime: (realPath: string) => void
+}
+
+export function createFsIdentityCache(
+ getFs: () => ReadFs = () => nodeReadFs,
+): FsIdentityResolver {
+ const cache = new Map()
+
+ const getIdentity = ((path: string): string => {
+ const resolved = resolve(path)
+ const cached = cache.get(resolved)
+ if (cached) return cached
+
+ const fs = getFs()
+ let identity: string
+ try {
+ identity = fs.lstatSync(resolved).isSymbolicLink()
+ ? fs.realpathSync(resolved)
+ : resolved
+ } catch {
+ identity = resolved
+ }
+
+ cache.set(resolved, identity)
+ return identity
+ }) as FsIdentityResolver
+
+ getIdentity.prime = (realPath: string): void => {
+ const resolved = resolve(realPath)
+ if (!cache.has(resolved)) cache.set(resolved, resolved)
+ }
+
+ return getIdentity
+}
diff --git a/packages/intent/src/shared/guards.ts b/packages/intent/src/shared/guards.ts
new file mode 100644
index 00000000..ec6b4a3b
--- /dev/null
+++ b/packages/intent/src/shared/guards.ts
@@ -0,0 +1,13 @@
+export function isRecord(value: unknown): value is Record {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+export function errorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error)
+}
+
+export function stringArray(value: unknown): Array {
+ return Array.isArray(value)
+ ? value.filter((entry): entry is string => typeof entry === 'string')
+ : []
+}
diff --git a/packages/intent/src/shared/node-modules.ts b/packages/intent/src/shared/node-modules.ts
new file mode 100644
index 00000000..b63731f5
--- /dev/null
+++ b/packages/intent/src/shared/node-modules.ts
@@ -0,0 +1,271 @@
+import { execFileSync } from 'node:child_process'
+import {
+ existsSync,
+ lstatSync,
+ readdirSync,
+ readlinkSync,
+ realpathSync,
+} from 'node:fs'
+import { basename, dirname, join, resolve } from 'node:path'
+import { normalizeReadlinkTarget } from './paths.js'
+import type { Dirent } from 'node:fs'
+
+/**
+ * Read dependencies and peerDependencies (and optionally devDependencies) from
+ * a parsed package.json object.
+ */
+export function getDeps(
+ pkgJson: Record,
+ includeDevDeps = false,
+): Array {
+ const deps = new Set()
+ const fields = includeDevDeps
+ ? ['dependencies', 'devDependencies', 'peerDependencies']
+ : ['dependencies', 'peerDependencies']
+ for (const field of fields) {
+ const d = pkgJson[field]
+ if (d && typeof d === 'object') {
+ for (const name of Object.keys(d)) {
+ deps.add(name)
+ }
+ }
+ }
+ return [...deps]
+}
+
+function readPackageEntries(dir: string): Array> {
+ try {
+ return readdirSync(dir, { withFileTypes: true, encoding: 'utf8' }).filter(
+ (entry) => entry.isDirectory() || entry.isSymbolicLink(),
+ )
+ } catch {
+ return []
+ }
+}
+
+function forEachPackageDir(
+ nodeModulesDir: string,
+ visit: (packageDir: string) => void,
+): void {
+ for (const entry of readPackageEntries(nodeModulesDir)) {
+ const dirPath = join(nodeModulesDir, entry.name)
+ if (entry.name.startsWith('@')) {
+ for (const scoped of readPackageEntries(dirPath)) {
+ visit(join(dirPath, scoped.name))
+ }
+ } else if (!entry.name.startsWith('.')) {
+ visit(dirPath)
+ }
+ }
+}
+
+export function listNodeModulesPackageDirs(
+ nodeModulesDir: string,
+): Array {
+ const packageDirs: Array = []
+ forEachPackageDir(nodeModulesDir, (dir) => packageDirs.push(dir))
+ return packageDirs
+}
+
+export function listNestedNodeModulesPackageDirs(
+ nodeModulesDir: string,
+ getFsIdentity: (path: string) => string,
+): Array {
+ const packageDirs: Array = []
+ const visitedNodeModulesDirs = new Set()
+ const visitedPackageDirs = new Set()
+
+ function addPackageDir(packageDir: string): void {
+ const key = getFsIdentity(packageDir)
+ if (visitedPackageDirs.has(key)) return
+ visitedPackageDirs.add(key)
+
+ if (existsSync(join(packageDir, 'package.json'))) {
+ packageDirs.push(packageDir)
+ }
+
+ scanNodeModulesDir(join(packageDir, 'node_modules'))
+ }
+
+ function scanNodeModulesDir(dir: string): void {
+ const key = getFsIdentity(dir)
+ if (visitedNodeModulesDirs.has(key)) return
+ visitedNodeModulesDirs.add(key)
+ forEachPackageDir(dir, addPackageDir)
+ }
+
+ scanNodeModulesDir(nodeModulesDir)
+ return packageDirs
+}
+
+const GLOBAL_NODE_MODULES_COMMAND_TIMEOUT_MS = 5_000
+
+export function detectGlobalNodeModules(packageManager: string): {
+ path: string | null
+ source?: string
+} {
+ const commands: Array<{
+ command: string
+ args: Array
+ transform?: (output: string) => string
+ }> = []
+
+ if (packageManager === 'pnpm') {
+ commands.push({ command: 'pnpm', args: ['root', '-g'] })
+ }
+ if (packageManager === 'yarn') {
+ commands.push({
+ command: 'yarn',
+ args: ['global', 'dir'],
+ transform: (output) => join(output, 'node_modules'),
+ })
+ }
+ commands.push({ command: 'npm', args: ['root', '-g'] })
+
+ for (const candidate of commands) {
+ try {
+ const output = execFileSync(candidate.command, candidate.args, {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ timeout: GLOBAL_NODE_MODULES_COMMAND_TIMEOUT_MS,
+ }).trim()
+ if (!output) continue
+
+ return {
+ path: candidate.transform ? candidate.transform(output) : output,
+ source: `${candidate.command} ${candidate.args.join(' ')}`,
+ }
+ } catch {
+ continue
+ }
+ }
+
+ return { path: null }
+}
+
+/**
+ * Resolve the directory of a dependency by name by walking up from
+ * `parentDir` and checking `node_modules//package.json` at each
+ * ancestor, the same lookup order Node uses. A symlinked match (pnpm's
+ * virtual store, workspace links) is collapsed to its real directory so
+ * callers see one identity per installed package.
+ *
+ * This deliberately avoids `createRequire().resolve`: Node's resolver
+ * evaluates export maps, reads the nearest package.json, and realpaths every
+ * path segment on each call. In a pnpm monorepo that dominated scan time, and
+ * the walk below already covers every layout the resolver handled (nested,
+ * hoisted, and virtual-store siblings) without executing package code.
+ */
+export function resolveDepDir(
+ depName: string,
+ parentDir: string,
+ cache: DepDirCache = createDepDirCache(),
+): string | null {
+ let dir = parentDir
+ let prev: string | undefined
+ while (dir !== prev) {
+ // Node skips ancestors that are themselves node_modules directories
+ // (`.../node_modules/node_modules/` is never a valid location).
+ if (basename(dir) !== 'node_modules') {
+ const nodeModulesDir = join(dir, 'node_modules')
+ if (hasNodeModulesDir(nodeModulesDir, cache)) {
+ const candidate = join(nodeModulesDir, depName)
+ let resolved = cache.candidates.get(candidate)
+ if (resolved === undefined) {
+ resolved = resolveCandidateDir(candidate, cache)
+ cache.candidates.set(candidate, resolved)
+ }
+ if (resolved) return resolved
+ }
+ }
+ prev = dir
+ dir = dirname(dir)
+ }
+
+ return null
+}
+
+/**
+ * Memo for `resolveDepDir` across one scan. A dependency graph revisits the
+ * same `node_modules` directories, candidate paths, and symlink targets many
+ * times (every package that depends on `semver` resolves it again), so the
+ * cache turns those repeats into map hits. It is never refreshed, so create
+ * one per scan rather than sharing it across runs.
+ */
+export interface DepDirCache {
+ /** `existsSync` result per `node_modules` directory. */
+ nodeModulesDirs: Map
+ /** Resolution result per `node_modules/` candidate path. */
+ candidates: Map
+ /** Real directory per resolved symlink target, shared by every link to it. */
+ targets: Map
+}
+
+export function createDepDirCache(): DepDirCache {
+ return {
+ nodeModulesDirs: new Map(),
+ candidates: new Map(),
+ targets: new Map(),
+ }
+}
+
+function hasNodeModulesDir(dir: string, cache: DepDirCache): boolean {
+ let exists = cache.nodeModulesDirs.get(dir)
+ if (exists === undefined) {
+ exists = existsSync(dir)
+ cache.nodeModulesDirs.set(dir, exists)
+ }
+ return exists
+}
+
+/**
+ * Resolve one `node_modules/` candidate to its real directory, or null
+ * when no package is installed there.
+ *
+ * `readlink` is the first probe because it is the cheapest call that also
+ * tells symlinks apart: a stat that traverses a pnpm virtual-store link costs
+ * several times more than reading the link. Real directories (npm and Yarn
+ * hoisting) make it fail with EINVAL and are then checked directly; a missing
+ * entry fails with ENOENT.
+ */
+function resolveCandidateDir(
+ candidate: string,
+ cache: DepDirCache,
+): string | null {
+ let target: string | null
+ try {
+ target = readlinkSync(candidate)
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null
+ target = null
+ }
+
+ if (target === null) {
+ return existsSync(join(candidate, 'package.json')) ? candidate : null
+ }
+
+ const resolvedTarget = resolve(
+ dirname(candidate),
+ normalizeReadlinkTarget(target),
+ )
+ let real = cache.targets.get(resolvedTarget)
+ if (real === undefined) {
+ real = existsSync(join(resolvedTarget, 'package.json'))
+ ? resolveRealDir(resolvedTarget)
+ : null
+ cache.targets.set(resolvedTarget, real)
+ }
+ return real
+}
+
+/**
+ * Collapse a symlinked directory to its real path with one `lstat` and, only
+ * when needed, one native `realpath` call. Non-links are returned as-is.
+ */
+function resolveRealDir(dir: string): string {
+ try {
+ return lstatSync(dir).isSymbolicLink() ? realpathSync.native(dir) : dir
+ } catch {
+ return dir
+ }
+}
diff --git a/packages/intent/src/shared/paths.ts b/packages/intent/src/shared/paths.ts
new file mode 100644
index 00000000..cfd23dc6
--- /dev/null
+++ b/packages/intent/src/shared/paths.ts
@@ -0,0 +1,37 @@
+import { isAbsolute, relative, sep } from 'node:path'
+
+export function isWithinOrEqual(path: string, parentDir: string): boolean {
+ const rel = relative(parentDir, path)
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
+}
+
+export function toPosixPath(p: string): string {
+ return p.split(sep).join('/')
+}
+
+/**
+ * Check whether a skill path belongs to the default skill discovery tree.
+ *
+ * Hidden directories and node_modules are excluded from default discovery,
+ * while explicitly declared or custom-root skills can still be handled by
+ * their respective discovery paths.
+ */
+export function isDefaultSkillPath(path: string): boolean {
+ return !path
+ .split('/')
+ .some((part) => part.startsWith('.') || part === 'node_modules')
+}
+
+/**
+ * Strip the Windows extended-length prefix that `readlink` can report for
+ * junction targets. `\\?\C:\dir` becomes `C:\dir`; `\\?\UNC\server\share`
+ * becomes `\\server\share` so the UNC root stays absolute. Other targets,
+ * including relative POSIX links, are returned unchanged.
+ */
+export function normalizeReadlinkTarget(target: string): string {
+ if (target.startsWith('\\\\?\\UNC\\')) {
+ return `\\\\${target.slice(8)}`
+ }
+ if (target.startsWith('\\\\?\\')) return target.slice(4)
+ return target
+}
diff --git a/packages/intent/src/shared/skill-files.ts b/packages/intent/src/shared/skill-files.ts
new file mode 100644
index 00000000..259f4b54
--- /dev/null
+++ b/packages/intent/src/shared/skill-files.ts
@@ -0,0 +1,62 @@
+import { join } from 'node:path'
+import { nodeReadFs } from './fs-identity.js'
+import type { Dirent } from 'node:fs'
+import type { ReadFs } from './fs-identity.js'
+
+/**
+ * Recursively find all SKILL.md files under a directory.
+ */
+export function findSkillFiles(
+ dir: string,
+ fs: ReadFs = nodeReadFs,
+): Array {
+ const files: Array = []
+ collectSkillFiles(dir, fs, files)
+ return files
+}
+
+function collectSkillFiles(
+ dir: string,
+ fs: ReadFs,
+ files: Array,
+): void {
+ let entries: Array>
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true, encoding: 'utf8' })
+ } catch {
+ return
+ }
+
+ for (const entry of entries) {
+ const fullPath = join(dir, entry.name)
+ if (entry.isDirectory()) {
+ collectSkillFiles(fullPath, fs, files)
+ } else if (entry.name === 'SKILL.md') {
+ files.push(fullPath)
+ }
+ }
+}
+
+/**
+ * Like `findSkillFiles`, but stops at the first SKILL.md found instead of
+ * enumerating the whole tree.
+ */
+export function hasAnySkillFile(dir: string, fs: ReadFs = nodeReadFs): boolean {
+ let entries: Array>
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true, encoding: 'utf8' })
+ } catch {
+ return false
+ }
+
+ for (const entry of entries) {
+ const fullPath = join(dir, entry.name)
+ if (entry.isDirectory()) {
+ if (hasAnySkillFile(fullPath, fs)) return true
+ } else if (entry.name === 'SKILL.md') {
+ return true
+ }
+ }
+
+ return false
+}
diff --git a/packages/intent/src/shared/types.ts b/packages/intent/src/shared/types.ts
index f2e1a388..b04b3fb5 100644
--- a/packages/intent/src/shared/types.ts
+++ b/packages/intent/src/shared/types.ts
@@ -1,7 +1,4 @@
-// ---------------------------------------------------------------------------
-// Intent config (lives in library package.json under "intent" key)
-// ---------------------------------------------------------------------------
-
+// Lives in a library's package.json under the "intent" key.
export interface IntentConfig {
version: number
repo: string
@@ -9,10 +6,6 @@ export interface IntentConfig {
requires?: Array
}
-// ---------------------------------------------------------------------------
-// Scanner types
-// ---------------------------------------------------------------------------
-
export interface ScanResult {
packageManager: PackageManager
packages: Array
@@ -78,10 +71,6 @@ export interface SkillEntry {
framework?: string
}
-// ---------------------------------------------------------------------------
-// Staleness types
-// ---------------------------------------------------------------------------
-
export interface StalenessReport {
library: string
currentVersion: string | null
diff --git a/packages/intent/src/shared/utils.ts b/packages/intent/src/shared/utils.ts
deleted file mode 100644
index 8e47165a..00000000
--- a/packages/intent/src/shared/utils.ts
+++ /dev/null
@@ -1,572 +0,0 @@
-import { execFileSync } from 'node:child_process'
-import {
- closeSync,
- existsSync,
- fstatSync,
- lstatSync,
- openSync,
- readFileSync,
- readSync,
- readdirSync,
- readlinkSync,
- realpathSync,
-} from 'node:fs'
-import { basename, dirname, join, resolve, sep } from 'node:path'
-import { parse as parseYaml } from 'yaml'
-import type { Dirent } from 'node:fs'
-
-/**
- * The subset of `node:fs` the scanner reads through. Under Yarn PnP this is
- * swapped for Yarn's libzip-patched `fs` so reads can reach files inside
- * `.yarn/cache/*.zip` (see scanner `loadPnpApi`). The static `node:fs` named
- * imports cannot be used directly for that, because their bindings are captured
- * before Yarn's `setup()` patches the CommonJS `fs` module.
- */
-export interface ReadFs {
- existsSync: typeof existsSync
- lstatSync: typeof lstatSync
- readFileSync: typeof readFileSync
- readdirSync: typeof readdirSync
- realpathSync: typeof realpathSync
- /**
- * Optional low-level read primitives. When present (always on `node:fs` and
- * Yarn's libzip-patched module) `parseFrontmatter` reads only the leading
- * region of a file instead of its whole body.
- */
- openSync?: typeof openSync
- readSync?: typeof readSync
- closeSync?: typeof closeSync
- fstatSync?: typeof fstatSync
-}
-
-export const nodeReadFs: ReadFs = {
- existsSync,
- lstatSync,
- readFileSync,
- readdirSync,
- realpathSync,
- openSync,
- readSync,
- closeSync,
- fstatSync,
-}
-
-/**
- * Convert a path to use forward slashes (for cross-platform consistency).
- */
-export function toPosixPath(p: string): string {
- return p.split(sep).join('/')
-}
-
-/**
- * Check whether a skill path belongs to the default skill discovery tree.
- *
- * Hidden directories and node_modules are excluded from default discovery,
- * while explicitly declared or custom-root skills can still be handled by
- * their respective discovery paths.
- */
-export function isDefaultSkillPath(path: string): boolean {
- return !path
- .split('/')
- .some((part) => part.startsWith('.') || part === 'node_modules')
-}
-
-export interface FsIdentityResolver {
- (path: string): string
- /**
- * Record that `realPath` is already an identity (not a symlink), so a later
- * lookup returns it without an `lstat`. Callers use this for directories
- * they have just resolved through `resolveDepDir`.
- */
- prime: (realPath: string) => void
-}
-
-export function createFsIdentityCache(
- getFs: () => ReadFs = () => nodeReadFs,
-): FsIdentityResolver {
- const cache = new Map()
-
- const getIdentity = ((path: string): string => {
- const resolved = resolve(path)
- const cached = cache.get(resolved)
- if (cached) return cached
-
- const fs = getFs()
- let identity: string
- try {
- identity = fs.lstatSync(resolved).isSymbolicLink()
- ? fs.realpathSync(resolved)
- : resolved
- } catch {
- identity = resolved
- }
-
- cache.set(resolved, identity)
- return identity
- }) as FsIdentityResolver
-
- getIdentity.prime = (realPath: string): void => {
- const resolved = resolve(realPath)
- if (!cache.has(resolved)) cache.set(resolved, resolved)
- }
-
- return getIdentity
-}
-
-/**
- * Recursively find all SKILL.md files under a directory.
- */
-export function findSkillFiles(
- dir: string,
- fs: ReadFs = nodeReadFs,
-): Array {
- const files: Array = []
- collectSkillFiles(dir, fs, files)
- return files
-}
-
-function collectSkillFiles(
- dir: string,
- fs: ReadFs,
- files: Array,
-): void {
- let entries: Array>
- try {
- entries = fs.readdirSync(dir, { withFileTypes: true, encoding: 'utf8' })
- } catch {
- return
- }
-
- for (const entry of entries) {
- const fullPath = join(dir, entry.name)
- if (entry.isDirectory()) {
- collectSkillFiles(fullPath, fs, files)
- } else if (entry.name === 'SKILL.md') {
- files.push(fullPath)
- }
- }
-}
-
-/**
- * Like `findSkillFiles`, but stops at the first SKILL.md found instead of
- * enumerating the whole tree.
- */
-export function hasAnySkillFile(dir: string, fs: ReadFs = nodeReadFs): boolean {
- let entries: Array>
- try {
- entries = fs.readdirSync(dir, { withFileTypes: true, encoding: 'utf8' })
- } catch {
- return false
- }
-
- for (const entry of entries) {
- const fullPath = join(dir, entry.name)
- if (entry.isDirectory()) {
- if (hasAnySkillFile(fullPath, fs)) return true
- } else if (entry.name === 'SKILL.md') {
- return true
- }
- }
-
- return false
-}
-
-/**
- * Read dependencies and peerDependencies (and optionally devDependencies) from
- * a parsed package.json object.
- */
-export function getDeps(
- pkgJson: Record] |