@pazmo/ai-workflow-kit 3.0.4 → 3.1.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.
@@ -6,6 +6,7 @@
6
6
  "plugins": [
7
7
  {
8
8
  "name": "ai-workflow-kit",
9
+ "version": "3.1.1",
9
10
  "source": ".",
10
11
  "description": "Concise requirements-to-delivery workflow with human approval and understanding gates.",
11
12
  "category": "development",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-workflow-kit",
3
- "version": "3.0.0",
3
+ "version": "3.1.1",
4
4
  "description": "Concise requirements-to-delivery workflow with human approval and understanding gates.",
5
5
  "author": {
6
6
  "name": "JongKun Kim"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-workflow-kit",
3
- "version": "3.0.0",
3
+ "version": "3.1.1",
4
4
  "description": "Concise requirements-to-delivery workflow with human approval and understanding gates.",
5
5
  "skills": "./skills/"
6
6
  }
package/README.md CHANGED
@@ -21,7 +21,7 @@ npx @pazmo/ai-workflow-kit init
21
21
  ─── G1 ─── "이게 맞아요?"
22
22
  │ 사람이 승인해야 다음으로 갑니다
23
23
  ▼
24
- 에이전트가 구현하고 테스트
24
+ 에이전트가 구현 → 테스트 통과 → 단순화 검토 → 리뷰 → 재검증
25
25
  │
26
26
  ▼
27
27
  ─── G4 ─── "이 변경이 뭘 할 것 같아요?"
@@ -87,7 +87,7 @@ npx @pazmo/ai-workflow-kit init
87
87
  │
88
88
  5 변경의 크기를 판정한다
89
89
  ├ 작고 되돌릴 수 있다 → 바로 8번으로
90
- ├ 보통이다 → 계획 → 작업 → 리뷰
90
+ ├ 보통이다 → 계획 → 작업·테스트 → 단순화 검토 → 리뷰·재검증
91
91
  └ 위험하고 되돌리기 어렵다 → 6번으로
92
92
  │
93
93
  6 ━━ G3 ━━ 사람에게 묻는다 (위험할 때만 생깁니다)
@@ -100,8 +100,9 @@ npx @pazmo/ai-workflow-kit init
100
100
  8 구현한다
101
101
  · 먼저 기존 코드를 읽는다
102
102
  · "꼭 되어야 하는 것"을 실제 코드 위치에 하나씩 연결한다
103
- · 실패하는 테스트를 먼저 쓰고 → 통과시키고 → 정리한다
104
- · 바뀐 코드를 스스로 다시 훑는다
103
+ · 실패하는 테스트를 먼저 쓰고 → 관련 테스트를 통과시킨다
104
+ · 단순화 검토로 중복·불필요한 상태·분기·복잡성을 살핀다 (수정할 것이 없으면 그대로)
105
+ · 단순화 이후 최종 변경을 리뷰하고, 수정한 부분을 재검증한다
105
106
  │
106
107
  9 ━━ G4 ━━ 사람에게 묻는다
107
108
  설명을 감추고, 바뀐 코드와 테스트 결과만 보여줍니다
@@ -217,11 +218,11 @@ npx @pazmo/ai-workflow-kit init --host codex
217
218
 
218
219
  | 도구 | 시작 |
219
220
  |---|---|
220
- | Claude Code | `/workflow 결제 취소 되게 해줘` |
221
- | Codex | `$workflow 결제 취소 되게 해줘` |
221
+ | Claude Code | `/workflow 결제 취소 되게 해줘` · `/workflow status` · `/workflow finish` |
222
+ | Codex | `$workflow 결제 취소 되게 해줘` · `$workflow status` · `$workflow finish` |
222
223
  | ChatGPT | `skills/workflow/` 폴더를 Skill로 올리면 관련 요청에서 **자동으로** 선택됩니다 |
223
224
 
224
- 한 번만 부르면 됩니다. 지금 어디까지 왔는지 합의서를 읽고 알아서 다음 단계로 갑니다. 대화가 끊겼다 돌아왔다면 `/workflow` 또는 `/workflow finish`로 다시 들어가면 됩니다.
225
+ 한 번만 부르면 됩니다. 지금 어디까지 왔는지 합의서를 읽고 알아서 다음 단계로 갑니다. 대화가 끊겼다 돌아왔다면 위 표의 호스트별 status 또는 finish 명령으로 다시 들어가면 됩니다. 설치·업데이트 후에는 새 Codex 작업 또는 새 Claude Code 세션을 시작해야 바뀐 스킬을 발견할 수 있습니다.
225
226
 
226
227
  ---
227
228
 
@@ -248,30 +249,44 @@ ai-workflow-kit doctor # 설치 상태 점검
248
249
  ai-workflow-kit check story <file>
249
250
  ai-workflow-kit check task <file>
250
251
  ai-workflow-kit check gate G4 <story-file>
252
+ ai-workflow-kit jira preview <story-file> # 로컬 미리보기만 출력
251
253
  ai-workflow-kit remove # 제거
252
254
  ```
253
255
 
254
256
  `init`은 여러 번 돌려도 안전합니다. `remove`는 표시 **사이만** 지우고, 사용자가 고친 서식과 확인 기록은 남깁니다.
255
257
 
258
+ 설치는 `.ai-workflow-install/`에 먼저 준비한 뒤 기존 파일을 백업하고 적용합니다. 처리 가능한 실패는 이전 파일·권한·디렉터리를 복구합니다. 프로세스가 강제 종료되면 다음 `init`이 같은 장비의 종료된 프로세스 기록을 확인하고 복구한 뒤 시작합니다. 여러 파일이 한순간에 동시에 바뀌는 것은 아니므로 설치 중에는 대상 파일을 편집하거나 다른 설치·제거를 실행하지 마세요. 복구까지 실패하면 백업과 기록을 보존하고 오류를 알립니다. 기록이 불완전하거나 소유 프로세스를 확인할 수 없으면 자동 삭제하지 않습니다. 영구 디스크 손상·전원 장애의 내구성을 보장하는 파일시스템 트랜잭션은 아닙니다.
259
+
260
+ ## Jira 발행 (선택)
261
+
262
+ `ai-workflow-kit jira preview <story-file>`은 Goal, Domain, MUST, SHOULD, OUT, Decisions, Verify 순서의 읽기 쉬운 미리보기만 출력합니다. 실제 발행은 G1 승인, 별도의 명시적 발행 승인과 대상, 호스트가 제공하는 어댑터가 필요합니다. 자격증명이나 Jira 클라이언트는 패키지에 포함하지 않습니다.
263
+
264
+ 새 `publishStory` 모듈은 안정적인 발행 ID, 생성 전 로컬 기록, 중복 조회, 생성 결과 재조회·내용 검증을 지원합니다. 생성 결과가 불명확하면 새 이슈를 다시 만들지 않고 확인을 요구합니다. 원본 Story는 수정하지 않습니다. ADF 설명과 어댑터 계약, 실패 복구 및 검증 한계는 [Jira 안내](skills/workflow/references/jira.md)를 확인하세요. 이 릴리스의 Jira 검증은 fixture 기반이며 실제 Jira 이슈 생성은 수행하지 않았습니다.
265
+
256
266
  ---
257
267
 
258
268
  ## Compound Engineering 연동 (선택)
259
269
 
260
- 설치돼 있으면 `ce-plan → ce-work → ce-code-review`를 그대로 씁니다. 없어도 같은 계획·작업·리뷰 단계를 도구 기본 기능으로 진행합니다. 이 패키지는 Compound Engineering을 포함하지 않습니다.
270
+ 기본 흐름은 **구현 → 관련 테스트 통과 → 단순화 검토 → 코드 리뷰 → 수정한 부분 재검증 → 기존 G4**입니다. Compound Engineering이 있으면 `ce-plan → ce-work → ce-simplify-code → ce-code-review`를 활용합니다. AI는 사용 가능한 `ce-simplify-code`의 실제 지침을 읽고 실행하며, 없으면 같은 기준으로 직접 검토합니다. 설치를 요구하거나 작업을 멈추지 않습니다.
271
+
272
+ 검토는 기본이지만 수정은 명확한 이득이 있을 때만 합니다. 줄 수 감소나 `for`를 stream으로 바꾸는 것 자체가 성과는 아니며, 체이닝과 실제 반복 횟수 감소도 다릅니다. 현재 변경과 필요한 연관 부분만 다루고, 동작·결과 순서·부수 효과·도메인 경계·실패 처리·안전 검증을 보존합니다. 이를 바꾸려면 기존 설계·범위 변경 절차를 따릅니다.
273
+
274
+ 리뷰 수정 후에는 영향받은 범위만 다시 확인합니다. 새 승인 단계·필수 문서·Jira Task는 생기지 않으며, 에이전트 사용 방식은 해당 스킬과 저장소·런타임 지침에 맡깁니다. 상세 기준은 [실행 안내](skills/workflow/references/execution.md)에 있습니다. 이 패키지는 Compound Engineering을 포함하지 않습니다.
261
275
 
262
276
  ---
263
277
 
264
278
  ## 개발
265
279
 
266
280
  ```bash
267
- npm test # 39 checks
281
+ npm test # 전체 테스트
268
282
  npm pack # 로컬 tarball
269
283
  ```
270
284
 
271
285
  로컬 tarball로 시험 설치:
272
286
 
273
287
  ```bash
274
- npx --package ./pazmo-ai-workflow-kit-3.0.3.tgz ai-workflow-kit init
288
+ # npm pack 출력에 나온 실제 파일명으로 <version>을 바꾸세요.
289
+ npx --package './pazmo-ai-workflow-kit-<version>.tgz' ai-workflow-kit init
275
290
  ```
276
291
 
277
292
  배포는 scope 소유자 인증 후:
package/assets/check.mjs CHANGED
@@ -28,6 +28,16 @@ function gateLine(text, gate) {
28
28
  return text.match(new RegExp(`^Understanding gate \\(${escaped}\\):\\s*(.+)$`, 'imu'))?.[1]?.trim();
29
29
  }
30
30
 
31
+ function hasG4Pass(text) {
32
+ return /^G4:\s*PASS\s*[—-]\s*\S.+$/imu.test(text);
33
+ }
34
+
35
+ // The publisher must recognize the same gate spelling/spacing as validation.
36
+ export function isGateMetadataLine(line) {
37
+ return ['G1', 'G3', 'G4'].some((gate) => Boolean(gateLine(line, gate)))
38
+ || /^Understanding gate \(G[134]\):\s*$/iu.test(line) || hasG4Pass(line);
39
+ }
40
+
31
41
  function parseArtifact(record) {
32
42
  return record.split(/\s*[·|]\s*/u)[0].trim();
33
43
  }
@@ -126,7 +136,7 @@ export async function checkGate({ root = process.cwd(), file, gate }) {
126
136
  const resolved = await evidencePath({ root, artifact, gate });
127
137
  if (resolved.error) return { ok: false, errors: [resolved.error] };
128
138
 
129
- if (gate === 'G4' && !/^G4:\s*PASS\s*[—-]\s*\S.+$/imu.test(text)) {
139
+ if (gate === 'G4' && !hasG4Pass(text)) {
130
140
  return { ok: false, errors: ['G4 evidence exists, but the Story is missing an explicit “G4: PASS — <human restatement evidence>” record.'] };
131
141
  }
132
142
 
@@ -155,16 +165,16 @@ function sectionBody(text, heading) {
155
165
  function idsInSection(text, heading, prefix) {
156
166
  const body = sectionBody(text, heading);
157
167
  const escaped = escapeRegExp(prefix);
158
- const regex = new RegExp(`^[-*]\\s+${escaped}(\\d+)\\b`, 'gimu');
168
+ const regex = new RegExp(`^[-*]\\s+${escaped}(-?\\d+)\\b`, 'gimu');
159
169
  return [...body.matchAll(regex)].map((match) => `${prefix}${match[1]}`.toUpperCase());
160
170
  }
161
171
 
162
172
  function verifyMappings(text) {
163
173
  const body = sectionBody(text, 'Verify');
164
- const lines = body.split(/\r?\n/u).filter((line) => /^[-*]\s+V\d+\b/iu.test(line));
174
+ const lines = body.split(/\r?\n/u).filter((line) => /^[-*]\s+V-?\d+\b/iu.test(line));
165
175
  const mapped = new Set();
166
176
  for (const line of lines) {
167
- for (const match of line.matchAll(/\bM(\d+)\b/giu)) mapped.add(`M${match[1]}`.toUpperCase());
177
+ for (const match of line.matchAll(/\bM(-?\d+)\b/giu)) mapped.add(`M${match[1]}`.toUpperCase());
168
178
  }
169
179
  return { lines, mapped };
170
180
  }
@@ -195,7 +205,7 @@ function checkTask(text) {
195
205
  requireOrderedHeadings(text, REQUIRED_TASK_HEADINGS, errors, 'Task');
196
206
 
197
207
  const covers = sectionBody(text, 'Covers — Story M/V IDs');
198
- if (!/\bM\d+\b/iu.test(covers) || !/\bV\d+\b/iu.test(covers)) {
208
+ if (!/\bM-?\d+\b/iu.test(covers) || !/\bV-?\d+\b/iu.test(covers)) {
199
209
  errors.push('Task Covers must reference at least one Story M# and V# ID.');
200
210
  }
201
211
  return { ok: errors.length === 0, errors };
@@ -225,11 +235,11 @@ function checkStoryShape(text) {
225
235
  } else {
226
236
  const verifySet = new Set();
227
237
  for (const line of verification.lines) {
228
- const verifyId = line.match(/^[-*]\s+(V\d+)\b/iu)?.[1]?.toUpperCase();
238
+ const verifyId = line.match(/^[-*]\s+(V-?\d+)\b/iu)?.[1]?.toUpperCase();
229
239
  if (verifyId && verifySet.has(verifyId)) errors.push(`Duplicate Verify ID: ${verifyId}.`);
230
240
  if (verifyId) verifySet.add(verifyId);
231
241
 
232
- const references = [...line.matchAll(/\bM(\d+)\b/giu)].map((match) => `M${match[1]}`.toUpperCase());
242
+ const references = [...line.matchAll(/\bM(-?\d+)\b/giu)].map((match) => `M${match[1]}`.toUpperCase());
233
243
  if (references.length === 0) errors.push(`Verify case is missing its M# mapping: ${line.trim()}`);
234
244
  for (const reference of references) {
235
245
  if (!mustSet.has(reference)) errors.push(`Verify case references unknown MUST ${reference}: ${line.trim()}`);
@@ -7,6 +7,7 @@ import { installWorkflow, removeWorkflow } from '../src/install.mjs';
7
7
  import { checkerVisibility, ignoredCheckerAdvice } from '../src/git-visibility.mjs';
8
8
  import { END_MARKER, START_MARKER } from '../src/managed-block.mjs';
9
9
  import { HOSTS } from '../src/paths.mjs';
10
+ import { publishStory } from '../src/jira.mjs';
10
11
 
11
12
  const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
12
13
 
@@ -18,8 +19,13 @@ Usage:
18
19
  ai-workflow-kit doctor [--root <dir>]
19
20
  ai-workflow-kit check story|task <file> [--root <dir>]
20
21
  ai-workflow-kit check gate G1|G4 <story-file> [--root <dir>]
22
+ ai-workflow-kit jira preview <story-file> [--root <dir>]
21
23
  ai-workflow-kit remove [--root <dir>]
22
- ai-workflow-kit --version`);
24
+ ai-workflow-kit --version
25
+
26
+ After installation, start a new task/session:
27
+ Codex: $workflow <request> | $workflow status | $workflow finish
28
+ Claude Code: /workflow <request> | /workflow status | /workflow finish`);
23
29
  }
24
30
 
25
31
  function parse(argv) {
@@ -118,6 +124,17 @@ async function main(argv) {
118
124
  const command = argv[0];
119
125
  const { root, hosts, positional } = parse(argv.slice(1));
120
126
 
127
+ if (command === 'jira') {
128
+ if (positional.length !== 2 || positional[0] !== 'preview') {
129
+ throw new Error('Usage: ai-workflow-kit jira preview <story-file>. Publication requires an explicitly authorized host adapter; CLI is preview-only.');
130
+ }
131
+ const result = await publishStory({ root, file: positional[1] });
132
+ console.log('PREVIEW — no issue created. Review content before sharing with Jira.');
133
+ console.log(result.summary);
134
+ console.log(result.preview);
135
+ return 0;
136
+ }
137
+
121
138
  if (command === 'init') {
122
139
  const result = await installWorkflow({ root, packageRoot, hosts });
123
140
  console.log(result.changed ? 'Installed/updated AI Workflow Kit.' : 'AI Workflow Kit is already up to date.');
package/package.json CHANGED
@@ -1,6 +1,9 @@
1
1
  {
2
2
  "name": "@pazmo/ai-workflow-kit",
3
- "version": "3.0.4",
3
+ "version": "3.1.1",
4
+ "repository": { "type": "git", "url": "git+https://github.com/syjkim0125/ai-workflow-kit.git" },
5
+ "homepage": "https://github.com/syjkim0125/ai-workflow-kit#readme",
6
+ "bugs": { "url": "https://github.com/syjkim0125/ai-workflow-kit/issues" },
4
7
  "description": "Portable DDD-inspired AI engineering workflow with concise contracts and a human understanding gate.",
5
8
  "type": "module",
6
9
  "bin": {
@@ -0,0 +1,53 @@
1
+ # Workflow communication scenarios
2
+
3
+ These are manual behavioral evaluations, not claims of automated coverage.
4
+
5
+ ## Explain before G1
6
+ Input: A user reports that returning from an external verification page leaves the app waiting.
7
+ Expected: Explain today's failure and the desired return behavior in plain language before presenting criteria. Distinguish observed facts from hypotheses; cover failure behavior and verification limits. Keep the explanation in the Story, not a duplicate specification.
8
+ Failure: Lead with callback APIs or ask for approval of unexplained M/V IDs.
9
+
10
+ ## Explain before G3
11
+ Input: The user has approved preserving a draft while leaving the page and restoring it on return.
12
+ Expected: Preserve that decision, explain the chosen approach, alternatives, safety rules and recovery, then show technical details. Explain Tasks as outcomes. Ask only about a new material decision.
13
+ Failure: Reopen the approved choice or describe Tasks only as client/server file lists.
14
+
15
+ ## Keep G4 prediction-before-reveal
16
+ Input: Implementation and tests are ready for the understanding gate.
17
+ Expected: Show raw evidence and ask familiar-language questions about changed behavior, safety, failure and remaining uncertainty. Wait for the user's answer before explaining the implementation.
18
+ Failure: Provide the answer first because earlier stages now require plain-language explanations.
19
+
20
+ ## Right-size the explanation
21
+ Input: A user requests a small wording correction.
22
+ Expected: One or two clear sentences; no forced analogy, separate explainer or extra approval round.
23
+ Failure: A long ELI5 lecture or a patronizing tone.
24
+
25
+ ## Jira section boundaries
26
+ Input: Publish a Story or Task with consecutive headings and MUST/SHOULD lists in Jira.
27
+ Expected: Use the editor's supported heading format, real newlines, standalone headings and blank lines before/after each heading. Keep peer sections at the same level. Inspect the rendered description after publication and preserve any user formatting corrections.
28
+ Failure: SHOULD appears inside MUST's list or paragraph; literal escaped newlines or Markdown headings appear in wiki-text mode; a heading is attached to the preceding content.
29
+
30
+ ## Simplify available after green
31
+ Input: The task's related tests pass. ce-simplify-code is discoverable; its instructions include a preflight and reviewer orchestration. Repository/runtime rules constrain agent use.
32
+ Expected: Read and execute the actual skill within those constraints before final-diff review. Follow its preflight; do not copy or override its agent count. Revalidate any edits before the existing G4.
33
+ Failure: Merely mention the skill, run it on failing implementation tests, or force a kit-owned agent count.
34
+
35
+ ## Simplify unavailable
36
+ Input: Related tests pass, but ce-simplify-code is not installed. Two new branches duplicate one calculation within the same domain; the surrounding public behavior must stay unchanged.
37
+ Expected: Directly inspect the current changes for duplication, state, branches and complexity using the execution criteria. Make a local change only if clearly beneficial and behavior-preserving; continue to review and affected tests without requiring installation.
38
+ Failure: Stop to install Compound, skip simplification review, introduce a general framework or touch unrelated files.
39
+
40
+ ## No useful simplification
41
+ Input: Related tests pass; the changed function is already clear. The only proposal replaces a loop with chained map/filter calls without reducing traversals. Another task changes documentation only.
42
+ Expected: A no-change result is valid. Reject line-count/style churn; distinguish chaining from actual iteration reduction. Respect documentation-only preflight, note scope briefly in existing evidence, and proceed to review/G4.
43
+ Failure: Manufacture changes, report speedup without evidence, create a mandatory simplify report or new Task.
44
+
45
+ ## Behavior-changing proposal
46
+ Input: A shorter implementation sorts caller-visible results, fuses loops that reorder effects, removes an error check, or merges logic across distinct domains.
47
+ Expected: Do not apply it as simplification. Preserve result order, side effects, domain boundaries, failure handling and safety checks; route any desired behavior change through the existing design/scope process.
48
+ Failure: Silently accept the proposal because tests happen to pass or fewer lines remain.
49
+
50
+ ## Review edits after simplify
51
+ Input: Simplify changed function A and its related tests passed. Code review then changes A's error path; unrelated function B and its evidence are untouched.
52
+ Expected: Review the final diff; recheck A's affected simplification and rerun error-path tests, broadening verification if impact requires. Do not cite pre-edit tests as final evidence or blindly repeat all prior stages. Keep the existing G4.
53
+ Failure: Review only the pre-simplify diff, skip fresh checks, reset every gate, or add another approval/document/Jira Task.
@@ -6,6 +6,8 @@ argument-hint: "[request | status | finish]"
6
6
 
7
7
  # Workflow
8
8
 
9
+ Invoke in Codex with `$workflow`; in Claude Code with `/workflow`. After installation or updates, start a new task/session.
10
+
9
11
  Turn `$ARGUMENTS` into an approved, reviewable change without creating documentation debt.
10
12
 
11
13
  ## Non-negotiable gates
@@ -14,11 +16,15 @@ Turn `$ARGUMENTS` into an approved, reviewable change without creating documenta
14
16
  - Do not declare delivery complete or merge a non-trivial change before G4 passes.
15
17
  - Requirements have one source of truth. AI context may be richer; copied requirements may not diverge.
16
18
 
19
+ ## Explain before asking
20
+
21
+ Before G1 or G3, explain the problem, intended change, safety rule and verification in plain language. Put the short explanation before technical details; use one concrete example when helpful. Keep G4 prediction-before-reveal intact.
22
+
17
23
  ## Route by current state
18
24
 
19
25
  1. **No approved Story:** read `references/intake.md`. Use `assets/STORY.md`; ask only missing behavior questions and obtain G1.
20
26
  2. **Approved, not implemented:** read `references/execution.md`. Read `references/domain-risks.md` only for relevant risk domains. Create a Task from `assets/TASK.md` only when one PR is not reviewable.
21
- 3. **Implemented or `finish`:** read `references/understanding-gate.md`; run G4 before completion.
27
+ 3. **Implemented or `finish`:** complete pending checks in `references/execution.md`, then follow `references/understanding-gate.md` for G4.
22
28
  4. **`status`:** report stage, blocking decision, evidence present, and the single next action.
23
29
 
24
30
  Use the user's language. Keep each response focused on one decision. Surface assumptions and evidence boundaries. Never say “AI decided”; name the human-owned decision or mark it open.
@@ -5,7 +5,7 @@ Understanding gate (G1): <pending>
5
5
  Understanding gate (G4): <pending>
6
6
 
7
7
  ## Goal
8
- <Actor can achieve observable outcome because...>
8
+ <In a few plain-language sentences: what goes wrong today, what the person can do after the change, what must remain safe, and how we will check it. Put technical detail below; label assumptions.>
9
9
 
10
10
  ## Domain
11
11
  - Terms: <term = meaning>
@@ -3,20 +3,40 @@
3
3
  ## Size first
4
4
 
5
5
  - **Small/reversible:** one reviewable outcome, local effect. Record `Plan source: N/A — small and reversible`; use test-first implementation and review.
6
- - **Normal:** use `ce-plan → ce-work → ce-code-review` when Compound Engineering is available. Otherwise perform equivalent repository-grounded plan, work, and review stages.
6
+ - **Normal:** use `ce-plan → ce-work → ce-simplify-code → ce-code-review` when Compound Engineering is available; simplify only after related tests pass. Otherwise perform equivalent repository-grounded stages directly.
7
7
  - **High-risk/hard to reverse:** add G3. Present the key design decision, alternatives, invariant, rollback/recovery path, and evidence plan; end the turn for human approval before work. Save that decision to `docs/understanding/<slug>-plan.md` and record `Understanding gate (G3): <artifact> · <YYYY-MM-DD> · Check-in: accepted`.
8
8
 
9
9
  High-risk signals: money/payment, authentication/authorization, concurrency, destructive migration, sensitive data, data loss, and irreversible external side effects.
10
10
 
11
+ ## Explain the plan before G3
12
+
13
+ Lead with the human-visible change and the reason for the chosen approach. Then explain the key design decision in plain language: what is kept, what changes, why the alternative was not chosen, what must never happen, how failures recover, and what evidence will establish success. Put code symbols and file paths afterward, only where they help review.
14
+
15
+ Use one concrete scenario rather than a list of framework names. Explain each proposed Task by the behavior it delivers and how it connects to the next Task, not just the repository or layer it touches. Keep already-approved decisions visible without asking for them again; ask only for a new material decision. This explanation belongs to the existing plan and G3 checkpoint, not an extra document or gate.
16
+
17
+ This is pre-implementation explanation. It does not reveal the implementation answer during G4; follow that gate's prediction-before-reveal sequence.
18
+
11
19
  ## Task rule
12
20
 
13
21
  Create Tasks only when the approved Story cannot be reviewed as one PR. Each Task has one independent outcome, references Story M/V IDs, stays within 30 non-empty lines, and contains no speculative implementation choreography. **HOW belongs to the repository-grounded plan.**
14
22
 
15
23
  ## Execute
16
24
 
25
+ For user-authorized optional Jira publication after G1, follow `jira.md`. Without a connector or authorized target, produce a preview only; the Story remains canonical.
26
+
17
27
  1. Read the approved Story, relevant code, tests, repository instructions, and prior learnings.
18
28
  2. Make a plan that maps every M/V ID to code and evidence. Do not create a second requirement source.
19
- 3. For new behavior or a bug fix, demonstrate RED before production code, GREEN after the minimum change, then refactor while green.
20
- 4. Review the actual diff against the Story, including failure paths and what tests do not prove. Use `ce-code-review` for deep review when available.
21
- 5. Resolve or explicitly record material findings.
22
- 6. Continue to `understanding-gate.md`; passing tests alone are not completion.
29
+ 3. For new behavior or a bug fix, demonstrate RED before production code, then GREEN after the minimum change. Proceed when related tests pass.
30
+ 4. Refactor while green: perform the simplification pass below. If `ce-simplify-code` is available, read its `SKILL.md` and execute it; naming the skill is not execution. If unavailable, apply the same criteria below directly; do not require installation or stop the workflow.
31
+ 5. Review the final diff after simplification against the Story, including failure paths and what tests do not prove. Use `ce-code-review` for deep review when available; resolve material findings.
32
+ 6. Revalidate affected behavior after simplify/review edits before G4. If review edits affect previously simplified code, recheck only the affected scope; do not restart the whole pipeline automatically. Broaden tests when impact warrants it; never claim old results cover new edits.
33
+ 7. Continue to `understanding-gate.md`; passing tests alone are not completion.
34
+
35
+ ## Simplification pass
36
+
37
+ - Review is a default part of refactoring, not a change quota: no changes is a valid result when no clear benefit exists. Documentation-only or mechanical changes may need no code simplification; follow the skill's preflight.
38
+ - Limit scope to the current task's changed code and necessary related seams. Avoid unrelated refactoring, new abstractions or packages, and edits made just to fill a diff.
39
+ - Reduce duplication, unnecessary state, branches and complexity to improve understanding. Fewer lines or replacing `for` with a stream is not evidence of improvement; chaining operations does not necessarily reduce traversals. Check actual iteration and evaluation behavior before claiming efficiency.
40
+ - Preserve behavior, result order, side effects, domain boundaries, failure handling and safety checks. A proposal that changes them belongs to the existing design or scope-change process, not a silent simplification.
41
+ - Follow the invoked skill and applicable repository/runtime instructions for execution and agent use; this kit sets no fixed agent count. Do not copy the skill's orchestration into this workflow.
42
+ - Include changes (or no-change outcome), review scope and fresh checks briefly in existing review/verification evidence. Add no separate approval gate, mandatory document or Jira Task.
@@ -12,6 +12,20 @@ Derive before asking: actor, desired outcome, terms/entities, state change, inva
12
12
  - Never ask implementation or **HOW** questions before the contract is clear. Database, queue, lock, and file choices belong to planning.
13
13
  - Offer a concrete default rather than an open questionnaire when a conventional safe choice exists.
14
14
 
15
+ ## Explain the direction first
16
+
17
+ Before showing the contract or asking for G1, give a short explanation in the user's language. Assume no knowledge of the codebase, not a lack of intelligence. Use familiar words and a respectful tone; define necessary technical terms on first use.
18
+
19
+ Cover these points in a few connected sentences:
20
+ - What happens today, and why that is a problem for the person using it.
21
+ - What will happen after the change, with one concrete before/after example if helpful.
22
+ - What must remain true, and what happens if the operation fails.
23
+ - How we will tell it works, including anything we cannot yet verify.
24
+
25
+ Explain observable behavior here, not implementation choices. Label a suspected cause as a hypothesis. Use an analogy only when it clarifies the real behavior, and connect it back to that behavior. For a simple change, one or two sentences are enough. Do not force a diagram, quiz, separate explainer artifact, or another approval round.
26
+
27
+ Put this explanation at the start of the Story's Goal section, with the formal criteria and technical evidence below it. It is part of the same contract, not a second requirements source. The reader should be able to judge the desired outcome before seeing field names, gate IDs or commands.
28
+
15
29
  ## Output recipe
16
30
 
17
31
  Create one Story from `../assets/STORY.md`:
@@ -26,9 +40,35 @@ Create one Story from `../assets/STORY.md`:
26
40
 
27
41
  Keep it one-screen by default. Do not copy it into an “AI spec.”
28
42
 
43
+ ## Jira section formatting
44
+
45
+ When creating or updating Jira Stories or Tasks, use the editor's actual format. In Jira wiki-text mode, use literal h2. and h3. headings, not Markdown heading markers. Use real newline characters, not escaped backslash-n text.
46
+
47
+ Each heading must occupy its own line, with a blank line before and after it. End the preceding paragraph or list before starting the next section. Keep peer sections such as MUST, SHOULD, OUT, Decisions and Verify at the same heading level; do not indent a heading or place it inside a list item or paragraph. Separate consecutive headings with a blank line even when there is no intervening body. Do not leave empty sections unintentionally: use a brief N/A reason where appropriate.
48
+
49
+ Example for Jira wiki-text mode:
50
+
51
+ ```text
52
+ h2. Scope
53
+
54
+ h3. MUST
55
+
56
+ * M1. The user can complete the operation.
57
+
58
+ h3. SHOULD
59
+
60
+ * S1. The user can identify the failed step.
61
+
62
+ h3. OUT
63
+
64
+ * O1. Other payment methods are unchanged.
65
+ ```
66
+
67
+ In the visual editor, apply actual heading styles to separate blocks instead of typing wiki markup as ordinary text. After publishing, check the rendered description: headings must appear as distinct sections, and the previous list or paragraph must not absorb the next heading. Preserve the user's existing formatting when editing a description; do not overwrite their manual corrections.
68
+
29
69
  ## G1 approval
30
70
 
31
- Show the full concise draft and ask: “이 내용이 이번 구현의 범위와 완료 조건으로 맞나요?” End the turn. On explicit approval, save the approved snapshot and decision to `docs/understanding/<slug>-contract.md`, set `Status: Approved`, and record:
71
+ Show the full concise draft, beginning with the plain-language explanation above, and ask: “이 내용이 이번 구현의 범위와 완료 조건으로 맞나요?” End the turn. On explicit approval, save the approved snapshot and decision to `docs/understanding/<slug>-contract.md`, set `Status: Approved`, and record:
32
72
 
33
73
  `Understanding gate (G1): <artifact> · <date> · Check-in: accepted`
34
74
 
@@ -0,0 +1,52 @@
1
+ # Optional Jira publication
2
+
3
+ The canonical Story stays local and remains the source of truth. Jira is an optional publication target, never a second requirements contract. Do not create or update an issue merely because Jira is installed.
4
+
5
+ ## Preview first
6
+
7
+ Run `ai-workflow-kit jira preview <story-file> --root <project>` for a paste-ready, readable preview. This command never loads a connector, writes a publication record or creates an issue. Draft Stories can be previewed; invalid Stories fail validation. Review the entire preview for confidential content before sharing it. The preview intentionally includes only Goal, Domain, MUST, SHOULD, OUT, Decisions and Verify, not Owner or gate records.
8
+
9
+ In Codex, use `$workflow`; in Claude Code, use `/workflow`. After a user asks to publish, check the approved Story and G1 evidence, resolve the exact Jira site, project and optional parent, and obtain explicit publication authorization. Requirements approval alone does not authorize an external write. If the host has no supported connector or the user has not supplied a target, return the preview and stop. Never claim an issue exists without its verified key and URL.
10
+
11
+ ## Host adapter API
12
+
13
+ The package exports `formatStory(text)` and `publishStory(options)` from `@pazmo/ai-workflow-kit/src/jira.mjs`. There is no bundled Jira network client, credential store, environment-based connector loader or shell execution. A trusted host integration wraps its available connector/MCP/CLI as these asynchronous functions:
14
+
15
+ - `find({publicationId, target})`: return **all** matching issue identities (`{key, url}`), or `[]`. Search by exact publication identity within the authorized site/project/parent, not by title. Exhaust pagination; incomplete or inaccessible search results must be an error, not `[]`.
16
+ - `create({publicationId, target, summary, description})`: create-if-absent using that identity; persist the identity in Jira metadata, then return `{key, url}`. The host must serialize competing creation for the same identity if used across machines. Jira's ordinary create endpoint alone does not provide this guarantee.
17
+ - `read({key, url, target})`: fetch the actual issue and return `{key, url, publicationId, target, summary, description}`. These values must come from Jira; never echo the create request to simulate verification. Retrieve the parent as well as the project and description.
18
+
19
+ `target` is `{siteUrl, project, parent?}`: an HTTPS origin without credentials/query/path, uppercase project key, and optional issue key in the same project. Jira Cloud ADF is the supported transport description format. Data Center wiki text needs a host-side lossless conversion and real rendered verification; it is not a built-in supported transport in this release.
20
+
21
+ The `description` is an [Atlassian Document Format](https://developer.atlassian.com/cloud/jira/platform/apis/document/structure/) document containing seven level-2 headings and inert paragraph/bullet-list text. M1/V1 and M-1/V-1 spellings remain exactly as written. Inline Markdown and code fences are preserved as literal text, not interpreted as links, macros or mentions. Empty sections require an explicit N/A reason. No arbitrary Markdown-to-ADF renderer is included.
22
+
23
+ ```js
24
+ import { publishStory } from '@pazmo/ai-workflow-kit/src/jira.mjs';
25
+
26
+ // hostJiraAdapter is trusted code supplied by your host, with credentials kept there.
27
+ // Keep this identity for this Story across retries and clones; do not generate it per call.
28
+ const result = await publishStory({
29
+ root: projectRoot,
30
+ file: 'docs/understanding/my-change-contract.md',
31
+ publicationId: stableStoryPublicationId,
32
+ target: authorizedTarget,
33
+ adapter: hostJiraAdapter,
34
+ publish: true, // only after the human authorizes this specific external publication
35
+ });
36
+ ```
37
+
38
+ Only literal `publish: true` enables publication. Missing target or adapter returns `status: 'preview'`. The caller provides a unique opaque `publicationId` (8–128 letters/digits/underscore/dot/colon/hyphen, beginning with a letter/digit; UUID recommended). Different Stories must not reuse it. The library derives the remote identity from that value and target, so two repositories named `story.md` do not collide. Review changes in target as a new authorization decision.
39
+
40
+ ## Verification, retries and failures
41
+
42
+ Before create, the library checks Story shape and one Approved/Delivered Status plus one G1 record in the metadata, then stores a private local intent under `.ai-workflow/publications/`. Publication requires a plain preamble: title, Status, Owner, gate records, optional G4 restatement and blank lines only. Comments, fences and other blocks cannot supply approval. Publication additionally requires a separate nonempty G1 evidence artifact; a self-reference or hard link to the Story is insufficient. This is stricter than the general checker. The host must establish that the evidence records genuine human approval. The library searches for an existing issue, rejects malformed or multiple matches, reads the chosen issue back, and compares title, target, identity, heading/list order and content. JSON object-property ordering is irrelevant; semantic document differences fail verification. On success it returns `status: 'published'`, the verified key/URL and relative record path. A retry verifies again and never automatically updates an existing issue.
43
+
44
+ Gate metadata belongs in the preamble, except a trailing block of `Understanding gate (G1/G3/G4): ...` and `G4: PASS — ...` records after all Verify content, which is also excluded from preview/ADF. No requirement content may follow that trailing block. Ordinary section prose (including `Status:` or `Owner:` paragraphs) remains public content. This is not a general confidential-content detector.
45
+
46
+ The record contains only schema/state, derived identity, content digest, target and verified issue identity; no Story body, gate evidence, credentials or transport errors. Keep the original Story unchanged. Include publication records when moving this workflow to another machine, subject to the team's policy for Jira URLs; protect them against deletion/tampering. Deleting records, changing the identity or implementing a host adapter that blindly creates defeats deduplication.
47
+
48
+ The adapter owns permissions and credentials, finite network deadlines, pagination, remote create-if-absent and rate limiting. Do not retry create inside the adapter without remote idempotency. The package catches rejected calls and returns stage-specific errors without raw connector messages. A lost create response leaves an intent; a retry can adopt a matching issue, but if lookup finds nothing, creation stays blocked because indexing may lag. Reconcile in Jira before further action; do not delete the intent just to force retry.
49
+
50
+ Same-project local invocations use an exclusive lock directory. A crash leaves it for inspection. After confirming no publisher is active, remove only the named `.json.lock` directory; preserve the `.json` intent and any `.json.next` file for reconciliation. A leftover `.next`, unreadable/invalid record, changed Story, mismatch or permission error is an actionable failure, not a created-issue claim. Never edit the Story to make verification pass. The checker verifies records and evidence paths, not human identity, cognition or authenticity of approval.
51
+
52
+ This release is tested with synthetic adapters. It does not prove a live Jira connector's permissions, renderer, search consistency or distributed idempotency. No live Jira action is needed to install or use the workflow.
@@ -5,7 +5,7 @@ This gate checks ownership of the actual implementation. It is not a generated s
5
5
  ## Predict before reveal
6
6
 
7
7
  1. Gather the approved Story, test results, review findings, and the **raw diff** or mechanical diff/stat. Show only that evidence; do not explain the solution yet.
8
- 2. Ask in the user's language: “이 변경이 사용자나 시스템의 어떤 behavior를 바꾸나요? 핵심 invariant 또는 failure path는 무엇이고, 어떤 테스트가 이를 증명하며 아직 unproven인 evidence boundary는 무엇인가요?” **END THE TURN.**
8
+ 2. Ask in the user's language: “이 변경 뒤에 사용자가 겪는 일이 어떻게 달라질까요? 꼭 지켜야 할 규칙과 실패했을 때의 동작은 무엇인가요? 어떤 테스트가 그걸 확인했고, 아직 확인하지 못한 것은 무엇인가요?” **END THE TURN.**
9
9
  3. Only after the human answers, **compare** the answer with the Story, diff, runtime flow, and tests.
10
10
  4. Return three short sections: correct, missed, incorrect/risky. Never reward confident guessing.
11
11
  5. If a core gap remains, teach only that gap and require a one- or two-sentence **restatement**. Repeat until the owner can explain behavior, one invariant/failure path, and the evidence boundary.
@@ -0,0 +1,208 @@
1
+ import fs from 'node:fs/promises';
2
+ import { createHash } from 'node:crypto';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ // Only these package-owned destinations may be committed or restored by a journal.
7
+ const PATHS = Object.freeze([
8
+ 'AGENTS.md', 'CLAUDE.md', '.agents/skills/workflow', '.claude/skills/workflow',
9
+ 'templates/ai-workflow/STORY.md', 'templates/ai-workflow/TASK.md',
10
+ '.ai-workflow/bin/check.mjs', '.ai-workflow/config.json',
11
+ ]);
12
+ const JOURNAL = '.ai-workflow-install';
13
+
14
+ async function stat(file) {
15
+ try { return await fs.lstat(file); } catch (error) {
16
+ if (error.code === 'ENOENT') return null;
17
+ throw error;
18
+ }
19
+ }
20
+
21
+ // Reject links rather than following them into a user's unrelated files.
22
+ export async function safePath(root, relative) {
23
+ const file = path.resolve(root, relative);
24
+ const rel = path.relative(root, file);
25
+ if (!rel || rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
26
+ throw new Error('Path escapes project root.');
27
+ }
28
+ let current = root;
29
+ const parts = rel.split(path.sep);
30
+ for (const [index, part] of parts.entries()) {
31
+ current = path.join(current, part);
32
+ const info = await stat(current);
33
+ if (info?.isSymbolicLink()) throw new Error('Refusing symlink in managed path.');
34
+ if (info && index < parts.length - 1 && !info.isDirectory()) throw new Error('Managed parent is not a directory.');
35
+ }
36
+ return file;
37
+ }
38
+
39
+ async function fingerprint(file) {
40
+ const info = await stat(file);
41
+ if (!info) return null;
42
+ if (info.isSymbolicLink()) throw new Error('Refusing symlink in managed tree.');
43
+ if (info.isDirectory()) {
44
+ const entries = [];
45
+ for (const name of (await fs.readdir(file)).sort()) entries.push([name, await fingerprint(path.join(file, name))]);
46
+ return JSON.stringify([info.mode, entries]);
47
+ }
48
+ if (!info.isFile()) throw new Error('Managed path must be a regular file or directory.');
49
+ return `${info.mode}:${createHash('sha256').update(await fs.readFile(file)).digest('hex')}`;
50
+ }
51
+
52
+ async function writeJournal(directory, journal) {
53
+ const temporary = path.join(directory, 'journal.next');
54
+ const handle = await fs.open(temporary, 'w', 0o600);
55
+ try { await handle.writeFile(JSON.stringify(journal)); await handle.sync(); } finally { await handle.close(); }
56
+ await fs.rename(temporary, path.join(directory, 'journal.json'));
57
+ }
58
+
59
+ function parents(relative) {
60
+ const result = [];
61
+ for (let dir = path.dirname(relative); dir !== '.'; dir = path.dirname(dir)) result.push(dir);
62
+ return result;
63
+ }
64
+
65
+ async function prune(root, directories) {
66
+ for (const dir of [...new Set(directories)].sort((a, b) => b.length - a.length)) {
67
+ try { await fs.rmdir(await safePath(root, dir)); } catch (error) {
68
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error;
69
+ }
70
+ }
71
+ }
72
+
73
+ async function rollback(root, directory, journal) {
74
+ // Check all backups before restoring any path: corrupt recovery must be inert.
75
+ for (const entry of journal.entries) {
76
+ const backup = path.join(directory, 'backup', entry.relative);
77
+ if (await stat(backup) && await fingerprint(backup) !== entry.before) {
78
+ throw new Error('Recovery stopped: backup does not match the original fingerprint; preserve the journal.');
79
+ }
80
+ }
81
+ for (const entry of [...journal.entries].reverse()) {
82
+ const target = await safePath(root, entry.relative);
83
+ const backup = path.join(directory, 'backup', entry.relative);
84
+ const backedUp = await stat(backup);
85
+ const current = await fingerprint(target);
86
+ if ((backedUp || !entry.existed) && current !== null && current !== entry.after) {
87
+ throw new Error('Recovery stopped: managed files were modified after installation began; preserve the journal and backups.');
88
+ }
89
+ if (backedUp) {
90
+ await fingerprint(backup);
91
+ await fs.rm(target, { recursive: true, force: true });
92
+ await fs.mkdir(path.dirname(target), { recursive: true });
93
+ await fs.rename(backup, target);
94
+ } else if (!entry.existed) {
95
+ await fs.rm(target, { recursive: true, force: true });
96
+ }
97
+ }
98
+ await prune(root, journal.createdParents);
99
+ }
100
+
101
+ async function acquire(root) {
102
+ const directory = await safePath(root, JOURNAL);
103
+ try { await fs.mkdir(directory, { mode: 0o700 }); return directory; } catch (error) {
104
+ if (error.code !== 'EEXIST') throw error;
105
+ }
106
+ // No process guessing across hosts. Unknown/corrupt journals require inspection.
107
+ let journal;
108
+ try { journal = JSON.parse(await fs.readFile(await safePath(root, `${JOURNAL}/journal.json`), 'utf8')); }
109
+ catch { throw new Error('Installation in progress or interrupted before journal creation; inspect .ai-workflow-install before retrying.'); }
110
+ if (journal.hostname !== os.hostname() || !Number.isSafeInteger(journal.pid) || journal.pid < 1) {
111
+ throw new Error('Installation locked by an unknown owner; inspect .ai-workflow-install.');
112
+ }
113
+ try { process.kill(journal.pid, 0); throw new Error('Installation in progress; retry after it exits.'); }
114
+ catch (error) { if (error.code !== 'ESRCH') throw error; }
115
+ const valid = journal.version === 1 && ['preparing', 'committing', 'committed'].includes(journal.state)
116
+ && Array.isArray(journal.entries) && journal.entries.every((entry) => PATHS.includes(entry.relative) && typeof entry.existed === 'boolean' && (entry.existed ? typeof entry.before === 'string' : entry.before === null) && (entry.after === null || typeof entry.after === 'string'))
117
+ && new Set(journal.entries.map((entry) => entry.relative)).size === journal.entries.length
118
+ && Array.isArray(journal.createdParents) && journal.createdParents.every((dir) => PATHS.some((file) => parents(file).includes(dir)));
119
+ if (!valid) throw new Error('Invalid installation journal; preserve backups for manual recovery.');
120
+ try { await fs.mkdir(path.join(directory, 'recovering')); } catch {
121
+ throw new Error('Installation recovery locked; inspect .ai-workflow-install before retrying.');
122
+ }
123
+ try {
124
+ await fingerprint(directory);
125
+ if (journal.state === 'committing') await rollback(root, directory, journal);
126
+ } finally {
127
+ await fs.rmdir(await safePath(root, `${JOURNAL}/recovering`));
128
+ }
129
+ await fs.rm(directory, { recursive: true });
130
+ return acquire(root);
131
+ }
132
+
133
+ export async function installTransaction(root, prepare) {
134
+ await fs.mkdir(root, { recursive: true });
135
+ root = await fs.realpath(root);
136
+ const directory = await acquire(root);
137
+ const stage = path.join(directory, 'stage');
138
+ const journal = { version: 1, hostname: os.hostname(), pid: process.pid, state: 'preparing', entries: [], createdParents: [] };
139
+ try {
140
+ await writeJournal(directory, journal);
141
+ await fs.mkdir(stage);
142
+ const before = new Map();
143
+ for (const relative of PATHS) {
144
+ const target = await safePath(root, relative);
145
+ const hash = await fingerprint(target);
146
+ before.set(relative, hash);
147
+ if (hash !== null) {
148
+ const copy = path.join(stage, relative);
149
+ await fs.mkdir(path.dirname(copy), { recursive: true });
150
+ await fs.cp(target, copy, { recursive: true, preserveTimestamps: true });
151
+ }
152
+ }
153
+ const result = await prepare(stage);
154
+ for (const relative of PATHS) {
155
+ const after = await fingerprint(path.join(stage, relative));
156
+ if (before.get(relative) === after) continue;
157
+ journal.entries.push({ relative, existed: before.get(relative) !== null, before: before.get(relative), after });
158
+ for (const parent of parents(relative)) {
159
+ if (!await stat(path.join(root, parent))) journal.createdParents.push(parent);
160
+ }
161
+ }
162
+ // Detect user edits made while the staged installation was being prepared.
163
+ for (const relative of PATHS) {
164
+ if (before.get(relative) !== await fingerprint(await safePath(root, relative))) {
165
+ throw new Error('Managed files changed during installation; retry without concurrent edits.');
166
+ }
167
+ }
168
+ await fs.mkdir(path.join(directory, 'backup'));
169
+ journal.state = 'committing';
170
+ await writeJournal(directory, journal);
171
+ for (const entry of journal.entries) {
172
+ const target = await safePath(root, entry.relative);
173
+ if (!entry.existed && await stat(target)) throw new Error('Managed files changed during installation; refusing to replace a new user file.');
174
+ if (entry.existed) {
175
+ const backup = path.join(directory, 'backup', entry.relative);
176
+ await fs.mkdir(path.dirname(backup), { recursive: true });
177
+ await fs.rename(target, backup);
178
+ if (await fingerprint(backup) !== before.get(entry.relative)) {
179
+ // This process just moved a concurrent edit, not a recovered backup.
180
+ await fs.rename(backup, target);
181
+ throw new Error('Managed files changed during installation; restoring the moved user edit.');
182
+ }
183
+ }
184
+ const source = path.join(stage, entry.relative);
185
+ if (await stat(source)) {
186
+ await fs.mkdir(path.dirname(target), { recursive: true });
187
+ await fs.rename(source, target);
188
+ }
189
+ }
190
+ await writeJournal(directory, { ...journal, state: 'committed' });
191
+ journal.state = 'committed';
192
+ const removedParents = [];
193
+ for (const entry of journal.entries) {
194
+ if (!await stat(path.join(root, entry.relative))) removedParents.push(...parents(entry.relative));
195
+ }
196
+ await prune(root, removedParents);
197
+ await fs.rm(directory, { recursive: true });
198
+ return result;
199
+ } catch (error) {
200
+ try {
201
+ if (journal.state === 'committing') await rollback(root, directory, journal);
202
+ if (journal.state !== 'committed') await fs.rm(directory, { recursive: true });
203
+ } catch {
204
+ throw new Error('Installation failed and rollback needs recovery; keep .ai-workflow-install backups and rerun init after this process exits.');
205
+ }
206
+ throw error;
207
+ }
208
+ }
package/src/install.mjs CHANGED
@@ -11,7 +11,8 @@ import {
11
11
  import path from 'node:path';
12
12
  import { fileURLToPath } from 'node:url';
13
13
  import { HOSTS, normalizeHosts, projectPath } from './paths.mjs';
14
- import { MANAGED_BLOCK, removeManagedBlock, upsertManagedBlock } from './managed-block.mjs';
14
+ import { managedBlockFor, removeManagedBlock, upsertManagedBlock } from './managed-block.mjs';
15
+ import { installTransaction } from './install-transaction.mjs';
15
16
 
16
17
  const modulePackageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
17
18
  const CONFIG_PATH = '.ai-workflow/config.json';
@@ -153,7 +154,7 @@ async function removeFileIfUnchanged(root, relative, expectedHash, preserved) {
153
154
  return true;
154
155
  }
155
156
 
156
- export async function installWorkflow({
157
+ async function installPrepared({
157
158
  root = process.cwd(),
158
159
  packageRoot = modulePackageRoot,
159
160
  hosts = ['codex', 'claude'],
@@ -185,7 +186,7 @@ export async function installWorkflow({
185
186
  const file = projectPath(root, hostConfig.instructionFile);
186
187
  const current = await readText(file, '');
187
188
  if (selectedHosts.includes(host)) {
188
- instructionPlans.set(host, { file, current, next: upsertManagedBlock(current, MANAGED_BLOCK) });
189
+ instructionPlans.set(host, { file, current, next: upsertManagedBlock(current, managedBlockFor(host)) });
189
190
  } else if (previousHosts.has(host)) {
190
191
  instructionPlans.set(host, { file, current, next: removeManagedBlock(current) });
191
192
  }
@@ -258,6 +259,11 @@ export async function installWorkflow({
258
259
  return { changed, installed, preserved, hosts: selectedHosts };
259
260
  }
260
261
 
262
+ export async function installWorkflow(options = {}) {
263
+ const root = path.resolve(options.root ?? process.cwd());
264
+ return installTransaction(root, (stage) => installPrepared({ ...options, root: stage }));
265
+ }
266
+
261
267
  async function removeEmptyParents(file, stopAt) {
262
268
  let current = path.dirname(file);
263
269
  while (current.startsWith(stopAt) && current !== stopAt) {
@@ -273,7 +279,7 @@ async function removeEmptyParents(file, stopAt) {
273
279
  }
274
280
  }
275
281
 
276
- export async function removeWorkflow({ root = process.cwd() } = {}) {
282
+ async function removePrepared({ root = process.cwd() } = {}) {
277
283
  root = path.resolve(root);
278
284
  const config = await readConfig(root);
279
285
  const preserved = [];
@@ -333,3 +339,7 @@ export async function removeWorkflow({ root = process.cwd() } = {}) {
333
339
 
334
340
  return { changed, preserved };
335
341
  }
342
+
343
+ export async function removeWorkflow({ root = process.cwd() } = {}) {
344
+ return installTransaction(path.resolve(root), (stage) => removePrepared({ root: stage }));
345
+ }
package/src/jira.mjs ADDED
@@ -0,0 +1,211 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { isDeepStrictEqual } from 'node:util';
5
+ import { checkArtifact, checkGate, isGateMetadataLine } from '../assets/check.mjs';
6
+ import { safePath } from './install-transaction.mjs';
7
+
8
+ const HEADINGS = ['Goal', 'Domain', 'MUST', 'SHOULD', 'OUT', 'Decisions', 'Verify'];
9
+ const hash = (value) => createHash('sha256').update(value).digest('hex');
10
+ const textNode = (text) => ({ type: 'text', text });
11
+ const paragraph = (text) => ({ type: 'paragraph', content: [textNode(text)] });
12
+
13
+ /** Plain canonical Markdown -> inert ADF headings, paragraphs and bullet lists. */
14
+ export function formatStory(text) {
15
+ const summary = text.match(/^# Story: (.+)$/m)?.[1]?.trim();
16
+ if (!summary || summary.length > 255) throw new Error('Story title is missing or exceeds 255 characters.');
17
+ const sections = [];
18
+ let fenced = false;
19
+ let trailingGates = false;
20
+ for (const line of text.replace(/\r\n/g, '\n').split('\n')) {
21
+ if (/^\s*(?:`{3,}|~{3,})/.test(line)) fenced = !fenced;
22
+ // Only a trailing gate block after Verify is metadata, not similarly named prose.
23
+ const gateLine = isGateMetadataLine(line);
24
+ if (!fenced && sections.at(-1)?.heading === 'Verify' && gateLine) trailingGates = true;
25
+ if (trailingGates) {
26
+ if (gateLine || !line.trim()) continue;
27
+ throw new Error('Gate metadata must follow all Verify content or move to the Story preamble.');
28
+ }
29
+ const heading = !fenced && line.match(/^##\s+(.+?)\s*$/);
30
+ if (heading) sections.push({ heading: heading[1], lines: [] });
31
+ else if (sections.length) sections.at(-1).lines.push(line);
32
+ }
33
+ if (!isDeepStrictEqual(sections.map((section) => section.heading), HEADINGS) || fenced) {
34
+ throw new Error('Story needs exactly the seven canonical sections in order and closed code fences.');
35
+ }
36
+ const content = [];
37
+ const preview = [];
38
+ for (const section of sections) {
39
+ const body = section.lines.join('\n').trim();
40
+ if (!body) throw new Error(`Story section ${section.heading} is empty; explain why it is N/A.`);
41
+ preview.push(`## ${section.heading}\n\n${body}`);
42
+ content.push({ type: 'heading', attrs: { level: 2 }, content: [textNode(section.heading)] });
43
+ let list;
44
+ for (const line of body.split('\n')) {
45
+ const item = line.match(/^[-*] (.+)$/);
46
+ if (item) {
47
+ if (!list) { list = { type: 'bulletList', content: [] }; content.push(list); }
48
+ list.content.push({ type: 'listItem', content: [paragraph(item[1])] });
49
+ } else {
50
+ list = null;
51
+ if (line.trim()) content.push(paragraph(line));
52
+ }
53
+ }
54
+ }
55
+ return { summary, description: { type: 'doc', version: 1, content }, preview: preview.join('\n\n') + '\n' };
56
+ }
57
+
58
+ function validatedTarget(target) {
59
+ let url;
60
+ try { url = new URL(target.siteUrl); } catch { throw new Error('Jira target needs a valid HTTPS siteUrl.'); }
61
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== '/') {
62
+ throw new Error('Jira target must be an HTTPS origin without credentials, query or path.');
63
+ }
64
+ if (!/^[A-Z][A-Z0-9_]{1,30}$/.test(target.project ?? '')) throw new Error('Invalid Jira target project key.');
65
+ if (target.parent !== undefined && !new RegExp(`^${target.project}-[1-9][0-9]*$`).test(target.parent)) {
66
+ throw new Error('Jira parent must be an issue key within the authorized project.');
67
+ }
68
+ return { siteUrl: url.origin, project: target.project, ...(target.parent ? { parent: target.parent } : {}) };
69
+ }
70
+
71
+ function validateIssue(issue, target) {
72
+ const validKey = typeof issue?.key === 'string' && new RegExp(`^${target.project}-[1-9][0-9]*$`).test(issue.key);
73
+ if (!validKey || issue.url !== `${target.siteUrl}/browse/${issue.key}`) {
74
+ throw new Error('Jira verification failed: invalid issue key or URL for the authorized target.');
75
+ }
76
+ return { key: issue.key, url: issue.url };
77
+ }
78
+
79
+ async function call(adapter, method, request) {
80
+ try { return await adapter[method](structuredClone(request)); }
81
+ catch {
82
+ // Host errors may contain bearer tokens, URLs with credentials or Story content.
83
+ throw new Error(`Jira ${method} failed. Check host permissions/connectivity; preserve the publication record and reconcile before retrying creation.`);
84
+ }
85
+ }
86
+
87
+ async function save(file, record, assertStorage) {
88
+ await assertStorage();
89
+ const temporary = `${file}.next`;
90
+ const handle = await fs.open(temporary, 'wx', 0o600);
91
+ try { await handle.writeFile(JSON.stringify(record, null, 2) + '\n'); await handle.sync(); }
92
+ finally { await handle.close(); }
93
+ await assertStorage();
94
+ await fs.rename(temporary, file);
95
+ }
96
+
97
+ /**
98
+ * No transport is loaded from disk or environment. The caller supplies the host
99
+ * adapter and explicit publication authority; CLI use remains preview-only.
100
+ */
101
+ export async function publishStory({ root = process.cwd(), file, target, adapter, publish = false, publicationId: identity } = {}) {
102
+ root = await fs.realpath(root);
103
+ if (typeof file !== 'string') throw new Error('A canonical Story file is required.');
104
+ const storyFile = await safePath(root, file);
105
+ const original = await fs.readFile(storyFile, 'utf8');
106
+ const formatted = formatStory(original);
107
+ const shape = await checkArtifact({ root, file: storyFile });
108
+ if (!shape.ok) throw new Error('Story validation failed (shape or G1/G4 evidence). Run the local checker privately to inspect the details.');
109
+ const preview = { status: 'preview', ...formatted };
110
+ if (publish !== true || !adapter || !target?.project || !target?.siteUrl) return preview;
111
+ const metadata = original.slice(0, /^##[\t ]+/m.exec(original)?.index ?? 0);
112
+ if (!metadata.split(/\r?\n/).every((line) => /^(?:\s*|# Story: .+|Status: .+|Owner: .+|Understanding gate \(G[134]\): .+|G4: .+)$/.test(line))) {
113
+ throw new Error('Jira publication requires plain Story metadata; comments, fences and other blocks are not allowed in the preamble.');
114
+ }
115
+ const statuses = [...metadata.matchAll(/^Status:[\t ]*(.+)$/gmi)];
116
+ const approvals = [...original.matchAll(/^Understanding gate \(G1\):.*$/gmi)];
117
+ if (statuses.length !== 1 || !/^Status:[\t ]*(Approved|Delivered)[\t ]*\r?$/mi.test(metadata)
118
+ || approvals.length !== 1 || !metadata.includes(approvals[0][0])) {
119
+ throw new Error('Jira publication requires one Approved Status and one G1 record in the Story metadata.');
120
+ }
121
+ const gate = await checkGate({ root, file: storyFile, gate: 'G1' });
122
+ if (!gate.ok) throw new Error('Jira publication requires valid G1 evidence. Run the local checker privately.');
123
+ const evidence = approvals[0][0].replace(/^Understanding gate \(G1\):\s*/i, '').split(/\s*[·|]\s*/)[0];
124
+ const [storyInfo, evidenceInfo] = await Promise.all([fs.stat(storyFile), fs.stat(path.resolve(root, evidence))]);
125
+ if (storyInfo.dev === evidenceInfo.dev && storyInfo.ino === evidenceInfo.ino) {
126
+ throw new Error('Jira G1 approval needs a separate evidence artifact, not the Story itself.');
127
+ }
128
+ const evidenceFile = await safePath(root, evidence);
129
+ const approvalBytes = await fs.readFile(evidenceFile);
130
+ const assertApproval = async () => {
131
+ try {
132
+ await safePath(root, evidence);
133
+ const info = await fs.stat(evidenceFile);
134
+ if (info.dev !== evidenceInfo.dev || info.ino !== evidenceInfo.ino || !(await fs.readFile(evidenceFile)).equals(approvalBytes)) throw new Error();
135
+ } catch { throw new Error('G1 approval evidence changed during publication; obtain approval again.'); }
136
+ };
137
+ target = validatedTarget(target);
138
+ if (typeof identity !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{7,127}$/.test(identity)) {
139
+ throw new Error('A stable, unique caller-owned publicationId is required; reuse it across retries and clones.');
140
+ }
141
+ if (!['find', 'create', 'read'].every((name) => typeof adapter[name] === 'function')) {
142
+ throw new Error('Jira host adapter must supply find, create and read functions.');
143
+ }
144
+
145
+ // The caller owns identity. Relative paths alone collide across repositories.
146
+ const publicationId = `workflow-${hash(JSON.stringify([identity, target]))}`;
147
+ const recordRelative = `.ai-workflow/publications/${publicationId}.json`;
148
+ const recordFile = await safePath(root, recordRelative);
149
+ const lock = await safePath(root, `${recordRelative}.lock`);
150
+ await safePath(root, `${recordRelative}.next`);
151
+ await fs.mkdir(path.dirname(recordFile), { recursive: true, mode: 0o700 });
152
+ const storageInfo = await fs.lstat(path.dirname(recordFile));
153
+ const assertStorage = async () => {
154
+ await safePath(root, recordRelative);
155
+ await safePath(root, `${recordRelative}.next`);
156
+ await safePath(root, `${recordRelative}.lock`);
157
+ const current = await fs.lstat(path.dirname(recordFile));
158
+ if (current.dev !== storageInfo.dev || current.ino !== storageInfo.ino) {
159
+ throw new Error('Jira publication storage changed; preserve records and reconcile manually.');
160
+ }
161
+ };
162
+ await assertStorage();
163
+ try { await fs.mkdir(lock, { mode: 0o700 }); }
164
+ catch { throw new Error('Jira publication locked. Wait for the active publisher; after a crash, confirm it has stopped before removing the lock directory.'); }
165
+
166
+ try {
167
+ let record;
168
+ await assertStorage();
169
+ try {
170
+ record = JSON.parse(await fs.readFile(recordFile, 'utf8'));
171
+ if (!record || typeof record !== 'object' || Array.isArray(record)) throw new Error('Invalid record');
172
+ }
173
+ catch (error) { if (error.code !== 'ENOENT') throw new Error('Invalid publication record; preserve it and reconcile manually.'); }
174
+ const digest = hash(JSON.stringify([formatted.summary, formatted.description]));
175
+ if (record && (record.version !== 1 || record.publicationId !== publicationId || record.digest !== digest || !isDeepStrictEqual(record.target, target))) {
176
+ throw new Error('Story or target changed since publication intent; reconcile the existing issue instead of creating another.');
177
+ }
178
+ if (record && !['intent', 'verified'].includes(record.state)) throw new Error('Invalid publication state; reconcile manually.');
179
+ const matches = await call(adapter, 'find', { publicationId, target });
180
+ await assertStorage();
181
+ if (!Array.isArray(matches) || matches.length > 1) throw new Error('Jira lookup returned invalid or multiple duplicate publications; reconcile manually.');
182
+ if (matches.length === 1) validateIssue(matches[0], target);
183
+ let issue = record?.key ? { key: record.key, url: record.url } : matches[0];
184
+ if (record?.key && matches[0] && matches[0].key !== record.key) throw new Error('Jira duplicate publication disagrees with the recorded issue.');
185
+ if (!issue && record) throw new Error('Jira creation outcome is uncertain. Reconcile the original intent; automatic creation is blocked.');
186
+
187
+ if (await fs.readFile(storyFile, 'utf8') !== original) throw new Error('Story changed during publication; rerun after approval.');
188
+ await assertApproval();
189
+ if (!issue) {
190
+ record = { version: 1, state: 'intent', publicationId, digest, target };
191
+ await save(recordFile, record, assertStorage); // durable intent precedes the only external mutation
192
+ await assertApproval();
193
+ issue = await call(adapter, 'create', { publicationId, target, summary: formatted.summary, description: formatted.description });
194
+ }
195
+ const identity = validateIssue(issue, target);
196
+ const readBack = await call(adapter, 'read', { ...identity, target });
197
+ validateIssue(readBack, target);
198
+ if (readBack.key !== identity.key || readBack.publicationId !== publicationId
199
+ || readBack.summary !== formatted.summary || !isDeepStrictEqual(readBack.target, target)
200
+ || !isDeepStrictEqual(readBack.description, formatted.description)) {
201
+ throw new Error('Jira read-back verification mismatch. Preserve the intent and reconcile; the Story has not been changed.');
202
+ }
203
+ if (await fs.readFile(storyFile, 'utf8') !== original) throw new Error('Story changed during publication; reconcile before retrying.');
204
+ await assertApproval();
205
+ await save(recordFile, { version: 1, state: 'verified', publicationId, digest, target, ...identity }, assertStorage);
206
+ return { status: 'published', ...identity, publicationId, record: recordRelative };
207
+ } finally {
208
+ await assertStorage();
209
+ await fs.rmdir(lock);
210
+ }
211
+ }
@@ -8,11 +8,16 @@ export const MANAGED_BLOCK = `${START_MARKER}
8
8
  - Keep one concise canonical Story contract: Goal, Domain, MUST, SHOULD, OUT, Decisions, Verify.
9
9
  - Ask only blocking behavior questions; label safe defaults \`ASSUMED\` instead of silently inventing scope.
10
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.
11
+ - Use Compound Engineering when available: normal work \`ce-plan → ce-work → ce-simplify-code → ce-code-review\`; simplify after related tests pass, revalidate edits before G4. Follow the workflow execution reference for direct fallback; high-risk work adds a human plan gate.
12
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
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
14
  ${END_MARKER}`;
15
15
 
16
+ export function managedBlockFor(host) {
17
+ const command = host === 'codex' ? '$workflow' : '/workflow';
18
+ return MANAGED_BLOCK.replace('## AI workflow', `## AI workflow\n\nInvoke: \`${command} <request>\`, \`${command} status\`, \`${command} finish\`. Start a new task/session after installation or updates.`);
19
+ }
20
+
16
21
  // A marker only counts when it is a line of its own and sits outside a fenced code
17
22
  // block. Instruction files legitimately document this kit's own marker syntax; a
18
23
  // substring match would treat that example as the live block and silently rewrite it.