@igorlau/dotagents 0.0.0-stage → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +81 -2
  3. package/THIRD_PARTY_NOTICES.md +73 -0
  4. package/content/rules/comments.md +13 -0
  5. package/content/rules/core.md +8 -0
  6. package/content/rules/ponytail.md +29 -0
  7. package/content/rules/ponytail.upstream.json +8 -0
  8. package/content/skills/code-review/SKILL.md +58 -0
  9. package/content/skills/commit/SKILL.md +77 -0
  10. package/content/skills/debug/SKILL.md +142 -0
  11. package/content/skills/debug/UPSTREAM.json +8 -0
  12. package/content/skills/debug/agents/openai.yaml +3 -0
  13. package/content/skills/debug/scripts/hitl-loop.template.sh +44 -0
  14. package/content/skills/docs-writing/SKILL.md +82 -0
  15. package/content/skills/docs-writing/references/formatting.md +150 -0
  16. package/content/skills/docs-writing/references/global-and-accessible.md +46 -0
  17. package/content/skills/docs-writing/references/word-list.md +112 -0
  18. package/content/skills/grill-me/SKILL.md +11 -0
  19. package/content/skills/grill-me/UPSTREAM.json +8 -0
  20. package/content/skills/grill-me/agents/openai.yaml +5 -0
  21. package/content/skills/grilling/SKILL.md +34 -0
  22. package/content/skills/grilling/UPSTREAM.json +8 -0
  23. package/content/skills/grilling/agents/openai.yaml +3 -0
  24. package/content/skills/handoff/SKILL.md +20 -0
  25. package/content/skills/handoff/UPSTREAM.json +8 -0
  26. package/content/skills/handoff/agents/openai.yaml +5 -0
  27. package/content/skills/plan/SKILL.md +58 -0
  28. package/content/skills/writing-for-agents/SKILL-MECHANICS.md +22 -0
  29. package/content/skills/writing-for-agents/SKILL.md +85 -0
  30. package/content/skills/writing-for-agents/UPSTREAM.json +8 -0
  31. package/content/skills/writing-for-agents/agents/openai.yaml +3 -0
  32. package/dist/apply.js +119 -0
  33. package/dist/blocks.js +28 -0
  34. package/dist/build-info.json +1 -0
  35. package/dist/catalog.js +50 -0
  36. package/dist/cli.js +80 -0
  37. package/dist/commands.js +181 -0
  38. package/dist/frontmatter.js +23 -0
  39. package/dist/git.js +7 -0
  40. package/dist/manifest.js +35 -0
  41. package/dist/paths.js +25 -0
  42. package/dist/targets.js +74 -0
  43. package/package.json +36 -4
