@prodshape/integration-openspec 0.1.0 → 0.3.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.
package/src/index.ts CHANGED
@@ -13,13 +13,28 @@
13
13
  * guidance, deduplicating identical entries so the operation is idempotent.
14
14
  */
15
15
  import { execFile } from 'node:child_process';
16
- import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
16
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
17
17
  import { dirname, join } from 'node:path';
18
18
  import { parse, stringify } from 'yaml';
19
+ import { envWithLocalBin, isOpenSpecWorkspace, pathExists } from './workspace.js';
20
+
21
+ export { isOpenSpecWorkspace } from './workspace.js';
22
+ export {
23
+ enumerateOpenSpecDocuments,
24
+ isOpenSpecCliAvailable,
25
+ openSpecProvider,
26
+ } from './population.js';
19
27
 
20
28
  /** The minimum supported OpenSpec CLI version. */
21
29
  export const MIN_SUPPORTED_OPENSPEC = '1.0.0';
22
30
 
31
+ /**
32
+ * The npm spec used when bootstrapping OpenSpec through npx. Pinned to the supported major:
33
+ * MIN_SUPPORTED_OPENSPEC guards the floor, the pin guards the ceiling, so a future OpenSpec 2.x
34
+ * cannot silently change what `init --tools none` does for new adopters.
35
+ */
36
+ export const OPENSPEC_NPX_SPEC = '@fission-ai/openspec@1';
37
+
23
38
  /**
24
39
  * Sentinel markers that bracket the PDaC-injected context block. They let `mergeConfig` find
25
40
  * and replace exactly the PDaC portion without touching user-authored context lines.
@@ -32,14 +47,16 @@ export const PDAC_CONTEXT_BLOCK = `${PDAC_CONTEXT_BEGIN}
32
47
  This repository uses Product Definition as Code (PDaC). The canonical product definition lives in docs/product/model (actors, journeys, use cases, business rules, domain terms, requirements) and is the single source of truth for product behaviour. OpenSpec artifacts are downstream consumers of it, never a second source of truth.
33
48
  Consumers bind to canonical text through the PDaC Citation Contract: a citation records the target artifact id, a sha256 content digest, and an optional verification scenario anchor. Verification reports one status per citation: current, stale, tampered or unresolved.
34
49
  To cite: run \`npx prodshape inspect <ID>\` to read the current digest, then \`npx prodshape cite --id <ID> --digest <digest>\` to emit the citation record. Place inline citations on their own line directly under the text they ground.
35
- The product definition changes only through a Product Change under docs/product/changes/. OpenSpec changes never edit docs/product/model directly.
50
+ Every current OpenSpec document (proposal, specs, design, tasks and openspec/specs/) has exactly one effective scope state: bound (it carries at least one citation, or declares \`pdac-scope: cited\`), exempt (a human declared \`pdac-scope: none\` because the document has no product-semantic dependency), or unclassified (neither declared — a verification failure). Binding and exemption are human declarations: never declare \`pdac-scope: none\` merely because citations are missing, and a document declared \`pdac-scope: cited\` with zero citations fails. Verify with \`npx prodshape citations verify --provider openspec\`: it enumerates the expected current document population (archived changes excluded by default), so zero discovered citations is a set of failures, never a pass.
51
+ The accepted Product Definition changes only through this lifecycle: propose a Product Change under docs/product/changes/, validate its overlay while the baseline remains untouched, obtain human product approval, apply explicitly on a working branch, review the applied result in a pull request, and accept the resulting baseline by human merge. A Product Change is not a pull request. Apply is not acceptance, and neither apply nor merge attests implementation, verification, release or deployment. OpenSpec changes never edit docs/product/model directly. Product-definition work and implementation work have independent cadence: an OpenSpec change may share a pull request with an applied Product Change or follow an accepted definition later, but it remains a downstream implementation concern and never supplies Product Change status.
36
52
  ${PDAC_CONTEXT_END}`;
37
53
 
38
54
  /** The PDaC citation rules injected per artifact into openspec/config.yaml `rules:`. */
