@pazmo/ai-workflow-kit 3.0.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.
@@ -0,0 +1,333 @@
1
+ import { createHash } from 'node:crypto';
2
+ import {
3
+ access,
4
+ cp,
5
+ mkdir,
6
+ readFile,
7
+ readdir,
8
+ rm,
9
+ writeFile,
10
+ } from 'node:fs/promises';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { HOSTS, normalizeHosts, projectPath } from './paths.mjs';
14
+ import { MANAGED_BLOCK, removeManagedBlock, upsertManagedBlock } from './managed-block.mjs';
15
+
16
+ const modulePackageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
17
+ const CONFIG_PATH = '.ai-workflow/config.json';
18
+ const CHECKER_PATH = '.ai-workflow/bin/check.mjs';
19
+ const TEMPLATE_PATHS = Object.freeze([
20
+ ['skills/workflow/assets/STORY.md', 'templates/ai-workflow/STORY.md'],
21
+ ['skills/workflow/assets/TASK.md', 'templates/ai-workflow/TASK.md'],
22
+ ]);
23
+
24
+ async function exists(file) {
25
+ try {
26
+ await access(file);
27
+ return true;
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+
33
+ async function readText(file, fallback = '') {
34
+ try {
35
+ return await readFile(file, 'utf8');
36
+ } catch (error) {
37
+ if (error?.code === 'ENOENT') return fallback;
38
+ throw error;
39
+ }
40
+ }
41
+
42
+ function sha256(content) {
43
+ return createHash('sha256').update(content).digest('hex');
44
+ }
45
+
46
+ async function fileHash(file) {
47
+ return sha256(await readFile(file));
48
+ }
49
+
50
+ async function treeHash(directory) {
51
+ if (!await exists(directory)) return null;
52
+ const entries = [];
53
+
54
+ async function walk(current, prefix = '') {
55
+ const children = await readdir(current, { withFileTypes: true });
56
+ children.sort((left, right) => left.name.localeCompare(right.name));
57
+ for (const child of children) {
58
+ const relative = path.posix.join(prefix, child.name);
59
+ const full = path.join(current, child.name);
60
+ if (child.isDirectory()) await walk(full, relative);
61
+ else entries.push(`${relative}:${await fileHash(full)}`);
62
+ }
63
+ }
64
+
65
+ await walk(directory);
66
+ return sha256(entries.join('\n'));
67
+ }
68
+
69
+ async function writeIfChanged(file, content) {
70
+ const previous = await readText(file, null);
71
+ if (previous === content) return false;
72
+ await mkdir(path.dirname(file), { recursive: true });
73
+ await writeFile(file, content);
74
+ return true;
75
+ }
76
+
77
+ async function packageVersion(packageRoot) {
78
+ try {
79
+ return JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8')).version;
80
+ } catch {
81
+ return '3.0.0';
82
+ }
83
+ }
84
+
85
+ async function readConfig(root) {
86
+ try {
87
+ return JSON.parse(await readFile(projectPath(root, CONFIG_PATH), 'utf8'));
88
+ } catch {
89
+ return null;
90
+ }
91
+ }
92
+
93
+ async function inspectManagedTree({ source, target, previousHash, relative }) {
94
+ const sourceHash = await treeHash(source);
95
+ const currentHash = await treeHash(target);
96
+
97
+ if (!sourceHash) throw new Error(`Canonical workflow skill is missing: ${source}`);
98
+ if (currentHash && currentHash !== sourceHash && !previousHash) {
99
+ throw new Error(`Refusing to overwrite existing skill: ${relative}`);
100
+ }
101
+
102
+ return { source, target, sourceHash, currentHash, previousHash, relative };
103
+ }
104
+
105
+ async function applyManagedTree(plan) {
106
+ const { source, target, sourceHash, currentHash, previousHash, relative } = plan;
107
+ if (currentHash === sourceHash) return { changed: false, hash: sourceHash, preserved: false };
108
+ if (currentHash && previousHash && currentHash !== previousHash) {
109
+ return { changed: false, hash: sourceHash, preserved: true, relative };
110
+ }
111
+
112
+ await rm(target, { recursive: true, force: true });
113
+ await mkdir(path.dirname(target), { recursive: true });
114
+ await cp(source, target, { recursive: true });
115
+ return { changed: true, hash: sourceHash, preserved: false };
116
+ }
117
+
118
+ async function applyManagedFile({ source, target, previousHash, relative }) {
119
+ const sourceContent = await readFile(source);
120
+ const sourceHash = sha256(sourceContent);
121
+ if (await exists(target)) {
122
+ const currentHash = await fileHash(target);
123
+ if (currentHash === sourceHash) return { changed: false, hash: sourceHash, preserved: false };
124
+ if (!previousHash || currentHash !== previousHash) {
125
+ return { changed: false, hash: sourceHash, preserved: true, relative };
126
+ }
127
+ }
128
+
129
+ await mkdir(path.dirname(target), { recursive: true });
130
+ await writeFile(target, sourceContent);
131
+ return { changed: true, hash: sourceHash, preserved: false };
132
+ }
133
+
134
+ async function removeTreeIfUnchanged(root, relative, expectedHash, preserved) {
135
+ const target = projectPath(root, relative);
136
+ if (!await exists(target)) return false;
137
+ if (!expectedHash || await treeHash(target) !== expectedHash) {
138
+ preserved.push(relative);
139
+ return false;
140
+ }
141
+ await rm(target, { recursive: true, force: true });
142
+ return true;
143
+ }
144
+
145
+ async function removeFileIfUnchanged(root, relative, expectedHash, preserved) {
146
+ const target = projectPath(root, relative);
147
+ if (!await exists(target)) return false;
148
+ if (!expectedHash || await fileHash(target) !== expectedHash) {
149
+ preserved.push(relative);
150
+ return false;
151
+ }
152
+ await rm(target, { force: true });
153
+ return true;
154
+ }
155
+
156
+ export async function installWorkflow({
157
+ root = process.cwd(),
158
+ packageRoot = modulePackageRoot,
159
+ hosts = ['codex', 'claude'],
160
+ } = {}) {
161
+ root = path.resolve(root);
162
+ packageRoot = path.resolve(packageRoot);
163
+ const selectedHosts = normalizeHosts(hosts);
164
+ const previous = await readConfig(root);
165
+ const previousHosts = new Set(previous?.hosts ?? []);
166
+ const skillSource = path.join(packageRoot, 'skills/workflow');
167
+ const preserved = [];
168
+ const installed = [];
169
+ let changed = false;
170
+
171
+ // Preflight conflicts and malformed instruction markers before any write.
172
+ const treePlans = new Map();
173
+ for (const host of selectedHosts) {
174
+ const hostConfig = HOSTS[host];
175
+ treePlans.set(host, await inspectManagedTree({
176
+ source: skillSource,
177
+ target: projectPath(root, hostConfig.skillDir),
178
+ previousHash: previous?.managedTrees?.[hostConfig.skillDir],
179
+ relative: hostConfig.skillDir,
180
+ }));
181
+ }
182
+
183
+ const instructionPlans = new Map();
184
+ for (const [host, hostConfig] of Object.entries(HOSTS)) {
185
+ const file = projectPath(root, hostConfig.instructionFile);
186
+ const current = await readText(file, '');
187
+ if (selectedHosts.includes(host)) {
188
+ instructionPlans.set(host, { file, current, next: upsertManagedBlock(current, MANAGED_BLOCK) });
189
+ } else if (previousHosts.has(host)) {
190
+ instructionPlans.set(host, { file, current, next: removeManagedBlock(current) });
191
+ }
192
+ }
193
+
194
+ for (const host of previousHosts) {
195
+ if (selectedHosts.includes(host) || !HOSTS[host]) continue;
196
+ const relative = HOSTS[host].skillDir;
197
+ changed = await removeTreeIfUnchanged(
198
+ root,
199
+ relative,
200
+ previous?.managedTrees?.[relative],
201
+ preserved,
202
+ ) || changed;
203
+ }
204
+
205
+ for (const { file, current, next } of instructionPlans.values()) {
206
+ if (next !== current) {
207
+ await mkdir(path.dirname(file), { recursive: true });
208
+ await writeFile(file, next);
209
+ changed = true;
210
+ }
211
+ }
212
+
213
+ const managedTrees = {};
214
+ for (const host of selectedHosts) {
215
+ const relative = HOSTS[host].skillDir;
216
+ const result = await applyManagedTree(treePlans.get(host));
217
+ changed = result.changed || changed;
218
+ managedTrees[relative] = result.hash;
219
+ if (result.changed) installed.push(relative);
220
+ if (result.preserved) preserved.push(relative);
221
+ }
222
+
223
+ const managedFiles = {};
224
+ for (const [sourceRelative, targetRelative] of TEMPLATE_PATHS) {
225
+ const result = await applyManagedFile({
226
+ source: path.join(packageRoot, sourceRelative),
227
+ target: projectPath(root, targetRelative),
228
+ previousHash: previous?.managedFiles?.[targetRelative]
229
+ ?? previous?.templateHashes?.[targetRelative],
230
+ relative: targetRelative,
231
+ });
232
+ changed = result.changed || changed;
233
+ managedFiles[targetRelative] = result.hash;
234
+ if (result.changed) installed.push(targetRelative);
235
+ if (result.preserved) preserved.push(targetRelative);
236
+ }
237
+
238
+ const checkerResult = await applyManagedFile({
239
+ source: path.join(packageRoot, 'assets/check.mjs'),
240
+ target: projectPath(root, CHECKER_PATH),
241
+ previousHash: previous?.managedFiles?.[CHECKER_PATH],
242
+ relative: CHECKER_PATH,
243
+ });
244
+ changed = checkerResult.changed || changed;
245
+ managedFiles[CHECKER_PATH] = checkerResult.hash;
246
+ if (checkerResult.changed) installed.push(CHECKER_PATH);
247
+ if (checkerResult.preserved) preserved.push(CHECKER_PATH);
248
+
249
+ const config = `${JSON.stringify({
250
+ schemaVersion: 2,
251
+ packageVersion: await packageVersion(packageRoot),
252
+ hosts: selectedHosts,
253
+ managedFiles,
254
+ managedTrees,
255
+ }, null, 2)}\n`;
256
+ changed = await writeIfChanged(projectPath(root, CONFIG_PATH), config) || changed;
257
+
258
+ return { changed, installed, preserved, hosts: selectedHosts };
259
+ }
260
+
261
+ async function removeEmptyParents(file, stopAt) {
262
+ let current = path.dirname(file);
263
+ while (current.startsWith(stopAt) && current !== stopAt) {
264
+ try {
265
+ if ((await readdir(current)).length > 0) break;
266
+ await rm(current, { recursive: false });
267
+ current = path.dirname(current);
268
+ } catch {
269
+ break;
270
+ }
271
+ }
272
+ }
273
+
274
+ export async function removeWorkflow({ root = process.cwd() } = {}) {
275
+ root = path.resolve(root);
276
+ const config = await readConfig(root);
277
+ const preserved = [];
278
+ let changed = false;
279
+
280
+ // Marker ownership makes these safe to strip even when config is missing.
281
+ const instructionPlans = [];
282
+ for (const { instructionFile } of Object.values(HOSTS)) {
283
+ const file = projectPath(root, instructionFile);
284
+ if (!await exists(file)) continue;
285
+ const current = await readFile(file, 'utf8');
286
+ instructionPlans.push({ file, current, next: removeManagedBlock(current) });
287
+ }
288
+ for (const { file, current, next } of instructionPlans) {
289
+ if (next !== current) {
290
+ await writeFile(file, next);
291
+ changed = true;
292
+ }
293
+ }
294
+
295
+ for (const host of config?.hosts ?? []) {
296
+ const relative = HOSTS[host]?.skillDir;
297
+ if (!relative) continue;
298
+ const removed = await removeTreeIfUnchanged(
299
+ root,
300
+ relative,
301
+ config?.managedTrees?.[relative],
302
+ preserved,
303
+ );
304
+ changed = removed || changed;
305
+ if (removed) await removeEmptyParents(projectPath(root, relative), root);
306
+ }
307
+
308
+ for (const [, targetRelative] of TEMPLATE_PATHS) {
309
+ const expectedHash = config?.managedFiles?.[targetRelative]
310
+ ?? config?.templateHashes?.[targetRelative];
311
+ const removed = await removeFileIfUnchanged(root, targetRelative, expectedHash, preserved);
312
+ changed = removed || changed;
313
+ if (removed) await removeEmptyParents(projectPath(root, targetRelative), root);
314
+ }
315
+
316
+ const checkerRemoved = await removeFileIfUnchanged(
317
+ root,
318
+ CHECKER_PATH,
319
+ config?.managedFiles?.[CHECKER_PATH],
320
+ preserved,
321
+ );
322
+ changed = checkerRemoved || changed;
323
+ if (checkerRemoved) await removeEmptyParents(projectPath(root, CHECKER_PATH), root);
324
+
325
+ const configFile = projectPath(root, CONFIG_PATH);
326
+ if (await exists(configFile)) {
327
+ await rm(configFile, { force: true });
328
+ changed = true;
329
+ await removeEmptyParents(configFile, root);
330
+ }
331
+
332
+ return { changed, preserved };
333
+ }
@@ -0,0 +1,70 @@
1
+ export const START_MARKER = '<!-- BEGIN ai-workflow-kit -->';
2
+ export const END_MARKER = '<!-- END ai-workflow-kit -->';
3
+
4
+ export const MANAGED_BLOCK = `${START_MARKER}
5
+ ## AI workflow
6
+
7
+ - Start product or engineering work with the \`workflow\` skill before implementation.
8
+ - Keep one concise canonical Story contract: Goal, Domain, MUST, SHOULD, OUT, Decisions, Verify.
9
+ - Ask only blocking behavior questions; label safe defaults \`ASSUMED\` instead of silently inventing scope.
10
+ - Keep Tasks at most 30 non-empty lines and reference Story M/V IDs; HOW belongs to the repository-grounded plan.
11
+ - Use Compound Engineering when available: normal work \`ce-plan → ce-work → ce-code-review\`; high-risk work adds a human plan gate.
12
+ - Do not merge non-trivial changes until the workflow's G4 question gate records that a human understands behavior, an invariant/failure path, and the evidence boundary.
13
+ - Gates are satisfied by evidence, not by assertion. Verify with \`node .ai-workflow/bin/check.mjs story <story-file>\` and report the exit code; exit 0 is the only pass.
14
+ ${END_MARKER}`;
15
+
16
+ // A marker only counts when it is a line of its own and sits outside a fenced code
17
+ // block. Instruction files legitimately document this kit's own marker syntax; a
18
+ // substring match would treat that example as the live block and silently rewrite it.
19
+ function scanMarkers(content) {
20
+ const lines = content.split(/\n/u);
21
+ let offset = 0;
22
+ let fenced = false;
23
+ const found = [];
24
+
25
+ for (const line of lines) {
26
+ const bare = line.replace(/\r$/u, '').trim();
27
+
28
+ if (/^(?:`{3,}|~{3,})/u.test(bare)) {
29
+ fenced = !fenced;
30
+ } else if (!fenced) {
31
+ if (bare === START_MARKER) found.push({ kind: 'start', start: offset, end: offset + line.length });
32
+ else if (bare === END_MARKER) found.push({ kind: 'end', start: offset, end: offset + line.length });
33
+ }
34
+
35
+ offset += line.length + 1; // + the newline consumed by split
36
+ }
37
+ return found;
38
+ }
39
+
40
+ function markerRange(content) {
41
+ const found = scanMarkers(content);
42
+ if (found.length === 0) return null;
43
+
44
+ const starts = found.filter((marker) => marker.kind === 'start');
45
+ const ends = found.filter((marker) => marker.kind === 'end');
46
+ if (starts.length !== 1 || ends.length !== 1 || ends[0].start < starts[0].start) {
47
+ throw new Error('Malformed ai-workflow-kit managed block. Restore both markers before retrying.');
48
+ }
49
+ return { start: starts[0].start, end: ends[0].end };
50
+ }
51
+
52
+ export function upsertManagedBlock(content = '', block = MANAGED_BLOCK) {
53
+ const range = markerRange(content);
54
+ if (range) {
55
+ return `${content.slice(0, range.start)}${block}${content.slice(range.end)}`;
56
+ }
57
+
58
+ const trimmed = content.replace(/\s+$/u, '');
59
+ return trimmed ? `${trimmed}\n\n${block}\n` : `${block}\n`;
60
+ }
61
+
62
+ export function removeManagedBlock(content = '') {
63
+ const range = markerRange(content);
64
+ if (!range) return content;
65
+
66
+ const before = content.slice(0, range.start).replace(/[ \t]+$/u, '');
67
+ const after = content.slice(range.end).replace(/^\s*\n/u, '');
68
+ const joined = `${before}${after ? `\n${after}` : ''}`;
69
+ return joined.replace(/\n{3,}/gu, '\n\n').replace(/^\n+/u, '').replace(/\s+$/u, '') + (joined.trim() ? '\n' : '');
70
+ }
package/src/paths.mjs ADDED
@@ -0,0 +1,25 @@
1
+ import path from 'node:path';
2
+
3
+ export const HOSTS = Object.freeze({
4
+ codex: {
5
+ instructionFile: 'AGENTS.md',
6
+ skillDir: '.agents/skills/workflow',
7
+ },
8
+ claude: {
9
+ instructionFile: 'CLAUDE.md',
10
+ skillDir: '.claude/skills/workflow',
11
+ },
12
+ });
13
+
14
+ export function normalizeHosts(hosts = ['codex', 'claude']) {
15
+ const normalized = [...new Set(hosts.map((host) => String(host).toLowerCase()))];
16
+ const invalid = normalized.filter((host) => !HOSTS[host]);
17
+ if (invalid.length > 0) {
18
+ throw new Error(`Unsupported host(s): ${invalid.join(', ')}. Use codex or claude.`);
19
+ }
20
+ return normalized.sort();
21
+ }
22
+
23
+ export function projectPath(root, relativePath) {
24
+ return path.join(path.resolve(root), relativePath);
25
+ }