@forwardimpact/libcoaligned 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,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 the 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 2026 Dick Olsson
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,27 @@
1
+ # libcoaligned
2
+
3
+ <!-- BEGIN:description — Do not edit. Generated from package.json. -->
4
+
5
+ Co-Aligned architecture checks — enforce instruction-layer length caps and JTBD
6
+ invariants across the repo.
7
+
8
+ <!-- END:description -->
9
+
10
+ ## Getting Started
11
+
12
+ ```sh
13
+ npx coaligned # run every check (instructions + jtbd)
14
+ npx coaligned instructions # enforce L1–L6 length and checklist caps
15
+ npx coaligned jtbd # validate JTBD entries against package.json
16
+ npx coaligned jtbd --fix # regenerate catalog and job blocks in place
17
+ ```
18
+
19
+ The two subcommands implement the contract described in
20
+ [COALIGNED.md](https://github.com/forwardimpact/monorepo/blob/main/COALIGNED.md):
21
+
22
+ - `instructions` — every layer (L1 CLAUDE.md, L2 CONTRIBUTING.md / JTBD.md,
23
+ L3 agent profile, L4 SKILL.md, L5 reference, L6 checklist block) is gated by
24
+ a line cap **and** a word cap. Either breach fails.
25
+ - `jtbd` — each `package.json .jobs` entry is validated against the JTBD
26
+ schema; with `--fix`, marker-delimited blocks in `<dir>/README.md`,
27
+ `<dir>/<pkg>/README.md`, and root `JTBD.md` are regenerated.
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFileSync } from "node:fs";
4
+ import { createCli } from "@forwardimpact/libcli";
5
+ import { checkInstructions, checkJtbd } from "../src/index.js";
6
+
7
+ const { version: VERSION } = JSON.parse(
8
+ readFileSync(new URL("../package.json", import.meta.url), "utf8"),
9
+ );
10
+
11
+ const definition = {
12
+ name: "coaligned",
13
+ version: VERSION,
14
+ description:
15
+ "Enforce the layered instruction architecture defined in COALIGNED.md (no subcommand: run every check)",
16
+ commands: [
17
+ {
18
+ name: "instructions",
19
+ args: [],
20
+ description: "Check L1–L6 length and checklist caps across the repo",
21
+ handler: instructionsHandler,
22
+ examples: ["coaligned instructions"],
23
+ },
24
+ {
25
+ name: "jtbd",
26
+ args: [],
27
+ description: "Validate package.json .jobs entries and generated blocks",
28
+ options: {
29
+ fix: {
30
+ type: "boolean",
31
+ description: "Regenerate stale catalog and jobs blocks in place",
32
+ },
33
+ },
34
+ handler: jtbdHandler,
35
+ examples: ["coaligned jtbd", "coaligned jtbd --fix"],
36
+ },
37
+ ],
38
+ globalOptions: {
39
+ help: { type: "boolean", short: "h", description: "Show this help" },
40
+ version: { type: "boolean", description: "Show version" },
41
+ json: { type: "boolean", description: "Output help as JSON" },
42
+ },
43
+ examples: ["coaligned", "coaligned instructions", "coaligned jtbd --fix"],
44
+ };
45
+
46
+ const cli = createCli(definition);
47
+
48
+ async function runInstructions(root) {
49
+ const errors = await checkInstructions({ root });
50
+ for (const e of errors) process.stderr.write(`error: ${e}\n`);
51
+ return errors.length > 0 ? 1 : 0;
52
+ }
53
+
54
+ async function runJtbd(root, fix) {
55
+ const { errors, stale, fixed } = await checkJtbd({ root, fix });
56
+ for (const e of errors) process.stderr.write(`${e}\n`);
57
+ for (const f of fixed) process.stdout.write(`Regenerated ${f}.\n`);
58
+ for (const s of stale) {
59
+ process.stderr.write(
60
+ `${s} out of date. Run \`coaligned jtbd --fix\` to regenerate.\n`,
61
+ );
62
+ }
63
+ return errors.length > 0 || stale.length > 0 ? 1 : 0;
64
+ }
65
+
66
+ async function instructionsHandler(ctx) {
67
+ return runInstructions(ctx.data.root);
68
+ }
69
+
70
+ async function jtbdHandler(ctx) {
71
+ return runJtbd(ctx.data.root, !!ctx.options.fix);
72
+ }
73
+
74
+ async function main() {
75
+ const parsed = cli.parse(process.argv.slice(2));
76
+ if (!parsed) return 0;
77
+
78
+ const root = process.cwd();
79
+
80
+ // No subcommand → run every check; --fix stays jtbd-only and must be opted
81
+ // into explicitly via `coaligned jtbd --fix`.
82
+ if (parsed.positionals.length === 0) {
83
+ const a = await runInstructions(root);
84
+ const b = await runJtbd(root, false);
85
+ return a || b;
86
+ }
87
+
88
+ const known = definition.commands.map((c) => c.name);
89
+ if (!known.includes(parsed.positionals[0])) {
90
+ cli.usageError(`unknown command "${parsed.positionals[0]}"`);
91
+ return 2;
92
+ }
93
+
94
+ return await cli.dispatch(parsed, { data: { root } });
95
+ }
96
+
97
+ main()
98
+ .then((code) => process.exit(code ?? 0))
99
+ .catch((err) => {
100
+ cli.error(err.message);
101
+ process.exit(1);
102
+ });
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@forwardimpact/libcoaligned",
3
+ "version": "0.1.0",
4
+ "description": "Co-Aligned architecture checks — enforce instruction-layer length caps and JTBD invariants across the repo.",
5
+ "keywords": [
6
+ "coaligned",
7
+ "instructions",
8
+ "jtbd",
9
+ "checklist",
10
+ "agent"
11
+ ],
12
+ "homepage": "https://www.forwardimpact.team",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/forwardimpact/monorepo.git",
16
+ "directory": "libraries/libcoaligned"
17
+ },
18
+ "license": "Apache-2.0",
19
+ "author": "D. Olsson <hi@senzilla.io>",
20
+ "jobs": [
21
+ {
22
+ "user": "Platform Builders",
23
+ "goal": "Keep Instruction Layers Honest",
24
+ "trigger": "Editing a CLAUDE.md or skill procedure and realizing the layer has quietly grown past its budget.",
25
+ "bigHire": "enforce instruction-layer length caps and JTBD invariants without hand-rolling repo checks.",
26
+ "littleHire": "verify a docs change before commit and trust the layered architecture has not drifted.",
27
+ "competesWith": "ad-hoc shell scripts; eyeballing word counts; tolerating slow drift in the instruction architecture"
28
+ }
29
+ ],
30
+ "type": "module",
31
+ "main": "./src/index.js",
32
+ "exports": {
33
+ ".": "./src/index.js",
34
+ "./bin/coaligned.js": "./bin/coaligned.js"
35
+ },
36
+ "bin": {
37
+ "coaligned": "./bin/coaligned.js"
38
+ },
39
+ "files": [
40
+ "src/**/*.js",
41
+ "bin/**/*.js",
42
+ "README.md"
43
+ ],
44
+ "scripts": {
45
+ "test": "bun test test/*.test.js"
46
+ },
47
+ "dependencies": {
48
+ "@forwardimpact/libcli": "^0.1.9",
49
+ "prettier": "^3.0.0"
50
+ },
51
+ "engines": {
52
+ "bun": ">=1.2.0",
53
+ "node": ">=18.0.0"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ }
58
+ }
package/src/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { checkInstructions } from "./instructions.js";
2
+ export { checkJtbd } from "./jtbd.js";
@@ -0,0 +1,220 @@
1
+ import { readFile, readdir } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+
4
+ const SKIP_DIRS = new Set([
5
+ ".cache",
6
+ ".git",
7
+ "build",
8
+ "dist",
9
+ "generated",
10
+ "node_modules",
11
+ "tmp",
12
+ "wiki",
13
+ "worktrees",
14
+ ]);
15
+
16
+ const L6_MAX_ITEMS = 9;
17
+ const L6_MAX_WORDS_PER_ITEM = 32;
18
+
19
+ const CHECKLIST_RE =
20
+ /<(read_do_checklist|do_confirm_checklist)\b[^>]*>([\s\S]*?)<\/\1>/g;
21
+ const ITEM_SPLIT_RE = /^\s*-\s*\[[ xX]\]\s*/m;
22
+
23
+ const lineCount = (text) => (text.match(/\n/g) || []).length;
24
+ const wordCount = (text) => (text.match(/\S+/g) || []).length;
25
+
26
+ async function walk(root, dir, visit) {
27
+ let entries;
28
+ try {
29
+ entries = await readdir(resolve(root, dir), { withFileTypes: true });
30
+ } catch {
31
+ return;
32
+ }
33
+ for (const e of entries) {
34
+ if (SKIP_DIRS.has(e.name)) continue;
35
+ const path = dir === "." ? e.name : `${dir}/${e.name}`;
36
+ await visit(e, path);
37
+ if (e.isDirectory()) await walk(root, path, visit);
38
+ }
39
+ }
40
+
41
+ async function listFiles(root, dir, match) {
42
+ try {
43
+ const entries = await readdir(resolve(root, dir), { withFileTypes: true });
44
+ return entries.filter(match).map((e) => `${dir}/${e.name}`);
45
+ } catch {
46
+ return [];
47
+ }
48
+ }
49
+
50
+ async function readText(root, path) {
51
+ try {
52
+ return await readFile(resolve(root, path), "utf8");
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ async function findByName(root, name, kind) {
59
+ const out = [];
60
+ await walk(root, ".", (e, path) => {
61
+ const isMatch = kind === "file" ? e.isFile() : e.isDirectory();
62
+ if (isMatch && e.name === name) out.push(path);
63
+ });
64
+ return out;
65
+ }
66
+
67
+ async function findAgentProfiles(root, claudeDirs) {
68
+ const out = [];
69
+ for (const d of claudeDirs) {
70
+ const files = await listFiles(
71
+ root,
72
+ `${d}/agents`,
73
+ (e) => e.isFile() && e.name.endsWith(".md"),
74
+ );
75
+ out.push(...files);
76
+ }
77
+ return out;
78
+ }
79
+
80
+ async function findSkillDirs(root, claudeDirs) {
81
+ const out = [];
82
+ for (const d of claudeDirs) {
83
+ const dirs = await listFiles(root, `${d}/skills`, (e) => e.isDirectory());
84
+ out.push(...dirs);
85
+ }
86
+ return out;
87
+ }
88
+
89
+ async function findSkillReferences(root, skillDirs) {
90
+ const out = [];
91
+ for (const d of skillDirs) {
92
+ const files = await listFiles(
93
+ root,
94
+ `${d}/references`,
95
+ (e) => e.isFile() && e.name.endsWith(".md"),
96
+ );
97
+ out.push(...files);
98
+ }
99
+ return out;
100
+ }
101
+
102
+ async function buildLayers(root) {
103
+ const claudeDirs = await findByName(root, ".claude", "dir");
104
+ const skillDirs = await findSkillDirs(root, claudeDirs);
105
+ return {
106
+ skillDirs,
107
+ layers: [
108
+ {
109
+ id: "L1",
110
+ name: "CLAUDE.md",
111
+ maxLines: 192,
112
+ maxWords: 896,
113
+ files: await findByName(root, "CLAUDE.md", "file"),
114
+ },
115
+ {
116
+ id: "L2",
117
+ name: "CONTRIBUTING.md",
118
+ maxLines: 320,
119
+ maxWords: 1408,
120
+ files: ["CONTRIBUTING.md"],
121
+ },
122
+ {
123
+ id: "L2",
124
+ name: "JTBD.md",
125
+ maxLines: 320,
126
+ maxWords: 1408,
127
+ files: ["JTBD.md"],
128
+ },
129
+ {
130
+ id: "L3",
131
+ name: "agent profile",
132
+ maxLines: 64,
133
+ maxWords: 384,
134
+ files: await findAgentProfiles(root, claudeDirs),
135
+ },
136
+ {
137
+ id: "L4",
138
+ name: "skill procedure",
139
+ maxLines: 192,
140
+ maxWords: 1280,
141
+ files: skillDirs.map((d) => `${d}/SKILL.md`),
142
+ },
143
+ {
144
+ id: "L5",
145
+ name: "skill reference",
146
+ maxLines: 128,
147
+ maxWords: 768,
148
+ files: await findSkillReferences(root, skillDirs),
149
+ },
150
+ ],
151
+ };
152
+ }
153
+
154
+ async function checkLayer(root, layer, errors) {
155
+ for (const path of layer.files) {
156
+ const text = await readText(root, path);
157
+ if (text == null) continue;
158
+ const lines = lineCount(text);
159
+ const words = wordCount(text);
160
+ if (lines > layer.maxLines) {
161
+ errors.push(
162
+ `${path} has ${lines} lines (max ${layer.maxLines}, ${layer.id} ${layer.name})`,
163
+ );
164
+ }
165
+ if (words > layer.maxWords) {
166
+ errors.push(
167
+ `${path} has ${words} words (max ${layer.maxWords}, ${layer.id} ${layer.name})`,
168
+ );
169
+ }
170
+ }
171
+ }
172
+
173
+ async function checkChecklists(root, sources, errors) {
174
+ for (const path of sources) {
175
+ const text = await readText(root, path);
176
+ if (text == null) continue;
177
+ let m;
178
+ let index = 0;
179
+ while ((m = CHECKLIST_RE.exec(text))) {
180
+ index += 1;
181
+ const type = m[1];
182
+ const items = m[2].split(ITEM_SPLIT_RE).slice(1);
183
+ if (items.length > L6_MAX_ITEMS) {
184
+ errors.push(
185
+ `${path} checklist #${index} (${type}) has ${items.length} items (max ${L6_MAX_ITEMS}, L6 checklist)`,
186
+ );
187
+ }
188
+ items.forEach((raw, i) => {
189
+ const w = wordCount(raw.trim());
190
+ if (w > L6_MAX_WORDS_PER_ITEM) {
191
+ errors.push(
192
+ `${path} checklist #${index} (${type}) item ${i + 1} has ${w} words (max ${L6_MAX_WORDS_PER_ITEM}, L6 checklist item)`,
193
+ );
194
+ }
195
+ });
196
+ }
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Walk the repo rooted at `root`, applying the L1–L6 caps from COALIGNED.md.
202
+ * Each layer is gated by a line cap AND a word cap; either breach fails.
203
+ *
204
+ * @param {{ root: string }} options
205
+ * @returns {Promise<string[]>} List of human-readable error messages; empty when the repo is conformant.
206
+ */
207
+ export async function checkInstructions({ root }) {
208
+ const errors = [];
209
+ const { layers, skillDirs } = await buildLayers(root);
210
+
211
+ for (const layer of layers) await checkLayer(root, layer, errors);
212
+
213
+ const checklistSources = [
214
+ "CONTRIBUTING.md",
215
+ ...skillDirs.map((d) => `${d}/SKILL.md`),
216
+ ];
217
+ await checkChecklists(root, checklistSources, errors);
218
+
219
+ return errors;
220
+ }
package/src/jtbd.js ADDED
@@ -0,0 +1,430 @@
1
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import * as prettier from "prettier";
4
+
5
+ const VALID_USERS = [
6
+ "Engineering Leaders",
7
+ "Empowered Engineers",
8
+ "Platform Builders",
9
+ ];
10
+
11
+ const USER_ORDER = new Map(VALID_USERS.map((u, i) => [u, i]));
12
+
13
+ function catalogs(root) {
14
+ return [
15
+ {
16
+ name: "products",
17
+ dir: join(root, "products"),
18
+ readme: join(root, "products", "README.md"),
19
+ filter: (name) => !name.startsWith(".") && name !== "node_modules",
20
+ column: "Product",
21
+ skipUniqueHires: true,
22
+ },
23
+ {
24
+ name: "services",
25
+ dir: join(root, "services"),
26
+ readme: join(root, "services", "README.md"),
27
+ filter: (name) => !name.startsWith(".") && name !== "node_modules",
28
+ column: "Service",
29
+ },
30
+ {
31
+ name: "libraries",
32
+ dir: join(root, "libraries"),
33
+ readme: join(root, "libraries", "README.md"),
34
+ filter: (name) => name.startsWith("lib"),
35
+ column: "Library",
36
+ },
37
+ ];
38
+ }
39
+
40
+ function loadPackages(dir, filter) {
41
+ if (!existsSync(dir)) return [];
42
+ const out = [];
43
+ for (const name of readdirSync(dir)) {
44
+ if (!filter(name)) continue;
45
+ const pkgPath = join(dir, name, "package.json");
46
+ let pkg;
47
+ try {
48
+ pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
49
+ } catch {
50
+ continue;
51
+ }
52
+ out.push({ dir: name, pkg });
53
+ }
54
+ return out.sort((a, b) => a.dir.localeCompare(b.dir));
55
+ }
56
+
57
+ function validateEntry(entry, prefix) {
58
+ const errors = [];
59
+ if (!(entry.user && VALID_USERS.includes(entry.user))) {
60
+ errors.push(
61
+ `${prefix}: invalid user "${entry.user}". Must be one of: ${VALID_USERS.join(", ")}`,
62
+ );
63
+ }
64
+ for (const field of ["goal", "trigger", "competesWith"]) {
65
+ if (!entry[field] || typeof entry[field] !== "string") {
66
+ errors.push(`${prefix}: ${field} is required and must be a string`);
67
+ }
68
+ }
69
+ for (const field of ["bigHire", "littleHire"]) {
70
+ if (!entry[field] || typeof entry[field] !== "string") {
71
+ errors.push(`${prefix}: ${field} is required and must be a string`);
72
+ } else if (!entry[field].endsWith(".")) {
73
+ errors.push(`${prefix}: ${field} must end with ".": "${entry[field]}"`);
74
+ }
75
+ }
76
+ return errors;
77
+ }
78
+
79
+ function checkHireUniqueness(entry, prefix, allHires, loc) {
80
+ const errors = [];
81
+ for (const field of ["bigHire", "littleHire"]) {
82
+ if (!entry[field] || typeof entry[field] !== "string") continue;
83
+ const key = `${field}:${entry[field].toLowerCase()}`;
84
+ if (allHires.has(key) && allHires.get(key).goal !== entry.goal) {
85
+ errors.push(
86
+ `${prefix}: duplicate ${field} "${entry[field]}" (also in ${allHires.get(key).loc})`,
87
+ );
88
+ }
89
+ allHires.set(key, { loc, goal: entry.goal });
90
+ }
91
+ return errors;
92
+ }
93
+
94
+ function validate(packages, dirName, { skipUniqueHires = false } = {}) {
95
+ const allHires = new Map();
96
+ const errors = [];
97
+ for (const { dir, pkg } of packages) {
98
+ const jobs = pkg.jobs;
99
+ if (!jobs) continue;
100
+ if (!Array.isArray(jobs)) {
101
+ errors.push(`${dir}/package.json: .jobs must be an array`);
102
+ continue;
103
+ }
104
+ for (let i = 0; i < jobs.length; i++) {
105
+ const entry = jobs[i];
106
+ const prefix = `${dirName}/${dir}/package.json .jobs[${i}]`;
107
+ errors.push(...validateEntry(entry, prefix));
108
+ if (!skipUniqueHires) {
109
+ errors.push(
110
+ ...checkHireUniqueness(entry, prefix, allHires, `${dirName}/${dir}`),
111
+ );
112
+ }
113
+ }
114
+ }
115
+ return errors;
116
+ }
117
+
118
+ function renderTable(headers, rows) {
119
+ const widths = headers.map((h, i) =>
120
+ Math.max(h.length, ...rows.map((r) => r[i].length)),
121
+ );
122
+ const line = (cells) =>
123
+ `| ${cells.map((c, i) => c.padEnd(widths[i])).join(" | ")} |`;
124
+ return [
125
+ line(headers),
126
+ line(widths.map((w) => "-".repeat(w))),
127
+ ...rows.map(line),
128
+ ].join("\n");
129
+ }
130
+
131
+ function findMarker(content, tag) {
132
+ const pattern = new RegExp(`<!--\\s*${tag}[^>]*-->`);
133
+ const match = content.match(pattern);
134
+ if (!match) return null;
135
+ return { text: match[0], index: match.index };
136
+ }
137
+
138
+ function replaceBlock(content, beginTag, endTag, body) {
139
+ const begin = findMarker(content, beginTag);
140
+ const end = findMarker(content, endTag);
141
+ if (!(begin && end) || end.index < begin.index) return null;
142
+ return (
143
+ content.slice(0, begin.index) +
144
+ `${begin.text}\n\n${body}\n\n${end.text}` +
145
+ content.slice(end.index + end.text.length)
146
+ );
147
+ }
148
+
149
+ function mergeTriggers(triggers) {
150
+ const stripped = triggers.map((t) => t.replace(/\.\s*$/, "").trim());
151
+ const unique = [...new Set(stripped)];
152
+ const parts = unique.map((s, i) =>
153
+ i > 0 ? s.charAt(0).toLowerCase() + s.slice(1) : s,
154
+ );
155
+ return parts.join("; ") + ".";
156
+ }
157
+
158
+ function mergeCompetesWith(fragments) {
159
+ if (fragments.length === 0) return null;
160
+ const seen = new Set();
161
+ const unique = [];
162
+ for (const f of fragments) {
163
+ const normalized = f.replace(/\.\s*$/, "").trim();
164
+ const key = normalized.toLowerCase();
165
+ if (!seen.has(key)) {
166
+ seen.add(key);
167
+ unique.push(normalized);
168
+ }
169
+ }
170
+ return unique.join("; ") + ".";
171
+ }
172
+
173
+ function mergeHireField(entries, capitalize) {
174
+ if (entries.length === 0) return null;
175
+ const stripped = entries.map((e) => e.text.replace(/\.\s*$/, "").trim());
176
+ const unique = [...new Set(stripped)];
177
+ const parts = unique.map((s, i) =>
178
+ i > 0 ? s.charAt(0).toLowerCase() + s.slice(1) : s,
179
+ );
180
+ const pkgs = [...new Set(entries.map((e) => e.pkg))];
181
+ const names = pkgs.map((p) =>
182
+ capitalize ? p.charAt(0).toUpperCase() + p.slice(1) : p,
183
+ );
184
+ return `Help me ${parts.join("; ")}. → **${names.join(", ")}**`;
185
+ }
186
+
187
+ function addEntryToGroup(group, entry, dir) {
188
+ if (entry.trigger) group.triggers.push(entry.trigger);
189
+ if (entry.bigHire) group.bigHires.push({ text: entry.bigHire, pkg: dir });
190
+ if (entry.littleHire)
191
+ group.littleHires.push({ text: entry.littleHire, pkg: dir });
192
+ if (entry.competesWith) {
193
+ for (const fragment of entry.competesWith.split(";")) {
194
+ const trimmed = fragment.trim();
195
+ if (trimmed) group.competesWith.push(trimmed);
196
+ }
197
+ }
198
+ if (entry.forces && !group.forces) group.forces = entry.forces;
199
+ if (entry.firedWhen && !group.firedWhen) group.firedWhen = entry.firedWhen;
200
+ }
201
+
202
+ function collectJobGroups(packages) {
203
+ const groups = new Map();
204
+ for (const { dir, pkg } of packages) {
205
+ if (!pkg.jobs) continue;
206
+ for (const entry of pkg.jobs) {
207
+ const key = `${entry.user}\0${entry.goal}`;
208
+ if (!groups.has(key)) {
209
+ groups.set(key, {
210
+ user: entry.user,
211
+ goal: entry.goal,
212
+ triggers: [],
213
+ bigHires: [],
214
+ littleHires: [],
215
+ competesWith: [],
216
+ forces: null,
217
+ firedWhen: null,
218
+ });
219
+ }
220
+ addEntryToGroup(groups.get(key), entry, dir);
221
+ }
222
+ }
223
+ return groups;
224
+ }
225
+
226
+ function buildJobProse(group, capitalize) {
227
+ const trigger = mergeTriggers(group.triggers);
228
+ const competesWith = mergeCompetesWith(group.competesWith);
229
+ const bigHire = mergeHireField(group.bigHires, capitalize);
230
+ const littleHire = mergeHireField(group.littleHires, capitalize);
231
+
232
+ const lines = [
233
+ `## ${group.user}: ${group.goal}`,
234
+ "",
235
+ `**Trigger:** ${trigger}`,
236
+ ];
237
+ if (bigHire) lines.push("", `**Big Hire:** ${bigHire}`);
238
+ if (littleHire) lines.push("", `**Little Hire:** ${littleHire}`);
239
+ lines.push("", `**Competes With:** ${competesWith}`);
240
+
241
+ if (group.forces) {
242
+ lines.push(
243
+ "",
244
+ "**Forces:**",
245
+ `- **Push:** ${group.forces.push}`,
246
+ `- **Pull:** ${group.forces.pull}`,
247
+ `- **Habit:** ${group.forces.habit}`,
248
+ `- **Anxiety:** ${group.forces.anxiety}`,
249
+ );
250
+ }
251
+ if (group.firedWhen) lines.push("", `**Fired When:** ${group.firedWhen}`);
252
+ return lines.join("\n");
253
+ }
254
+
255
+ function makeFormatter(prettierConfig) {
256
+ return async function formatMarkdown(text) {
257
+ const formatted = await prettier.format(text, {
258
+ ...prettierConfig,
259
+ parser: "markdown",
260
+ });
261
+ // Prettier inserts a blank line between bold labels and bullet lists;
262
+ // remove it to match the hand-written JTBD.md style.
263
+ return formatted.replace(/\*\*\n\n(- )/g, "**\n$1").trimEnd();
264
+ };
265
+ }
266
+
267
+ async function buildCatalog(content, packages, column, formatMarkdown) {
268
+ const rows = packages
269
+ .filter(({ pkg }) => pkg.description)
270
+ .map(({ dir, pkg }) => [`**${dir}**`, pkg.description]);
271
+ if (rows.length === 0) return content;
272
+ const body = await formatMarkdown(renderTable([column, "Description"], rows));
273
+ return replaceBlock(content, "BEGIN:catalog", "END:catalog", body) ?? content;
274
+ }
275
+
276
+ async function buildJobs(
277
+ content,
278
+ packages,
279
+ formatMarkdown,
280
+ { capitalize = false } = {},
281
+ ) {
282
+ const groups = collectJobGroups(packages);
283
+ if (groups.size === 0) return content;
284
+
285
+ const sorted = [...groups.values()].sort((a, b) => {
286
+ const ua = USER_ORDER.get(a.user) ?? 99;
287
+ const ub = USER_ORDER.get(b.user) ?? 99;
288
+ if (ua !== ub) return ua - ub;
289
+ return a.goal.localeCompare(b.goal);
290
+ });
291
+
292
+ const blocks = await Promise.all(
293
+ sorted.map(async (group) => {
294
+ const formatted = await formatMarkdown(buildJobProse(group, capitalize));
295
+ return `<job user="${group.user}" goal="${group.goal}">\n\n${formatted}\n\n</job>`;
296
+ }),
297
+ );
298
+
299
+ const body = blocks.join("\n\n");
300
+ return replaceBlock(content, "BEGIN:jobs", "END:jobs", body) ?? content;
301
+ }
302
+
303
+ async function buildDescription(content, description, formatMarkdown) {
304
+ const formatted = await formatMarkdown(description);
305
+ const result = replaceBlock(
306
+ content,
307
+ "BEGIN:description",
308
+ "END:description",
309
+ formatted,
310
+ );
311
+ if (result !== null) return result;
312
+
313
+ const headingMatch = content.match(/^# .+\n/);
314
+ if (!headingMatch) return null;
315
+ const headingEnd = headingMatch[0].length;
316
+ const nextSection = content.indexOf("\n\n## ", headingEnd);
317
+ const descEnd = nextSection !== -1 ? nextSection : content.length;
318
+
319
+ const begin =
320
+ "<!-- BEGIN:description — Do not edit. Generated from package.json. -->";
321
+ const end = "<!-- END:description -->";
322
+
323
+ return (
324
+ content.slice(0, headingEnd) +
325
+ `\n${begin}\n\n${formatted}\n\n${end}` +
326
+ content.slice(descEnd)
327
+ );
328
+ }
329
+
330
+ function commitUpdate(filePath, label, original, updated, fix, result) {
331
+ if (updated === null || updated === original) return;
332
+ if (!fix) {
333
+ result.stale.push(label);
334
+ return;
335
+ }
336
+ writeFileSync(filePath, updated);
337
+ result.fixed.push(label);
338
+ }
339
+
340
+ async function processCatalog(catalog, fix, formatMarkdown, result) {
341
+ const packages = loadPackages(catalog.dir, catalog.filter);
342
+ const errors = validate(packages, catalog.name, {
343
+ skipUniqueHires: catalog.skipUniqueHires ?? false,
344
+ });
345
+ if (errors.length > 0) {
346
+ result.errors.push(...errors);
347
+ return;
348
+ }
349
+
350
+ if (existsSync(catalog.readme)) {
351
+ const original = readFileSync(catalog.readme, "utf8");
352
+ let content = original;
353
+ content = await buildCatalog(
354
+ content,
355
+ packages,
356
+ catalog.column,
357
+ formatMarkdown,
358
+ );
359
+ content = await buildJobs(content, packages, formatMarkdown);
360
+ commitUpdate(
361
+ catalog.readme,
362
+ `${catalog.name}/README.md`,
363
+ original,
364
+ content,
365
+ fix,
366
+ result,
367
+ );
368
+ }
369
+
370
+ for (const { dir, pkg } of packages) {
371
+ if (!pkg.description) continue;
372
+ const pkgReadme = join(catalog.dir, dir, "README.md");
373
+ if (!existsSync(pkgReadme)) continue;
374
+ const original = readFileSync(pkgReadme, "utf8");
375
+ const updated = await buildDescription(
376
+ original,
377
+ pkg.description,
378
+ formatMarkdown,
379
+ );
380
+ commitUpdate(
381
+ pkgReadme,
382
+ `${catalog.name}/${dir}/README.md`,
383
+ original,
384
+ updated,
385
+ fix,
386
+ result,
387
+ );
388
+ }
389
+ }
390
+
391
+ async function processJtbdMd(root, fix, formatMarkdown, result) {
392
+ const jtbdPath = join(root, "JTBD.md");
393
+ if (!existsSync(jtbdPath)) return;
394
+ const productsCatalog = catalogs(root).find((c) => c.name === "products");
395
+ const packages = loadPackages(productsCatalog.dir, productsCatalog.filter);
396
+ const errors = validate(packages, "products", { skipUniqueHires: true });
397
+ if (errors.length > 0) {
398
+ if (result.errors.length === 0) result.errors.push(...errors);
399
+ return;
400
+ }
401
+ const original = readFileSync(jtbdPath, "utf8");
402
+ const updated = await buildJobs(original, packages, formatMarkdown, {
403
+ capitalize: true,
404
+ });
405
+ commitUpdate(jtbdPath, "JTBD.md", original, updated, fix, result);
406
+ }
407
+
408
+ /**
409
+ * Validate every `package.json .jobs` entry under products/, services/, and
410
+ * libraries/, and (when `fix` is true) regenerate the marker-delimited catalog,
411
+ * jobs, and description blocks in the corresponding README.md and JTBD.md.
412
+ *
413
+ * @param {{ root: string, fix?: boolean }} options
414
+ * @returns {Promise<{ errors: string[], stale: string[], fixed: string[] }>}
415
+ * `errors` are validation failures; `stale` is files whose generated blocks
416
+ * are out of date (only populated when `fix` is false); `fixed` is files
417
+ * that were rewritten in place.
418
+ */
419
+ export async function checkJtbd({ root, fix = false }) {
420
+ const result = { errors: [], stale: [], fixed: [] };
421
+ const prettierConfig = await prettier.resolveConfig(join(root, "JTBD.md"));
422
+ const formatMarkdown = makeFormatter(prettierConfig);
423
+
424
+ for (const catalog of catalogs(root)) {
425
+ await processCatalog(catalog, fix, formatMarkdown, result);
426
+ }
427
+ await processJtbdMd(root, fix, formatMarkdown, result);
428
+
429
+ return result;
430
+ }