pactwright 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +68 -0
  3. package/dist/adapter/claude-code.d.ts +53 -0
  4. package/dist/adapter/claude-code.js +241 -0
  5. package/dist/adapter/commands.d.ts +19 -0
  6. package/dist/adapter/commands.js +162 -0
  7. package/dist/atomic.d.ts +6 -0
  8. package/dist/atomic.js +11 -0
  9. package/dist/cli.d.ts +2 -0
  10. package/dist/cli.js +561 -0
  11. package/dist/config/config.d.ts +55 -0
  12. package/dist/config/config.js +199 -0
  13. package/dist/config/lifecycle.d.ts +34 -0
  14. package/dist/config/lifecycle.js +81 -0
  15. package/dist/config/lock.d.ts +43 -0
  16. package/dist/config/lock.js +141 -0
  17. package/dist/context.d.ts +59 -0
  18. package/dist/context.js +111 -0
  19. package/dist/errors.d.ts +21 -0
  20. package/dist/errors.js +25 -0
  21. package/dist/eval/case.d.ts +123 -0
  22. package/dist/eval/case.js +17 -0
  23. package/dist/eval/core-suite.d.ts +3 -0
  24. package/dist/eval/core-suite.js +431 -0
  25. package/dist/eval/runner.d.ts +75 -0
  26. package/dist/eval/runner.js +159 -0
  27. package/dist/eval/sandbox.d.ts +39 -0
  28. package/dist/eval/sandbox.js +143 -0
  29. package/dist/extension/manage.d.ts +65 -0
  30. package/dist/extension/manage.js +372 -0
  31. package/dist/extension/manifest.d.ts +36 -0
  32. package/dist/extension/manifest.js +164 -0
  33. package/dist/extension/resolve.d.ts +77 -0
  34. package/dist/extension/resolve.js +271 -0
  35. package/dist/graph/edge-schema.d.ts +55 -0
  36. package/dist/graph/edge-schema.js +0 -0
  37. package/dist/graph/edges.d.ts +22 -0
  38. package/dist/graph/edges.js +63 -0
  39. package/dist/graph/ids.d.ts +14 -0
  40. package/dist/graph/ids.js +38 -0
  41. package/dist/graph/lineage.d.ts +48 -0
  42. package/dist/graph/lineage.js +226 -0
  43. package/dist/graph/mutations.d.ts +108 -0
  44. package/dist/graph/mutations.js +356 -0
  45. package/dist/graph/nodes.d.ts +46 -0
  46. package/dist/graph/nodes.js +137 -0
  47. package/dist/graph/revision.d.ts +50 -0
  48. package/dist/graph/revision.js +75 -0
  49. package/dist/graph/schema.d.ts +54 -0
  50. package/dist/graph/schema.js +90 -0
  51. package/dist/index.d.ts +33 -0
  52. package/dist/index.js +33 -0
  53. package/dist/init.d.ts +47 -0
  54. package/dist/init.js +132 -0
  55. package/dist/lifecycle/engine.d.ts +75 -0
  56. package/dist/lifecycle/engine.js +146 -0
  57. package/dist/lifecycle/record.d.ts +18 -0
  58. package/dist/lifecycle/record.js +157 -0
  59. package/dist/lifecycle/run.d.ts +62 -0
  60. package/dist/lifecycle/run.js +167 -0
  61. package/dist/loader.d.ts +38 -0
  62. package/dist/loader.js +64 -0
  63. package/dist/pack/capabilities.d.ts +22 -0
  64. package/dist/pack/capabilities.js +31 -0
  65. package/dist/pack/locate.d.ts +22 -0
  66. package/dist/pack/locate.js +80 -0
  67. package/dist/pack/manifest.d.ts +34 -0
  68. package/dist/pack/manifest.js +168 -0
  69. package/dist/pack/resolve.d.ts +92 -0
  70. package/dist/pack/resolve.js +238 -0
  71. package/dist/project.d.ts +22 -0
  72. package/dist/project.js +37 -0
  73. package/dist/sync.d.ts +54 -0
  74. package/dist/sync.js +98 -0
  75. package/dist/validate.d.ts +23 -0
  76. package/dist/validate.js +32 -0
  77. package/dist/validation.d.ts +24 -0
  78. package/dist/validation.js +83 -0
  79. package/dist/version.d.ts +2 -0
  80. package/dist/version.js +8 -0
  81. package/dist/yaml.d.ts +12 -0
  82. package/dist/yaml.js +32 -0
  83. package/package.json +65 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Samir Benzenine
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # Pactwright
2
+
3
+ An AI software delivery runtime built for Claude Code. Human intent moves through an explicit lifecycle — **intent → decision → contract → brief → evidence** — recorded as nodes and edges of a file-based Delivery Graph inside the repository itself. The runtime owns the lifecycle: it validates the graph, decides what is permitted next, and writes every record atomically; agent packs supply the prompts and skills that do the work.
4
+
5
+ ## Quick Start
6
+
7
+ > The first npm release (`0.0.1`) ships at the end of the current checkpoint.
8
+
9
+ Install the runtime and generate the project integration:
10
+
11
+ ```bash
12
+ pnpm add -D pactwright
13
+ pnpm pactwright init
14
+ pnpm pactwright sync
15
+ ```
16
+
17
+ - `pnpm pactwright init` creates the Pactwright-owned core structure: `.pactwright/` configuration, an empty Delivery Graph under `specs/` and the empty `.claude/` adapter directories.
18
+ - `pnpm pactwright sync` renders the Claude Code adapter into `.claude/`: one agent file per pack agent and one command per lifecycle stage.
19
+
20
+ Run one Delivery with the generated Claude Code commands, in order:
21
+
22
+ 1. `/capture-intent <text>` — records the intent as the first node of a new lineage.
23
+ 2. `/propose-contracts <intent-id>` — drafts transient contract alternatives for the decision; nothing is recorded.
24
+ 3. `/approve-contract <intent-id> <alternative> [notes]` — records your decision and, on proceed, the one canonical contract it selects.
25
+ 4. `/write-brief <contract-id>` — records the focused brief that implements the contract.
26
+ 5. `/deliver-brief <brief-id>` — executes the brief against the repository; changes stay in the working tree for review.
27
+ 6. `/review <brief-id>` — reviews the delivered changes against the contract and brief; findings are reported, not recorded.
28
+ 7. `/prepare-evidence <brief-id>` — records what was delivered and the verification that proves it, completing the lineage.
29
+
30
+ Inspect the graph at any time:
31
+
32
+ ```bash
33
+ pnpm pactwright validate
34
+ pnpm pactwright lifecycle status
35
+ pnpm pactwright context <intent-id>
36
+ ```
37
+
38
+ - `validate` checks every node, edge and lineage and prints the graph revision.
39
+ - `lifecycle status` derives each intent's state and the next permitted stage.
40
+ - `context <intent-id>` prints the current lineage only — the high-signal context for a human or agent picking up the work.
41
+
42
+ Learn more: the [Getting Started guide](docs/getting-started.md) and the [runnable core Delivery example](examples/core-delivery/README.md).
43
+
44
+ ## Packages
45
+
46
+ This repository is a pnpm workspace with two published packages:
47
+
48
+ - `pactwright` (repository root) — the runtime and CLI.
49
+ - `@pactwright/standard` (`packages/standard/`) — the default agent pack. It provides the three core Delivery capabilities (`delivery-specification`, `delivery-execution`, `delivery-review`). `pactwright` depends on it, so one `pnpm add -D pactwright` installs both; `.pactwright/config.yml` selects it by default.
50
+
51
+ ## What the runtime provides
52
+
53
+ - **Initialiser** — `pactwright init`: creates the Pactwright-owned core structure in a clean repository (`.pactwright/` configuration, an empty Delivery Graph under `specs/`, the empty `.claude/` adapter directories) and resolves the lock; existing files are never overwritten.
54
+ - **Delivery Graph** — canonical records (`specs/nodes/*.md`, `specs/graph/edges.yml`) with schema validation, typed-edge rules, lineage derivation and a deterministic revision hash.
55
+ - **Lifecycle engine** — `pactwright lifecycle status|next|run|record`: derives each intent's state from graph structure alone and refuses out-of-order records at the runtime, regardless of executor behaviour.
56
+ - **Claude Code adapter** — renders one agent file per pack agent and one command per lifecycle stage into `.claude/`, deterministically from the locked pack.
57
+ - **Sync** — `pactwright sync`: loads config, lock and extensions, validates the required capability union, and renders only the Pactwright-managed `.claude/` surface. Repeated sync with unchanged inputs is byte-identical. Ownership is proved per file by the generated banner standing in its rendered position, never by location, so a hand-written file inside `.claude/agents/` or `.claude/commands/` is never overwritten or removed — it is reported instead, even if it quotes the banner in its prose.
58
+ - **Evaluation runner** — `pactwright eval`: runs an agent pack against scripted delivery cases in throw-away sandboxes; failures are data in the report, and the exit code gates on deterministic assertions only.
59
+ - **Pack resolution and locking** — resolves the configured agent pack, checks capabilities and version compatibility, and pins exact content hashes in `.pactwright/lock.yml`.
60
+ - **Extension model** — `pactwright extension add|remove|upgrade`: package-backed extensions with versioned manifests, dependency resolution, capability-union validation, command namespaces and extension-owned graph types. Removal is blocked while enabled dependants exist and always preserves canonical extension data.
61
+
62
+ ## How to contribute
63
+
64
+ Intent first, then implementation. See `CONTRIBUTING.md` in the repository.
65
+
66
+ ## License
67
+
68
+ Apache-2.0. See `LICENSE`.
@@ -0,0 +1,53 @@
1
+ import { type ResolvedPack } from "../pack/resolve.js";
2
+ /**
3
+ * The directories the Claude Code adapter may write in (Distribution §8).
4
+ * They are the *scope* of ownership, not the proof of it: a file inside them
5
+ * belongs to Pactwright only when its banner stands in the rendered position
6
+ * (see `isGenerated`). Nothing else under `.claude/` is touched.
7
+ */
8
+ export declare const MANAGED_DIRS: readonly [".claude/agents", ".claude/commands"];
9
+ /**
10
+ * The marker opening the banner every rendered file carries. Ownership is
11
+ * proved by the banner standing in its rendered position, not by the marker
12
+ * appearing somewhere in the file — see `isGenerated`. Deleting the banner
13
+ * line from a generated file takes it out of Pactwright's ownership
14
+ * (Distribution §14: fail safe rather than delete user state).
15
+ */
16
+ export declare const GENERATED_MARKER = "<!-- Generated by pactwright";
17
+ /**
18
+ * Whether `file` is a Pactwright-generated file: it opens with frontmatter
19
+ * and the first line after it is the banner. Position is the proof, so
20
+ * quoting the marker anywhere else in a file claims nothing. Any read failure
21
+ * answers `false`, so an unreadable file is kept rather than destroyed.
22
+ */
23
+ export declare function isGenerated(file: string): boolean;
24
+ /** Relative path → file content, keys sorted. */
25
+ export type RenderedFiles = ReadonlyMap<string, string>;
26
+ /**
27
+ * Renders the Claude Code adapter for a resolved pack: one agent file per
28
+ * pack agent (skills inlined) and one command file per core stage. Pure and
29
+ * deterministic: same pack bytes → same output bytes. Reads pack files the
30
+ * way the lock hashes them (LF-normalised).
31
+ */
32
+ export declare function renderClaudeCodeAdapter(pack: ResolvedPack): RenderedFiles;
33
+ export interface WriteAdapterResult {
34
+ readonly written: readonly string[];
35
+ readonly removed: readonly string[];
36
+ /** Files in a managed directory that carry no marker, so were left alone. */
37
+ readonly kept: readonly string[];
38
+ /** Rendered paths already occupied by an unmarked file, so were not written. */
39
+ readonly conflicts: readonly string[];
40
+ }
41
+ /**
42
+ * Writes rendered files under `root` and removes generated files the render
43
+ * no longer produces, inside the managed directories only. Every file is
44
+ * written to a temporary sibling first and renamed into place.
45
+ *
46
+ * Ownership is proved per file, never by location: a file Pactwright did not
47
+ * generate is neither overwritten nor removed. Such files are reported —
48
+ * as `conflicts` when they occupy a rendered path, under the name the
49
+ * directory actually holds, and as `kept` otherwise, never both — rather than
50
+ * thrown on, because they are user state and not a render bug
51
+ * (Distribution §14).
52
+ */
53
+ export declare function writeAdapter(root: string, files: RenderedFiles): WriteAdapterResult;
@@ -0,0 +1,241 @@
1
+ import { closeSync, existsSync, mkdirSync, openSync, readSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync, } from "node:fs";
2
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
3
+ import { dump } from "js-yaml";
4
+ import { tempSibling } from "../atomic.js";
5
+ import { PactwrightError } from "../errors.js";
6
+ import { CORE_STAGES } from "../config/lifecycle.js";
7
+ import { SKILLS_DIR, readPackFile } from "../pack/manifest.js";
8
+ import { agentFor } from "../pack/resolve.js";
9
+ import { COMMAND_TEMPLATES } from "./commands.js";
10
+ /**
11
+ * The directories the Claude Code adapter may write in (Distribution §8).
12
+ * They are the *scope* of ownership, not the proof of it: a file inside them
13
+ * belongs to Pactwright only when its banner stands in the rendered position
14
+ * (see `isGenerated`). Nothing else under `.claude/` is touched.
15
+ */
16
+ export const MANAGED_DIRS = [".claude/agents", ".claude/commands"];
17
+ /**
18
+ * The marker opening the banner every rendered file carries. Ownership is
19
+ * proved by the banner standing in its rendered position, not by the marker
20
+ * appearing somewhere in the file — see `isGenerated`. Deleting the banner
21
+ * line from a generated file takes it out of Pactwright's ownership
22
+ * (Distribution §14: fail safe rather than delete user state).
23
+ */
24
+ export const GENERATED_MARKER = "<!-- Generated by pactwright";
25
+ /**
26
+ * How much of a file is read to find the banner. Every rendered file opens
27
+ * with frontmatter of a few short keys, so the banner is well inside the
28
+ * first kilobyte; the fixed head bounds the read for a file of any size.
29
+ */
30
+ const HEAD_BYTES = 8192;
31
+ /**
32
+ * The banner position: the frontmatter block, then the first non-blank line.
33
+ * Anchoring here — rather than searching the head for the marker — is what
34
+ * separates a generated file from a user document that happens to mention
35
+ * the banner in its prose, which no anchored match can reach.
36
+ */
37
+ const BANNER_POSITION = /^---\r?\n[\s\S]*?\r?\n---\r?\n(?:[ \t]*\r?\n)*/;
38
+ /**
39
+ * Whether `file` is a Pactwright-generated file: it opens with frontmatter
40
+ * and the first line after it is the banner. Position is the proof, so
41
+ * quoting the marker anywhere else in a file claims nothing. Any read failure
42
+ * answers `false`, so an unreadable file is kept rather than destroyed.
43
+ */
44
+ export function isGenerated(file) {
45
+ let fd;
46
+ try {
47
+ fd = openSync(file, "r");
48
+ const head = Buffer.alloc(HEAD_BYTES);
49
+ const read = readSync(fd, head, 0, HEAD_BYTES, 0);
50
+ const text = head.subarray(0, read).toString("utf8");
51
+ const frontmatter = BANNER_POSITION.exec(text);
52
+ return frontmatter !== null && text.slice(frontmatter[0].length).startsWith(GENERATED_MARKER);
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ finally {
58
+ if (fd !== undefined)
59
+ closeSync(fd);
60
+ }
61
+ }
62
+ /**
63
+ * The name `target` actually has in its directory. A case-insensitive
64
+ * filesystem resolves a rendered `spec.md` onto an existing `Spec.md`, and
65
+ * reporting the rendered spelling would name a path no listing shows and
66
+ * leave a remediation message the user cannot act on.
67
+ */
68
+ function onDiskName(target) {
69
+ const wanted = basename(target);
70
+ try {
71
+ const entries = readdirSync(dirname(target));
72
+ if (entries.includes(wanted))
73
+ return wanted;
74
+ const lowered = wanted.toLowerCase();
75
+ return entries.find((entry) => entry.toLowerCase() === lowered) ?? wanted;
76
+ }
77
+ catch {
78
+ return wanted;
79
+ }
80
+ }
81
+ function frontmatter(fields) {
82
+ return `---\n${dump(fields, { lineWidth: -1 })}---\n\n`;
83
+ }
84
+ function banner(pack, source) {
85
+ return `${GENERATED_MARKER} from ${pack.manifest.name}@${pack.manifest.version} (${source}). Do not edit; run \`pactwright sync\`, which overwrites this file and removes it once it is no longer rendered. Delete this line to take ownership. -->\n\n`;
86
+ }
87
+ /** Capabilities an agent key implements, sorted. */
88
+ function capabilitiesOf(pack, agentKey) {
89
+ return Object.keys(pack.manifest.capabilities)
90
+ .filter((capability) => pack.manifest.capabilities[capability] === agentKey)
91
+ .sort();
92
+ }
93
+ function renderAgent(pack, key) {
94
+ const agent = pack.manifest.agents[key];
95
+ const capabilities = capabilitiesOf(pack, key);
96
+ const parts = [
97
+ frontmatter({
98
+ name: key,
99
+ description: `${pack.manifest.name} ${key}${capabilities.length === 0 ? "" : ` — ${capabilities.join(", ")}`}`,
100
+ }),
101
+ banner(pack, agent.prompt),
102
+ readPackFile(pack.dir, agent.prompt).trimEnd(),
103
+ "\n",
104
+ ];
105
+ for (const skill of agent.skills) {
106
+ parts.push(`\n## Skill: ${skill}\n\n`, readPackFile(pack.dir, `${SKILLS_DIR}/${skill}.md`).trimEnd(), "\n");
107
+ }
108
+ return parts.join("");
109
+ }
110
+ function renderCommand(pack, stage) {
111
+ const template = COMMAND_TEMPLATES.find((candidate) => candidate.stage === stage);
112
+ const agent = template.capability === undefined ? undefined : agentFor(pack, template.capability)?.key;
113
+ const id = template.argumentHint.startsWith("<text>")
114
+ ? undefined
115
+ : template.argumentHint.split(" ")[0];
116
+ const askRuntime = [
117
+ `## 1. Ask the runtime first`,
118
+ ``,
119
+ id === undefined
120
+ ? `Run \`pnpm pactwright validate\`. The runtime owns the lifecycle: it decides what is permitted, who may decide and how records are linked. Never reason about that yourself.`
121
+ : `Run \`pnpm pactwright context ${id}\` for the current lineage and \`pnpm pactwright lifecycle status --intent <intent-id>\` for the completed stages. The runtime owns the lifecycle: it decides what is permitted, who may decide and how records are linked. Never reason about that yourself.`,
122
+ `If the runtime reports a validation problem, or lists \`${stage}\` as already completed, show its output and stop. The runtime refuses any record that is out of order.`,
123
+ ].join("\n");
124
+ return [
125
+ frontmatter({ description: template.description, "argument-hint": template.argumentHint }),
126
+ banner(pack, "pactwright runtime"),
127
+ `# /${stage} ${template.argumentHint}\n\n`,
128
+ askRuntime,
129
+ "\n\n",
130
+ template.body(agent),
131
+ "\n",
132
+ ].join("");
133
+ }
134
+ /**
135
+ * Renders the Claude Code adapter for a resolved pack: one agent file per
136
+ * pack agent (skills inlined) and one command file per core stage. Pure and
137
+ * deterministic: same pack bytes → same output bytes. Reads pack files the
138
+ * way the lock hashes them (LF-normalised).
139
+ */
140
+ export function renderClaudeCodeAdapter(pack) {
141
+ const files = new Map();
142
+ for (const key of Object.keys(pack.manifest.agents).sort()) {
143
+ files.set(`.claude/agents/${key}.md`, renderAgent(pack, key));
144
+ }
145
+ for (const stage of CORE_STAGES) {
146
+ files.set(`.claude/commands/${stage}.md`, renderCommand(pack, stage));
147
+ }
148
+ return new Map([...files.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
149
+ }
150
+ /**
151
+ * Writes rendered files under `root` and removes generated files the render
152
+ * no longer produces, inside the managed directories only. Every file is
153
+ * written to a temporary sibling first and renamed into place.
154
+ *
155
+ * Ownership is proved per file, never by location: a file Pactwright did not
156
+ * generate is neither overwritten nor removed. Such files are reported —
157
+ * as `conflicts` when they occupy a rendered path, under the name the
158
+ * directory actually holds, and as `kept` otherwise, never both — rather than
159
+ * thrown on, because they are user state and not a render bug
160
+ * (Distribution §14).
161
+ */
162
+ export function writeAdapter(root, files) {
163
+ // Normalise then check: every key must resolve strictly inside a managed
164
+ // directory, and its canonical form is the single key used to write,
165
+ // report and prune — a traversal segment or duplicate spelling cannot
166
+ // escape the guard or desynchronise the prune bookkeeping.
167
+ const canonical = new Map();
168
+ for (const [key, content] of files) {
169
+ const target = resolve(root, key);
170
+ const contained = MANAGED_DIRS.some((dir) => target.startsWith(resolve(root, dir) + sep));
171
+ if (!contained) {
172
+ throw new PactwrightError("unmanaged-path", `refusing to write outside the managed adapter directories: ${key}`);
173
+ }
174
+ const clean = relative(root, target).split(sep).join("/");
175
+ if (canonical.has(clean)) {
176
+ throw new PactwrightError("duplicate-render-path", `render produces "${clean}" twice`);
177
+ }
178
+ canonical.set(clean, { target, content });
179
+ }
180
+ // A rendered path already occupied by an unmarked file is user state: skip
181
+ // it, report it, and leave the bytes exactly as they are. The conflict is
182
+ // reported under the name the directory actually holds, and that name goes
183
+ // into `rendered` so the prune — which compares directory entries — skips
184
+ // the same file. Both halves therefore name one file once: a conflict, not
185
+ // also a kept.
186
+ const rendered = new Set(canonical.keys());
187
+ const conflicts = [];
188
+ for (const [clean, { target }] of canonical) {
189
+ // Only a regular file can be user content. Anything else occupying a
190
+ // rendered path is a broken working tree, and the write below reports it
191
+ // by failing rather than quietly stepping around it.
192
+ if (statSync(target, { throwIfNoEntry: false })?.isFile() !== true)
193
+ continue;
194
+ if (isGenerated(target))
195
+ continue;
196
+ const actual = `${dirname(clean)}/${onDiskName(target)}`;
197
+ conflicts.push(actual);
198
+ rendered.add(actual);
199
+ canonical.delete(clean);
200
+ }
201
+ const temps = [];
202
+ try {
203
+ for (const { target, content } of canonical.values()) {
204
+ mkdirSync(dirname(target), { recursive: true });
205
+ const temp = tempSibling(target);
206
+ writeFileSync(temp, content, "utf8");
207
+ temps.push([temp, target]);
208
+ }
209
+ for (const entry of temps) {
210
+ renameSync(entry[0], entry[1]);
211
+ entry[0] = "";
212
+ }
213
+ }
214
+ catch (error) {
215
+ for (const [temp] of temps) {
216
+ if (temp !== "" && existsSync(temp))
217
+ unlinkSync(temp);
218
+ }
219
+ throw error;
220
+ }
221
+ const removed = [];
222
+ const kept = [];
223
+ for (const dir of MANAGED_DIRS) {
224
+ const absolute = join(root, dir);
225
+ if (!existsSync(absolute))
226
+ continue;
227
+ for (const entry of readdirSync(absolute).sort()) {
228
+ const rel = `${dir}/${entry}`;
229
+ if (!entry.endsWith(".md") || rendered.has(rel))
230
+ continue;
231
+ if (isGenerated(join(absolute, entry))) {
232
+ unlinkSync(join(absolute, entry));
233
+ removed.push(rel);
234
+ }
235
+ else {
236
+ kept.push(rel);
237
+ }
238
+ }
239
+ }
240
+ return { written: [...canonical.keys()].sort(), removed, kept, conflicts: conflicts.sort() };
241
+ }
@@ -0,0 +1,19 @@
1
+ import { type StageName } from "../config/lifecycle.js";
2
+ /**
3
+ * One generated adapter command (Delivery Graph §19). The body only says
4
+ * how to call the runtime and which pack agent does the work: which stage
5
+ * is permitted, who may decide and how records are linked stay with the
6
+ * runtime (§18). `capability` names the pack agent the command delegates
7
+ * to; absent when the command needs no agent.
8
+ */
9
+ export interface CommandTemplate {
10
+ readonly stage: StageName;
11
+ readonly description: string;
12
+ readonly argumentHint: string;
13
+ readonly capability?: string;
14
+ /** Body sections after the common "Ask the runtime first" section. */
15
+ readonly body: (agent: string | undefined) => string;
16
+ }
17
+ export declare const COMMAND_TEMPLATES: readonly CommandTemplate[];
18
+ /** Every core stage has exactly one template, in lifecycle order. */
19
+ export declare function templateFor(stage: StageName): CommandTemplate;