@@ -0,0 +1,85 @@
1
+ ---
2
+ name: writing-for-agents
3
+ description: Writing documents for agents. Use when creating or editing skills, or modifying AGENTS.md or CLAUDE.md.
4
+ ---
5
+
6
+ Reference for writing any document an agent consumes: a skill, an `AGENTS.md` / `CLAUDE.md`, a doc reached by a pointer. The packaging differs; the writing does not: the same levers make each one predictable, since the agent takes the same _process_ every run rather than producing the same output.
7
+
8
+ When the document you're writing is a skill, read [`SKILL-MECHANICS.md`](SKILL-MECHANICS.md) for frontmatter, invocation choice, and router skills.
9
+
10
+ ## Repository conventions first
11
+
12
+ Before you start, read what the repository defines: agent instructions (`AGENTS.md`, `CLAUDE.md`, `.github/copilot-instructions.md`, `.github/instructions/`, `.cursor/rules/`), project skills, `CONTRIBUTING.md`, style guides, linter and formatter configuration, and the patterns in the surrounding code. They take precedence over this skill: where they differ, follow the repository, and point out the difference instead of changing the repository's standard. When you edit a repository's `AGENTS.md`, `CLAUDE.md`, or skills, keep their existing structure, format, and conventions.
13
+
14
+ ## Context pointers
15
+
16
+ A **context pointer** is a reference held in the agent's context that names some out-of-context material and encodes the condition for reaching it. A skill's description is one; a line in `AGENTS.md` naming a doc is the same object. The pointer's _wording_, not its target, decides when the agent reaches the material, and how reliably. A must-have target behind a weakly worded pointer is a variance bug: sharpen the wording first, and inline the material only if sharpening fails.
17
+
18
+ A pointer does two jobs: state what the material is, and list the **branches** that should trigger reaching it (a branch is a distinct case the document handles, so different runs take different paths through it). Every word of an always-loaded pointer costs on every turn, so it earns even harder pruning than the body:
19
+
20
+ - **Front-load the leading word**: the pointer is where it does its triggering work.
21
+ - **One trigger per branch.** Synonyms that rename a single branch are one branch written twice; collapse them and keep only genuinely distinct branches.
22
+ - **Cut identity the body already carries.**
23
+
24
+ ## The two loads
25
+
26
+ Every document and pointer you add spends one of two budgets:
27
+
28
+ - **Context load** is the cost of always-loaded material on the agent's window: an `AGENTS.md` line, a skill description, anything sitting in context every turn, spending tokens and attention whether or not it fires.
29
+ - **Cognitive load** is the cost on the human: which documents exist and when to reach for each. The human is the index. Not a cost to minimise: it is the price of human agency; spend it where human judgement matters, remove it where it does not.
30
+
31
+ Material reached only through a pointer escapes context load at the price of the pointer's own line; material with no pointer at all rides entirely on cognitive load.
32
+
33
+ ## Information hierarchy
34
+
35
+ A document is built from two content types: **steps** (the ordered actions the agent performs) and **reference** (definitions, rules, facts consulted on demand). The two mix freely: all steps (a recipe), all reference (a review's rules, this skill), or both. The core decision is where each piece sits on the **information hierarchy**, a ladder ranked by how immediately the agent needs the material:
36
+
37
+ 1. **In-file step** is the primary tier: what the agent does, in order.
38
+ 2. **In-file reference** is consulted on demand. Often a legitimately flat peer-set (every rule of a review on one rung), which is a fine arrangement, not a smell.
39
+ 3. **Disclosed reference** is pushed out into a separate file, reached by a context pointer, loaded only when the pointer fires. Spans a sibling file in the same folder through fully external reference that lives anywhere and any document can point at.
40
+
41
+ Push too little down and the top bloats; push too much and you hide material the agent actually needs. That tension is the whole decision.
42
+
43
+ **Progressive disclosure** is the move down the ladder (out of the main file and behind a pointer) so the top stays legible. Not primarily a token optimisation: it is how the hierarchy is protected. Branching is the cleanest disclosure test: inline what every branch needs, and push behind a pointer what only some branches reach. When a document has steps, in-file reference that should be disclosed buries them and turns attending to them into a coin-flip: a variance lever, not just a legibility one.
44
+
45
+ **Co-location** is the within-file companion: where the ladder decides _how far down_ a piece sits, co-location decides _what sits beside it_ once there. Keep a concept's definition, rules, and caveats under one heading rather than scattered, so reading one part brings its neighbours with it. The test: the document should read like documentation written for the agent. Grouped material reads that way; scattered material does not. (Distinct from duplication: that repeats one meaning in two places; scattering fragments one meaning across many.)
46
+
47
+ **Sprawl** is the failure mode here: a document simply too long, even when every line is live and unique. Attention thins across the excess, and every extra line is one more to keep relevant. The cure is the ladder: disclose reference behind pointers, and split by branch or sequence so each path carries only what it needs.
48
+
49
+ ## Steps and completion criteria
50
+
51
+ Every step ends on a **completion criterion**, the condition that tells the agent the work is done. Two properties make it a lever:
52
+
53
+ - **Clarity**: can the agent tell done from not-done? A vague bound ("understanding reached") invites **premature completion**: ending the step before it is genuinely done, attention slipping to _being done_. The visible steps still ahead (the **post-completion steps**) supply the pull; the criterion's clarity is the resistance. Defend in order: **sharpen the bound first** (local and cheap); only if it is irreducibly fuzzy _and_ you observe the rush, hide the later steps by splitting the sequence. Hiding only works across a real context boundary (a hand-off or a subagent dispatch; an inline call leaves the later steps in context and clears nothing).
54
+ - **Demand**: how much it requires. "Every modified model accounted for" forces thorough work where "produce a change list" does not. Demand drives **legwork** (the digging the agent does within the work, latent in the wording rather than written as its own step), and it is not step-bound: "every rule applied" binds a body of flat reference just as "every step done" binds a sequence, which is how an all-reference document still carries an exhaustiveness bar.
55
+
56
+ The strongest criteria are both checkable and exhaustive.
57
+
58
+ ## When to split
59
+
60
+ Splitting one document into two spends one of the two loads, so split only when the cut earns it:
61
+
62
+ - **By sequence**: split a run of steps where the post-completion steps tempt the agent to rush the one in front of it. Keeping them out of view drives more legwork on the current task. Beware the reverse: merging sequences exposes each step's later steps to what follows, inviting premature completion.
63
+ - **By invocation**, skill-specific: see [`SKILL-MECHANICS.md`](SKILL-MECHANICS.md).
64
+
65
+ ## Leading words
66
+
67
+ A **leading word** is a compact concept already living in the model's pretraining that the agent thinks with while running the document (_lesson_, _fog of war_, _tracer bullets_). Repeated as a token, never as a sentence, it accumulates a distributed definition and anchors a whole region of behaviour in the fewest tokens, by recruiting priors the model already holds. Coining your own works if you define it clearly, but a made-up word recruits no priors: you pay in definition tokens what a pretrained word gives free; reach for an existing word first.
68
+
69
+ It anchors twice. In the body, _execution_: the agent reaches for the same behaviour every time the word appears, and inside flat reference it focuses attention on a class of thing to look for. In a pointer, _invocation_: when the same word lives in your prompts, your docs, and your codebase, the agent links that shared language to the material and reaches it more reliably.
70
+
71
+ Hunt for opportunities to refactor with leading words. A triad spelled out at three sites, a pointer spending a sentence to gesture at one idea. Each is a passage begging to collapse into a single token:
72
+
73
+ - "fast, deterministic, low-overhead" → _tight_ (a _tight_ loop).
74
+ - "a loop you believe in" → _red_, turning a fuzzy gate into a binary observable state (the loop goes _red_ on the bug, or it doesn't).
75
+
76
+ You win twice: fewer tokens, and a sharper hook for the agent to hang its thinking on. Assume every document is carrying restatements that leading words retire. Go find them.
77
+
78
+ **Negation** is the failure mode beside this lever: steering by prohibition drags the forbidden behaviour into context and makes it _more_ available, not less. _Don't think of an elephant_, and the elephant is all there is; the negation is a weak modifier the strongly-activated concept overruns, so the ban half-reads as an instruction to do the thing. Prompt the **positive**: state the target behaviour ("write one-line comments") so the banned one is never spoken. A prohibition earns its place only as a hard guardrail you cannot phrase positively; even then, pair it with the positive target so attention lands on what to do.
79
+
80
+ ## Pruning
81
+
82
+ - Keep each meaning in a **single source of truth**: one authoritative place, so changing the behaviour is a one-place edit. **Duplication** (the same meaning in more than one place) costs maintenance and tokens, and inflates a meaning's prominence on the ladder past its real rank. (The accidental inverse of a leading word, which repeats a token on purpose, never the meaning.)
83
+ - The **environment** is a source of truth too (`package.json` scripts, config files, the directory layout, `--help` output), and a document that restates it is a **cache**: a copy of a lookup, earning its load only when the lookup is expensive. Cache what the agent cannot find by looking: the unwritten convention, the reason behind a choice, the gotcha no config confesses. Leave the one-file, one-command lookups to the environment, where they cannot go stale.
84
+ - Check every line for **relevance**: does it still bear on what the document does? A line loses relevance by never bearing on the task (mere exposition, or a branch that should be disclosed) or by going stale as the behaviour or world it describes changes. Shorter documents are easier to keep relevant. Without a pruning discipline the default fate is **sediment**: stale layers that settle because adding feels safe and removing feels risky, until you must core down through them to find what is still live.
85
+ - Hunt **no-ops** sentence by sentence: an instruction the model already obeys by default pays load to say nothing. The test (does it change behaviour versus the default?) is model-relative, not reader-relative: two people disagreeing about a no-op disagree about the default, and settle it by running the document, not by debate. When a sentence fails, delete the whole sentence rather than trim words from it. The test also grades leading words: a word too weak to beat the default (_be thorough_ when the agent is already thorough-ish) is a no-op, and the fix is a stronger word (_relentless_), not a different technique.
@@ -0,0 +1,8 @@
1
+ {
2
+ "repository": "https://github.com/mattpocock/skills",
3
+ "path": "skills/productivity/writing-for-agents",
4
+ "commit": "49dd158d1076134a641b33efb035946536778336",
5
+ "license": "MIT",
6
+ "modified": true,
7
+ "notes": "Added a 'Repository conventions first' section."
8
+ }
@@ -0,0 +1,3 @@
1
+ interface:
2
+ display_name: "Writing for Agents"
3
+ short_description: "Write documents agents consume"
package/dist/apply.js ADDED
@@ -0,0 +1,119 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { readBlock, removeBlock, upsertBlock } from "./blocks.js";
4
+ import { hash } from "./manifest.js";
5
+ // Directories that agents expect to exist; pruning empty parents stops here.
6
+ const PRUNE_STOP = new Set(["skills", ".claude", ".agents", ".github", ".codex", ".copilot"]);
7
+ // Writes `ops` and removes whatever `previous` owned that `ops` no longer
8
+ // includes. Files that changed since dotagents wrote them, and files that
9
+ // dotagents never wrote, are left alone unless `force` is set.
10
+ export function apply(ops, previous, options) {
11
+ const owned = new Map(previous.map((entry) => [entry.path, entry]));
12
+ const result = { entries: [], changes: [], problems: [] };
13
+ for (const op of ops) {
14
+ const entry = op.kind === "file" ? applyFile(op, owned.get(op.path), options, result) : applyBlock(op, owned.get(op.path), options, result);
15
+ if (entry)
16
+ result.entries.push(entry);
17
+ }
18
+ const kept = new Set(result.entries.map((entry) => entry.path));
19
+ for (const entry of previous) {
20
+ if (kept.has(entry.path))
21
+ continue;
22
+ if (!removeEntry(entry, options, result))
23
+ result.entries.push(entry);
24
+ }
25
+ return result;
26
+ }
27
+ function read(file) {
28
+ return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : undefined;
29
+ }
30
+ function write(file, content, options, executable = false) {
31
+ if (options.dryRun)
32
+ return;
33
+ fs.mkdirSync(path.dirname(file), { recursive: true });
34
+ fs.writeFileSync(file, content);
35
+ if (executable)
36
+ fs.chmodSync(file, 0o755);
37
+ }
38
+ function applyFile(op, owned, options, result) {
39
+ const entry = { path: op.path, kind: "file", hash: hash(op.content) };
40
+ const current = read(op.path);
41
+ if (current === undefined) {
42
+ write(op.path, op.content, options, op.executable);
43
+ result.changes.push(`create ${op.path}`);
44
+ return entry;
45
+ }
46
+ if (current === op.content)
47
+ return entry;
48
+ if (!options.force) {
49
+ if (!owned) {
50
+ result.problems.push(`${op.path}: exists and wasn't written by dotagents (use --force to overwrite)`);
51
+ return undefined;
52
+ }
53
+ if (hash(current) !== owned.hash) {
54
+ result.problems.push(`${op.path}: modified locally, skipped (use --force to overwrite)`);
55
+ return owned;
56
+ }
57
+ }
58
+ write(op.path, op.content, options, op.executable);
59
+ result.changes.push(`update ${op.path}`);
60
+ return entry;
61
+ }
62
+ function applyBlock(op, owned, options, result) {
63
+ const body = op.content.trim();
64
+ const entry = { path: op.path, kind: "block", hash: hash(body) };
65
+ const current = read(op.path);
66
+ const block = current === undefined ? undefined : readBlock(current);
67
+ entry.created = owned?.created ?? current === undefined;
68
+ if (block === body)
69
+ return entry;
70
+ if (owned && block !== undefined && hash(block) !== owned.hash && !options.force) {
71
+ result.problems.push(`${op.path}: dotagents block modified locally, skipped (use --force to overwrite)`);
72
+ return owned;
73
+ }
74
+ write(op.path, upsertBlock(current, body), options);
75
+ result.changes.push(`${block === undefined ? "add block to" : "update block in"} ${op.path}`);
76
+ return entry;
77
+ }
78
+ // Returns true when the entry no longer needs tracking.
79
+ function removeEntry(entry, options, result) {
80
+ const current = read(entry.path);
81
+ if (current === undefined)
82
+ return true;
83
+ if (entry.kind === "file") {
84
+ if (hash(current) !== entry.hash && !options.force) {
85
+ result.problems.push(`${entry.path}: modified locally, not removed (use --force to remove)`);
86
+ return false;
87
+ }
88
+ if (!options.dryRun) {
89
+ fs.rmSync(entry.path);
90
+ prune(path.dirname(entry.path));
91
+ }
92
+ result.changes.push(`remove ${entry.path}`);
93
+ return true;
94
+ }
95
+ const block = readBlock(current);
96
+ if (block === undefined)
97
+ return true;
98
+ if (hash(block) !== entry.hash && !options.force) {
99
+ result.problems.push(`${entry.path}: dotagents block modified locally, not removed (use --force to remove)`);
100
+ return false;
101
+ }
102
+ const rest = removeBlock(current);
103
+ if (rest === "" && entry.created) {
104
+ if (!options.dryRun)
105
+ fs.rmSync(entry.path);
106
+ result.changes.push(`remove ${entry.path}`);
107
+ }
108
+ else {
109
+ write(entry.path, rest, options);
110
+ result.changes.push(`remove block from ${entry.path}`);
111
+ }
112
+ return true;
113
+ }
114
+ function prune(dir) {
115
+ while (!PRUNE_STOP.has(path.basename(dir)) && fs.existsSync(dir) && fs.readdirSync(dir).length === 0) {
116
+ fs.rmdirSync(dir);
117
+ dir = path.dirname(dir);
118
+ }
119
+ }
package/dist/blocks.js ADDED
@@ -0,0 +1,28 @@
1
+ // A block is the dotagents-owned region inside a file that other people also
2
+ // edit, such as AGENTS.md. Text outside the markers is never touched.
3
+ export const BLOCK_START = "<!-- dotagents:start -->";
4
+ export const BLOCK_END = "<!-- dotagents:end -->";
5
+ const BLOCK_PATTERN = new RegExp(`${escape(BLOCK_START)}\\n([\\s\\S]*?)\\n?${escape(BLOCK_END)}\\n?`);
6
+ export function readBlock(text) {
7
+ return BLOCK_PATTERN.exec(text)?.[1];
8
+ }
9
+ export function upsertBlock(text, body) {
10
+ const block = `${BLOCK_START}\n${body.trim()}\n${BLOCK_END}\n`;
11
+ if (text === undefined || text.trim() === "")
12
+ return block;
13
+ if (BLOCK_PATTERN.test(text))
14
+ return text.replace(BLOCK_PATTERN, () => block);
15
+ return `${text.replace(/\n*$/, "\n")}\n${block}`;
16
+ }
17
+ export function removeBlock(text) {
18
+ const match = BLOCK_PATTERN.exec(text);
19
+ if (!match)
20
+ return text;
21
+ const before = text.slice(0, match.index).replace(/\n+$/, "\n");
22
+ const after = text.slice(match.index + match[0].length);
23
+ const joined = before + after;
24
+ return joined.trim() === "" ? "" : joined;
25
+ }
26
+ function escape(value) {
27
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28
+ }
@@ -0,0 +1 @@
1
+ {"commit":"353f166"}
@@ -0,0 +1,50 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { contentRoot } from "./paths.js";
4
+ import { parseFrontmatter } from "./frontmatter.js";
5
+ // Files that describe a skill's origin but aren't part of the skill itself.
6
+ const META_FILES = new Set(["UPSTREAM.json"]);
7
+ export function loadCatalog(root = contentRoot) {
8
+ const rules = loadRules(path.join(root, "rules"));
9
+ const skillsDir = path.join(root, "skills");
10
+ const skills = fs
11
+ .readdirSync(skillsDir, { withFileTypes: true })
12
+ .filter((entry) => entry.isDirectory())
13
+ .map((entry) => loadSkill(path.join(skillsDir, entry.name)))
14
+ .sort((a, b) => a.name.localeCompare(b.name));
15
+ return { rules, skills };
16
+ }
17
+ // Joins rules/*.md, core first. Headings drop one level because the rules
18
+ // often land inside someone else's AGENTS.md, which owns the top level.
19
+ function loadRules(dir) {
20
+ return fs
21
+ .readdirSync(dir)
22
+ .filter((name) => name.endsWith(".md"))
23
+ .sort((a, b) => Number(b === "core.md") - Number(a === "core.md") || a.localeCompare(b))
24
+ .map((name) => fs.readFileSync(path.join(dir, name), "utf8").trim().replace(/^#/gm, "##"))
25
+ .join("\n\n");
26
+ }
27
+ function loadSkill(dir) {
28
+ const name = path.basename(dir);
29
+ const files = listFiles(dir)
30
+ .filter((rel) => !META_FILES.has(rel))
31
+ .map((rel) => {
32
+ const abs = path.join(dir, rel);
33
+ return {
34
+ rel,
35
+ content: fs.readFileSync(abs, "utf8"),
36
+ executable: (fs.statSync(abs).mode & 0o111) !== 0,
37
+ };
38
+ });
39
+ const skillMd = files.find((file) => file.rel === "SKILL.md");
40
+ if (!skillMd)
41
+ throw new Error(`Skill ${name} has no SKILL.md`);
42
+ const description = parseFrontmatter(skillMd.content)?.data.description ?? "";
43
+ return { name, description, files };
44
+ }
45
+ function listFiles(dir, prefix = "") {
46
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
47
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
48
+ return entry.isDirectory() ? listFiles(path.join(dir, entry.name), rel) : [rel];
49
+ });
50
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { doctor, init, install, list, saveSource, selfUpdate, uninstall, update, version } from "./commands.js";
4
+ import { parseAgents } from "./targets.js";
5
+ const HELP = `dotagents: install curated agent skills and rules
6
+
7
+ Usage:
8
+ dotagents install Install globally (default for all projects)
9
+ dotagents init Install into the current repository (commit the files)
10
+ dotagents update [--global|--project]
11
+ dotagents uninstall [--global|--project]
12
+ dotagents doctor Check installs for problems
13
+ dotagents list List the skills in the catalog
14
+ dotagents self-update Run \`update\` with the latest release
15
+
16
+ Options:
17
+ --agents <list> Comma-separated: claude,codex,copilot (default: all)
18
+ --dry-run Print changes without writing them
19
+ --force Overwrite files that were modified or not written by dotagents
20
+ --source <spec> With install: where self-update fetches dotagents from
21
+ -v, --version Print the version
22
+ -h, --help Print this help
23
+ `;
24
+ function main(argv) {
25
+ const { values, positionals } = parseArgs({
26
+ args: argv,
27
+ allowPositionals: true,
28
+ options: {
29
+ agents: { type: "string" },
30
+ "dry-run": { type: "boolean", default: false },
31
+ force: { type: "boolean", default: false },
32
+ global: { type: "boolean", default: false },
33
+ project: { type: "boolean", default: false },
34
+ source: { type: "string" },
35
+ version: { type: "boolean", short: "v", default: false },
36
+ help: { type: "boolean", short: "h", default: false },
37
+ },
38
+ });
39
+ if (values.version) {
40
+ console.log(version());
41
+ return 0;
42
+ }
43
+ const [command] = positionals;
44
+ if (values.help || !command) {
45
+ console.log(HELP);
46
+ return command || values.help ? 0 : 1;
47
+ }
48
+ const options = { agents: parseAgents(values.agents), dryRun: values["dry-run"], force: values.force };
49
+ const which = values.global ? "global" : values.project ? "project" : undefined;
50
+ const cwd = process.cwd();
51
+ switch (command) {
52
+ case "install":
53
+ if (values.source && !options.dryRun)
54
+ saveSource(values.source);
55
+ return install(options) ? 0 : 1;
56
+ case "init":
57
+ return init(cwd, options) ? 0 : 1;
58
+ case "update":
59
+ return update(cwd, which, options) ? 0 : 1;
60
+ case "uninstall":
61
+ return uninstall(cwd, which, options) ? 0 : 1;
62
+ case "doctor":
63
+ return doctor(cwd) ? 0 : 1;
64
+ case "list":
65
+ list();
66
+ return 0;
67
+ case "self-update":
68
+ return selfUpdate(argv.slice(1)) ? 0 : 1;
69
+ default:
70
+ console.error(`Unknown command "${command}".\n\n${HELP}`);
71
+ return 1;
72
+ }
73
+ }
74
+ try {
75
+ process.exitCode = main(process.argv.slice(2));
76
+ }
77
+ catch (error) {
78
+ console.error(`dotagents: ${error instanceof Error ? error.message : String(error)}`);
79
+ process.exitCode = 1;
80
+ }
@@ -0,0 +1,181 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { apply } from "./apply.js";
5
+ import { readBlock } from "./blocks.js";
6
+ import { loadCatalog } from "./catalog.js";
7
+ import { repoRoot } from "./git.js";
8
+ import { fromStored, globalManifestPath, hash, projectManifestPath, readManifest, toStored, writeManifest, } from "./manifest.js";
9
+ import { codexHome, configDir, packageRoot } from "./paths.js";
10
+ import { planInstall } from "./targets.js";
11
+ export const DEFAULT_SOURCE = "@igorlau/dotagents@latest";
12
+ // Release tags carry a real version. Builds from a branch carry X.Y.0-dev,
13
+ // so the commit tells them apart.
14
+ export function version() {
15
+ const base = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8")).version;
16
+ const buildInfo = path.join(packageRoot, "dist", "build-info.json");
17
+ if (!base.endsWith("-dev") || !fs.existsSync(buildInfo))
18
+ return base;
19
+ const { commit } = JSON.parse(fs.readFileSync(buildInfo, "utf8"));
20
+ return commit ? `${base}+${commit}` : base;
21
+ }
22
+ function log(message = "") {
23
+ console.log(message);
24
+ }
25
+ function globalScope() {
26
+ return { mode: "global", root: undefined, manifestPath: globalManifestPath() };
27
+ }
28
+ function projectScope(cwd) {
29
+ const root = repoRoot(cwd);
30
+ if (!root)
31
+ throw new Error("Not inside a Git repository. Run this command from a repository, or use `dotagents install` for a global install.");
32
+ return { mode: "project", root, manifestPath: projectManifestPath(root) };
33
+ }
34
+ function existingProjectScope(cwd) {
35
+ const root = repoRoot(cwd);
36
+ if (!root)
37
+ return undefined;
38
+ const manifest = readManifest(projectManifestPath(root));
39
+ return manifest ? { mode: manifest.mode, root, manifestPath: projectManifestPath(root) } : undefined;
40
+ }
41
+ // Install, update, and uninstall all reduce to: apply a plan, then record it.
42
+ function run(scope, agents, options, uninstall = false) {
43
+ const previous = readManifest(scope.manifestPath);
44
+ const catalog = loadCatalog();
45
+ const ops = uninstall ? [] : planInstall(catalog, scope.mode, agents, scope.root);
46
+ const result = apply(ops, fromStored(previous?.entries ?? [], scope.root), options);
47
+ report(result, options.dryRun);
48
+ if (options.dryRun)
49
+ return result.problems.length === 0;
50
+ if (result.entries.length === 0) {
51
+ fs.rmSync(scope.manifestPath, { force: true });
52
+ }
53
+ else {
54
+ writeManifest(scope.manifestPath, {
55
+ schema: 1,
56
+ version: version(),
57
+ mode: scope.mode,
58
+ agents,
59
+ skills: uninstall ? (previous?.skills ?? []) : catalog.skills.map((skill) => skill.name),
60
+ entries: toStored(result.entries, scope.root),
61
+ updatedAt: new Date().toISOString(),
62
+ });
63
+ }
64
+ return result.problems.length === 0;
65
+ }
66
+ function report(result, dryRun) {
67
+ const prefix = dryRun ? "would " : "";
68
+ for (const change of result.changes)
69
+ log(` ${prefix}${change}`);
70
+ for (const problem of result.problems)
71
+ log(` ! ${problem}`);
72
+ if (result.changes.length === 0 && result.problems.length === 0)
73
+ log(" Already up to date.");
74
+ }
75
+ export function install(options) {
76
+ log(`Installing dotagents ${version()} globally for ${options.agents.join(", ")}:`);
77
+ return run(globalScope(), options.agents, options);
78
+ }
79
+ export function init(cwd, options) {
80
+ const scope = projectScope(cwd);
81
+ log(`Installing dotagents ${version()} into ${scope.root}:`);
82
+ const ok = run(scope, options.agents, options);
83
+ if (!options.dryRun)
84
+ log("Commit the new files so that collaborators get them too.");
85
+ return ok;
86
+ }
87
+ function selectScopes(cwd, which) {
88
+ const scopes = [];
89
+ if (which !== "project" && readManifest(globalManifestPath()))
90
+ scopes.push(globalScope());
91
+ if (which !== "global") {
92
+ const project = existingProjectScope(cwd);
93
+ if (project)
94
+ scopes.push(project);
95
+ }
96
+ return scopes;
97
+ }
98
+ export function update(cwd, which, options) {
99
+ const scopes = selectScopes(cwd, which);
100
+ if (scopes.length === 0) {
101
+ log("Nothing to update. Run `dotagents install` or `dotagents init` first.");
102
+ return true;
103
+ }
104
+ let ok = true;
105
+ for (const scope of scopes) {
106
+ const manifest = readManifest(scope.manifestPath);
107
+ log(`Updating ${describe(scope)} to dotagents ${version()}:`);
108
+ ok = run(scope, manifest.agents, { ...options, agents: manifest.agents }) && ok;
109
+ }
110
+ return ok;
111
+ }
112
+ export function uninstall(cwd, which, options) {
113
+ const scopes = selectScopes(cwd, which);
114
+ if (scopes.length === 0) {
115
+ log("Nothing to uninstall.");
116
+ return true;
117
+ }
118
+ let ok = true;
119
+ for (const scope of scopes) {
120
+ const manifest = readManifest(scope.manifestPath);
121
+ log(`Uninstalling ${describe(scope)}:`);
122
+ ok = run(scope, manifest.agents, { ...options, agents: manifest.agents }, true) && ok;
123
+ }
124
+ return ok;
125
+ }
126
+ function describe(scope) {
127
+ return scope.root ? `the project install in ${scope.root}` : "the global install";
128
+ }
129
+ export function doctor(cwd) {
130
+ const scopes = selectScopes(cwd, undefined);
131
+ const issues = [];
132
+ if (scopes.length === 0)
133
+ issues.push("No dotagents install found. Run `dotagents install`.");
134
+ for (const scope of scopes) {
135
+ const manifest = readManifest(scope.manifestPath);
136
+ log(`Checking ${describe(scope)} (dotagents ${manifest.version}, agents: ${manifest.agents.join(", ")})`);
137
+ for (const entry of fromStored(manifest.entries, scope.root)) {
138
+ if (!fs.existsSync(entry.path)) {
139
+ issues.push(`${entry.path}: missing. Run \`dotagents update\`.`);
140
+ continue;
141
+ }
142
+ const content = fs.readFileSync(entry.path, "utf8");
143
+ const owned = entry.kind === "file" ? content : readBlock(content);
144
+ if (owned === undefined)
145
+ issues.push(`${entry.path}: dotagents block missing. Run \`dotagents update\`.`);
146
+ else if (hash(entry.kind === "file" ? owned : owned.trim()) !== entry.hash)
147
+ issues.push(`${entry.path}: modified since dotagents wrote it.`);
148
+ }
149
+ if (scope.mode === "global" && manifest.agents.includes("codex") && fs.existsSync(path.join(codexHome(), "AGENTS.override.md"))) {
150
+ issues.push(`${path.join(codexHome(), "AGENTS.override.md")} exists, so Codex ignores the rules in AGENTS.md.`);
151
+ }
152
+ if (version() !== manifest.version)
153
+ log(` Installed version ${manifest.version} differs from this CLI (${version()}). Run \`dotagents update\`.`);
154
+ }
155
+ for (const issue of issues)
156
+ log(` ! ${issue}`);
157
+ if (issues.length === 0)
158
+ log(" No problems found.");
159
+ return issues.length === 0;
160
+ }
161
+ export function list() {
162
+ for (const skill of loadCatalog().skills)
163
+ log(`${skill.name}\n ${skill.description}`);
164
+ }
165
+ function configFile() {
166
+ return path.join(configDir(), "config.json");
167
+ }
168
+ export function readSource() {
169
+ const file = configFile();
170
+ return fs.existsSync(file) ? (JSON.parse(fs.readFileSync(file, "utf8")).source ?? DEFAULT_SOURCE) : DEFAULT_SOURCE;
171
+ }
172
+ export function saveSource(source) {
173
+ fs.mkdirSync(configDir(), { recursive: true });
174
+ fs.writeFileSync(configFile(), JSON.stringify({ source }, null, 2) + "\n");
175
+ }
176
+ export function selfUpdate(args) {
177
+ const source = readSource();
178
+ log(`Running the latest dotagents from ${source}:`);
179
+ const result = spawnSync("npx", ["--yes", "--prefer-online", source, "update", ...args], { stdio: "inherit" });
180
+ return result.status === 0;
181
+ }
@@ -0,0 +1,23 @@
1
+ // Parses the flat `key: value` frontmatter that skills use. Nested YAML isn't
2
+ // supported; lint-content rejects lines that this parser can't read.
3
+ export function parseFrontmatter(text) {
4
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
5
+ if (!match)
6
+ return undefined;
7
+ const data = {};
8
+ for (const line of match[1].split(/\r?\n/)) {
9
+ if (line.trim() === "")
10
+ continue;
11
+ const kv = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
12
+ if (!kv)
13
+ throw new Error(`Unsupported frontmatter line: ${line}`);
14
+ data[kv[1]] = unquote(kv[2].trim());
15
+ }
16
+ return { data, body: text.slice(match[0].length) };
17
+ }
18
+ function unquote(value) {
19
+ if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.at(-1) === value[0]) {
20
+ return value.slice(1, -1);
21
+ }
22
+ return value;
23
+ }
package/dist/git.js ADDED
@@ -0,0 +1,7 @@
1
+ import { spawnSync } from "node:child_process";
2
+ export function repoRoot(cwd) {
3
+ const result = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8" });
4
+ if (result.error)
5
+ throw result.error;
6
+ return result.status === 0 ? result.stdout.trim() : undefined;
7
+ }
@@ -0,0 +1,35 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { configDir } from "./paths.js";
5
+ export const PROJECT_MANIFEST = ".dotagents.json";
6
+ export function hash(content) {
7
+ return crypto.createHash("sha256").update(content).digest("hex");
8
+ }
9
+ export function globalManifestPath() {
10
+ return path.join(configDir(), "manifest.json");
11
+ }
12
+ export function projectManifestPath(root) {
13
+ return path.join(root, PROJECT_MANIFEST);
14
+ }
15
+ export function readManifest(file) {
16
+ if (!fs.existsSync(file))
17
+ return undefined;
18
+ return JSON.parse(fs.readFileSync(file, "utf8"));
19
+ }
20
+ export function writeManifest(file, manifest) {
21
+ fs.mkdirSync(path.dirname(file), { recursive: true });
22
+ fs.writeFileSync(file, JSON.stringify(manifest, null, 2) + "\n");
23
+ }
24
+ // Project manifests store paths relative to the repository root so that they
25
+ // stay valid in other clones. Global manifests store absolute paths.
26
+ export function toStored(entries, root) {
27
+ if (!root)
28
+ return entries;
29
+ return entries.map((entry) => ({ ...entry, path: path.relative(root, entry.path).split(path.sep).join("/") }));
30
+ }
31
+ export function fromStored(entries, root) {
32
+ if (!root)
33
+ return entries;
34
+ return entries.map((entry) => ({ ...entry, path: path.join(root, ...entry.path.split("/")) }));
35
+ }
package/dist/paths.js ADDED
@@ -0,0 +1,25 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ export function homeDir() {
5
+ return os.homedir();
6
+ }
7
+ export function claudeHome() {
8
+ return process.env.CLAUDE_CONFIG_DIR ?? path.join(homeDir(), ".claude");
9
+ }
10
+ export function codexHome() {
11
+ return process.env.CODEX_HOME ?? path.join(homeDir(), ".codex");
12
+ }
13
+ export function copilotHome() {
14
+ return process.env.COPILOT_HOME ?? path.join(homeDir(), ".copilot");
15
+ }
16
+ export function agentsHome() {
17
+ return path.join(homeDir(), ".agents");
18
+ }
19
+ export function configDir() {
20
+ const xdg = process.env.XDG_CONFIG_HOME;
21
+ return xdg ? path.join(xdg, "dotagents") : path.join(homeDir(), ".config", "dotagents");
22
+ }
23
+ // Works from both src/ (tests, scripts) and dist/ (installed package).
24
+ export const packageRoot = fileURLToPath(new URL("..", import.meta.url));
25
+ export const contentRoot = path.join(packageRoot, "content");