39
55
  export const PDAC_RULES: Record<string, string[]> = {
40
56
  proposal: [
41
57
  'State which PDaC artifacts this change touches, each with an inline citation emitted by `npx prodshape cite --id <ID> --digest <digest>`. Never write a citation record by hand.',
42
- 'If the change alters product behaviour, name the Product Change (CHG id) it implements. If no Product Change exists yet, stop and ask for one instead of proceeding.',
58
+ 'If the change implements altered product behaviour, name the Product Change (CHG id) whose applied or accepted artifacts it implements. If no overlay-validated and human-approved Product Change exists yet, stop and ask for one instead of proceeding. The OpenSpec change is not the Product Change.',
59
+ 'Every document of this change must end up bound or exempt: bind by citing the canonical text it depends on, or declare `pdac-scope: none` on a line of its own (frontmatter or `<!-- pdac-scope: none -->`) when a human judges the document has no product-semantic dependency. Never declare an exemption just because citations are missing.',
43
60
  ],
44
61
  specs: [
45
62
  'Every requirement derived from canonical product text MUST carry a citation to every PDaC artifact it derives from, one citation per line, placed after the requirement text and before the first scenario. A requirement often derives from more than one artifact; citing only the closest one silently hides the other derivations. Never place citations between the requirement heading and the requirement text; OpenSpec reads the first paragraph as the requirement.',
@@ -52,6 +69,7 @@ export const PDAC_RULES: Record<string, string[]> = {
52
69
  ],
53
70
  tasks: [
54
71
  'A task that changes cited behaviour must include a follow-up task to refresh the affected citations.',
72
+ 'Never infer implementation, verification, release or deployment from Product Change status; record that evidence in the delivery workflow.',
55
73
  ],
56
74
  };
57
75
 
@@ -62,16 +80,36 @@ export const PDAC_OPERATIONS: {
62
80
  } = {
63
81
  apply: {
64
82
  guidance: [
65
- 'Before finishing, run `npx prodshape citations verify` and fix every stale, tampered or unresolved citation. Refresh a stale digest by re-running `npx prodshape inspect <ID>`; never delete a citation to silence a diagnostic.',
83
+ 'Before finishing, run `npx prodshape citations verify --provider openspec` and fix every stale, tampered or unresolved citation, every unclassified document and every bound document without citations. Refresh a stale digest by re-running `npx prodshape inspect <ID>`; never delete a citation or declare `pdac-scope: none` to silence a diagnostic.',
66
84
  ],
67
85
  },
68
86
  archive: {
69
87
  guidance: [
70
- 'Run `npx prodshape citations verify` one final time. Archive only when every citation is current.',
88
+ 'Run `npx prodshape citations verify --provider openspec` one final time. Archive only when every document is bound or exempt and every citation is current.',
71
89
  ],
72
90
  },
73
91
  };
74
92
 
93
+ /**
94
+ * The exact strings PDaC injected into openspec/config.yaml, recorded so a later update can
95
+ * remove entries whose wording has since changed instead of appending duplicates alongside them.
96
+ * The context block needs no record: its sentinels already identify it in place.
97
+ */
98
+ export interface ManagedStrings {
99
+ rules: Record<string, string[]>;
100
+ operations: Record<string, string[]>;
101
+ }
102
+
103
+ /** The managed strings the current PDaC guidance injects. */
104
+ export function currentManagedStrings(): ManagedStrings {
105
+ return {
106
+ rules: Object.fromEntries(Object.entries(PDAC_RULES).map(([key, list]) => [key, [...list]])),
107
+ operations: Object.fromEntries(
108
+ Object.entries(PDAC_OPERATIONS).map(([key, op]) => [key, [...op.guidance]]),
109
+ ),
110
+ };
111
+ }
112
+
75
113
  /** Metadata recorded under .product/integrations/openspec.json. */
76
114
  export interface OpenSpecIntegrationMeta {
77
115
  provider: 'openspec';
@@ -79,11 +117,80 @@ export interface OpenSpecIntegrationMeta {
79
117
  openspecVersion: string;
80
118
  installedAt: string;
81
119
  configPath: string;
120
+ /** Absent in metadata written before the CI example existed; `integration update` adds it. */
121
+ ciExamplePath?: string;
122
+ /** Absent in metadata written before the field existed; treated as the current guidance. */
123
+ managed?: ManagedStrings;
82
124
  }
83
125
 
84
126
  /** Repository-relative paths used by this integration. */
85
127
  const CONFIG_RELATIVE = 'openspec/config.yaml';
86
128
  const META_RELATIVE = '.product/integrations/openspec.json';
129
+ const CI_EXAMPLE_RELATIVE = '.product/integrations/openspec.ci.yml';
130
+
131
+ /** The repository-relative path of the integration metadata file, for callers that probe it. */
132
+ export const OPENSPEC_META_RELATIVE = META_RELATIVE;
133
+
134
+ /** The repository-relative path of the installed CI-ready example workflow. */
135
+ export const OPENSPEC_CI_EXAMPLE_RELATIVE = CI_EXAMPLE_RELATIVE;
136
+
137
+ /** The exact provider-aware verification command the integration stands behind. */
138
+ export const OPENSPEC_VERIFY_COMMAND = 'npx prodshape citations verify --provider openspec';
139
+
140
+ /**
141
+ * Render the CI-ready example workflow installed at {@link OPENSPEC_CI_EXAMPLE_RELATIVE}.
142
+ *
143
+ * The gate always blocks unresolved citations, tampered embedded projections, unclassified
144
+ * current documents and bound documents with zero citations. Stale citations follow the
145
+ * repository's configured warning policy (`validation.warnings-as-errors` in
146
+ * `.product/config.yaml`); the example never changes that policy, but it states explicitly what
147
+ * the repository's current choice means and how to escalate it, so the blocking behaviour is a
148
+ * deliberate decision rather than a silent default.
149
+ */
150
+ export function renderCiExample(options: { warningsAsErrors: boolean }): string {
151
+ const stalePolicy = options.warningsAsErrors
152
+ ? [
153
+ '# - stale citations BLOCK this gate: .product/config.yaml sets',
154
+ '# `validation.warnings-as-errors: true`, escalating the PRODUCT061 warning to an error.',
155
+ '# The integration never changes that policy; relax it by setting the key to false.',
156
+ ]
157
+ : [
158
+ '# - stale citations DO NOT block this gate: .product/config.yaml sets',
159
+ '# `validation.warnings-as-errors: false`, so PRODUCT061 stays a warning. To make stale',
160
+ '# citations block the merge, set `validation.warnings-as-errors: true` in',
161
+ '# .product/config.yaml. The integration never changes that policy for you.',
162
+ ];
163
+ return [
164
+ '# PDaC citation gate for OpenSpec consumer documents (CI-ready example).',
165
+ '# Managed by `prodshape integration add openspec`; copy it into your pipeline',
166
+ '# (e.g. .github/workflows/) and adapt the triggers.',
167
+ '#',
168
+ '# The gate runs ProductShape citation and scope verification only. It never invokes',
169
+ "# `openspec validate`; keep OpenSpec's own verdict a separate step so a native-spec defect",
170
+ '# and a grounding defect stay distinguishable.',
171
+ '#',
172
+ '# Blocking behaviour:',
173
+ '# - unresolved citations, tampered embedded projections, unclassified current documents',
174
+ '# and bound documents with zero citations always fail the gate;',
175
+ ...stalePolicy,
176
+ 'name: pdac-citations',
177
+ 'on:',
178
+ ' pull_request:',
179
+ 'jobs:',
180
+ ' verify:',
181
+ ' runs-on: ubuntu-latest',
182
+ ' steps:',
183
+ ' - uses: actions/checkout@v4',
184
+ ' - uses: actions/setup-node@v4',
185
+ ' with:',
186
+ " node-version: '22'",
187
+ ' # The OpenSpec CLI ships as @fission-ai/openspec; population discovery runs',
188
+ ' # `openspec list`, so the gate needs it installed.',
189
+ ` - run: npm install -g ${OPENSPEC_NPX_SPEC}`,
190
+ ` - run: ${OPENSPEC_VERIFY_COMMAND}`,
191
+ '',
192
+ ].join('\n');
193
+ }
87
194
 
88
195
  function configPath(root: string): string {
89
196
  return join(root, ...CONFIG_RELATIVE.split('/'));
@@ -93,13 +200,8 @@ function metaPath(root: string): string {
93
200
  return join(root, ...META_RELATIVE.split('/'));
94
201
  }
95
202
 
96
- async function exists(path: string): Promise<boolean> {
97
- try {
98
- await access(path);
99
- return true;
100
- } catch {
101
- return false;
102
- }
203
+ function ciExamplePath(root: string): string {
204
+ return join(root, ...CI_EXAMPLE_RELATIVE.split('/'));
103
205
  }
104
206
 
105
207
  /**
@@ -119,39 +221,107 @@ function compareVersions(a: string, b: string): number {
119
221
  return aPatch - bPatch;
120
222
  }
121
223
 
122
- /** Detect the installed OpenSpec CLI version by running `openspec --version`. */
123
- export async function detectOpenSpecVersion(): Promise<{ version: string } | { error: string }> {
224
+ /** Run a command at the repository root, resolving stdout+stderr or rejecting on failure. */
225
+ function runAtRoot(root: string, command: string, args: string[]): Promise<string> {
226
+ return new Promise((resolve, reject) => {
227
+ // Commands are typically .cmd shims on Windows; `shell: true` lets execFile find them on PATH
228
+ // across platforms without callers needing to know the extension.
229
+ execFile(
230
+ command,
231
+ args,
232
+ { cwd: root, shell: true, env: envWithLocalBin(root) },
233
+ (error, stdout, stderr) => {
234
+ if (error) {
235
+ reject(new Error(`${command} ${args.join(' ')} failed: ${error.message}`));
236
+ return;
237
+ }
238
+ resolve(`${stdout}${stderr}`);
239
+ },
240
+ );
241
+ });
242
+ }
243
+
244
+ /**
245
+ * Detect the installed OpenSpec CLI version by running `openspec --version`. When a repository
246
+ * root is given, its node_modules/.bin is consulted first, so a devDependency install counts.
247
+ */
248
+ export async function detectOpenSpecVersion(
249
+ root?: string,
250
+ ): Promise<{ version: string } | { error: string }> {
124
251
  return new Promise((resolve) => {
125
252
  // `openspec` is typically a .cmd shim on Windows; `shell: true` lets execFile find it on PATH
126
253
  // across platforms without callers needing to know the extension.
127
- execFile('openspec', ['--version'], { shell: true }, (error, stdout, stderr) => {
128
- if (error) {
129
- resolve({
130
- error: `OpenSpec CLI not found on PATH (run: npm install -g openspec). ${error.message}`,
131
- });
132
- return;
133
- }
134
- const output = `${stdout}${stderr}`.trim();
135
- // `openspec --version` prints something like "1.3.0" or "openspec/1.3.0 ...".
136
- const match = output.match(/(\d+\.\d+\.\d+(?:-[^\s]+)?)/);
137
- if (!match?.[1]) {
138
- resolve({ error: `Could not parse OpenSpec version from output: ${output}` });
139
- return;
140
- }
141
- resolve({ version: match[1] });
142
- });
254
+ execFile(
255
+ 'openspec',
256
+ ['--version'],
257
+ { shell: true, ...(root ? { env: envWithLocalBin(root) } : {}) },
258
+ (error, stdout, stderr) => {
259
+ if (error) {
260
+ resolve({
261
+ error: `OpenSpec CLI not found on PATH (run: npm install -g ${OPENSPEC_NPX_SPEC}). ${error.message}`,
262
+ });
263
+ return;
264
+ }
265
+ const output = `${stdout}${stderr}`.trim();
266
+ // `openspec --version` prints something like "1.3.0" or "openspec/1.3.0 ...".
267
+ const match = output.match(/(\d+\.\d+\.\d+(?:-[^\s]+)?)/);
268
+ if (!match?.[1]) {
269
+ resolve({ error: `Could not parse OpenSpec version from output: ${output}` });
270
+ return;
271
+ }
272
+ resolve({ version: match[1] });
273
+ },
274
+ );
143
275
  });
144
276
  }
145
277
 
146
- /** Check if an OpenSpec workspace exists at the given root (openspec/ directory present). */
147
- export async function isOpenSpecWorkspace(root: string): Promise<boolean> {
148
- return exists(join(root, 'openspec'));
278
+ /**
279
+ * Create an OpenSpec workspace at the root. Uses the installed CLI when one is on PATH (or in
280
+ * node_modules/.bin); otherwise runs the pinned OpenSpec major through npx, which downloads
281
+ * nothing permanent and never mutates the global environment. `--tools none` keeps the
282
+ * framework's own initializer non-interactive.
283
+ *
284
+ * Returns the CLI version that ran and whether it came through npx, so callers can pass the
285
+ * version on to `addOpenSpecIntegration` (nothing may be on PATH afterwards) and recommend a
286
+ * permanent install.
287
+ */
288
+ export async function bootstrapOpenSpecWorkspace(
289
+ root: string,
290
+ ): Promise<{ version: string; viaNpx: boolean; command: string }> {
291
+ if (await isOpenSpecWorkspace(root)) {
292
+ throw new Error('An OpenSpec workspace already exists at this root.');
293
+ }
294
+ const detected = await detectOpenSpecVersion(root);
295
+ if (!('error' in detected)) {
296
+ if (compareVersions(detected.version, MIN_SUPPORTED_OPENSPEC) < 0) {
297
+ throw new Error(
298
+ `OpenSpec CLI version ${detected.version} is below the minimum supported ${MIN_SUPPORTED_OPENSPEC}. Please upgrade OpenSpec.`,
299
+ );
300
+ }
301
+ const command = 'openspec init --tools none';
302
+ await runAtRoot(root, 'openspec', ['init', '--tools', 'none']);
303
+ return { version: detected.version, viaNpx: false, command };
304
+ }
305
+ const command = `npx -y ${OPENSPEC_NPX_SPEC} init --tools none`;
306
+ await runAtRoot(root, 'npx', ['-y', OPENSPEC_NPX_SPEC, 'init', '--tools', 'none']);
307
+ // A second npx call resolves from the cache the first one populated.
308
+ const output = await runAtRoot(root, 'npx', ['-y', OPENSPEC_NPX_SPEC, '--version']);
309
+ const match = output.trim().match(/(\d+\.\d+\.\d+(?:-[^\s]+)?)/);
310
+ if (!match?.[1]) {
311
+ throw new Error(`Could not parse OpenSpec version from npx output: ${output.trim()}`);
312
+ }
313
+ return { version: match[1], viaNpx: true, command };
314
+ }
315
+
316
+ /** Check if the OpenSpec integration is installed (its metadata file is present). */
317
+ export async function isOpenSpecIntegrationInstalled(root: string): Promise<boolean> {
318
+ return pathExists(metaPath(root));
149
319
  }
150
320
 
151
321
  /** Read and parse the existing openspec/config.yaml, or null if it does not exist. */
152
322
  export async function readOpenSpecConfig(root: string): Promise<Record<string, unknown> | null> {
153
323
  const path = configPath(root);
154
- if (!(await exists(path))) return null;
324
+ if (!(await pathExists(path))) return null;
155
325
  const text = await readFile(path, 'utf8');
156
326
  const parsed = parse(text);
157
327
  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
@@ -180,19 +350,29 @@ function extractPdacContext(context: string | undefined): string | null {
180
350
  * (idempotent); otherwise the PDaC block is appended after a separator. User-authored context
181
351
  * lines are never lost.
182
352
  * - `rules`: for each PDaC artifact (proposal, specs, design, tasks), PDaC rules are appended to
183
- * existing rules, deduplicating identical entries.
184
- * - `operations`: PDaC apply/archive guidance is appended to existing guidance, deduplicating.
353
+ * existing rules, deduplicating identical entries. Entries recorded as previously managed whose
354
+ * wording is no longer current are removed first, so a guidance change replaces the old string
355
+ * instead of accumulating next to it. User-authored entries are never removed.
356
+ * - `operations`: PDaC apply/archive guidance is appended to existing guidance, deduplicating,
357
+ * with the same previously-managed replacement.
185
358
  * - Any other fields (githubCopilot, etc.) are preserved untouched.
186
359
  *
187
360
  * Returns the merged config and a list of human-readable change descriptions.
188
361
  */
189
- export function mergeConfig(existing: Record<string, unknown> | null): {
362
+ export function mergeConfig(
363
+ existing: Record<string, unknown> | null,
364
+ previouslyManaged?: ManagedStrings,
365
+ ): {
190
366
  config: Record<string, unknown>;
191
367
  changes: string[];
192
368
  } {
193
369
  const config: Record<string, unknown> = { ...(existing ?? {}) };
194
370
  const changes: string[] = [];
195
371
 
372
+ // Strings PDaC injected in the past but no longer injects verbatim: remove before appending.
373
+ const staleManaged = (recorded: string[] | undefined, current: string[]): string[] =>
374
+ (recorded ?? []).filter((entry) => !current.includes(entry));
375
+
196
376
  // --- context ---
197
377
  const existingContext =
198
378
  typeof config['context'] === 'string' ? (config['context'] as string) : undefined;
@@ -223,22 +403,45 @@ export function mergeConfig(existing: Record<string, unknown> | null): {
223
403
  ? { ...(config['rules'] as Record<string, unknown>) }
224
404
  : {};
225
405
  let rulesChanged = false;
226
- for (const [artifact, pdacRules] of Object.entries(PDAC_RULES)) {
406
+ let staleRulesRemoved = false;
407
+ const ruleArtifacts = new Set([
408
+ ...Object.keys(PDAC_RULES),
409
+ ...Object.keys(previouslyManaged?.rules ?? {}),
410
+ ]);
411
+ for (const artifact of ruleArtifacts) {
412
+ const pdacRules = PDAC_RULES[artifact] ?? [];
413
+ const stale = staleManaged(previouslyManaged?.rules[artifact], pdacRules);
227
414
  const existingList = Array.isArray(existingRules[artifact])
228
415
  ? [...(existingRules[artifact] as string[])]
229
416
  : [];
230
- const merged = [...existingList];
417
+ const merged = existingList.filter((entry) => !stale.includes(entry));
418
+ if (merged.length !== existingList.length) {
419
+ staleRulesRemoved = true;
420
+ rulesChanged = true;
421
+ }
231
422
  for (const rule of pdacRules) {
232
423
  if (!merged.includes(rule)) {
233
424
  merged.push(rule);
234
425
  rulesChanged = true;
235
426
  }
236
427
  }
237
- existingRules[artifact] = merged;
428
+ if (merged.length === 0) {
429
+ delete existingRules[artifact];
430
+ } else {
431
+ existingRules[artifact] = merged;
432
+ }
238
433
  }
239
434
  if (rulesChanged) {
240
- config['rules'] = existingRules;
241
- changes.push('Merged PDaC citation rules into openspec/config.yaml (rules:).');
435
+ if (Object.keys(existingRules).length === 0) {
436
+ delete config['rules'];
437
+ } else {
438
+ config['rules'] = existingRules;
439
+ }
440
+ changes.push(
441
+ staleRulesRemoved
442
+ ? 'Merged PDaC citation rules into openspec/config.yaml (rules:), replacing outdated PDaC entries.'
443
+ : 'Merged PDaC citation rules into openspec/config.yaml (rules:).',
444
+ );
242
445
  }
243
446
 
244
447
  // --- operations ---
@@ -249,8 +452,10 @@ export function mergeConfig(existing: Record<string, unknown> | null): {
249
452
  ? { ...(config['operations'] as Record<string, unknown>) }
250
453
  : {};
251
454
  let opsChanged = false;
455
+ let staleOpsRemoved = false;
252
456
  for (const opKey of ['apply', 'archive'] as const) {
253
457
  const pdacGuidance = PDAC_OPERATIONS[opKey].guidance;
458
+ const stale = staleManaged(previouslyManaged?.operations[opKey], pdacGuidance);
254
459
  const existingOp =
255
460
  existingOperations[opKey] &&
256
461
  typeof existingOperations[opKey] === 'object' &&
@@ -260,7 +465,11 @@ export function mergeConfig(existing: Record<string, unknown> | null): {
260
465
  const existingGuidance = Array.isArray(existingOp['guidance'])
261
466
  ? [...(existingOp['guidance'] as string[])]
262
467
  : [];
263
- const merged = [...existingGuidance];
468
+ const merged = existingGuidance.filter((entry) => !stale.includes(entry));
469
+ if (merged.length !== existingGuidance.length) {
470
+ staleOpsRemoved = true;
471
+ opsChanged = true;
472
+ }
264
473
  for (const guidance of pdacGuidance) {
265
474
  if (!merged.includes(guidance)) {
266
475
  merged.push(guidance);
@@ -272,7 +481,11 @@ export function mergeConfig(existing: Record<string, unknown> | null): {
272
481
  }
273
482
  if (opsChanged) {
274
483
  config['operations'] = existingOperations;
275
- changes.push('Merged PDaC operation guidance into openspec/config.yaml (operations:).');
484
+ changes.push(
485
+ staleOpsRemoved
486
+ ? 'Merged PDaC operation guidance into openspec/config.yaml (operations:), replacing outdated PDaC entries.'
487
+ : 'Merged PDaC operation guidance into openspec/config.yaml (operations:).',
488
+ );
276
489
  }
277
490
 
278
491
  return { config, changes };
@@ -280,7 +493,7 @@ export function mergeConfig(existing: Record<string, unknown> | null): {
280
493
 
281
494
  /** Serialize config back to YAML with a trailing newline. */
282
495
  export function serializeConfig(config: Record<string, unknown>): string {
283
- return `${stringify(config)}\n`;
496
+ return `${stringify(config).trimEnd()}\n`;
284
497
  }
285
498
 
286
499
  /** Read the ProductShape version from the integration-openspec package.json. */
@@ -295,26 +508,42 @@ async function productshapeVersion(): Promise<string> {
295
508
  * Add the OpenSpec integration to a repository.
296
509
  *
297
510
  * - Detects the OpenSpec CLI version; rejects if not found or below MIN_SUPPORTED_OPENSPEC.
511
+ * A caller that already ran the CLI (the init bootstrap) can pass `cliVersion` to skip the
512
+ * probe: after an npx bootstrap nothing is on PATH, yet the version is known.
298
513
  * - Requires an existing `openspec/` workspace (run `openspec init` first).
299
514
  * - Merges PDaC guidance into `openspec/config.yaml`, preserving existing user configuration.
300
- * - Records metadata under `.product/integrations/openspec.json`.
515
+ * - Records metadata under `.product/integrations/openspec.json`, including the exact strings
516
+ * injected, so a later update replaces outdated PDaC entries instead of accumulating them.
301
517
  * - Idempotent: running twice produces the same result.
302
518
  * - `--dry-run` reports what would change without writing.
303
519
  * - `--force` re-merges even if the PDaC block is already present (useful after a PDaC upgrade).
304
520
  */
305
521
  export async function addOpenSpecIntegration(
306
522
  root: string,
307
- options: { force?: boolean; dryRun?: boolean } = {},
523
+ options: {
524
+ force?: boolean;
525
+ dryRun?: boolean;
526
+ cliVersion?: string;
527
+ /**
528
+ * The repository's configured `validation.warnings-as-errors` policy, reflected verbatim in
529
+ * the installed CI example so its blocking behaviour is stated, never silently changed.
530
+ */
531
+ warningsAsErrors?: boolean;
532
+ } = {},
308
533
  ): Promise<{ written: string[]; changes: string[]; meta: OpenSpecIntegrationMeta }> {
309
- const { force = false, dryRun = false } = options;
534
+ const { force = false, dryRun = false, warningsAsErrors = false } = options;
310
535
 
311
- const detected = await detectOpenSpecVersion();
312
- if ('error' in detected) {
313
- throw new Error(detected.error);
536
+ let openspecVersion = options.cliVersion;
537
+ if (!openspecVersion) {
538
+ const detected = await detectOpenSpecVersion(root);
539
+ if ('error' in detected) {
540
+ throw new Error(detected.error);
541
+ }
542
+ openspecVersion = detected.version;
314
543
  }
315
- if (compareVersions(detected.version, MIN_SUPPORTED_OPENSPEC) < 0) {
544
+ if (compareVersions(openspecVersion, MIN_SUPPORTED_OPENSPEC) < 0) {
316
545
  throw new Error(
317
- `OpenSpec CLI version ${detected.version} is below the minimum supported ${MIN_SUPPORTED_OPENSPEC}. Please upgrade OpenSpec.`,
546
+ `OpenSpec CLI version ${openspecVersion} is below the minimum supported ${MIN_SUPPORTED_OPENSPEC}. Please upgrade OpenSpec.`,
318
547
  );
319
548
  }
320
549
 
@@ -323,29 +552,36 @@ export async function addOpenSpecIntegration(
323
552
  }
324
553
 
325
554
  const existing = await readOpenSpecConfig(root);
555
+ const previousMeta = await readMeta(root);
326
556
 
327
- // Detect a conflicting user context that is NOT the PDaC block and has no room for it.
328
- // In practice we always append, so a "conflict" only arises if the user explicitly removed the
329
- // PDaC block after a previous install and we are re-adding without --force.
330
- if (!force && existing) {
331
- const existingContext =
332
- typeof existing['context'] === 'string' ? (existing['context'] as string) : undefined;
333
- if (existingContext && extractPdacContext(existingContext) === null) {
334
- // The user has context but no PDaC block. We will append, which is safe — not a conflict.
335
- }
557
+ const { config, changes: configChanges } = mergeConfig(existing, previousMeta?.managed);
558
+
559
+ const ciDesired = renderCiExample({ warningsAsErrors });
560
+ const ciAbsolute = ciExamplePath(root);
561
+ const ciExisting = (await pathExists(ciAbsolute)) ? await readFile(ciAbsolute, 'utf8') : null;
562
+ const ciChanged = ciExisting !== ciDesired;
563
+
564
+ const changes = [...configChanges];
565
+ if (ciChanged) {
566
+ changes.push(
567
+ ciExisting === null
568
+ ? `Installed CI-ready verification example at ${CI_EXAMPLE_RELATIVE}.`
569
+ : `Updated CI-ready verification example at ${CI_EXAMPLE_RELATIVE}.`,
570
+ );
336
571
  }
337
572
 
338
- const { config, changes } = mergeConfig(existing);
573
+ const meta: OpenSpecIntegrationMeta = {
574
+ provider: 'openspec',
575
+ version: await productshapeVersion(),
576
+ openspecVersion,
577
+ installedAt: new Date().toISOString(),
578
+ configPath: CONFIG_RELATIVE,
579
+ ciExamplePath: CI_EXAMPLE_RELATIVE,
580
+ managed: currentManagedStrings(),
581
+ };
339
582
 
340
583
  if (changes.length === 0 && !force) {
341
584
  // Already up to date. Still record/refresh metadata.
342
- const meta: OpenSpecIntegrationMeta = {
343
- provider: 'openspec',
344
- version: await productshapeVersion(),
345
- openspecVersion: detected.version,
346
- installedAt: new Date().toISOString(),
347
- configPath: CONFIG_RELATIVE,
348
- };
349
585
  if (!dryRun) {
350
586
  await writeMeta(root, meta);
351
587
  }
@@ -354,33 +590,22 @@ export async function addOpenSpecIntegration(
354
590
 
355
591
  const written: string[] = [];
356
592
  if (!dryRun) {
357
- const serialized = serializeConfig(config);
358
- await mkdir(dirname(configPath(root)), { recursive: true });
359
- await writeFile(configPath(root), serialized, 'utf8');
360
- written.push(CONFIG_RELATIVE);
361
-
362
- const meta: OpenSpecIntegrationMeta = {
363
- provider: 'openspec',
364
- version: await productshapeVersion(),
365
- openspecVersion: detected.version,
366
- installedAt: new Date().toISOString(),
367
- configPath: CONFIG_RELATIVE,
368
- };
593
+ if (configChanges.length > 0 || force) {
594
+ const serialized = serializeConfig(config);
595
+ await mkdir(dirname(configPath(root)), { recursive: true });
596
+ await writeFile(configPath(root), serialized, 'utf8');
597
+ written.push(CONFIG_RELATIVE);
598
+ }
599
+ if (ciChanged || force) {
600
+ await mkdir(dirname(ciAbsolute), { recursive: true });
601
+ await writeFile(ciAbsolute, ciDesired, 'utf8');
602
+ written.push(CI_EXAMPLE_RELATIVE);
603
+ }
369
604
  await writeMeta(root, meta);
370
605
  written.push(META_RELATIVE);
371
606
  }
372
607
 
373
- return {
374
- written,
375
- changes,
376
- meta: {
377
- provider: 'openspec',
378
- version: await productshapeVersion(),
379
- openspecVersion: detected.version,
380
- installedAt: new Date().toISOString(),
381
- configPath: CONFIG_RELATIVE,
382
- },
383
- };
608
+ return { written, changes, meta };
384
609
  }
385
610
 
386
611
  /** Write the integration metadata file. */
@@ -393,7 +618,7 @@ async function writeMeta(root: string, meta: OpenSpecIntegrationMeta): Promise<v
393
618
  /** Read the integration metadata file, or null if absent. */
394
619
  async function readMeta(root: string): Promise<OpenSpecIntegrationMeta | null> {
395
620
  const path = metaPath(root);
396
- if (!(await exists(path))) return null;
621
+ if (!(await pathExists(path))) return null;
397
622
  return JSON.parse(await readFile(path, 'utf8')) as OpenSpecIntegrationMeta;
398
623
  }
399
624
 
@@ -403,11 +628,15 @@ async function readMeta(root: string): Promise<OpenSpecIntegrationMeta | null> {
403
628
  */
404
629
  export async function updateOpenSpecIntegration(
405
630
  root: string,
406
- options: { force?: boolean; dryRun?: boolean } = {},
631
+ options: { force?: boolean; dryRun?: boolean; warningsAsErrors?: boolean } = {},
407
632
  ): Promise<{ written: string[]; changes: string[] }> {
408
633
  // `add` already re-merges idempotently; `force` ensures the metadata is refreshed even when
409
634
  // the config content did not change.
410
- const result = await addOpenSpecIntegration(root, { force: true, dryRun: options.dryRun });
635
+ const result = await addOpenSpecIntegration(root, {
636
+ force: true,
637
+ dryRun: options.dryRun,
638
+ warningsAsErrors: options.warningsAsErrors,
639
+ });
411
640
  return { written: result.written, changes: result.changes };
412
641
  }
413
642
 
@@ -425,7 +654,7 @@ export async function checkOpenSpecIntegration(root: string): Promise<{
425
654
  const checks: { name: string; ok: boolean; detail: string }[] = [];
426
655
 
427
656
  // 1. OpenSpec CLI installed and supported.
428
- const detected = await detectOpenSpecVersion();
657
+ const detected = await detectOpenSpecVersion(root);
429
658
  if ('error' in detected) {
430
659
  checks.push({ name: 'openspec CLI', ok: false, detail: detected.error });
431
660
  } else if (compareVersions(detected.version, MIN_SUPPORTED_OPENSPEC) < 0) {
@@ -494,6 +723,21 @@ export async function checkOpenSpecIntegration(root: string): Promise<{
494
723
  });
495
724
  }
496
725
 
726
+ // 3b. CI-ready verification example present.
727
+ if (await pathExists(ciExamplePath(root))) {
728
+ checks.push({
729
+ name: 'ci example',
730
+ ok: true,
731
+ detail: `CI-ready verification example present at ${CI_EXAMPLE_RELATIVE}.`,
732
+ });
733
+ } else {
734
+ checks.push({
735
+ name: 'ci example',
736
+ ok: false,
737
+ detail: `CI-ready verification example missing (${CI_EXAMPLE_RELATIVE}). Run: prodshape integration update`,
738
+ });
739
+ }
740
+
497
741
  // 4. PDaC rules present.
498
742
  if (config) {
499
743
  const rules =
@@ -539,6 +783,30 @@ export async function removeOpenSpecIntegration(
539
783
  const { dryRun = false } = options;
540
784
  const removed: string[] = [];
541
785
 
786
+ // Remove both what the metadata recorded as injected and what the current guidance would
787
+ // inject: the union covers metadata written before the record existed as well as entries left
788
+ // behind by an older ProductShape.
789
+ const recorded = (await readMeta(root))?.managed;
790
+ const current = currentManagedStrings();
791
+ const managedRules: Record<string, string[]> = {};
792
+ for (const key of new Set([
793
+ ...Object.keys(current.rules),
794
+ ...Object.keys(recorded?.rules ?? {}),
795
+ ])) {
796
+ managedRules[key] = [
797
+ ...new Set([...(current.rules[key] ?? []), ...(recorded?.rules[key] ?? [])]),
798
+ ];
799
+ }
800
+ const managedOperations: Record<string, string[]> = {};
801
+ for (const key of new Set([
802
+ ...Object.keys(current.operations),
803
+ ...Object.keys(recorded?.operations ?? {}),
804
+ ])) {
805
+ managedOperations[key] = [
806
+ ...new Set([...(current.operations[key] ?? []), ...(recorded?.operations[key] ?? [])]),
807
+ ];
808
+ }
809
+
542
810
  const config = await readOpenSpecConfig(root);
543
811
  if (config !== null) {
544
812
  let configChanged = false;
@@ -569,7 +837,7 @@ export async function removeOpenSpecIntegration(
569
837
  : null;
570
838
  if (rules) {
571
839
  let rulesChanged = false;
572
- for (const [artifact, pdacRules] of Object.entries(PDAC_RULES)) {
840
+ for (const [artifact, pdacRules] of Object.entries(managedRules)) {
573
841
  if (!Array.isArray(rules[artifact])) continue;
574
842
  const list = rules[artifact] as string[];
575
843
  const filtered = list.filter((r) => !pdacRules.includes(r));
@@ -600,7 +868,7 @@ export async function removeOpenSpecIntegration(
600
868
  if (operations) {
601
869
  let opsChanged = false;
602
870
  for (const opKey of ['apply', 'archive'] as const) {
603
- const pdacGuidance = PDAC_OPERATIONS[opKey].guidance;
871
+ const pdacGuidance = managedOperations[opKey] ?? [];
604
872
  const op =
605
873
  operations[opKey] &&
606
874
  typeof operations[opKey] === 'object' &&
@@ -639,8 +907,16 @@ export async function removeOpenSpecIntegration(
639
907
  }
640
908
  }
641
909
 
910
+ // Remove the installed CI example.
911
+ if (await pathExists(ciExamplePath(root))) {
912
+ if (!dryRun) {
913
+ await rm(ciExamplePath(root), { force: true });
914
+ }
915
+ removed.push(CI_EXAMPLE_RELATIVE);
916
+ }
917
+
642
918
  // Remove metadata file.
643
- if (await exists(metaPath(root))) {
919
+ if (await pathExists(metaPath(root))) {
644
920
  if (!dryRun) {
645
921
  await rm(metaPath(root), { force: true });
646
922
  }