first-tree 0.0.1

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # seed-tree
2
+
3
+ Template source and CLI for [Context Tree](https://context-tree.ai) — the living source of truth for your organization.
4
+
5
+ ## What is Context Tree?
6
+
7
+ A tree-structured knowledge base that agents and humans build and maintain together. Every node represents a domain, decision, or design. Every node has an owner. When things change, the tree updates. See [docs/about.md](docs/about.md) for the full story.
8
+
9
+ ## Quick Start
10
+
11
+ ```bash
12
+ npx context-tree init
13
+ ```
14
+
15
+ Run this inside a git repo. It clones the framework, renders scaffolding, and generates a task list for your agent to work through.
16
+
17
+ ## Commands
18
+
19
+ | Command | What it does |
20
+ |---------|-------------|
21
+ | `context-tree init` | Bootstrap a new context tree in the current git repo |
22
+ | `context-tree verify` | Run checks against the tree, report pass/fail |
23
+ | `context-tree upgrade` | Compare local framework version to upstream, generate upgrade tasks |
24
+
25
+ ## What `init` creates
26
+
27
+ ```
28
+ your-tree/
29
+ .context-tree/ # framework (upgradable from seed-tree)
30
+ VERSION
31
+ principles.md
32
+ ownership-and-naming.md
33
+ templates/
34
+ workflows/
35
+ examples/
36
+ NODE.md # root node — your domains (from template)
37
+ AGENT.md # agent instructions with framework markers (from template)
38
+ members/
39
+ NODE.md # members domain (from template)
40
+ ```
41
+
42
+ ## Upgrades
43
+
44
+ After init, seed-tree is added as a git remote (`context-tree-upstream`). To upgrade the framework:
45
+
46
+ ```bash
47
+ context-tree upgrade # shows what changed and what to do
48
+ ```
49
+
50
+ ## Documentation
51
+
52
+ - [docs/onboarding.md](docs/onboarding.md) — Onboarding guide for setting up a context tree (for agents)
53
+ - [docs/about.md](docs/about.md) — What is Context Tree and who it's for
54
+ - [.context-tree/principles.md](.context-tree/principles.md) — Core principles with examples
55
+ - [.context-tree/ownership-and-naming.md](.context-tree/ownership-and-naming.md) — Node naming and ownership model
56
+
57
+ ## Development
58
+
59
+ ```bash
60
+ pnpm install
61
+ pnpm test # run tests
62
+ pnpm typecheck # type check
63
+ pnpm build # build CLI
64
+ ```
65
+
66
+ ## License
67
+
68
+ Apache 2.0
package/dist/cli.js ADDED
@@ -0,0 +1,41 @@
1
+ #!/usr/bin/env node
2
+ //#region src/cli.ts
3
+ const USAGE = `usage: context-tree <command>
4
+
5
+ Commands:
6
+ init Bootstrap a new context tree (clones seed-tree, copies framework files)
7
+ verify Run verification checks against the current tree
8
+ upgrade Generate an upgrade task list from upstream changes
9
+
10
+ Options:
11
+ --help Show this help message
12
+ `;
13
+ async function main() {
14
+ const args = process.argv.slice(2);
15
+ if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
16
+ console.log(USAGE);
17
+ return 0;
18
+ }
19
+ const command = args[0];
20
+ switch (command) {
21
+ case "init": {
22
+ const { runInit } = await import("./init-CE_944sb.js");
23
+ return runInit();
24
+ }
25
+ case "verify": {
26
+ const { runVerify } = await import("./verify-DIz6qmBX.js");
27
+ return runVerify();
28
+ }
29
+ case "upgrade": {
30
+ const { runUpgrade } = await import("./upgrade-Chr7z0CY.js");
31
+ return runUpgrade();
32
+ }
33
+ default:
34
+ console.log(`Unknown command: ${command}`);
35
+ console.log(USAGE);
36
+ return 1;
37
+ }
38
+ }
39
+ main().then((code) => process.exit(code));
40
+ //#endregion
41
+ export {};
@@ -0,0 +1,283 @@
1
+ import { n as Repo, t as FRAMEWORK_END_MARKER } from "./repo-BByc3VvM.js";
2
+ import { execFileSync } from "node:child_process";
3
+ import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ //#region \0rolldown/runtime.js
7
+ var __defProp = Object.defineProperty;
8
+ var __exportAll = (all, no_symbols) => {
9
+ let target = {};
10
+ for (var name in all) __defProp(target, name, {
11
+ get: all[name],
12
+ enumerable: true
13
+ });
14
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
15
+ return target;
16
+ };
17
+ //#endregion
18
+ //#region src/rules/agent-instructions.ts
19
+ var agent_instructions_exports = /* @__PURE__ */ __exportAll({ evaluate: () => evaluate$5 });
20
+ function evaluate$5(repo) {
21
+ const tasks = [];
22
+ if (!repo.pathExists("AGENT.md")) tasks.push("AGENT.md is missing — create from `.context-tree/templates/agent.md.template`");
23
+ else if (!repo.hasAgentMdMarkers()) tasks.push("AGENT.md exists but is missing framework markers — add `<!-- BEGIN CONTEXT-TREE FRAMEWORK -->` and `<!-- END CONTEXT-TREE FRAMEWORK -->` sections");
24
+ else {
25
+ const afterMarker = (repo.readFile("AGENT.md") ?? "").split(FRAMEWORK_END_MARKER);
26
+ if (afterMarker.length > 1) {
27
+ if (afterMarker[1].trim().split("\n").filter((l) => l.trim() && !l.trim().startsWith("#") && !l.trim().startsWith("<!--")).length === 0) tasks.push("Add your project-specific instructions below the framework markers in AGENT.md");
28
+ }
29
+ }
30
+ return {
31
+ group: "Agent Instructions",
32
+ order: 3,
33
+ tasks
34
+ };
35
+ }
36
+ //#endregion
37
+ //#region src/rules/agent-integration.ts
38
+ var agent_integration_exports = /* @__PURE__ */ __exportAll({ evaluate: () => evaluate$4 });
39
+ function evaluate$4(repo) {
40
+ const tasks = [];
41
+ if (repo.pathExists(".claude/settings.json")) {
42
+ if (!repo.fileContains(".claude/settings.json", "inject-tree-context")) tasks.push("Add SessionStart hook to `.claude/settings.json` (see `.context-tree/examples/claude-code/`)");
43
+ } else if (!repo.anyAgentConfig()) tasks.push("No agent configuration detected. Configure your agent to load tree context at session start. See `.context-tree/examples/` for supported agents. You can skip this and set it up later.");
44
+ return {
45
+ group: "Agent Integration",
46
+ order: 5,
47
+ tasks
48
+ };
49
+ }
50
+ //#endregion
51
+ //#region src/rules/ci-validation.ts
52
+ var ci_validation_exports = /* @__PURE__ */ __exportAll({ evaluate: () => evaluate$3 });
53
+ function evaluate$3(repo) {
54
+ const tasks = [];
55
+ let hasValidation = false;
56
+ const workflowsDir = join(repo.root, ".github", "workflows");
57
+ try {
58
+ if (statSync(workflowsDir).isDirectory()) for (const name of readdirSync(workflowsDir)) {
59
+ if (!name.endsWith(".yml") && !name.endsWith(".yaml")) continue;
60
+ const fullPath = join(workflowsDir, name);
61
+ try {
62
+ if (!statSync(fullPath).isFile()) continue;
63
+ const content = readFileSync(fullPath, "utf-8");
64
+ if (content.includes("validate_nodes") || content.includes("validate_members")) {
65
+ hasValidation = true;
66
+ break;
67
+ }
68
+ } catch {
69
+ continue;
70
+ }
71
+ }
72
+ } catch {}
73
+ if (!hasValidation) tasks.push("No validation workflow found — copy `.context-tree/workflows/validate.yml` to `.github/workflows/validate.yml`");
74
+ return {
75
+ group: "CI / Validation",
76
+ order: 6,
77
+ tasks
78
+ };
79
+ }
80
+ //#endregion
81
+ //#region src/rules/framework.ts
82
+ var framework_exports = /* @__PURE__ */ __exportAll({ evaluate: () => evaluate$2 });
83
+ const SEED_TREE_URL$1 = "https://github.com/agent-team-foundation/seed-tree";
84
+ function evaluate$2(repo) {
85
+ const tasks = [];
86
+ if (!repo.hasFramework()) tasks.push(`\`.context-tree/\` not found — run \`context-tree init\` to clone the framework from ${SEED_TREE_URL$1}`);
87
+ return {
88
+ group: "Framework",
89
+ order: 1,
90
+ tasks
91
+ };
92
+ }
93
+ //#endregion
94
+ //#region src/rules/members.ts
95
+ var members_exports = /* @__PURE__ */ __exportAll({ evaluate: () => evaluate$1 });
96
+ function evaluate$1(repo) {
97
+ const tasks = [];
98
+ if (!repo.pathExists("members")) tasks.push("`members/` directory is missing — create it with a NODE.md");
99
+ else if (!repo.pathExists("members/NODE.md")) tasks.push("`members/NODE.md` is missing — create it from the template");
100
+ if (repo.hasMembers() && repo.memberCount() === 0) tasks.push("Add at least one member node for a team member or agent under `members/`");
101
+ else if (!repo.hasMembers()) tasks.push("Add at least one member node for a team member or agent under `members/`");
102
+ return {
103
+ group: "Members",
104
+ order: 4,
105
+ tasks
106
+ };
107
+ }
108
+ //#endregion
109
+ //#region src/rules/root-node.ts
110
+ var root_node_exports = /* @__PURE__ */ __exportAll({ evaluate: () => evaluate });
111
+ function evaluate(repo) {
112
+ const tasks = [];
113
+ if (!repo.pathExists("NODE.md")) tasks.push("NODE.md is missing — create from `.context-tree/templates/root-node.md.template`, fill in your project's domains");
114
+ else {
115
+ const fm = repo.frontmatter("NODE.md");
116
+ if (fm === null) tasks.push("NODE.md exists but has no frontmatter — add frontmatter with title and owners fields");
117
+ else {
118
+ if (!fm.title || fm.title.startsWith("<")) tasks.push("NODE.md has a placeholder title — replace with your organization name");
119
+ if (!fm.owners || fm.owners.length === 0 || fm.owners.length === 1 && fm.owners[0].startsWith("<")) tasks.push("NODE.md has placeholder owners — set owners to your GitHub username(s)");
120
+ }
121
+ if (repo.hasPlaceholderNode()) tasks.push("NODE.md has placeholder content — fill in your project's domains and description");
122
+ }
123
+ return {
124
+ group: "Root Node",
125
+ order: 2,
126
+ tasks
127
+ };
128
+ }
129
+ //#endregion
130
+ //#region src/rules/index.ts
131
+ const ALL_RULES = [
132
+ framework_exports,
133
+ root_node_exports,
134
+ agent_instructions_exports,
135
+ members_exports,
136
+ agent_integration_exports,
137
+ ci_validation_exports
138
+ ];
139
+ function evaluateAll(repo) {
140
+ const results = [];
141
+ for (const rule of ALL_RULES) {
142
+ const result = rule.evaluate(repo);
143
+ if (result.tasks.length > 0) results.push(result);
144
+ }
145
+ return results.sort((a, b) => a.order - b.order);
146
+ }
147
+ //#endregion
148
+ //#region src/init.ts
149
+ const SEED_TREE_URL = "https://github.com/agent-team-foundation/seed-tree";
150
+ const FRAMEWORK_DIR = ".context-tree";
151
+ const TEMPLATE_MAP = [
152
+ ["root-node.md.template", "NODE.md"],
153
+ ["agent.md.template", "AGENT.md"],
154
+ ["members-domain.md.template", "members/NODE.md"]
155
+ ];
156
+ function cloneSeedTree() {
157
+ const tmp = mkdtempSync(join(tmpdir(), "context-tree-"));
158
+ console.log(`Cloning seed-tree from ${SEED_TREE_URL}...`);
159
+ try {
160
+ execFileSync("git", [
161
+ "clone",
162
+ "--depth",
163
+ "1",
164
+ SEED_TREE_URL,
165
+ tmp
166
+ ], {
167
+ encoding: "utf-8",
168
+ stdio: "pipe"
169
+ });
170
+ } catch (err) {
171
+ const message = err instanceof Error ? err.message : "unknown error";
172
+ console.error(`Failed to clone seed-tree: ${message}`);
173
+ rmSync(tmp, {
174
+ recursive: true,
175
+ force: true
176
+ });
177
+ process.exit(1);
178
+ }
179
+ return tmp;
180
+ }
181
+ function copyFramework(source, target) {
182
+ const src = join(source, FRAMEWORK_DIR);
183
+ const dst = join(target, FRAMEWORK_DIR);
184
+ if (existsSync(dst)) rmSync(dst, {
185
+ recursive: true,
186
+ force: true
187
+ });
188
+ cpSync(src, dst, { recursive: true });
189
+ console.log(` Copied ${FRAMEWORK_DIR}/`);
190
+ }
191
+ function renderTemplates(frameworkDir, target) {
192
+ const templatesDir = join(frameworkDir, "templates");
193
+ for (const [templateName, targetPath] of TEMPLATE_MAP) {
194
+ const src = join(templatesDir, templateName);
195
+ const dst = join(target, targetPath);
196
+ if (existsSync(dst)) console.log(` Skipped ${targetPath} (already exists)`);
197
+ else if (existsSync(src)) {
198
+ mkdirSync(dirname(dst), { recursive: true });
199
+ copyFileSync(src, dst);
200
+ console.log(` Created ${targetPath}`);
201
+ }
202
+ }
203
+ }
204
+ function addUpstreamRemote(target) {
205
+ try {
206
+ if (!execFileSync("git", ["remote"], {
207
+ cwd: target,
208
+ encoding: "utf-8"
209
+ }).split(/\s+/).includes("context-tree-upstream")) {
210
+ execFileSync("git", [
211
+ "remote",
212
+ "add",
213
+ "context-tree-upstream",
214
+ SEED_TREE_URL
215
+ ], {
216
+ cwd: target,
217
+ encoding: "utf-8",
218
+ stdio: "pipe"
219
+ });
220
+ console.log(` Added git remote 'context-tree-upstream' -> ${SEED_TREE_URL}`);
221
+ }
222
+ } catch {}
223
+ }
224
+ function formatTaskList(groups) {
225
+ const lines = ["# Context Tree Init\n"];
226
+ for (const group of groups) {
227
+ lines.push(`## ${group.group}`);
228
+ for (const task of group.tasks) lines.push(`- [ ] ${task}`);
229
+ lines.push("");
230
+ }
231
+ lines.push("## Verification");
232
+ lines.push("After completing the tasks above, run `context-tree verify` to confirm:");
233
+ lines.push("- [ ] `.context-tree/VERSION` exists");
234
+ lines.push("- [ ] Root NODE.md has valid frontmatter (title, owners)");
235
+ lines.push("- [ ] AGENT.md exists with framework markers");
236
+ lines.push("- [ ] `context-tree verify` passes with no errors");
237
+ lines.push("- [ ] At least one member node exists");
238
+ lines.push("");
239
+ lines.push("---");
240
+ lines.push("");
241
+ lines.push("**Important:** As you complete each task, check it off in `.context-tree/progress.md` by changing `- [ ]` to `- [x]`. Run `context-tree verify` when done — it will fail if any items remain unchecked.");
242
+ lines.push("");
243
+ return lines.join("\n");
244
+ }
245
+ function writeProgress(repo, content) {
246
+ const progressPath = join(repo.root, ".context-tree", "progress.md");
247
+ mkdirSync(dirname(progressPath), { recursive: true });
248
+ writeFileSync(progressPath, content);
249
+ }
250
+ function runInit(repo) {
251
+ const r = repo ?? new Repo();
252
+ if (!r.isGitRepo()) {
253
+ console.error("Error: not a git repository. Initialize one first:\n git init");
254
+ return 1;
255
+ }
256
+ if (!r.hasFramework()) {
257
+ const seed = cloneSeedTree();
258
+ try {
259
+ console.log("Copying framework and scaffolding...");
260
+ copyFramework(seed, r.root);
261
+ renderTemplates(join(r.root, FRAMEWORK_DIR), r.root);
262
+ addUpstreamRemote(r.root);
263
+ } finally {
264
+ rmSync(seed, {
265
+ recursive: true,
266
+ force: true
267
+ });
268
+ }
269
+ console.log();
270
+ }
271
+ const groups = evaluateAll(r);
272
+ if (groups.length === 0) {
273
+ console.log("All checks passed. Your context tree is set up.");
274
+ return 0;
275
+ }
276
+ const output = formatTaskList(groups);
277
+ console.log(output);
278
+ writeProgress(r, output);
279
+ console.log("Progress file written to .context-tree/progress.md");
280
+ return 0;
281
+ }
282
+ //#endregion
283
+ export { runInit };
@@ -0,0 +1,111 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ //#region src/repo.ts
5
+ const FRONTMATTER_RE = /^---\s*\n(.*?)\n---/s;
6
+ const OWNERS_RE = /^owners:\s*\[([^\]]*)\]/m;
7
+ const TITLE_RE = /^title:\s*['"]?(.+?)['"]?\s*$/m;
8
+ const FRAMEWORK_END_MARKER = "<!-- END CONTEXT-TREE FRAMEWORK -->";
9
+ var Repo = class {
10
+ root;
11
+ constructor(root) {
12
+ this.root = resolve(root ?? process.cwd());
13
+ }
14
+ pathExists(relPath) {
15
+ return existsSync(join(this.root, relPath));
16
+ }
17
+ fileContains(relPath, text) {
18
+ const fullPath = join(this.root, relPath);
19
+ try {
20
+ if (!statSync(fullPath).isFile()) return false;
21
+ return readFileSync(fullPath, "utf-8").includes(text);
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+ readFile(relPath) {
27
+ try {
28
+ return readFileSync(join(this.root, relPath), "utf-8");
29
+ } catch {
30
+ return null;
31
+ }
32
+ }
33
+ frontmatter(relPath) {
34
+ const text = this.readFile(relPath);
35
+ if (text === null) return null;
36
+ const m = text.match(FRONTMATTER_RE);
37
+ if (!m) return null;
38
+ const fm = m[1];
39
+ const result = {};
40
+ const titleM = fm.match(TITLE_RE);
41
+ if (titleM) result.title = titleM[1].trim();
42
+ const ownersM = fm.match(OWNERS_RE);
43
+ if (ownersM) {
44
+ const raw = ownersM[1].trim();
45
+ result.owners = raw ? raw.split(",").map((o) => o.trim()).filter(Boolean) : [];
46
+ }
47
+ return result.title !== void 0 || result.owners !== void 0 ? result : null;
48
+ }
49
+ anyAgentConfig() {
50
+ return [".claude/settings.json", ".codex/config.json"].some((c) => this.pathExists(c));
51
+ }
52
+ isGitRepo() {
53
+ try {
54
+ return statSync(join(this.root, ".git")).isDirectory();
55
+ } catch {
56
+ return false;
57
+ }
58
+ }
59
+ hasFramework() {
60
+ return this.pathExists(".context-tree/VERSION");
61
+ }
62
+ readVersion() {
63
+ const text = this.readFile(".context-tree/VERSION");
64
+ return text ? text.trim() : null;
65
+ }
66
+ hasAgentMdMarkers() {
67
+ const text = this.readFile("AGENT.md");
68
+ if (text === null) return false;
69
+ return text.includes("<!-- BEGIN CONTEXT-TREE FRAMEWORK") && text.includes("<!-- END CONTEXT-TREE FRAMEWORK -->");
70
+ }
71
+ hasMembers() {
72
+ const membersDir = join(this.root, "members");
73
+ try {
74
+ if (!statSync(membersDir).isDirectory()) return false;
75
+ } catch {
76
+ return false;
77
+ }
78
+ return existsSync(join(membersDir, "NODE.md"));
79
+ }
80
+ memberCount() {
81
+ const membersDir = join(this.root, "members");
82
+ try {
83
+ if (!statSync(membersDir).isDirectory()) return 0;
84
+ } catch {
85
+ return 0;
86
+ }
87
+ let count = 0;
88
+ for (const entry of readdirSync(membersDir)) {
89
+ const childPath = join(membersDir, entry);
90
+ try {
91
+ if (statSync(childPath).isDirectory() && existsSync(join(childPath, "NODE.md"))) count++;
92
+ } catch {}
93
+ }
94
+ return count;
95
+ }
96
+ hasPlaceholderNode() {
97
+ return this.fileContains("NODE.md", "<!-- PLACEHOLDER");
98
+ }
99
+ hasUpstreamRemote() {
100
+ try {
101
+ return execFileSync("git", ["remote"], {
102
+ cwd: this.root,
103
+ encoding: "utf-8"
104
+ }).split(/\s+/).includes("context-tree-upstream");
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+ };
110
+ //#endregion
111
+ export { Repo as n, FRAMEWORK_END_MARKER as t };
@@ -0,0 +1,82 @@
1
+ import { n as Repo } from "./repo-BByc3VvM.js";
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdirSync, writeFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ //#region src/upgrade.ts
6
+ const SEED_TREE_URL = "https://github.com/agent-team-foundation/seed-tree";
7
+ function getUpstreamVersion(repo) {
8
+ try {
9
+ execFileSync("git", [
10
+ "fetch",
11
+ "context-tree-upstream",
12
+ "--depth",
13
+ "1"
14
+ ], {
15
+ cwd: repo.root,
16
+ encoding: "utf-8",
17
+ stdio: "pipe"
18
+ });
19
+ } catch {
20
+ return null;
21
+ }
22
+ try {
23
+ return execFileSync("git", ["show", "context-tree-upstream/main:.context-tree/VERSION"], {
24
+ cwd: repo.root,
25
+ encoding: "utf-8",
26
+ stdio: "pipe"
27
+ }).trim();
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+ function writeProgress(repo, content) {
33
+ const progressPath = join(repo.root, ".context-tree", "progress.md");
34
+ mkdirSync(dirname(progressPath), { recursive: true });
35
+ writeFileSync(progressPath, content);
36
+ }
37
+ function runUpgrade() {
38
+ const repo = new Repo();
39
+ if (!repo.hasFramework()) {
40
+ console.error("Error: no .context-tree/ found. Run `context-tree init` first.");
41
+ return 1;
42
+ }
43
+ const localVersion = repo.readVersion() ?? "unknown";
44
+ console.log(`Local framework version: ${localVersion}\n`);
45
+ if (!repo.hasUpstreamRemote()) {
46
+ const output = [
47
+ "# Context Tree Upgrade\n",
48
+ "## Setup",
49
+ `- [ ] Add upstream remote: \`git remote add context-tree-upstream ${SEED_TREE_URL}\``,
50
+ "- [ ] Then run `context-tree upgrade` again to check for updates"
51
+ ].join("\n");
52
+ console.log(output);
53
+ writeProgress(repo, output + "\n");
54
+ console.log("\nProgress file written to .context-tree/progress.md");
55
+ return 0;
56
+ }
57
+ const upstreamVersion = getUpstreamVersion(repo);
58
+ if (upstreamVersion === null) {
59
+ console.log("Could not fetch upstream version. Check your network and try again.");
60
+ return 1;
61
+ }
62
+ if (upstreamVersion === localVersion) {
63
+ console.log(`Already up to date (v${localVersion}).`);
64
+ return 0;
65
+ }
66
+ const lines = [
67
+ `# Context Tree Upgrade — v${localVersion} -> v${upstreamVersion}\n`,
68
+ "## Framework",
69
+ "- [ ] Pull latest from upstream: `git fetch context-tree-upstream && git merge context-tree-upstream/main`",
70
+ "- [ ] Resolve any conflicts in `.context-tree/` (framework files should generally take upstream version)",
71
+ ""
72
+ ];
73
+ if (repo.hasAgentMdMarkers()) lines.push("## Agent Instructions", "- [ ] Check if AGENT.md framework section needs updating — compare content between markers to the new template", "");
74
+ lines.push("## Verification", `- [ ] \`.context-tree/VERSION\` reads \`${upstreamVersion}\``, "- [ ] `context-tree verify` passes", "- [ ] AGENT.md framework section matches upstream", "", "---", "", "**Important:** As you complete each task, check it off in `.context-tree/progress.md` by changing `- [ ]` to `- [x]`. Run `context-tree verify` when done — it will fail if any items remain unchecked.", "");
75
+ const output = lines.join("\n");
76
+ console.log(output);
77
+ writeProgress(repo, output);
78
+ console.log("Progress file written to .context-tree/progress.md");
79
+ return 0;
80
+ }
81
+ //#endregion
82
+ export { runUpgrade };
@@ -0,0 +1,392 @@
1
+ import { n as Repo } from "./repo-BByc3VvM.js";
2
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { join, relative } from "node:path";
4
+ //#region src/validators/nodes.ts
5
+ const FRONTMATTER_RE = /^---\s*\n(.*?)\n---/s;
6
+ const OWNERS_RE = /^owners:\s*\[([^\]]*)\]/m;
7
+ const SOFT_LINKS_INLINE_RE = /^soft_links:\s*\[([^\]]*)\]/m;
8
+ const SOFT_LINKS_BLOCK_RE = /^soft_links:\s*\n((?:\s+-\s+.+\n?)+)/m;
9
+ const TITLE_RE = /^title:\s*['"]?(.+?)['"]?\s*$/m;
10
+ const GITHUB_USER_RE = /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?$/;
11
+ const SKIP = new Set(["node_modules", "__pycache__"]);
12
+ const SKIP_FILES = new Set(["AGENT.md", "CLAUDE.md"]);
13
+ const MIN_BODY_LENGTH = 20;
14
+ var Findings = class {
15
+ errors = [];
16
+ warnings = [];
17
+ infos = [];
18
+ error(msg) {
19
+ this.errors.push(msg);
20
+ }
21
+ warning(msg) {
22
+ this.warnings.push(msg);
23
+ }
24
+ info(msg) {
25
+ this.infos.push(msg);
26
+ }
27
+ hasErrors() {
28
+ return this.errors.length > 0;
29
+ }
30
+ printReport(totalFiles) {
31
+ const all = [
32
+ ...this.errors.map((e) => ["error", e]),
33
+ ...this.warnings.map((w) => ["warning", w]),
34
+ ...this.infos.map((i) => ["info", i])
35
+ ];
36
+ if (all.length > 0) {
37
+ const counts = [];
38
+ if (this.errors.length) counts.push(`${this.errors.length} error(s)`);
39
+ if (this.warnings.length) counts.push(`${this.warnings.length} warning(s)`);
40
+ if (this.infos.length) counts.push(`${this.infos.length} info(s)`);
41
+ console.log(`Found ${counts.join(", ")}:\n`);
42
+ const icons = {
43
+ error: "✗",
44
+ warning: "⚠",
45
+ info: "ℹ"
46
+ };
47
+ for (const [severity, msg] of all) console.log(` ${icons[severity]} [${severity}] ${msg}`);
48
+ } else console.log(`All ${totalFiles} node(s) passed validation.`);
49
+ }
50
+ };
51
+ let treeRoot = "";
52
+ const textCache = /* @__PURE__ */ new Map();
53
+ function setTreeRoot(root) {
54
+ treeRoot = root;
55
+ textCache.clear();
56
+ }
57
+ function rel(path) {
58
+ return relative(treeRoot, path);
59
+ }
60
+ function shouldSkip(path) {
61
+ return relative(treeRoot, path).split("/").some((part) => SKIP.has(part) || part.startsWith("."));
62
+ }
63
+ function readText(path) {
64
+ if (!textCache.has(path)) try {
65
+ textCache.set(path, readFileSync(path, "utf-8"));
66
+ } catch {
67
+ textCache.set(path, null);
68
+ }
69
+ return textCache.get(path);
70
+ }
71
+ function parseFrontmatter(path) {
72
+ const text = readText(path);
73
+ if (text === null) return null;
74
+ const m = text.match(FRONTMATTER_RE);
75
+ return m ? m[1] : null;
76
+ }
77
+ function parseBody(path) {
78
+ const text = readText(path);
79
+ if (text === null) return null;
80
+ const m = text.match(FRONTMATTER_RE);
81
+ if (m) return text.slice(m[0].length);
82
+ return text;
83
+ }
84
+ function parseSoftLinks(fm) {
85
+ let m = fm.match(SOFT_LINKS_INLINE_RE);
86
+ if (m) {
87
+ const raw = m[1].trim();
88
+ if (!raw) return [];
89
+ return raw.split(",").map((s) => s.trim().replace(/^['"]|['"]$/g, "")).filter(Boolean);
90
+ }
91
+ m = fm.match(SOFT_LINKS_BLOCK_RE);
92
+ if (m) return m[1].trim().split("\n").map((line) => line.trim().replace(/^-\s*/, "").trim().replace(/^['"]|['"]$/g, ""));
93
+ return null;
94
+ }
95
+ function resolveSoftLink(link) {
96
+ const clean = link.replace(/^\/+/, "");
97
+ const target = join(treeRoot, clean);
98
+ try {
99
+ if (statSync(target).isFile() && target.endsWith(".md")) return true;
100
+ } catch {}
101
+ try {
102
+ if (statSync(target).isDirectory() && existsSync(join(target, "NODE.md"))) return true;
103
+ } catch {}
104
+ return false;
105
+ }
106
+ function normalizeSoftLink(link) {
107
+ const clean = link.replace(/^\/+/, "");
108
+ const target = join(treeRoot, clean);
109
+ try {
110
+ if (statSync(target).isDirectory()) return join(target, "NODE.md");
111
+ } catch {}
112
+ return target;
113
+ }
114
+ function collectMdFiles() {
115
+ const files = [];
116
+ function walk(dir) {
117
+ let entries;
118
+ try {
119
+ entries = readdirSync(dir).sort();
120
+ } catch {
121
+ return;
122
+ }
123
+ for (const entry of entries) {
124
+ const full = join(dir, entry);
125
+ if (shouldSkip(full)) continue;
126
+ try {
127
+ const stat = statSync(full);
128
+ if (stat.isDirectory()) walk(full);
129
+ else if (stat.isFile() && entry.endsWith(".md") && !SKIP_FILES.has(entry)) files.push(full);
130
+ } catch {}
131
+ }
132
+ }
133
+ walk(treeRoot);
134
+ return files;
135
+ }
136
+ function validateOwners(fm, path, findings) {
137
+ const m = fm.match(OWNERS_RE);
138
+ if (!m) {
139
+ findings.error(`${rel(path)}: missing 'owners' field in frontmatter`);
140
+ return;
141
+ }
142
+ const raw = m[1].trim();
143
+ if (!raw) return;
144
+ const owners = raw.split(",").map((o) => o.trim()).filter(Boolean);
145
+ if (owners.length === 0) {
146
+ findings.error(`${rel(path)}: owners list contains only whitespace entries`);
147
+ return;
148
+ }
149
+ if (owners.length === 1 && owners[0] === "*") return;
150
+ for (const owner of owners) if (owner === "*") findings.error(`${rel(path)}: wildcard '*' must be the sole entry, not mixed with usernames`);
151
+ else if (!GITHUB_USER_RE.test(owner)) findings.error(`${rel(path)}: invalid owner '${owner}'`);
152
+ }
153
+ function validateSoftLinks(fm, path, findings) {
154
+ const links = parseSoftLinks(fm);
155
+ if (links === null) return;
156
+ for (const link of links) if (!link) findings.error(`${rel(path)}: empty soft_link entry`);
157
+ else if (!resolveSoftLink(link)) findings.error(`${rel(path)}: soft_link '${link}' does not resolve to an existing node`);
158
+ }
159
+ function validateFolders(findings) {
160
+ function walk(dir) {
161
+ let entries;
162
+ try {
163
+ entries = readdirSync(dir).sort();
164
+ } catch {
165
+ return;
166
+ }
167
+ for (const entry of entries) {
168
+ const full = join(dir, entry);
169
+ if (shouldSkip(full)) continue;
170
+ try {
171
+ if (!statSync(full).isDirectory()) continue;
172
+ } catch {
173
+ continue;
174
+ }
175
+ if (!existsSync(join(full, "NODE.md"))) findings.error(`${rel(full)}/: missing NODE.md`);
176
+ walk(full);
177
+ }
178
+ }
179
+ walk(treeRoot);
180
+ }
181
+ function validateDirectoryListing(findings) {
182
+ function walk(dir) {
183
+ let entries;
184
+ try {
185
+ entries = readdirSync(dir).sort();
186
+ } catch {
187
+ return;
188
+ }
189
+ for (const entry of entries) {
190
+ const full = join(dir, entry);
191
+ if (shouldSkip(full)) continue;
192
+ try {
193
+ if (!statSync(full).isDirectory()) continue;
194
+ } catch {
195
+ continue;
196
+ }
197
+ const nodeMd = join(full, "NODE.md");
198
+ if (!existsSync(nodeMd)) {
199
+ walk(full);
200
+ continue;
201
+ }
202
+ const body = parseBody(nodeMd);
203
+ if (body !== null) {
204
+ const actualLeaves = /* @__PURE__ */ new Set();
205
+ for (const f of readdirSync(full).sort()) {
206
+ const fp = join(full, f);
207
+ try {
208
+ if (statSync(fp).isFile() && f.endsWith(".md") && f !== "NODE.md") actualLeaves.add(f);
209
+ } catch {}
210
+ }
211
+ const referenced = /* @__PURE__ */ new Set();
212
+ let linkMatch;
213
+ const linkRe = /\[.*?\]\(([^)]+\.md)\)/g;
214
+ while ((linkMatch = linkRe.exec(body)) !== null) {
215
+ const ref = linkMatch[1];
216
+ if (ref.startsWith("http") || ref.startsWith("/")) continue;
217
+ if (!ref.includes("/")) referenced.add(ref);
218
+ }
219
+ for (const orphan of [...actualLeaves].filter((f) => !referenced.has(f)).sort()) findings.warning(`${rel(nodeMd)}: leaf file '${orphan}' exists but is not mentioned in NODE.md`);
220
+ for (const ref of [...referenced].filter((f) => !actualLeaves.has(f)).sort()) if (!existsSync(join(full, ref))) findings.warning(`${rel(nodeMd)}: references '${ref}' but the file does not exist`);
221
+ }
222
+ walk(full);
223
+ }
224
+ }
225
+ walk(treeRoot);
226
+ }
227
+ function validateRootDomainSync(findings) {
228
+ const body = parseBody(join(treeRoot, "NODE.md"));
229
+ if (body === null) return;
230
+ const bodyNoComments = body.replace(/<!--.*?-->/gs, "");
231
+ const listedDomains = /* @__PURE__ */ new Set();
232
+ let dm;
233
+ const domainRe = /\[(\w[\w-]*)\/?\]\((\w[\w-]*)\/NODE\.md\)/g;
234
+ while ((dm = domainRe.exec(bodyNoComments)) !== null) listedDomains.add(dm[2]);
235
+ const actualDomains = /* @__PURE__ */ new Set();
236
+ for (const child of readdirSync(treeRoot).sort()) {
237
+ const full = join(treeRoot, child);
238
+ try {
239
+ if (!statSync(full).isDirectory()) continue;
240
+ } catch {
241
+ continue;
242
+ }
243
+ if (child.startsWith(".") || SKIP.has(child)) continue;
244
+ if (existsSync(join(full, "NODE.md"))) actualDomains.add(child);
245
+ }
246
+ for (const missing of [...actualDomains].filter((d) => !listedDomains.has(d)).sort()) findings.error(`NODE.md: domain directory '${missing}/' exists but is not listed in root NODE.md`);
247
+ for (const extra of [...listedDomains].filter((d) => !actualDomains.has(d)).sort()) findings.error(`NODE.md: lists domain '${extra}/' but the directory does not exist or has no NODE.md`);
248
+ }
249
+ function validateSoftLinkReciprocity(files, findings) {
250
+ const allLinks = [];
251
+ for (const path of files) {
252
+ const fm = parseFrontmatter(path);
253
+ if (fm === null) continue;
254
+ const links = parseSoftLinks(fm);
255
+ if (!links) continue;
256
+ for (const link of links) {
257
+ if (!link) continue;
258
+ const target = normalizeSoftLink(link);
259
+ allLinks.push([path, target]);
260
+ }
261
+ }
262
+ for (const [source, target] of allLinks) {
263
+ if (!existsSync(target)) continue;
264
+ let hasBackLink = false;
265
+ const targetFm = parseFrontmatter(target);
266
+ if (targetFm) {
267
+ const targetLinks = parseSoftLinks(targetFm);
268
+ if (targetLinks) for (const tl of targetLinks) {
269
+ if (!tl) continue;
270
+ const resolved = normalizeSoftLink(tl);
271
+ if (resolved === source || resolved === join(source, "..", "NODE.md")) {
272
+ hasBackLink = true;
273
+ break;
274
+ }
275
+ }
276
+ }
277
+ if (!hasBackLink) {
278
+ const targetBody = parseBody(target);
279
+ if (targetBody) {
280
+ const sourceRel = rel(source);
281
+ const linkRe = /\[.*?\]\(([^)]+\.md)\)/g;
282
+ let lm;
283
+ while ((lm = linkRe.exec(targetBody)) !== null) {
284
+ const ref = lm[1];
285
+ if (ref.startsWith("http") || ref.startsWith("/")) continue;
286
+ if (sourceRel.endsWith(ref) || ref === sourceRel) {
287
+ hasBackLink = true;
288
+ break;
289
+ }
290
+ }
291
+ }
292
+ }
293
+ if (!hasBackLink) findings.info(`${rel(source)}: soft_link to '${rel(target)}' is one-way (target has no reference back)`);
294
+ }
295
+ }
296
+ function validateEmptyNodes(files, findings) {
297
+ for (const path of files) {
298
+ const text = readText(path);
299
+ if (text === null) continue;
300
+ const m = text.match(FRONTMATTER_RE);
301
+ if (!m) continue;
302
+ if (text.slice(m[0].length).replace(/\s+/g, "").length < MIN_BODY_LENGTH) findings.warning(`${rel(path)}: node has little or no body content`);
303
+ }
304
+ }
305
+ function validateTitleMismatch(files, findings) {
306
+ for (const path of files) {
307
+ const text = readText(path);
308
+ if (text === null) continue;
309
+ const fmMatch = text.match(FRONTMATTER_RE);
310
+ if (!fmMatch) continue;
311
+ const titleMatch = fmMatch[1].match(TITLE_RE);
312
+ if (!titleMatch) continue;
313
+ const fmTitle = titleMatch[1].trim();
314
+ const headingMatch = text.slice(fmMatch[0].length).match(/^#\s+(.+)$/m);
315
+ if (!headingMatch) continue;
316
+ const bodyHeading = headingMatch[1].trim();
317
+ if (fmTitle !== bodyHeading) findings.warning(`${rel(path)}: frontmatter title '${fmTitle}' differs from first heading '${bodyHeading}'`);
318
+ }
319
+ }
320
+ function runValidateNodes(root) {
321
+ setTreeRoot(root);
322
+ const files = collectMdFiles();
323
+ const findings = new Findings();
324
+ validateFolders(findings);
325
+ for (const path of files) {
326
+ const fm = parseFrontmatter(path);
327
+ if (fm === null) {
328
+ findings.error(`${rel(path)}: no frontmatter found`);
329
+ continue;
330
+ }
331
+ validateOwners(fm, path, findings);
332
+ validateSoftLinks(fm, path, findings);
333
+ }
334
+ validateDirectoryListing(findings);
335
+ validateRootDomainSync(findings);
336
+ validateSoftLinkReciprocity(files, findings);
337
+ validateEmptyNodes(files, findings);
338
+ validateTitleMismatch(files, findings);
339
+ findings.printReport(files.length);
340
+ return {
341
+ exitCode: findings.hasErrors() ? 1 : 0,
342
+ findings
343
+ };
344
+ }
345
+ //#endregion
346
+ //#region src/verify.ts
347
+ const UNCHECKED_RE = /^- \[ \] (.+)$/gm;
348
+ function check(label, passed) {
349
+ console.log(` ${passed ? "✓" : "✗"} [${passed ? "PASS" : "FAIL"}] ${label}`);
350
+ return passed;
351
+ }
352
+ function checkProgress(repo) {
353
+ const text = repo.readFile(".context-tree/progress.md");
354
+ if (text === null) return [];
355
+ const matches = [];
356
+ let m;
357
+ UNCHECKED_RE.lastIndex = 0;
358
+ while ((m = UNCHECKED_RE.exec(text)) !== null) matches.push(m[1]);
359
+ return matches;
360
+ }
361
+ function defaultNodeValidator(root) {
362
+ const { exitCode } = runValidateNodes(root);
363
+ return { exitCode };
364
+ }
365
+ function runVerify(repo, nodeValidator) {
366
+ const r = repo ?? new Repo();
367
+ const validate = nodeValidator ?? defaultNodeValidator;
368
+ let allPassed = true;
369
+ console.log("Context Tree Verification\n");
370
+ const unchecked = checkProgress(r);
371
+ if (unchecked.length > 0) {
372
+ console.log(" Unchecked items in .context-tree/progress.md:\n");
373
+ for (const item of unchecked) console.log(` - [ ] ${item}`);
374
+ console.log();
375
+ console.log(" Verify each step above and check it off in progress.md before running verify again.\n");
376
+ allPassed = false;
377
+ }
378
+ console.log(" Checks:\n");
379
+ allPassed = check(".context-tree/VERSION exists", r.hasFramework()) && allPassed;
380
+ const fm = r.frontmatter("NODE.md");
381
+ allPassed = check("Root NODE.md has valid frontmatter (title, owners)", fm !== null && fm.title !== void 0 && fm.owners !== void 0) && allPassed;
382
+ allPassed = check("AGENT.md exists with framework markers", r.hasAgentMdMarkers()) && allPassed;
383
+ const { exitCode } = validate(r.root);
384
+ allPassed = check("Node validation passes", exitCode === 0) && allPassed;
385
+ allPassed = check("At least one member node exists under members/", r.memberCount() > 0) && allPassed;
386
+ console.log();
387
+ if (allPassed) console.log("All checks passed.");
388
+ else console.log("Some checks failed. See above for details.");
389
+ return allPassed ? 0 : 1;
390
+ }
391
+ //#endregion
392
+ export { runVerify };
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "first-tree",
3
+ "version": "0.0.1",
4
+ "description": "CLI tools for Context Tree — the living source of truth for your organization.",
5
+ "type": "module",
6
+ "bin": {
7
+ "context-tree": "./dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "scripts": {
13
+ "build": "tsdown src/cli.ts --format esm --out-dir dist",
14
+ "prepublishOnly": "pnpm build",
15
+ "test": "vitest run",
16
+ "typecheck": "tsc --noEmit"
17
+ },
18
+ "license": "Apache-2.0",
19
+ "devDependencies": {
20
+ "@types/node": "^25.5.0",
21
+ "tsdown": "^0.12.0",
22
+ "typescript": "^5.8.0",
23
+ "vitest": "^3.2.0"
24
+ }
25
+ }