@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/out/sync.js ADDED
@@ -0,0 +1,157 @@
1
+ // `canons init` / `canons sync`: write the managed block, managed rules,
2
+ // client adapters and the lock. Never overwrites local edits silently.
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, readdirSync, rmSync, symlinkSync, writeFileSync, } from "node:fs";
4
+ import { dirname, posix, relative, resolve } from "node:path";
5
+ import { CONFIG_FILE, DEFAULT_CONFIG, LOCK_FILE, ROOT_FILE, loadConfig, } from "./config.js";
6
+ import { MANAGED_SUBDIR, CONTENT_ROOT, extractBlock, isBreakingUpgrade, loadCanon, parseLock, renderBlock, renderLock, sha256, upsertBlock, } from "./content.js";
7
+ import { listMarkdown } from "./rules.js";
8
+ const PROJECT_TEMPLATE = `## Project rules
9
+
10
+ <!-- Project-specific red lines, stack, naming and verification commands go here, outside the canons block. -->
11
+ `;
12
+ export function readLock(root) {
13
+ const file = resolve(root, LOCK_FILE);
14
+ return existsSync(file) ? parseLock(readFileSync(file, "utf8")) : undefined;
15
+ }
16
+ /** Client adapter links: link path -> relative target, both repo-relative. */
17
+ export function clientLinks(config) {
18
+ const links = new Map();
19
+ if (config.clients.includes("claude")) {
20
+ links.set("CLAUDE.md", ROOT_FILE);
21
+ links.set(".claude/rules", posix.relative(".claude", config.rulesDir));
22
+ links.set(".claude/skills", posix.relative(".claude", config.skillsDir));
23
+ }
24
+ return links;
25
+ }
26
+ export function managedRulePath(config, file) {
27
+ return `${config.rulesDir}/${MANAGED_SUBDIR}/${file}`;
28
+ }
29
+ export function sync(root, options = {}) {
30
+ const log = [];
31
+ const config = loadConfig(root);
32
+ const canon = loadCanon(config.locale, options.contentRoot ?? CONTENT_ROOT);
33
+ const lock = readLock(root);
34
+ if (lock && isBreakingUpgrade(lock.canons, canon.version) && !options.acceptMajor)
35
+ throw new Error(`canons ${lock.canons} -> ${canon.version} is a breaking upgrade of the rules. Review the changelog, then rerun with --accept-major.`);
36
+ // Refuse to overwrite local edits to managed content.
37
+ const rootPath = resolve(root, ROOT_FILE);
38
+ const rootText = existsSync(rootPath) ? readFileSync(rootPath, "utf8") : "";
39
+ const edited = [];
40
+ const current = rootText ? extractBlock(rootText) : undefined;
41
+ if (current && sha256(current.body) !== current.attrs.sha256)
42
+ edited.push(`${ROOT_FILE} (managed block)`);
43
+ for (const [path, hash] of Object.entries(lock?.files ?? {})) {
44
+ const abs = resolve(root, path);
45
+ if (existsSync(abs) && sha256(readFileSync(abs, "utf8")) !== hash)
46
+ edited.push(path);
47
+ }
48
+ const managedDir = resolve(root, config.rulesDir, MANAGED_SUBDIR);
49
+ const known = new Set([
50
+ ...Object.keys(lock?.files ?? {}),
51
+ ...[...canon.rules.keys()].map((f) => managedRulePath(config, f)),
52
+ ]);
53
+ if (existsSync(managedDir))
54
+ for (const file of listMarkdown(managedDir)) {
55
+ const path = managedRulePath(config, file);
56
+ if (!known.has(path))
57
+ edited.push(`${path} (not managed by canons)`);
58
+ }
59
+ if (edited.length && !options.force)
60
+ throw new Error(`local edits to managed content:\n ${edited.join("\n ")}\nMove project-specific text outside the canons block / ${config.rulesDir}/${MANAGED_SUBDIR}/, or rerun with --force to discard the edits.`);
61
+ // Root file and block.
62
+ const block = renderBlock(canon);
63
+ const nextRoot = rootText
64
+ ? upsertBlock(rootText, block)
65
+ : `# AGENTS.md\n\n${block}\n\n${PROJECT_TEMPLATE}`;
66
+ if (nextRoot !== rootText.replace(/\r\n/g, "\n")) {
67
+ writeFileSync(rootPath, nextRoot);
68
+ log.push(`${rootText ? "updated" : "created"} ${ROOT_FILE}`);
69
+ }
70
+ // Managed rules: write shipped files, remove ones no longer shipped.
71
+ const files = {};
72
+ for (const [file, text] of canon.rules) {
73
+ const path = managedRulePath(config, file);
74
+ const abs = resolve(root, path);
75
+ mkdirSync(dirname(abs), { recursive: true });
76
+ if (!existsSync(abs) || readFileSync(abs, "utf8") !== text) {
77
+ writeFileSync(abs, text);
78
+ log.push(`wrote ${path}`);
79
+ }
80
+ files[path] = sha256(text);
81
+ }
82
+ for (const path of Object.keys(lock?.files ?? {}))
83
+ if (!(path in files) && existsSync(resolve(root, path))) {
84
+ rmSync(resolve(root, path));
85
+ log.push(`removed ${path}`);
86
+ }
87
+ if (existsSync(managedDir))
88
+ for (const file of listMarkdown(managedDir)) {
89
+ const path = managedRulePath(config, file);
90
+ if (!(path in files)) {
91
+ rmSync(resolve(root, path));
92
+ log.push(`removed ${path}`);
93
+ }
94
+ }
95
+ // Git does not track empty directories; without a placeholder a fresh clone
96
+ // would get a dangling .claude/skills link.
97
+ const skillsAbs = resolve(root, config.skillsDir);
98
+ mkdirSync(skillsAbs, { recursive: true });
99
+ if (!readdirSync(skillsAbs).length) {
100
+ writeFileSync(resolve(skillsAbs, ".gitkeep"), "");
101
+ log.push(`created ${config.skillsDir}/.gitkeep`);
102
+ }
103
+ // Client adapters (relative symlinks; never clobber a real file).
104
+ for (const [link, target] of clientLinks(config)) {
105
+ const abs = resolve(root, link);
106
+ const stat = lstatSync(abs, { throwIfNoEntry: false });
107
+ if (stat?.isSymbolicLink() && readlinkSync(abs) === target)
108
+ continue;
109
+ if (stat)
110
+ throw new Error(`${link} exists but is not a symlink to ${target}. Merge its content into ${ROOT_FILE} (outside the canons block) or ${config.rulesDir}, remove it, and rerun.`);
111
+ mkdirSync(dirname(abs), { recursive: true });
112
+ symlinkSync(target, abs);
113
+ log.push(`linked ${link} -> ${target}`);
114
+ }
115
+ const nextLock = {
116
+ lockfileVersion: 1,
117
+ canons: canon.version,
118
+ locale: canon.locale,
119
+ block: sha256(canon.block),
120
+ files,
121
+ };
122
+ const lockText = renderLock(nextLock);
123
+ const lockPath = resolve(root, LOCK_FILE);
124
+ if (!existsSync(lockPath) || readFileSync(lockPath, "utf8") !== lockText) {
125
+ writeFileSync(lockPath, lockText);
126
+ log.push(`wrote ${LOCK_FILE}`);
127
+ }
128
+ return log;
129
+ }
130
+ export function init(root, locale = DEFAULT_CONFIG.locale, options = {}) {
131
+ const configPath = resolve(root, CONFIG_FILE);
132
+ if (existsSync(configPath))
133
+ throw new Error(`${CONFIG_FILE} already exists; run "canons sync"`);
134
+ // Validate the locale before writing anything.
135
+ loadCanon(locale, options.contentRoot ?? CONTENT_ROOT);
136
+ const config = { version: 1, locale, clients: DEFAULT_CONFIG.clients };
137
+ writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`);
138
+ return [`created ${CONFIG_FILE}`, ...sync(root, options)];
139
+ }
140
+ /** Used by check: lists repo-relative paths of files under a dir, recursively. */
141
+ export function filesUnder(root, dir) {
142
+ const abs = resolve(root, dir);
143
+ if (!existsSync(abs))
144
+ return [];
145
+ const out = [];
146
+ const walk = (sub) => {
147
+ for (const e of readdirSync(resolve(abs, sub), { withFileTypes: true })) {
148
+ const rel = sub ? `${sub}/${e.name}` : e.name;
149
+ if (e.isDirectory())
150
+ walk(rel);
151
+ else
152
+ out.push(relative(root, resolve(abs, rel)).split("\\").join("/"));
153
+ }
154
+ };
155
+ walk("");
156
+ return out.sort();
157
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@canons-dev/canons",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "One source of truth for coding-agent instructions (AGENTS.md, path-scoped rules, skills) shared by Codex, Claude Code and other clients, with deterministic checks.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "canons": "out/cli.js"
9
+ },
10
+ "files": [
11
+ "out",
12
+ "LICENSE",
13
+ "NOTICE",
14
+ "README.md",
15
+ "README.zh-CN.md"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22"
19
+ },
20
+ "scripts": {
21
+ "build": "node src/build.ts",
22
+ "typecheck": "tsc -p tsconfig.json",
23
+ "test": "node --test \"src/test/**/*.test.ts\"",
24
+ "prepack": "npm run build"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/canons-dev/canons.git"
29
+ },
30
+ "homepage": "https://github.com/canons-dev/canons#readme",
31
+ "bugs": "https://github.com/canons-dev/canons/issues",
32
+ "keywords": [
33
+ "agents-md",
34
+ "codex",
35
+ "claude-code",
36
+ "coding-agent",
37
+ "rules",
38
+ "conventions"
39
+ ],
40
+ "devDependencies": {
41
+ "@types/node": "^22.20.5",
42
+ "typescript": "^6.0.3"
43
+ }
44
+ }