@canons-dev/canons 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +55 -0
- package/NOTICE +4 -0
- package/README.md +97 -2
- package/README.zh-CN.md +98 -0
- package/out/canon/core/locales/en/AGENTS.block.md +30 -0
- package/out/canon/core/locales/en/rules/layout.md +20 -0
- package/out/canon/core/locales/en/rules/vendor.md +12 -0
- package/out/canon/core/locales/zh-CN/AGENTS.block.md +30 -0
- package/out/canon/core/locales/zh-CN/rules/layout.md +20 -0
- package/out/canon/core/locales/zh-CN/rules/vendor.md +12 -0
- package/out/check.js +165 -0
- package/out/cli.js +133 -0
- package/out/config.js +111 -0
- package/out/content.js +116 -0
- package/out/doctor.js +39 -0
- package/out/rules.js +211 -0
- package/out/sync.js +157 -0
- package/package.json +42 -4
package/out/cli.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// canons CLI entry. Exit code 0 = ok, 1 = errors (or warnings with --strict).
|
|
3
|
+
import { realpathSync } from "node:fs";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { check } from "./check.js";
|
|
7
|
+
import { findRoot, loadConfig } from "./config.js";
|
|
8
|
+
import { packageVersion } from "./content.js";
|
|
9
|
+
import { doctor } from "./doctor.js";
|
|
10
|
+
import { changedScopePaths, expandScopePaths, loadScopeRules, matchScopeRules, } from "./rules.js";
|
|
11
|
+
import { init, sync } from "./sync.js";
|
|
12
|
+
const HELP = `canons ${packageVersion()}
|
|
13
|
+
|
|
14
|
+
Usage:
|
|
15
|
+
canons init [--locale <code>] create canons.json and run sync
|
|
16
|
+
canons sync [--accept-major] [--force]
|
|
17
|
+
write the AGENTS.md block, managed rules, client links, lock
|
|
18
|
+
canons check [--strict] deterministic hygiene checks (for CI and pre-commit)
|
|
19
|
+
canons scopes [--changed] [--json] <file-or-dir>...
|
|
20
|
+
list the rules that apply to the given paths
|
|
21
|
+
canons doctor environment diagnostics with fix hints
|
|
22
|
+
canons --version | --help
|
|
23
|
+
|
|
24
|
+
A rule with no match does not mean "no constraints": the root AGENTS.md still applies.`;
|
|
25
|
+
function takeOption(args, name) {
|
|
26
|
+
const at = args.indexOf(name);
|
|
27
|
+
if (at < 0)
|
|
28
|
+
return undefined;
|
|
29
|
+
const value = args[at + 1];
|
|
30
|
+
if (!value || value.startsWith("--"))
|
|
31
|
+
throw new Error(`${name} needs a value`);
|
|
32
|
+
args.splice(at, 2);
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
function assertFlags(args, allowed) {
|
|
36
|
+
const unknown = args.filter((a) => a.startsWith("--") && !allowed.includes(a));
|
|
37
|
+
if (unknown.length)
|
|
38
|
+
throw new Error(`unknown option ${unknown.join(", ")}; see canons --help`);
|
|
39
|
+
}
|
|
40
|
+
export function main(argv, cwd = process.cwd()) {
|
|
41
|
+
const args = [...argv];
|
|
42
|
+
const command = args.shift();
|
|
43
|
+
if (!command || command === "--help" || command === "-h") {
|
|
44
|
+
console.log(HELP);
|
|
45
|
+
return 0;
|
|
46
|
+
}
|
|
47
|
+
if (command === "--version" || command === "-v") {
|
|
48
|
+
console.log(packageVersion());
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
const root = findRoot(cwd);
|
|
52
|
+
switch (command) {
|
|
53
|
+
case "init": {
|
|
54
|
+
const locale = takeOption(args, "--locale");
|
|
55
|
+
assertFlags(args, []);
|
|
56
|
+
for (const line of init(root, locale))
|
|
57
|
+
console.log(line);
|
|
58
|
+
console.log('done. Next: write project rules outside the canons block, then run "canons check".');
|
|
59
|
+
return 0;
|
|
60
|
+
}
|
|
61
|
+
case "sync": {
|
|
62
|
+
assertFlags(args, ["--accept-major", "--force"]);
|
|
63
|
+
const log = sync(root, {
|
|
64
|
+
acceptMajor: args.includes("--accept-major"),
|
|
65
|
+
force: args.includes("--force"),
|
|
66
|
+
});
|
|
67
|
+
for (const line of log)
|
|
68
|
+
console.log(line);
|
|
69
|
+
if (!log.length)
|
|
70
|
+
console.log("already up to date");
|
|
71
|
+
return 0;
|
|
72
|
+
}
|
|
73
|
+
case "check": {
|
|
74
|
+
assertFlags(args, ["--strict"]);
|
|
75
|
+
const { errors, warnings } = check(root);
|
|
76
|
+
for (const e of errors)
|
|
77
|
+
console.log(`error ${e}`);
|
|
78
|
+
for (const w of warnings)
|
|
79
|
+
console.log(`warn ${w}`);
|
|
80
|
+
const failed = errors.length > 0 || (args.includes("--strict") && warnings.length > 0);
|
|
81
|
+
console.log(failed
|
|
82
|
+
? `canons check failed: ${errors.length} error(s), ${warnings.length} warning(s)`
|
|
83
|
+
: `canons check passed${warnings.length ? ` with ${warnings.length} warning(s)` : ""}`);
|
|
84
|
+
return failed ? 1 : 0;
|
|
85
|
+
}
|
|
86
|
+
case "scopes": {
|
|
87
|
+
assertFlags(args, ["--changed", "--json"]);
|
|
88
|
+
const changed = args.includes("--changed");
|
|
89
|
+
const inputs = args.filter((a) => !a.startsWith("--"));
|
|
90
|
+
if (!inputs.length && !changed)
|
|
91
|
+
throw new Error("pass files/directories, or --changed");
|
|
92
|
+
const config = loadConfig(root);
|
|
93
|
+
const paths = [
|
|
94
|
+
...new Set([
|
|
95
|
+
...expandScopePaths(root, inputs, cwd),
|
|
96
|
+
...(changed ? changedScopePaths(root) : []),
|
|
97
|
+
]),
|
|
98
|
+
].sort();
|
|
99
|
+
const rules = matchScopeRules(loadScopeRules(root, config.rulesDir), paths);
|
|
100
|
+
if (args.includes("--json")) {
|
|
101
|
+
console.log(JSON.stringify({ paths, rules }, null, 2));
|
|
102
|
+
return 0;
|
|
103
|
+
}
|
|
104
|
+
console.log(`${paths.length} path(s), ${rules.length} rule(s). Read every listed rule before editing.`);
|
|
105
|
+
for (const rule of rules) {
|
|
106
|
+
console.log(`\n${rule.file}`);
|
|
107
|
+
if (!rule.matches.length)
|
|
108
|
+
console.log(" global rule (no paths)");
|
|
109
|
+
for (const { path, glob } of rule.matches)
|
|
110
|
+
console.log(` ${path} <- ${glob}`);
|
|
111
|
+
}
|
|
112
|
+
return 0;
|
|
113
|
+
}
|
|
114
|
+
case "doctor":
|
|
115
|
+
assertFlags(args, []);
|
|
116
|
+
for (const line of doctor(root))
|
|
117
|
+
console.log(line);
|
|
118
|
+
return 0;
|
|
119
|
+
default:
|
|
120
|
+
throw new Error(`unknown command "${command}"; see canons --help`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const invokedDirectly = !!process.argv[1] &&
|
|
124
|
+
realpathSync(resolve(process.argv[1])) === realpathSync(fileURLToPath(import.meta.url));
|
|
125
|
+
if (invokedDirectly) {
|
|
126
|
+
try {
|
|
127
|
+
process.exitCode = main(process.argv.slice(2));
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
console.error(`canons: ${error.message}`);
|
|
131
|
+
process.exitCode = 1;
|
|
132
|
+
}
|
|
133
|
+
}
|
package/out/config.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// canons.json: the consumer's declaration. Unknown keys are rejected so typos
|
|
2
|
+
// cannot silently disable a setting.
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { dirname, resolve } from "node:path";
|
|
5
|
+
export const CONFIG_FILE = "canons.json";
|
|
6
|
+
export const LOCK_FILE = "canons.lock.json";
|
|
7
|
+
export const ROOT_FILE = "AGENTS.md";
|
|
8
|
+
/** Codex stops loading project instructions once their combined size reaches this (default `project_doc_max_bytes`). */
|
|
9
|
+
export const CODEX_CHAIN_MAX_BYTES = 32 * 1024;
|
|
10
|
+
export const CLIENTS = ["codex", "claude"];
|
|
11
|
+
export const DEFAULT_CONFIG = {
|
|
12
|
+
version: 1,
|
|
13
|
+
locale: "en",
|
|
14
|
+
clients: ["codex", "claude"],
|
|
15
|
+
rulesDir: ".agents/rules",
|
|
16
|
+
skillsDir: ".agents/skills",
|
|
17
|
+
budgetBytes: 24 * 1024,
|
|
18
|
+
presets: [],
|
|
19
|
+
hooks: false,
|
|
20
|
+
};
|
|
21
|
+
const KEYS = new Set([
|
|
22
|
+
"$schema",
|
|
23
|
+
"version",
|
|
24
|
+
"locale",
|
|
25
|
+
"clients",
|
|
26
|
+
"rulesDir",
|
|
27
|
+
"skillsDir",
|
|
28
|
+
"budgetBytes",
|
|
29
|
+
"ruleNamePattern",
|
|
30
|
+
"presets",
|
|
31
|
+
"hooks",
|
|
32
|
+
]);
|
|
33
|
+
export function parseConfig(raw) {
|
|
34
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
35
|
+
throw new Error(`${CONFIG_FILE} must be a JSON object`);
|
|
36
|
+
const obj = raw;
|
|
37
|
+
for (const key of Object.keys(obj))
|
|
38
|
+
if (!KEYS.has(key))
|
|
39
|
+
throw new Error(`${CONFIG_FILE}: unknown key "${key}"`);
|
|
40
|
+
const config = { ...DEFAULT_CONFIG, ...obj };
|
|
41
|
+
const fail = (msg) => {
|
|
42
|
+
throw new Error(`${CONFIG_FILE}: ${msg}`);
|
|
43
|
+
};
|
|
44
|
+
if (config.version !== 1)
|
|
45
|
+
fail(`unsupported version ${String(config.version)}`);
|
|
46
|
+
if (typeof config.locale !== "string" || !config.locale)
|
|
47
|
+
fail("locale must be a non-empty string");
|
|
48
|
+
if (!Array.isArray(config.clients) ||
|
|
49
|
+
config.clients.some((c) => !CLIENTS.includes(c)))
|
|
50
|
+
fail(`clients must be a list drawn from: ${CLIENTS.join(", ")}`);
|
|
51
|
+
for (const key of ["rulesDir", "skillsDir"]) {
|
|
52
|
+
const value = config[key];
|
|
53
|
+
if (typeof value !== "string" ||
|
|
54
|
+
!value ||
|
|
55
|
+
value.startsWith("/") ||
|
|
56
|
+
value.split("/").includes(".."))
|
|
57
|
+
fail(`${key} must be a repo-relative path`);
|
|
58
|
+
}
|
|
59
|
+
if (!Number.isInteger(config.budgetBytes) || config.budgetBytes <= 0)
|
|
60
|
+
fail("budgetBytes must be a positive integer");
|
|
61
|
+
if (config.budgetBytes > CODEX_CHAIN_MAX_BYTES)
|
|
62
|
+
fail(`budgetBytes must not exceed ${CODEX_CHAIN_MAX_BYTES} (Codex stops loading instructions beyond that)`);
|
|
63
|
+
if (config.ruleNamePattern !== undefined) {
|
|
64
|
+
if (typeof config.ruleNamePattern !== "string")
|
|
65
|
+
fail("ruleNamePattern must be a string");
|
|
66
|
+
try {
|
|
67
|
+
new RegExp(config.ruleNamePattern);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
fail("ruleNamePattern is not a valid regular expression");
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (!Array.isArray(config.presets))
|
|
74
|
+
fail("presets must be a list");
|
|
75
|
+
if (config.presets.length)
|
|
76
|
+
fail("presets are not available in this version; leave the list empty");
|
|
77
|
+
if (typeof config.hooks !== "boolean")
|
|
78
|
+
fail("hooks must be true or false");
|
|
79
|
+
if (config.hooks)
|
|
80
|
+
fail("hooks are not available in this version; set hooks to false");
|
|
81
|
+
return config;
|
|
82
|
+
}
|
|
83
|
+
export function loadConfig(root) {
|
|
84
|
+
const file = resolve(root, CONFIG_FILE);
|
|
85
|
+
if (!existsSync(file))
|
|
86
|
+
throw new Error(`${CONFIG_FILE} not found in ${root}; run "canons init"`);
|
|
87
|
+
let raw;
|
|
88
|
+
try {
|
|
89
|
+
raw = JSON.parse(readFileSync(file, "utf8"));
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
throw new Error(`${CONFIG_FILE} is not valid JSON: ${error.message}`);
|
|
93
|
+
}
|
|
94
|
+
return parseConfig(raw);
|
|
95
|
+
}
|
|
96
|
+
/** Walks up from `start` to the nearest directory holding canons.json, else the git root. */
|
|
97
|
+
export function findRoot(start) {
|
|
98
|
+
let dir = resolve(start);
|
|
99
|
+
let gitRoot;
|
|
100
|
+
for (;;) {
|
|
101
|
+
if (existsSync(resolve(dir, CONFIG_FILE)))
|
|
102
|
+
return dir;
|
|
103
|
+
if (!gitRoot && existsSync(resolve(dir, ".git")))
|
|
104
|
+
gitRoot = dir;
|
|
105
|
+
const parent = dirname(dir);
|
|
106
|
+
if (parent === dir)
|
|
107
|
+
break;
|
|
108
|
+
dir = parent;
|
|
109
|
+
}
|
|
110
|
+
return gitRoot ?? resolve(start);
|
|
111
|
+
}
|
package/out/content.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// Content shipped in this package (canon/) and the managed-block / lock formats.
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
4
|
+
import { dirname, resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { listMarkdown } from "./rules.js";
|
|
7
|
+
// The modules run from src/ in development and from out/ when installed; both
|
|
8
|
+
// sit one level below the package root, and each holds its own canon/ copy
|
|
9
|
+
// (the build copies src/canon to out/canon).
|
|
10
|
+
export const CONTENT_ROOT = dirname(fileURLToPath(import.meta.url));
|
|
11
|
+
export const PACKAGE_ROOT = resolve(CONTENT_ROOT, "..");
|
|
12
|
+
/** Managed rule files live in this subdirectory of the consumer's rulesDir. */
|
|
13
|
+
export const MANAGED_SUBDIR = "canons";
|
|
14
|
+
export function sha256(text) {
|
|
15
|
+
return createHash("sha256").update(text).digest("hex");
|
|
16
|
+
}
|
|
17
|
+
export function packageVersion(root = PACKAGE_ROOT) {
|
|
18
|
+
return JSON.parse(readFileSync(resolve(root, "package.json"), "utf8")).version;
|
|
19
|
+
}
|
|
20
|
+
export function availableLocales(root = CONTENT_ROOT) {
|
|
21
|
+
return readdirSync(resolve(root, "canon/core/locales"), {
|
|
22
|
+
withFileTypes: true,
|
|
23
|
+
})
|
|
24
|
+
.filter((e) => e.isDirectory())
|
|
25
|
+
.map((e) => e.name)
|
|
26
|
+
.sort();
|
|
27
|
+
}
|
|
28
|
+
/** `root` is the directory holding `canon/` (src/ or out/). */
|
|
29
|
+
export function loadCanon(locale, root = CONTENT_ROOT) {
|
|
30
|
+
const dir = resolve(root, "canon/core/locales", locale);
|
|
31
|
+
if (!existsSync(dir))
|
|
32
|
+
throw new Error(`locale "${locale}" is not shipped; available: ${availableLocales(root).join(", ")}`);
|
|
33
|
+
const rules = new Map();
|
|
34
|
+
const rulesDir = resolve(dir, "rules");
|
|
35
|
+
if (existsSync(rulesDir))
|
|
36
|
+
for (const file of listMarkdown(rulesDir))
|
|
37
|
+
rules.set(file, readFileSync(resolve(rulesDir, file), "utf8"));
|
|
38
|
+
return {
|
|
39
|
+
version: packageVersion(resolve(root, "..")),
|
|
40
|
+
locale,
|
|
41
|
+
block: readFileSync(resolve(dir, "AGENTS.block.md"), "utf8").trim(),
|
|
42
|
+
rules,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
// ---- managed block -------------------------------------------------------
|
|
46
|
+
const BEGIN_RE = /^<!-- canons:begin ([^\n]*?) -->$/m;
|
|
47
|
+
const END = "<!-- canons:end -->";
|
|
48
|
+
export function renderBlock(canon) {
|
|
49
|
+
return [
|
|
50
|
+
`<!-- canons:begin version=${canon.version} locale=${canon.locale} sha256=${sha256(canon.block)} -->`,
|
|
51
|
+
"<!-- Generated by canons. Do not edit inside this block: run `canons sync`. Put project rules outside it. -->",
|
|
52
|
+
"",
|
|
53
|
+
canon.block,
|
|
54
|
+
"",
|
|
55
|
+
END,
|
|
56
|
+
].join("\n");
|
|
57
|
+
}
|
|
58
|
+
export function extractBlock(text) {
|
|
59
|
+
const normalized = text.replace(/\r\n/g, "\n");
|
|
60
|
+
const begins = normalized.match(new RegExp(BEGIN_RE.source, "gm")) ?? [];
|
|
61
|
+
const ends = normalized.split(END).length - 1;
|
|
62
|
+
if (!begins.length && !ends)
|
|
63
|
+
return undefined;
|
|
64
|
+
if (begins.length !== 1 || ends !== 1)
|
|
65
|
+
throw new Error("AGENTS.md must contain exactly one canons:begin / canons:end pair");
|
|
66
|
+
const m = BEGIN_RE.exec(normalized);
|
|
67
|
+
const start = m.index;
|
|
68
|
+
const endAt = normalized.indexOf(END, start);
|
|
69
|
+
if (endAt < 0)
|
|
70
|
+
throw new Error("canons:end appears before canons:begin");
|
|
71
|
+
const attrs = Object.fromEntries(m[1]
|
|
72
|
+
.split(/\s+/)
|
|
73
|
+
.filter(Boolean)
|
|
74
|
+
.map((pair) => {
|
|
75
|
+
const at = pair.indexOf("=");
|
|
76
|
+
return [pair.slice(0, at), pair.slice(at + 1)];
|
|
77
|
+
}));
|
|
78
|
+
const inner = normalized.slice(start + m[0].length, endAt).split("\n");
|
|
79
|
+
// Drop the generated "Do not edit" comment line.
|
|
80
|
+
const bodyLines = inner.filter((line, i) => !(i <= 1 && line.startsWith("<!-- Generated by canons.")));
|
|
81
|
+
return {
|
|
82
|
+
attrs,
|
|
83
|
+
body: bodyLines.join("\n").trim(),
|
|
84
|
+
start,
|
|
85
|
+
end: endAt + END.length,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** Replaces the block in `text`, or inserts it at the top (after a leading H1, if any). */
|
|
89
|
+
export function upsertBlock(text, block) {
|
|
90
|
+
const normalized = text.replace(/\r\n/g, "\n");
|
|
91
|
+
const info = extractBlock(normalized);
|
|
92
|
+
if (info)
|
|
93
|
+
return normalized.slice(0, info.start) + block + normalized.slice(info.end);
|
|
94
|
+
const h1 = normalized.match(/^# [^\n]*\n/);
|
|
95
|
+
if (h1)
|
|
96
|
+
return `${h1[0]}\n${block}\n\n${normalized.slice(h1[0].length).replace(/^\n+/, "")}`;
|
|
97
|
+
return `${block}\n\n${normalized.replace(/^\n+/, "")}`;
|
|
98
|
+
}
|
|
99
|
+
export function parseLock(text) {
|
|
100
|
+
const lock = JSON.parse(text);
|
|
101
|
+
if (lock.lockfileVersion !== 1 || typeof lock.files !== "object")
|
|
102
|
+
throw new Error("canons.lock.json has an unsupported format");
|
|
103
|
+
return lock;
|
|
104
|
+
}
|
|
105
|
+
export function renderLock(lock) {
|
|
106
|
+
const files = Object.fromEntries(Object.entries(lock.files).sort(([a], [b]) => a.localeCompare(b)));
|
|
107
|
+
return `${JSON.stringify({ ...lock, files }, null, 2)}\n`;
|
|
108
|
+
}
|
|
109
|
+
/** True when going from `from` to `to` crosses a breaking boundary (major, or minor while 0.x). */
|
|
110
|
+
export function isBreakingUpgrade(from, to) {
|
|
111
|
+
const [fa = 0, fb = 0] = from.split(".").map(Number);
|
|
112
|
+
const [ta = 0, tb = 0] = to.split(".").map(Number);
|
|
113
|
+
if (ta !== fa)
|
|
114
|
+
return ta > fa;
|
|
115
|
+
return fa === 0 && tb > fb;
|
|
116
|
+
}
|
package/out/doctor.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// `canons doctor`: environment diagnostics with fix hints. Informational only.
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import { loadConfig } from "./config.js";
|
|
6
|
+
export function doctor(root) {
|
|
7
|
+
const out = [];
|
|
8
|
+
const [major = 0] = process.versions.node.split(".").map(Number);
|
|
9
|
+
out.push(major >= 22
|
|
10
|
+
? `ok Node ${process.versions.node}`
|
|
11
|
+
: `fix Node ${process.versions.node} is below the supported 22`);
|
|
12
|
+
try {
|
|
13
|
+
const symlinks = execFileSync("git", ["config", "--get", "core.symlinks"], {
|
|
14
|
+
cwd: root,
|
|
15
|
+
encoding: "utf8",
|
|
16
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
17
|
+
}).trim();
|
|
18
|
+
if (symlinks === "false")
|
|
19
|
+
out.push("fix git core.symlinks=false: client adapters would be checked out as plain files. Run `git config core.symlinks true` (on Windows enable Developer Mode first) and re-checkout.");
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
// Unset means the platform default (true outside Windows).
|
|
23
|
+
}
|
|
24
|
+
let clients = [];
|
|
25
|
+
try {
|
|
26
|
+
clients = loadConfig(root).clients;
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
out.push(`fix ${error.message}`);
|
|
30
|
+
}
|
|
31
|
+
if (clients.includes("codex"))
|
|
32
|
+
out.push("note Codex skips project AGENTS.md when the project is not trusted: trust this project in Codex.", "note Codex reads .agents/skills natively; no adapter needed.");
|
|
33
|
+
if (clients.includes("claude"))
|
|
34
|
+
out.push("note Claude Code loads .claude/rules recursively and honors only the `paths` frontmatter key; queries via `canons scopes` still apply.");
|
|
35
|
+
out.push("note Cursor and GitHub Copilot read AGENTS.md natively. For Gemini CLI set context.fileName to [\"AGENTS.md\"] in .gemini/settings.json.");
|
|
36
|
+
if (existsSync(resolve(root, ".codex/hooks.json")))
|
|
37
|
+
out.push("note .codex/hooks.json found: Codex runs repo hooks only after you review and trust them (/hooks).");
|
|
38
|
+
return out;
|
|
39
|
+
}
|
package/out/rules.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
// Rule files: frontmatter parsing, glob matching and scope queries.
|
|
2
|
+
// Read-only, no network. Unsupported syntax must throw: a silently ignored
|
|
3
|
+
// declaration means a rule that never fires.
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
5
|
+
import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
6
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
7
|
+
/** Parses a top-level YAML block list (`key:` followed by ` - item` lines). */
|
|
8
|
+
export function parseListKey(source, key) {
|
|
9
|
+
const fm = frontmatter(source);
|
|
10
|
+
if (fm === undefined)
|
|
11
|
+
throw new Error("rule is missing YAML frontmatter");
|
|
12
|
+
const lines = fm.split("\n");
|
|
13
|
+
const keyRe = new RegExp(`^${key}:(?:\\s|$)`);
|
|
14
|
+
const start = lines.findIndex((line) => keyRe.test(line));
|
|
15
|
+
if (start < 0)
|
|
16
|
+
return [];
|
|
17
|
+
if (lines[start].trim() !== `${key}:`)
|
|
18
|
+
throw new Error(`${key} must be a YAML block list`);
|
|
19
|
+
const result = [];
|
|
20
|
+
for (const line of lines.slice(start + 1)) {
|
|
21
|
+
if (/^\S/.test(line))
|
|
22
|
+
break;
|
|
23
|
+
if (!line.trim() || line.trim().startsWith("#"))
|
|
24
|
+
continue;
|
|
25
|
+
const item = line.match(/^\s+-\s+(?:"([^"\n]+)"|'([^'\n]+)'|([^'"\s][^\n]*?))\s*$/);
|
|
26
|
+
if (!item)
|
|
27
|
+
throw new Error(`cannot parse ${key} entry: ${line}`);
|
|
28
|
+
// An unquoted value containing " #" would become part of the glob and never match.
|
|
29
|
+
if (/\s#/.test(item[3] ?? ""))
|
|
30
|
+
throw new Error(`${key} does not support trailing comments: ${line}`);
|
|
31
|
+
result.push((item[1] ?? item[2] ?? item[3]));
|
|
32
|
+
}
|
|
33
|
+
if (!result.length)
|
|
34
|
+
throw new Error(`${key} must not be empty`);
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
export function frontmatter(source) {
|
|
38
|
+
return source
|
|
39
|
+
.replace(/\r\n/g, "\n")
|
|
40
|
+
.match(/^---\n([\s\S]*?)\n---(?:\n|$)/)?.[1];
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Supported syntax: `*` (within a segment), `?` (one char), `**` (any depth;
|
|
44
|
+
* `**\/` also matches zero directories). Parentheses and brackets are literal,
|
|
45
|
+
* because frameworks such as Next.js use them in real paths.
|
|
46
|
+
*/
|
|
47
|
+
export function globToRe(glob) {
|
|
48
|
+
if (!glob ||
|
|
49
|
+
glob.startsWith("/") ||
|
|
50
|
+
glob.split("/").includes("..") ||
|
|
51
|
+
/[{}!\\]/.test(glob))
|
|
52
|
+
throw new Error(`unsupported rule path: ${glob} (use repo-relative paths with *, ?, **)`);
|
|
53
|
+
let pattern = "^";
|
|
54
|
+
for (let i = 0; i < glob.length; i++) {
|
|
55
|
+
const char = glob[i];
|
|
56
|
+
if (char === "*" && glob[i + 1] === "*") {
|
|
57
|
+
i++;
|
|
58
|
+
if (glob[i + 1] === "/") {
|
|
59
|
+
pattern += "(?:.*/)?";
|
|
60
|
+
i++;
|
|
61
|
+
}
|
|
62
|
+
else
|
|
63
|
+
pattern += ".*";
|
|
64
|
+
}
|
|
65
|
+
else if (char === "*")
|
|
66
|
+
pattern += "[^/]*";
|
|
67
|
+
else if (char === "?")
|
|
68
|
+
pattern += "[^/]";
|
|
69
|
+
else
|
|
70
|
+
pattern += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
71
|
+
}
|
|
72
|
+
return new RegExp(`${pattern}$`);
|
|
73
|
+
}
|
|
74
|
+
/** The directory part of a glob before its first wildcard segment. */
|
|
75
|
+
export function staticPrefix(glob) {
|
|
76
|
+
const parts = glob.split("/");
|
|
77
|
+
const wildcard = parts.findIndex((part) => /[*?]/.test(part));
|
|
78
|
+
return (wildcard < 0 ? parts : parts.slice(0, wildcard)).join("/");
|
|
79
|
+
}
|
|
80
|
+
export function normalizeScopePath(root, input, cwd = root) {
|
|
81
|
+
const path = relative(resolve(root), resolve(cwd, input));
|
|
82
|
+
if (isAbsolute(path) || path === ".." || path.startsWith(`..${sep}`))
|
|
83
|
+
throw new Error(`path is outside the repository: ${input}`);
|
|
84
|
+
return path.split(sep).join("/");
|
|
85
|
+
}
|
|
86
|
+
// A path entered through a symlink (e.g. .claude/rules -> ../.agents/rules) is
|
|
87
|
+
// mapped to its real path: git tracks the link, not the files behind it.
|
|
88
|
+
function realScopePath(root, path) {
|
|
89
|
+
try {
|
|
90
|
+
return normalizeScopePath(realpathSync(root), realpathSync(resolve(root, path)));
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// A planned file that does not exist yet, or a link leaving the repo.
|
|
94
|
+
return path;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** Lists `.md` files under `dir`, recursively, as sorted relative paths. */
|
|
98
|
+
export function listMarkdown(dir) {
|
|
99
|
+
const out = [];
|
|
100
|
+
const walk = (sub) => {
|
|
101
|
+
for (const entry of readdirSync(resolve(dir, sub), {
|
|
102
|
+
withFileTypes: true,
|
|
103
|
+
})) {
|
|
104
|
+
const rel = sub ? `${sub}/${entry.name}` : entry.name;
|
|
105
|
+
if (entry.isDirectory())
|
|
106
|
+
walk(rel);
|
|
107
|
+
else if (entry.name.endsWith(".md"))
|
|
108
|
+
out.push(rel);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
walk("");
|
|
112
|
+
return out.sort();
|
|
113
|
+
}
|
|
114
|
+
export function loadScopeRules(root, rulesDir) {
|
|
115
|
+
const files = listMarkdown(resolve(root, rulesDir));
|
|
116
|
+
if (!files.length)
|
|
117
|
+
throw new Error(`rules directory is empty: ${rulesDir}`);
|
|
118
|
+
return files.map((file) => {
|
|
119
|
+
const source = readFileSync(resolve(root, rulesDir, file), "utf8");
|
|
120
|
+
let paths;
|
|
121
|
+
try {
|
|
122
|
+
paths = parseListKey(source, "paths");
|
|
123
|
+
for (const path of paths)
|
|
124
|
+
globToRe(path);
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
throw new Error(`${rulesDir}/${file}: ${error.message}`);
|
|
128
|
+
}
|
|
129
|
+
return { file: `${rulesDir}/${file}`, paths };
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/** Rules without `paths` are global and always returned. */
|
|
133
|
+
export function matchScopeRules(rules, paths) {
|
|
134
|
+
return rules.flatMap((rule) => {
|
|
135
|
+
const matches = rule.paths.flatMap((glob) => {
|
|
136
|
+
const re = globToRe(glob);
|
|
137
|
+
return paths
|
|
138
|
+
.filter((path) => re.test(path))
|
|
139
|
+
.map((path) => ({ path, glob }));
|
|
140
|
+
});
|
|
141
|
+
return matches.length || !rule.paths.length
|
|
142
|
+
? [{ file: rule.file, matches }]
|
|
143
|
+
: [];
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
export function gitPaths(root, args) {
|
|
147
|
+
return execFileSync("git", args, {
|
|
148
|
+
cwd: root,
|
|
149
|
+
encoding: "utf8",
|
|
150
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
151
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
152
|
+
})
|
|
153
|
+
.split("\0")
|
|
154
|
+
.filter(Boolean);
|
|
155
|
+
}
|
|
156
|
+
/** Tracked and untracked-but-not-ignored files. */
|
|
157
|
+
export function repoFiles(root) {
|
|
158
|
+
return gitPaths(root, [
|
|
159
|
+
"ls-files",
|
|
160
|
+
"--cached",
|
|
161
|
+
"--others",
|
|
162
|
+
"--exclude-standard",
|
|
163
|
+
"-z",
|
|
164
|
+
]);
|
|
165
|
+
}
|
|
166
|
+
export function changedScopePaths(root) {
|
|
167
|
+
const hasHead = (() => {
|
|
168
|
+
try {
|
|
169
|
+
gitPaths(root, ["rev-parse", "--verify", "-q", "HEAD"]);
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
})();
|
|
176
|
+
// Staged and unstaged are unioned separately so they cannot cancel out;
|
|
177
|
+
// --no-renames keeps both the old and new path of a rename.
|
|
178
|
+
return [
|
|
179
|
+
...new Set([
|
|
180
|
+
...(hasHead
|
|
181
|
+
? gitPaths(root, [
|
|
182
|
+
"diff",
|
|
183
|
+
"--cached",
|
|
184
|
+
"--name-only",
|
|
185
|
+
"--no-renames",
|
|
186
|
+
"-z",
|
|
187
|
+
"HEAD",
|
|
188
|
+
"--",
|
|
189
|
+
])
|
|
190
|
+
: gitPaths(root, ["diff", "--cached", "--name-only", "-z", "--"])),
|
|
191
|
+
...gitPaths(root, ["diff", "--name-only", "--no-renames", "-z", "--"]),
|
|
192
|
+
...gitPaths(root, ["ls-files", "--others", "--exclude-standard", "-z"]),
|
|
193
|
+
]),
|
|
194
|
+
].sort();
|
|
195
|
+
}
|
|
196
|
+
/** Files are kept as given (planned files included); directories expand to their files. */
|
|
197
|
+
export function expandScopePaths(root, inputs, cwd = root) {
|
|
198
|
+
let files;
|
|
199
|
+
return [
|
|
200
|
+
...new Set(inputs.flatMap((input) => {
|
|
201
|
+
const path = normalizeScopePath(root, input, cwd);
|
|
202
|
+
const real = realScopePath(root, path);
|
|
203
|
+
if (!statSync(resolve(root, path), {
|
|
204
|
+
throwIfNoEntry: false,
|
|
205
|
+
})?.isDirectory())
|
|
206
|
+
return [path, real];
|
|
207
|
+
files ??= repoFiles(root);
|
|
208
|
+
return files.filter((file) => !real || file.startsWith(`${real}/`));
|
|
209
|
+
})),
|
|
210
|
+
].sort();
|
|
211
|
+
}
|