@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 ADDED
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ canons
2
+ Copyright 2026 The canons authors
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,98 @@
1
- # Temporary Holding Version
1
+ # canons
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One source of truth for the instructions your coding agents follow — `AGENTS.md`, path-scoped rules and skills — shared by Codex, Claude Code and other clients, and kept honest by deterministic checks.
4
+
5
+ [简体中文](README.zh-CN.md)
6
+
7
+ ## Why
8
+
9
+ Teams that use more than one coding agent end up with `AGENTS.md`, `CLAUDE.md`, `.cursor/rules` and friends drifting apart, rules that only one client loads, and red lines that quietly disappear when someone trims a file. canons gives every repository the same layout and a small CLI that enforces it:
10
+
11
+ - **One copy of every instruction.** `AGENTS.md`, `.agents/rules/` and `.agents/skills/` are the only real files; client entry points are relative symlinks.
12
+ - **Path-scoped rules for every client.** Rules declare `paths` in frontmatter. Claude Code loads them natively; for every other client the root instructions require `canons scopes <path>` before editing and `canons scopes --changed` before finishing.
13
+ - **A shared baseline.** A managed block in `AGENTS.md` carries agent conventions (Git authority, verification, handoffs, documentation hygiene). Your project rules live outside the block.
14
+ - **Deterministic guards.** `canons check` catches hand-edited managed content, copies instead of links, broken rule links, an `AGENTS.override.md` that would make Codex skip `AGENTS.md`, and instruction chains over the 32 KiB Codex reads.
15
+
16
+ ## Quick start
17
+
18
+ Requires Node 22 or newer and a git repository.
19
+
20
+ ```sh
21
+ npm install --save-dev @canons-dev/canons
22
+ npx canons init # or: npx canons init --locale zh-CN
23
+ npx canons check
24
+ ```
25
+
26
+ The package installs a `canons` command; install it as a dev dependency so that `npx canons`, which the managed rules tell agents to run, resolves to the pinned local copy. `init` creates `canons.json`, inserts the managed block into `AGENTS.md` (creating it if needed), writes the managed rules to `.agents/rules/canons/`, links the Claude Code entry points and writes `canons.lock.json`. Commit all of them.
27
+
28
+ Then add your own rules:
29
+
30
+ ```md
31
+ <!-- .agents/rules/apis.md -->
32
+ ---
33
+ paths:
34
+ - "src/api/**"
35
+ ---
36
+
37
+ # API handlers
38
+
39
+ - Validate every request body at the boundary.
40
+ ```
41
+
42
+ ```sh
43
+ npx canons scopes src/api/users.ts # which rules apply here?
44
+ npx canons scopes --changed # which rules apply to my diff?
45
+ ```
46
+
47
+ ## Commands
48
+
49
+ | Command | What it does |
50
+ | --- | --- |
51
+ | `canons init [--locale <code>]` | Create `canons.json` and run `sync`. |
52
+ | `canons sync [--accept-major] [--force]` | Update the managed block, managed rules, client links and lock. Refuses to overwrite hand edits unless `--force`; refuses breaking rule upgrades unless `--accept-major`. |
53
+ | `canons check [--strict]` | Deterministic checks; exit code 1 on errors (or on warnings with `--strict`). |
54
+ | `canons scopes [--changed] [--json] <path>...` | List the rules whose `paths` match. Rules without `paths` are global and always listed. |
55
+ | `canons doctor` | Environment hints (symlink support, Codex trust, other clients). |
56
+
57
+ ## Configuration
58
+
59
+ `canons.json` (all keys except `version` are optional):
60
+
61
+ ```json
62
+ {
63
+ "version": 1,
64
+ "locale": "en",
65
+ "clients": ["codex", "claude"],
66
+ "rulesDir": ".agents/rules",
67
+ "skillsDir": ".agents/skills",
68
+ "budgetBytes": 24576,
69
+ "ruleNamePattern": "^[a-z-]+$"
70
+ }
71
+ ```
72
+
73
+ - `budgetBytes` limits the root `AGENTS.md` alone (default 24 KiB, at most 32 KiB) so nested instruction files still fit in what Codex loads.
74
+ - `ruleNamePattern` optionally constrains the names of your own top-level rule files.
75
+ - `presets` and `hooks` are reserved for later versions and must stay empty / `false`.
76
+
77
+ ## Clients
78
+
79
+ | Client | How it sees the instructions |
80
+ | --- | --- |
81
+ | Codex | Reads `AGENTS.md` from the repository root down to the working directory and `.agents/skills/` natively. Trust the project, or Codex skips project instructions. |
82
+ | Claude Code | `CLAUDE.md -> AGENTS.md`, `.claude/rules -> ../.agents/rules`, `.claude/skills -> ../.agents/skills`; rules load natively by `paths`. |
83
+ | Cursor, GitHub Copilot | Read `AGENTS.md` natively. |
84
+ | Gemini CLI | Set `context.fileName` to `["AGENTS.md"]`. |
85
+
86
+ On Windows enable symlinks (`git config core.symlinks true` with Developer Mode) before cloning; canons never falls back to copies.
87
+
88
+ ## Versioning
89
+
90
+ Rule content follows semver. A **major** release adds or tightens a red line, or changes what consumers must do; while in `0.x`, a minor release counts as major. `canons sync` stops on a breaking upgrade until you pass `--accept-major`, so rule changes get the same review as code.
91
+
92
+ ## Security
93
+
94
+ canons never fetches rules at run time: `sync` copies files from the installed package only, and nothing it writes is executed. Releases are published from GitHub Actions with npm provenance. See [SECURITY.md](.github/SECURITY.md).
95
+
96
+ ## License
97
+
98
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,98 @@
1
+ # canons
2
+
3
+ 为 coding agent 的指令(`AGENTS.md`、按路径生效的规则、技能)提供唯一真源,Codex、Claude Code 等客户端共用同一份内容,并由确定性检查守住。
4
+
5
+ [English](README.md)
6
+
7
+ ## 为什么需要它
8
+
9
+ 同时用多个 coding agent 的团队,常常遇到 `AGENTS.md`、`CLAUDE.md`、`.cursor/rules` 各自漂移,规则只有某一个客户端会加载,红线在有人精简文件时悄悄消失。canons 给每个仓库同一套布局,并用一个小 CLI 守住它:
10
+
11
+ - **每条指令只有一份。** 只有 `AGENTS.md`、`.agents/rules/`、`.agents/skills/` 是实体文件;客户端入口都是相对软链接。
12
+ - **路径级规则对所有客户端生效。** 规则在 frontmatter 里声明 `paths`。Claude Code 原生加载;其他客户端由根指令要求修改前跑 `canons scopes <路径>`、完成前跑 `canons scopes --changed`。
13
+ - **共享基线。** `AGENTS.md` 里的托管区块承载通用的 agent 约定(Git 授权、验证、交接、文档卫生)。项目自己的规则写在区块之外。
14
+ - **确定性守护。** `canons check` 能发现:托管内容被手改、用复制代替软链接、规则里的死链、会让 Codex 跳过 `AGENTS.md` 的 `AGENTS.override.md`,以及超出 Codex 读取上限(32 KiB)的指令链。
15
+
16
+ ## 快速开始
17
+
18
+ 需要 Node 22 及以上,并且在 git 仓库里运行。
19
+
20
+ ```sh
21
+ npm install --save-dev @canons-dev/canons
22
+ npx canons init --locale zh-CN
23
+ npx canons check
24
+ ```
25
+
26
+ 包会安装一个 `canons` 命令。请把它装成 dev dependency,这样托管规则要求 agent 运行的 `npx canons` 会解析到锁定版本的本地副本。`init` 会创建 `canons.json`,在 `AGENTS.md` 里插入托管区块(文件不存在就新建),把托管规则写进 `.agents/rules/canons/`,为 Claude Code 建好软链接,并写出 `canons.lock.json`。这些文件都要提交。
27
+
28
+ 然后添加项目自己的规则:
29
+
30
+ ```md
31
+ <!-- .agents/rules/apis.md -->
32
+ ---
33
+ paths:
34
+ - "src/api/**"
35
+ ---
36
+
37
+ # API 处理器
38
+
39
+ - 在边界处校验每个请求体。
40
+ ```
41
+
42
+ ```sh
43
+ npx canons scopes src/api/users.ts # 这个路径适用哪些规则?
44
+ npx canons scopes --changed # 我的改动适用哪些规则?
45
+ ```
46
+
47
+ ## 命令
48
+
49
+ | 命令 | 作用 |
50
+ | --- | --- |
51
+ | `canons init [--locale <code>]` | 创建 `canons.json` 并执行 `sync`。 |
52
+ | `canons sync [--accept-major] [--force]` | 更新托管区块、托管规则、客户端软链接和 lock。默认拒绝覆盖手工修改(`--force` 才覆盖),拒绝破坏性的规则升级(`--accept-major` 才放行)。 |
53
+ | `canons check [--strict]` | 确定性检查;有 error 时退出码为 1(`--strict` 下 warning 也算失败)。 |
54
+ | `canons scopes [--changed] [--json] <路径>...` | 列出 `paths` 命中的规则。没有 `paths` 的规则是全局规则,始终列出。 |
55
+ | `canons doctor` | 环境提示(软链接支持、Codex 信任、其他客户端)。 |
56
+
57
+ ## 配置
58
+
59
+ `canons.json`(除 `version` 外都是可选项):
60
+
61
+ ```json
62
+ {
63
+ "version": 1,
64
+ "locale": "zh-CN",
65
+ "clients": ["codex", "claude"],
66
+ "rulesDir": ".agents/rules",
67
+ "skillsDir": ".agents/skills",
68
+ "budgetBytes": 24576,
69
+ "ruleNamePattern": "^[a-z]{6}$"
70
+ }
71
+ ```
72
+
73
+ - `budgetBytes` 只限制根 `AGENTS.md`(默认 24 KiB,最多 32 KiB),给嵌套的指令文件留出 Codex 能加载的空间。
74
+ - `ruleNamePattern` 可选,用来约束项目自己的顶层规则文件名。
75
+ - `presets` 和 `hooks` 留给后续版本,目前必须保持为空 / `false`。
76
+
77
+ ## 客户端
78
+
79
+ | 客户端 | 如何读到指令 |
80
+ | --- | --- |
81
+ | Codex | 原生从仓库根往下读到工作目录的各级 `AGENTS.md`,并读取 `.agents/skills/`。需要在 Codex 里信任该项目,否则会跳过项目指令。 |
82
+ | Claude Code | `CLAUDE.md -> AGENTS.md`、`.claude/rules -> ../.agents/rules`、`.claude/skills -> ../.agents/skills`;规则按 `paths` 原生加载。 |
83
+ | Cursor、GitHub Copilot | 原生读取 `AGENTS.md`。 |
84
+ | Gemini CLI | 把 `context.fileName` 设为 `["AGENTS.md"]`。 |
85
+
86
+ Windows 用户在 clone 前先启用软链接(开启开发者模式后执行 `git config core.symlinks true`);canons 不会退化成复制文件。
87
+
88
+ ## 版本
89
+
90
+ 规则内容遵循 semver。**major** 版本会新增或收紧红线,或改变使用方必须做的事;`0.x` 期间 minor 版本按 major 对待。遇到破坏性升级时 `canons sync` 会停下,直到你加上 `--accept-major`,让规则变更和代码一样经过 review。
91
+
92
+ ## 安全
93
+
94
+ canons 运行时从不联网拉取规则:`sync` 只从已安装的包里复制文件,写出的内容也不会被执行。发布只经 GitHub Actions 进行,并附带 npm provenance。详见 [SECURITY.md](.github/SECURITY.md)。
95
+
96
+ ## 协议
97
+
98
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,30 @@
1
+ ## Agent conventions (canons)
2
+
3
+ These apply to every coding agent working in this repository (Codex, Claude Code, Cursor, Copilot and others). Project rules outside this block add to them; a project rule may tighten C1, C3, C8, C9, C11 and C12 but never relax them.
4
+
5
+ ### Sources of truth and loading
6
+
7
+ - **C1** Edit only the real sources: `AGENTS.md`, the rules directory (`.agents/rules/`) and the skills directory (`.agents/skills/`). Client entry points such as `CLAUDE.md`, `.claude/rules` and `.claude/skills` are relative symlinks to them. Never copy their content into a second file and never reverse a link.
8
+ - **C2** Three tiers: this root file holds global red lines; path-scoped rules in the rules directory hold subsystem guards (`paths` frontmatter); skills hold multi-step procedures loaded on demand. Global red lines never move down a tier.
9
+ - **C3** Before editing, run `npx canons scopes <file-or-dir>...` (pass the planned path for new files) and read every rule it lists. Before finishing, run `npx canons scopes --changed` against the actual diff. No match does not mean no constraints: this file still applies. A client loading rules natively is a convenience, not a substitute for the query.
10
+ - **C4** Keep this file within its byte budget (`npx canons check` enforces it). To make room, condense wording or move rationale into docs; never delete a red line.
11
+
12
+ ### Knowledge and documents
13
+
14
+ - **C5** Conventions an agent must remember go into repository files reviewed through git, never only into a client's private memory.
15
+ - **C6** Docs and rules state current knowledge and its reasons, not history. Facts the code shows directly get a pointer, not a copy. Invariants that must hold are guarded by tests. Each constraint is written in exactly one place.
16
+ - **C7** Temporary files, one-off scripts and in-flight plans go in `tmp/` (git-ignored). Reusable tools are committed. Docs and code never point at files in `tmp/`.
17
+
18
+ ### Collaboration and authority
19
+
20
+ - **C8** Never change Git state (commit, push, pull, fetch, merge, rebase, reset, stash, tag, switching branches, opening a PR) without an explicit instruction from the user. Read-only commands are fine. Steps of an already authorized task need no second confirmation.
21
+ - **C9** Run `git status` before changing anything and never overwrite someone else's in-progress changes; ask before editing a file another session is changing. Prefer a separate worktree for parallel work; worktrees do not isolate databases, ports or other shared resources.
22
+ - **C10** When requirements, behavior, interfaces or naming are genuinely ambiguous, or a user decision conflicts with these rules, say so and wait for a decision. Offer 2–4 mutually exclusive options, the recommended one first with its cost.
23
+ - **C11** Mark unverified judgements as unverified, with their basis and how to verify them. Label second-hand conclusions with their source; never promote them to fact.
24
+ - **C12** A missing capability (no sub-agents, no browser, no question UI) changes how you work, not what is required: required confirmations and verification are never skipped, and anything left unverified is reported as such.
25
+ - **C13** When handing work to another agent, write down the goal, scope, changed files, decisions, verification results, remaining work and open decisions in `tmp/`, and pass it on explicitly. Durable knowledge goes back into docs.
26
+ - **C14** End every stage with a settlement verdict: is this session done and safe to archive? If not, list the open items as a table (item | status or blocker | owner | next step). Unmerged PRs, pending deploys, pending re-tests and pending user decisions all count as open.
27
+
28
+ ### Finishing a change
29
+
30
+ - **C15** After changing code, update in the same change: tests for logic that can be tested automatically, docs, and any rule whose guarded invariant the change touches. Report what was updated and, for anything not updated, why not.
@@ -0,0 +1,20 @@
1
+ ---
2
+ paths:
3
+ - "AGENTS.md"
4
+ - "**/AGENTS.md"
5
+ - "CLAUDE.md"
6
+ - ".agents/**"
7
+ - ".claude/**"
8
+ - ".codex/**"
9
+ - "canons.json"
10
+ - "canons.lock.json"
11
+ ---
12
+
13
+ # Instruction layout (canons)
14
+
15
+ - **L1** The block in `AGENTS.md` and the files under `.agents/rules/canons/` are generated by `canons sync`. Put project changes outside them, or propose them upstream; `canons check` rejects hand edits.
16
+ - **L2** Rule frontmatter declares `paths` as a YAML block list using `*`, `?` and `**` (`**/` also matches zero directories); parentheses and brackets are literal. Empty or unparsable lists are errors. A rule without `paths` is global, but it must not be used to move red lines out of `AGENTS.md`.
17
+ - **L3** Links inside a rule resolve from the rule's own directory (for example `../../docs/x.md`), not from the repository root.
18
+ - **L4** No `AGENTS.override.md` in the repository: Codex reads it instead of `AGENTS.md`. Nested `AGENTS.md` files are allowed, but each root-to-directory chain must stay under 32 KiB in total, or Codex silently drops the rest.
19
+ - **L5** Client configuration and permissions stay in each client's own directory; an allow-list for one client never authorizes another. A new client gets a thin adapter (a relative symlink or a one-line pointer), never a copy of the content.
20
+ - **L6** Skills describe the capabilities they need in plain terms; anything client-specific (parameters, UI, delegation) needs a stated fallback, and required confirmations and verification stay mandatory.
@@ -0,0 +1,12 @@
1
+ ---
2
+ paths:
3
+ - ".agents/skills/**"
4
+ - "skills-lock.json"
5
+ ---
6
+
7
+ # Third-party skills (canons)
8
+
9
+ - **V1** A third-party skill is a supply-chain dependency: its body runs as instructions and its scripts may run as code. It gets no default trust.
10
+ - **V2** Bring it into `tmp/` first, not straight into the skills directory where clients may load it. Read `SKILL.md` and every script; reject network egress, running downloaded code, or reading secrets and environment variables without a clear need.
11
+ - **V3** Vendor the audited version, record its source and content hash in a lock (for example `skills-lock.json`), and narrow its `description` to the project's real triggers.
12
+ - **V4** Keep upstream text and local changes apart; never recompute the upstream hash to hide a local edit. Upgrades are deliberate and audited again.
@@ -0,0 +1,30 @@
1
+ ## Agent 协作约定(canons)
2
+
3
+ 本区块适用于在本仓库工作的所有 coding agent(Codex、Claude Code、Cursor、Copilot 等)。区块外的项目规则在此基础上补充;项目规则可以收紧 C1、C3、C8、C9、C11、C12,但不能放宽。
4
+
5
+ ### 真源与加载
6
+
7
+ - **C1** 只编辑实体真源:`AGENTS.md`、规则目录(`.agents/rules/`)和技能目录(`.agents/skills/`)。`CLAUDE.md`、`.claude/rules`、`.claude/skills` 等客户端入口都是指向它们的相对软链接。禁止把内容复制成第二份文件,禁止反向链接。
8
+ - **C2** 三层加载:本根文件放全局红线;规则目录里带 `paths` frontmatter 的规则放子系统约束;技能放按需加载的多步流程。全局红线不得下放到下层。
9
+ - **C3** 修改前运行 `npx canons scopes <文件或目录>...`(新文件传拟创建路径),读完列出的每条规则。完成前对实际 diff 运行 `npx canons scopes --changed`。没有命中不等于没有约束:本文件始终适用。客户端原生加载规则只是便利,不能代替查询。
10
+ - **C4** 本文件保持在字节预算内(`npx canons check` 会检查)。需要腾空间时精简措辞或把理由移进文档,绝不删红线。
11
+
12
+ ### 知识与文档
13
+
14
+ - **C5** 要求 agent 记住的约定必须写进仓库文件、经 git review,不能只存在客户端的私有 memory 里。
15
+ - **C6** 文档和规则只写当前知识及其理由,不写历史。能从代码直接看到的事实只留指针、不复述。必须守住的不变量用测试守护。同一约束只写在一处。
16
+ - **C7** 临时文件、一次性脚本和在途方案放 `tmp/`(git 忽略)。可复用的工具必须入库。文档和代码不得指向 `tmp/` 里的文件。
17
+
18
+ ### 协作与授权
19
+
20
+ - **C8** 没有用户明确指令,不改变 Git 状态(commit、push、pull、fetch、merge、rebase、reset、stash、tag、切分支、建 PR)。只读命令不受限。已授权任务所需的步骤不必重复确认。
21
+ - **C9** 改动前先 `git status`,不覆盖他人的在途修改;要改另一个 session 正在改的文件,先确认。并行工作优先用独立 worktree;worktree 不隔离数据库、端口等共享资源。
22
+ - **C10** 需求、行为、接口或命名有实质歧义,或用户的决定与本约定冲突时,明确指出并等待决定。给出 2–4 个互斥选项,推荐项放第一个并说明代价。
23
+ - **C11** 未验证的判断要标注为未验证,并写明依据和验证方法。二手结论注明来源,不得升格为事实。
24
+ - **C12** 缺少某种能力(没有子 agent、没有浏览器、没有提问界面)只改变做法,不改变要求:必需的确认和验证不能跳过,没能验证的内容要如实说明。
25
+ - **C13** 把工作交给另一个 agent 时,在 `tmp/` 写下目标、范围、改动文件、设计决定、验证结果、剩余工作和待决项,并显式交给对方。长期知识回写到文档。
26
+ - **C14** 每个阶段收尾都要给结清判定:本 session 是否做完、能否归档?没做完就用表格列出待办(事项 | 状态或卡点 | 负责方 | 下一步)。PR 未合、待部署、待复测、待用户决定都算未结清。
27
+
28
+ ### 完成改动
29
+
30
+ - **C15** 改完代码,在同一次改动里同步:能自动测试的逻辑补测试、更新文档、更新受影响不变量所在的规则。汇报同步了什么;没同步的说明原因。
@@ -0,0 +1,20 @@
1
+ ---
2
+ paths:
3
+ - "AGENTS.md"
4
+ - "**/AGENTS.md"
5
+ - "CLAUDE.md"
6
+ - ".agents/**"
7
+ - ".claude/**"
8
+ - ".codex/**"
9
+ - "canons.json"
10
+ - "canons.lock.json"
11
+ ---
12
+
13
+ # 指令布局(canons)
14
+
15
+ - **L1** `AGENTS.md` 里的区块和 `.agents/rules/canons/` 下的文件由 `canons sync` 生成。项目改动写在它们之外,或者向上游提议;`canons check` 会拒绝手工修改。
16
+ - **L2** 规则 frontmatter 用 YAML block list 声明 `paths`,支持 `*`、`?`、`**`(`**/` 也匹配零层目录);圆括号和方括号按字面量处理。空列表或无法解析的列表报错。没有 `paths` 的规则是全局规则,但不能借此把红线移出 `AGENTS.md`。
17
+ - **L3** 规则里的链接从规则文件自己的目录解析(例如 `../../docs/x.md`),不是从仓库根解析。
18
+ - **L4** 仓库里不放 `AGENTS.override.md`:Codex 会读它而不读 `AGENTS.md`。允许嵌套的 `AGENTS.md`,但从根到任一目录的整条链合计必须低于 32 KiB,否则 Codex 会静默丢弃超出部分。
19
+ - **L5** 客户端配置与权限留在各自客户端的目录里;一个客户端的允许清单不构成对另一个客户端的授权。新客户端只接薄适配(相对软链接或一行指针),绝不复制内容。
20
+ - **L6** 技能用通用语言描述所需能力;客户端专属的参数、界面或委派要写明替代路径,必需的确认与验证仍然必须做。
@@ -0,0 +1,12 @@
1
+ ---
2
+ paths:
3
+ - ".agents/skills/**"
4
+ - "skills-lock.json"
5
+ ---
6
+
7
+ # 第三方技能(canons)
8
+
9
+ - **V1** 第三方技能是供应链依赖:正文被当作指令执行,附带脚本可能被当作代码运行。默认不信任。
10
+ - **V2** 先放进 `tmp/`,不要直接放进可能被客户端自动加载的技能目录。读完 `SKILL.md` 和每个脚本;有网络外发、运行下载来的代码、或无明确理由读取密钥和环境变量的,一律拒绝。
11
+ - **V3** 把审计过的版本 vendor 进仓库,在 lock(例如 `skills-lock.json`)里记录来源和内容 hash,并把 `description` 收窄到本项目真实的触发场景。
12
+ - **V4** 上游正文与本地改动分开存放;绝不重算上游 hash 来掩盖本地修改。升级要有意为之,并重新审计。
package/out/check.js ADDED
@@ -0,0 +1,165 @@
1
+ // `canons check`: deterministic hygiene checks. Errors fail the run; warnings
2
+ // fail only with --strict. No network, no AI.
3
+ import { existsSync, lstatSync, readFileSync, readlinkSync, realpathSync, statSync, } from "node:fs";
4
+ import { dirname, posix, resolve } from "node:path";
5
+ import { CODEX_CHAIN_MAX_BYTES, ROOT_FILE, loadConfig, } from "./config.js";
6
+ import { MANAGED_SUBDIR, CONTENT_ROOT, extractBlock, loadCanon, sha256, } from "./content.js";
7
+ import { globToRe, listMarkdown, loadScopeRules, repoFiles, staticPrefix, } from "./rules.js";
8
+ import { clientLinks, managedRulePath, readLock } from "./sync.js";
9
+ function listFiles(root) {
10
+ try {
11
+ return repoFiles(root);
12
+ }
13
+ catch {
14
+ throw new Error("canons check must run inside a git repository");
15
+ }
16
+ }
17
+ export function check(root, options = {}) {
18
+ const errors = [];
19
+ const warnings = [];
20
+ let config;
21
+ try {
22
+ config = loadConfig(root);
23
+ }
24
+ catch (error) {
25
+ return { errors: [error.message], warnings };
26
+ }
27
+ const files = listFiles(root);
28
+ const fileSet = new Set(files);
29
+ // 1. Root file, managed block, lock.
30
+ const rootPath = resolve(root, ROOT_FILE);
31
+ const lock = readLock(root);
32
+ if (!lock)
33
+ errors.push(`canons.lock.json is missing; run "canons sync"`);
34
+ if (!existsSync(rootPath))
35
+ errors.push(`${ROOT_FILE} is missing`);
36
+ else {
37
+ const text = readFileSync(rootPath, "utf8");
38
+ const bytes = Buffer.byteLength(text, "utf8");
39
+ if (bytes > config.budgetBytes)
40
+ errors.push(`${ROOT_FILE} is ${bytes} bytes, over the ${config.budgetBytes}-byte budget; trim it or move rationale into docs (never drop red lines)`);
41
+ try {
42
+ const block = extractBlock(text);
43
+ if (!block)
44
+ errors.push(`${ROOT_FILE} has no canons block; run "canons sync"`);
45
+ else {
46
+ if (sha256(block.body) !== block.attrs.sha256)
47
+ errors.push(`${ROOT_FILE}: the canons block was edited by hand; move the change outside the block, or propose it upstream`);
48
+ if (lock && block.attrs.sha256 !== lock.block)
49
+ errors.push(`${ROOT_FILE}: the canons block does not match canons.lock.json; run "canons sync"`);
50
+ }
51
+ }
52
+ catch (error) {
53
+ errors.push(error.message);
54
+ }
55
+ }
56
+ if (lock) {
57
+ let canonBlockHash;
58
+ try {
59
+ const canon = loadCanon(config.locale, options.contentRoot ?? CONTENT_ROOT);
60
+ canonBlockHash = sha256(canon.block);
61
+ if (lock.canons !== canon.version || lock.locale !== config.locale)
62
+ errors.push(`canons.lock.json is for canons ${lock.canons} (${lock.locale}) but ${canon.version} (${config.locale}) is installed; run "canons sync"`);
63
+ else if (canonBlockHash !== lock.block)
64
+ errors.push(`canons.lock.json does not match the installed canons; run "canons sync"`);
65
+ }
66
+ catch (error) {
67
+ errors.push(error.message);
68
+ }
69
+ for (const [path, hash] of Object.entries(lock.files)) {
70
+ const abs = resolve(root, path);
71
+ if (!existsSync(abs))
72
+ errors.push(`${path} is missing; run "canons sync"`);
73
+ else if (sha256(readFileSync(abs, "utf8")) !== hash)
74
+ errors.push(`${path} was edited by hand; put project rules outside ${config.rulesDir}/${MANAGED_SUBDIR}/`);
75
+ }
76
+ const managedDir = resolve(root, config.rulesDir, MANAGED_SUBDIR);
77
+ if (existsSync(managedDir))
78
+ for (const file of listMarkdown(managedDir)) {
79
+ const path = managedRulePath(config, file);
80
+ if (!(path in lock.files))
81
+ errors.push(`${path} is not managed by canons; move it to ${config.rulesDir}/`);
82
+ }
83
+ }
84
+ // 2. Codex: AGENTS.override.md shadows AGENTS.md in its directory, and the
85
+ // instructions along any root-to-cwd chain are cut off at 32 KiB.
86
+ for (const file of files)
87
+ if (posix.basename(file) === "AGENTS.override.md")
88
+ errors.push(`${file}: Codex reads it instead of AGENTS.md in that directory, bypassing the canons block; remove it (personal overrides belong in ~/.codex)`);
89
+ const agentsFiles = files.filter((f) => posix.basename(f) === ROOT_FILE);
90
+ const size = (f) => statSync(resolve(root, f), { throwIfNoEntry: false })?.size ?? 0;
91
+ for (const file of agentsFiles) {
92
+ let total = 0;
93
+ const chain = [];
94
+ let dir = posix.dirname(file);
95
+ const dirs = [];
96
+ for (;;) {
97
+ dirs.unshift(dir);
98
+ if (dir === ".")
99
+ break;
100
+ dir = posix.dirname(dir);
101
+ }
102
+ for (const d of dirs) {
103
+ const candidate = d === "." ? ROOT_FILE : `${d}/${ROOT_FILE}`;
104
+ if (fileSet.has(candidate) || (d === "." && existsSync(rootPath))) {
105
+ total += size(candidate);
106
+ chain.push(candidate);
107
+ }
108
+ }
109
+ if (total > CODEX_CHAIN_MAX_BYTES)
110
+ errors.push(`${chain.join(" + ")} = ${total} bytes; Codex stops loading project instructions at ${CODEX_CHAIN_MAX_BYTES} bytes`);
111
+ }
112
+ // 3. Client adapters must be relative symlinks, never copies.
113
+ for (const [link, target] of clientLinks(config)) {
114
+ const abs = resolve(root, link);
115
+ const stat = lstatSync(abs, { throwIfNoEntry: false });
116
+ if (!stat)
117
+ errors.push(`${link} is missing; run "canons sync"`);
118
+ else if (!stat.isSymbolicLink())
119
+ errors.push(`${link} must be a symlink to ${target}, not a copy`);
120
+ else if (readlinkSync(abs) !== target)
121
+ errors.push(`${link} points to ${readlinkSync(abs)}; expected ${target}`);
122
+ else if (!existsSync(abs))
123
+ errors.push(`${link} is a dangling symlink`);
124
+ }
125
+ // 4. Rule files: parseable frontmatter, valid globs, naming, links.
126
+ const rulesAbs = resolve(root, config.rulesDir);
127
+ if (!existsSync(rulesAbs))
128
+ errors.push(`${config.rulesDir} is missing`);
129
+ else {
130
+ try {
131
+ const rules = loadScopeRules(root, config.rulesDir);
132
+ const managedPrefix = `${config.rulesDir}/${MANAGED_SUBDIR}/`;
133
+ // Managed rules are generic and may name files a project does not have.
134
+ for (const rule of rules.filter((r) => !r.file.startsWith(managedPrefix)))
135
+ for (const glob of rule.paths) {
136
+ const re = globToRe(glob);
137
+ if (!files.some((f) => re.test(f)))
138
+ warnings.push(`${rule.file}: "${glob}" matches no file${/[*?]/.test(glob) ? ` under ${staticPrefix(glob) || "."}` : ""}`);
139
+ }
140
+ }
141
+ catch (error) {
142
+ errors.push(error.message);
143
+ }
144
+ const ruleFiles = listMarkdown(rulesAbs);
145
+ if (config.ruleNamePattern) {
146
+ const re = new RegExp(config.ruleNamePattern);
147
+ for (const file of ruleFiles)
148
+ if (!file.includes("/") && !re.test(file.replace(/\.md$/, "")))
149
+ errors.push(`${config.rulesDir}/${file}: name does not match ruleNamePattern ${config.ruleNamePattern}`);
150
+ }
151
+ for (const file of ruleFiles) {
152
+ const abs = resolve(rulesAbs, file);
153
+ const text = readFileSync(abs, "utf8");
154
+ const base = dirname(realpathSync(abs));
155
+ for (const m of text.matchAll(/\]\(<?([^)>\s]+)>?\)/g)) {
156
+ const raw = decodeURIComponent(m[1].split("#")[0].trim());
157
+ if (!raw || /^[a-z]+:/i.test(raw))
158
+ continue;
159
+ if (!existsSync(resolve(base, raw)))
160
+ errors.push(`${config.rulesDir}/${file}: broken link ${m[1]} (links resolve from the rule's own directory)`);
161
+ }
162
+ }
163
+ }
164
+ return { errors, warnings };
165
+ }