@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,19 @@
1
+ {
2
+ "name": "syjkim-ai-workflows",
3
+ "owner": {
4
+ "name": "JongKun Kim"
5
+ },
6
+ "plugins": [
7
+ {
8
+ "name": "ai-workflow-kit",
9
+ "source": ".",
10
+ "description": "Concise requirements-to-delivery workflow with human approval and understanding gates.",
11
+ "category": "development",
12
+ "tags": [
13
+ "workflow",
14
+ "requirements",
15
+ "review"
16
+ ]
17
+ }
18
+ ]
19
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "ai-workflow-kit",
3
+ "version": "3.0.0",
4
+ "description": "Concise requirements-to-delivery workflow with human approval and understanding gates.",
5
+ "author": {
6
+ "name": "JongKun Kim"
7
+ },
8
+ "license": "MIT",
9
+ "skills": [
10
+ "./skills/"
11
+ ]
12
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "ai-workflow-kit",
3
+ "version": "3.0.0",
4
+ "description": "Concise requirements-to-delivery workflow with human approval and understanding gates.",
5
+ "skills": "./skills/"
6
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JongKun Kim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,183 @@
1
+ # AI Workflow Kit
2
+
3
+ AI와 함께 일할 때 **사람이 이해를 놓치지 않게** 하는 작업 규칙입니다.
4
+ Claude Code · Codex · ChatGPT에서 같은 방식으로 씁니다.
5
+
6
+ ```bash
7
+ npx @pazmo/ai-workflow-kit init
8
+ ```
9
+
10
+ ---
11
+
12
+ ## 그림 한 장
13
+
14
+ ```mermaid
15
+ flowchart TD
16
+ A["한 줄 요청<br/>'결제 취소 되게 해줘'"] --> B["사람과 이야기하며<br/>무엇을 만들지 정함"]
17
+ B --> G1{{"G1<br/>이게 맞아요?"}}
18
+ G1 --> C["사람이 승인"]
19
+ C --> D["에이전트가 구현하고 테스트"]
20
+ D --> G4{{"G4<br/>이 변경이 뭘 할 것 같아요?"}}
21
+ G4 --> E["사람이 이해한 채로 머지"]
22
+
23
+ style G1 fill:#fff3cd,stroke:#d39e00,color:#000
24
+ style G4 fill:#fff3cd,stroke:#d39e00,color:#000
25
+ ```
26
+
27
+ ## 다섯 문장
28
+
29
+ 에이전트는 코드를 아주 빨리 씁니다.
30
+ 사람이 읽는 속도는 그대로입니다.
31
+ 그래서 아무도 이해하지 못한 코드가 쌓입니다.
32
+ 이 키트는 사람이 승인하기 **직전**마다 짧은 확인을 거치게 합니다.
33
+ 확인 없이는 다음 단계로 못 갑니다.
34
+
35
+ ---
36
+
37
+ ## 노란 상자 두 개가 하는 일
38
+
39
+ ### G1 — 만들기 전
40
+
41
+ 무엇을 만들 건지 한 화면짜리 계약서로 정리해서 보여줍니다. 그리고 묻습니다:
42
+
43
+ > **"이 내용이 이번 구현의 범위와 완료 조건으로 맞나요?"**
44
+
45
+ 여기서 중요한 건 **질문을 아껴 쓴다**는 점입니다. 동작이 달라지는 것만 묻고, 최대 세 개까지, 두 번 물어보고 멈춥니다. 나머지는 안전한 기본값으로 채우고 `ASSUMED`라고 표시해둡니다. 끝없는 인터뷰가 되지 않게요.
46
+
47
+ ### G4 — 머지 전
48
+
49
+ **설명을 먼저 안 보여줍니다.** 바뀐 코드와 테스트 결과만 보여주고 묻습니다:
50
+
51
+ > **"이 변경이 무엇을 바꾸나요? 어떤 불변 조건이나 실패 경로가 있고, 어떤 테스트가 그걸 증명하나요?"**
52
+
53
+ 답하고 나서야 정답이 나옵니다. 그리고 **맞은 것 / 놓친 것 / 틀린 것** 세 가지로 짚어줍니다.
54
+
55
+ 먼저 맞춰보게 하는 이유는, 설명을 읽는 것과 이해하는 것이 다르기 때문입니다.
56
+
57
+ ---
58
+
59
+ ## 지키게 만드는 방법
60
+
61
+ 규칙을 문서에 적어두는 것만으로는 지켜지지 않습니다. 그래서 게이트는 **파일을 남기고, 그 파일을 기계가 검사합니다.**
62
+
63
+ ```text
64
+ Understanding gate (G4): docs/understanding/cancel-diff.md · 2026-08-31 · Check-in: accepted
65
+ G4: PASS — 환불은 결제수단으로만 돌아간다는 불변 조건을 담당자가 재진술함
66
+ ```
67
+
68
+ ```bash
69
+ node .ai-workflow/bin/check.mjs story docs/STORY.md
70
+ ```
71
+
72
+ 이 검사기가 잡는 것:
73
+
74
+ | 검사 | 막는 상황 |
75
+ |---|---|
76
+ | 게이트 기록 줄이 있는가 | 확인 없이 넘어감 |
77
+ | 증거 파일이 실제로 있고 **비어 있지 않은가** | 백지를 제출함 |
78
+ | 모든 `MUST`가 `Verify` 항목에 연결됐는가 | 검증 안 되는 요구사항 |
79
+ | `OPEN BLOCKING`이 남아 있는데 승인됐는가 | 미해결 쟁점을 안고 출발 |
80
+ | `G4: PASS`에 사람의 재진술이 적혀 있는가 | "이해했다"는 주장만 있음 |
81
+
82
+ 작은 변경이라 건너뛰고 싶으면 그것도 적습니다. 다만 **구체적인 이유**를 요구합니다:
83
+
84
+ ```text
85
+ Understanding gate (G4): N/A — 주석만 변경, 실행 동작 변화 없음
86
+ ```
87
+
88
+ 건너뛴 것도 기록이라 눈에 보입니다.
89
+
90
+ ---
91
+
92
+ ## 시작하기
93
+
94
+ ```bash
95
+ npx @pazmo/ai-workflow-kit init
96
+ ```
97
+
98
+ 레포에 이것만 들어갑니다:
99
+
100
+ ```text
101
+ AGENTS.md · CLAUDE.md 마커 사이에 짧은 규칙 블록 (바깥은 안 건드림)
102
+ .claude/skills/workflow/ Claude Code용 스킬
103
+ .agents/skills/workflow/ Codex용 스킬
104
+ .ai-workflow/bin/ 검사기
105
+ templates/ai-workflow/ Story · Task 템플릿
106
+ ```
107
+
108
+ 한쪽 런타임만 쓴다면:
109
+
110
+ ```bash
111
+ npx @pazmo/ai-workflow-kit init --host claude
112
+ npx @pazmo/ai-workflow-kit init --host codex
113
+ ```
114
+
115
+ ### 부르는 법
116
+
117
+ | 런타임 | 시작 |
118
+ |---|---|
119
+ | Claude Code | `/workflow 결제 취소 되게 해줘` |
120
+ | Codex | `$workflow 결제 취소 되게 해줘` |
121
+ | ChatGPT | `skills/workflow/` 폴더를 Skill로 올리면 관련 요청에서 **자동으로** 선택됩니다 |
122
+
123
+ 한 번만 부르면 됩니다. 스킬이 Story의 상태를 읽고 알아서 다음 단계로 갑니다. 세션이 끊겼다 돌아왔다면 `/workflow` 또는 `/workflow finish`로 다시 들어가면 됩니다.
124
+
125
+ ---
126
+
127
+ ## 계약서는 한 장뿐
128
+
129
+ 요구사항 원본은 **Story 하나**입니다.
130
+
131
+ ```text
132
+ Goal · Domain · MUST · SHOULD · OUT · Decisions · Verify
133
+ ```
134
+
135
+ 별도의 "AI용 요구사항 문서"를 만들지 않습니다. AI가 필요한 코드·테스트·plan 맥락은 실행할 때 붙이면 됩니다. 원본이 둘이 되는 순간 둘은 어긋나기 시작합니다.
136
+
137
+ **Task는 Story 하나를 한 PR로 리뷰할 수 없을 때만** 만듭니다. 30줄 이하로, Story의 `M`/`V` 번호만 참조합니다. 구현 방법은 Task가 아니라 plan이 담당합니다.
138
+
139
+ ---
140
+
141
+ ## 명령어
142
+
143
+ ```bash
144
+ ai-workflow-kit init # 설치 · 업데이트
145
+ ai-workflow-kit doctor # 설치 상태 점검
146
+ ai-workflow-kit check story <file>
147
+ ai-workflow-kit check task <file>
148
+ ai-workflow-kit check gate G4 <story-file>
149
+ ai-workflow-kit remove # 제거
150
+ ```
151
+
152
+ `init`은 여러 번 돌려도 안전합니다. `remove`는 마커 **사이만** 지우고, 사용자가 고친 템플릿과 게이트 증거는 남깁니다.
153
+
154
+ ---
155
+
156
+ ## Compound Engineering 연동 (선택)
157
+
158
+ 설치돼 있으면 `ce-plan → ce-work → ce-code-review`를 그대로 씁니다. 없어도 같은 plan·work·review 단계를 호스트 기본 기능으로 진행합니다. 이 패키지는 Compound Engineering을 포함하지 않습니다.
159
+
160
+ ---
161
+
162
+ ## 개발
163
+
164
+ ```bash
165
+ npm test # 34 checks
166
+ npm pack # 로컬 tarball
167
+ ```
168
+
169
+ 로컬 tarball로 시험 설치:
170
+
171
+ ```bash
172
+ npx --package ./pazmo-ai-workflow-kit-3.0.0.tgz ai-workflow-kit init
173
+ ```
174
+
175
+ 배포는 scope 소유자 인증 후:
176
+
177
+ ```bash
178
+ npm publish --access public
179
+ ```
180
+
181
+ ---
182
+
183
+ MIT · [JongKun Kim](https://github.com/syjkim0125)
@@ -0,0 +1,301 @@
1
+ #!/usr/bin/env node
2
+ import { access, readFile, realpath } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const REQUIRED_STORY_HEADINGS = ['Goal', 'Domain', 'MUST', 'SHOULD', 'OUT', 'Decisions', 'Verify'];
7
+ const REQUIRED_TASK_HEADINGS = ['Outcome', 'Covers — Story M/V IDs', 'Scope', 'Constraints', 'Verify'];
8
+
9
+ async function exists(file) {
10
+ try {
11
+ await access(file);
12
+ return true;
13
+ } catch {
14
+ return false;
15
+ }
16
+ }
17
+
18
+ function nonEmptyLineCount(text) {
19
+ return text.split(/\r?\n/u).filter((line) => line.trim()).length;
20
+ }
21
+
22
+ function escapeRegExp(value) {
23
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
24
+ }
25
+
26
+ function gateLine(text, gate) {
27
+ const escaped = escapeRegExp(gate);
28
+ return text.match(new RegExp(`^Understanding gate \\(${escaped}\\):\\s*(.+)$`, 'imu'))?.[1]?.trim();
29
+ }
30
+
31
+ function parseArtifact(record) {
32
+ return record.split(/\s*[·|]\s*/u)[0].trim();
33
+ }
34
+
35
+ function isWithin(root, target) {
36
+ const relative = path.relative(path.resolve(root), path.resolve(target));
37
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
38
+ }
39
+
40
+ async function evidencePath({ root, artifact, gate }) {
41
+ if (path.isAbsolute(artifact)) {
42
+ return { error: `${gate} evidence artifact must use a project-relative path.` };
43
+ }
44
+
45
+ const candidate = path.resolve(root, artifact);
46
+ if (!isWithin(root, candidate)) {
47
+ return { error: `${gate} evidence artifact escapes project root: ${artifact}` };
48
+ }
49
+ if (!await exists(candidate)) {
50
+ return { error: `${gate} evidence artifact does not exist: ${artifact}` };
51
+ }
52
+
53
+ // Resolve symlinks as well as lexical ".." traversal.
54
+ const [realRoot, realCandidate] = await Promise.all([realpath(root), realpath(candidate)]);
55
+ if (!isWithin(realRoot, realCandidate)) {
56
+ return { error: `${gate} evidence artifact escapes project root through a symlink: ${artifact}` };
57
+ }
58
+
59
+ // A recorded gate with a blank artifact means the line was written but the gate was
60
+ // never held. Existence alone is a signature on an empty page.
61
+ let evidence;
62
+ try {
63
+ evidence = await readFile(candidate, 'utf8');
64
+ } catch (error) {
65
+ return { error: `${gate} evidence artifact cannot be read: ${artifact} (${error.message})` };
66
+ }
67
+ if (!evidence.trim()) {
68
+ return { error: `${gate} evidence artifact is empty: ${artifact}` };
69
+ }
70
+
71
+ return { file: candidate };
72
+ }
73
+
74
+ function isSpecificNoBehaviorChange(record) {
75
+ const match = record.match(/^N\/A\s*[—-]\s*(.+)$/iu);
76
+ if (!match) return false;
77
+ const reason = match[1].trim();
78
+ if (reason.length < 12) return false;
79
+ return /no\s+(?:runtime\s+|observable\s+)?behaviou?r\s+change(?:d)?|docs?(?:umentation)?[- ]only|comment[- ]only|format(?:ting)?[- ]only|(?:실행\s*)?(?:동작|행동)\s*(?:변경|변화)(?:이)?\s*(?:없음|없다|없습니다)|문서만\s*변경|주석만\s*변경|서식만\s*변경|포맷팅만\s*변경/iu.test(reason);
80
+ }
81
+
82
+ export async function checkGate({ root = process.cwd(), file, gate }) {
83
+ if (!file) return { ok: false, errors: ['A Story file is required.'] };
84
+ if (!gate) return { ok: false, errors: ['A gate name is required.'] };
85
+ if (!['G1', 'G4'].includes(gate)) return { ok: false, errors: [`Unsupported gate: ${gate}.`] };
86
+
87
+ root = path.resolve(root);
88
+ const storyFile = path.isAbsolute(file) ? path.resolve(file) : path.resolve(root, file);
89
+ if (!isWithin(root, storyFile)) {
90
+ return { ok: false, errors: [`Story file escapes project root: ${file}`] };
91
+ }
92
+
93
+ let text;
94
+ try {
95
+ text = await readFile(storyFile, 'utf8');
96
+ } catch (error) {
97
+ return { ok: false, errors: [`Cannot read Story: ${error.message}`] };
98
+ }
99
+
100
+ const record = gateLine(text, gate);
101
+ if (!record) {
102
+ return { ok: false, errors: [`Missing Understanding gate (${gate}) record.`] };
103
+ }
104
+
105
+ if (/^N\/A\b/iu.test(record)) {
106
+ if (gate !== 'G4') {
107
+ return { ok: false, errors: [`${gate} cannot be N/A.`] };
108
+ }
109
+ if (!isSpecificNoBehaviorChange(record)) {
110
+ return { ok: false, errors: ['G4 N/A requires a specific reason showing that no implementation behavior changed.'] };
111
+ }
112
+ return { ok: true, errors: [] };
113
+ }
114
+
115
+ if (/Check-in:\s*(declined|rejected|fail(?:ed)?)/iu.test(record)) {
116
+ return { ok: false, errors: [`${gate} check-in was declined.`] };
117
+ }
118
+ if (!/Check-in:\s*(accepted|pass(?:ed)?)/iu.test(record)) {
119
+ return { ok: false, errors: [`${gate} record must contain “Check-in: accepted”.`] };
120
+ }
121
+
122
+ const artifact = parseArtifact(record);
123
+ if (!artifact || artifact === record) {
124
+ return { ok: false, errors: [`${gate} record must start with an evidence artifact path.`] };
125
+ }
126
+ const resolved = await evidencePath({ root, artifact, gate });
127
+ if (resolved.error) return { ok: false, errors: [resolved.error] };
128
+
129
+ if (gate === 'G4' && !/^G4:\s*PASS\s*[—-]\s*\S.+$/imu.test(text)) {
130
+ return { ok: false, errors: ['G4 evidence exists, but the Story is missing an explicit “G4: PASS — <human restatement evidence>” record.'] };
131
+ }
132
+
133
+ return { ok: true, errors: [] };
134
+ }
135
+
136
+ function headingIndex(text, heading) {
137
+ const escaped = escapeRegExp(heading);
138
+ return text.search(new RegExp(`^##\\s+${escaped}\\s*$`, 'imu'));
139
+ }
140
+
141
+ function hasHeading(text, heading) {
142
+ return headingIndex(text, heading) >= 0;
143
+ }
144
+
145
+ function sectionBody(text, heading) {
146
+ const escaped = escapeRegExp(heading);
147
+ const match = new RegExp(`^##\\s+${escaped}\\s*$`, 'imu').exec(text);
148
+ if (!match) return '';
149
+ const start = match.index + match[0].length;
150
+ const rest = text.slice(start);
151
+ const next = /^##\s+/mu.exec(rest);
152
+ return next ? rest.slice(0, next.index) : rest;
153
+ }
154
+
155
+ function idsInSection(text, heading, prefix) {
156
+ const body = sectionBody(text, heading);
157
+ const escaped = escapeRegExp(prefix);
158
+ const regex = new RegExp(`^[-*]\\s+${escaped}(\\d+)\\b`, 'gimu');
159
+ return [...body.matchAll(regex)].map((match) => `${prefix}${match[1]}`.toUpperCase());
160
+ }
161
+
162
+ function verifyMappings(text) {
163
+ const body = sectionBody(text, 'Verify');
164
+ const lines = body.split(/\r?\n/u).filter((line) => /^[-*]\s+V\d+\b/iu.test(line));
165
+ const mapped = new Set();
166
+ for (const line of lines) {
167
+ for (const match of line.matchAll(/\bM(\d+)\b/giu)) mapped.add(`M${match[1]}`.toUpperCase());
168
+ }
169
+ return { lines, mapped };
170
+ }
171
+
172
+ function requireOrderedHeadings(text, headings, errors, label) {
173
+ const indexes = headings.map((heading) => headingIndex(text, heading));
174
+ for (let index = 0; index < headings.length; index += 1) {
175
+ if (indexes[index] < 0) errors.push(`Missing ${label} section: ${headings[index]}.`);
176
+ }
177
+ const present = indexes.filter((index) => index >= 0);
178
+ if (present.some((value, index) => index > 0 && value < present[index - 1])) {
179
+ errors.push(`${label} sections are out of order; keep the canonical template order.`);
180
+ }
181
+ }
182
+
183
+ function checkTask(text) {
184
+ const errors = [];
185
+ const count = nonEmptyLineCount(text);
186
+ if (count > 30) errors.push(`Task has ${count} non-empty lines; maximum is 30.`);
187
+ if (!/^#\s+Task:\s*\S.+$/imu.test(text)) errors.push('Task needs a descriptive “# Task:” title.');
188
+ if (!/^Readiness:\s*(Draft|Implementation-ready)\s*$/imu.test(text)) {
189
+ errors.push('Task Readiness must be Draft or Implementation-ready.');
190
+ }
191
+ if (!/^Story:\s*(?!<|pending\b)\S.+$/imu.test(text)) errors.push('Task must reference its canonical Story.');
192
+ if (!/^Plan source:\s*(?!<|pending\b)\S.+$/imu.test(text)) {
193
+ errors.push('Task must record its Plan source, or “N/A — small and reversible”.');
194
+ }
195
+ requireOrderedHeadings(text, REQUIRED_TASK_HEADINGS, errors, 'Task');
196
+
197
+ const covers = sectionBody(text, 'Covers — Story M/V IDs');
198
+ if (!/\bM\d+\b/iu.test(covers) || !/\bV\d+\b/iu.test(covers)) {
199
+ errors.push('Task Covers must reference at least one Story M# and V# ID.');
200
+ }
201
+ return { ok: errors.length === 0, errors };
202
+ }
203
+
204
+ function checkStoryShape(text) {
205
+ const errors = [];
206
+ requireOrderedHeadings(text, REQUIRED_STORY_HEADINGS, errors, 'Story');
207
+
208
+ if (!/^#\s+Story:\s*\S.+$/imu.test(text)) errors.push('Story needs a descriptive “# Story:” title.');
209
+ if (!/^Status:\s*(Draft|Approved|Delivered)\s*$/imu.test(text)) {
210
+ errors.push('Status must be Draft, Approved, or Delivered.');
211
+ }
212
+ if (!/^Owner:\s*(?!<|pending\b)\S.+$/imu.test(text)) errors.push('Story needs a human Owner.');
213
+
214
+ const mustIds = idsInSection(text, 'MUST', 'M');
215
+ if (mustIds.length === 0) errors.push('MUST needs at least one M# observable behavior.');
216
+ const mustSet = new Set();
217
+ for (const mustId of mustIds) {
218
+ if (mustSet.has(mustId)) errors.push(`Duplicate MUST ID: ${mustId}.`);
219
+ mustSet.add(mustId);
220
+ }
221
+
222
+ const verification = verifyMappings(text);
223
+ if (verification.lines.length === 0) {
224
+ errors.push('Verify needs at least one V# evidence case.');
225
+ } else {
226
+ const verifySet = new Set();
227
+ for (const line of verification.lines) {
228
+ const verifyId = line.match(/^[-*]\s+(V\d+)\b/iu)?.[1]?.toUpperCase();
229
+ if (verifyId && verifySet.has(verifyId)) errors.push(`Duplicate Verify ID: ${verifyId}.`);
230
+ if (verifyId) verifySet.add(verifyId);
231
+
232
+ const references = [...line.matchAll(/\bM(\d+)\b/giu)].map((match) => `M${match[1]}`.toUpperCase());
233
+ if (references.length === 0) errors.push(`Verify case is missing its M# mapping: ${line.trim()}`);
234
+ for (const reference of references) {
235
+ if (!mustSet.has(reference)) errors.push(`Verify case references unknown MUST ${reference}: ${line.trim()}`);
236
+ }
237
+ }
238
+ for (const mustId of mustSet) {
239
+ if (!verification.mapped.has(mustId)) errors.push(`MUST ${mustId} is not mapped to a V# verification case.`);
240
+ }
241
+ }
242
+
243
+ const approved = /^Status:\s*(Approved|Delivered)\s*$/imu.test(text);
244
+ if (approved && /^[-*]\s+OPEN\s+BLOCKING\b/imu.test(text)) {
245
+ errors.push('Approved Story contains OPEN BLOCKING and cannot proceed.');
246
+ }
247
+ return errors;
248
+ }
249
+
250
+ export async function checkArtifact({ root = process.cwd(), file, kind = 'story' }) {
251
+ if (!file) return { ok: false, errors: ['An artifact file is required.'] };
252
+ root = path.resolve(root);
253
+ const artifactFile = path.isAbsolute(file) ? path.resolve(file) : path.resolve(root, file);
254
+ if (!isWithin(root, artifactFile)) {
255
+ return { ok: false, errors: [`Artifact file escapes project root: ${file}`] };
256
+ }
257
+
258
+ let text;
259
+ try {
260
+ text = await readFile(artifactFile, 'utf8');
261
+ } catch (error) {
262
+ return { ok: false, errors: [`Cannot read artifact: ${error.message}`] };
263
+ }
264
+
265
+ if (kind === 'task') return checkTask(text);
266
+ if (kind !== 'story') return { ok: false, errors: [`Unsupported artifact kind: ${kind}`] };
267
+
268
+ const errors = checkStoryShape(text);
269
+ if (/^Status:\s*(Approved|Delivered)\s*$/imu.test(text)) {
270
+ const g1 = await checkGate({ root, file: artifactFile, gate: 'G1' });
271
+ errors.push(...g1.errors);
272
+ }
273
+ if (/^Status:\s*Delivered\s*$/imu.test(text)) {
274
+ const g4 = await checkGate({ root, file: artifactFile, gate: 'G4' });
275
+ errors.push(...g4.errors);
276
+ }
277
+ return { ok: errors.length === 0, errors };
278
+ }
279
+
280
+ async function runCli(argv) {
281
+ const [command, ...args] = argv;
282
+ let result;
283
+ if (command === 'story' || command === 'task') {
284
+ result = await checkArtifact({ file: args[0], kind: command });
285
+ } else if (command === 'gate') {
286
+ result = await checkGate({ gate: args[0], file: args[1] });
287
+ } else {
288
+ console.error('Usage: check.mjs story <file> | task <file> | gate <G1|G4> <story-file>');
289
+ return 2;
290
+ }
291
+
292
+ if (result.ok) {
293
+ console.log('PASS');
294
+ return 0;
295
+ }
296
+ for (const error of result.errors) console.error(`- ${error}`);
297
+ return 1;
298
+ }
299
+
300
+ const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
301
+ if (isMain) process.exitCode = await runCli(process.argv.slice(2));