cliewen-openspec 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +16 -12
  3. package/adapters/node-test.mjs +9 -4
  4. package/dist/ac-coordination.d.ts +33 -0
  5. package/dist/ac-coordination.js +318 -0
  6. package/dist/ac.d.ts +4 -3
  7. package/dist/ac.js +20 -1
  8. package/dist/ci-github.d.ts +19 -0
  9. package/dist/ci-github.js +70 -0
  10. package/dist/ci-inspection.d.ts +48 -0
  11. package/dist/ci-inspection.js +246 -0
  12. package/dist/ci-settings.d.ts +15 -0
  13. package/dist/ci-settings.js +50 -0
  14. package/dist/cli.js +73 -12
  15. package/dist/core.d.ts +32 -3
  16. package/dist/core.js +167 -15
  17. package/dist/documentation-settings.d.ts +16 -0
  18. package/dist/documentation-settings.js +65 -0
  19. package/dist/documentation.d.ts +47 -0
  20. package/dist/documentation.js +337 -0
  21. package/dist/mermaid-check.d.ts +10 -0
  22. package/dist/mermaid-check.js +40 -0
  23. package/dist/mermaid-worker.d.ts +1 -0
  24. package/dist/mermaid-worker.js +24 -0
  25. package/dist/quality.d.ts +1 -1
  26. package/dist/quality.js +22 -7
  27. package/dist/release.d.ts +2 -2
  28. package/dist/release.js +3 -3
  29. package/dist/schema-source.js +1 -1
  30. package/dist/setup-profile.d.ts +31 -0
  31. package/dist/setup-profile.js +59 -0
  32. package/dist/state-lock.d.ts +2 -0
  33. package/dist/state-lock.js +92 -0
  34. package/docs/configuration.md +170 -10
  35. package/docs/testing/evidence.md +14 -1
  36. package/docs/testing/test-quality.md +3 -1
  37. package/package.json +67 -65
  38. package/schemas/base/instructions/ci-inspection.md +9 -0
  39. package/schemas/base/instructions/closure.md +4 -2
  40. package/schemas/base/instructions/context-entry.md +1 -0
  41. package/schemas/base/instructions/context-selection.md +33 -0
  42. package/schemas/base/instructions/documentation-checks.md +2 -0
  43. package/schemas/base/instructions/humanizer.md +12 -5
  44. package/schemas/base/instructions/planning.md +60 -27
  45. package/schemas/delivery/instructions/apply.md +2 -0
package/dist/core.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { withStateLock } from './state-lock.js';
2
+ import { documentationDefaults, documentationSettings } from './documentation-settings.js';
3
+ import { ciDefaults, ciSettings } from './ci-settings.js';
1
4
  import fs from 'node:fs';
2
5
  import path from 'node:path';
3
6
  import { createHash } from 'node:crypto';
@@ -45,7 +48,7 @@ const normalize = (s) => s.replace(/\r\n/g, '\n');
45
48
  const hash = (s) => createHash('sha256').update(normalize(s)).digest('hex');
46
49
  const read = (p) => fs.readFileSync(p, 'utf8');
47
50
  export function defaults() {
48
- return { docsRoot: 'docs', learnings: { enabled: false, directory: 'learnings' }, writing: { humanizer: 'auto' }, features: Object.fromEntries(features.map(f => [f, true])), evidence: { report: '.cliewen-openspec/evidence.json' }, ac: { capabilities: {}, padding: 3 }, testing: { ...qualityDefaults(), placement: 'per-task', types: {
51
+ return { ciInspection: ciDefaults(), documentationChecks: documentationDefaults(), contextSelection: { mode: 'guided', roots: [], exclude: [], maxFiles: 8 }, readiness: { enabled: true, threshold: 3 }, docsRoot: 'docs', learnings: { enabled: false, directory: 'learnings' }, writing: { humanizer: 'auto' }, features: Object.fromEntries(features.map(f => [f, true])), evidence: { report: '.cliewen-openspec/evidence.json' }, ac: { capabilities: {}, padding: 3 }, testing: { ...qualityDefaults(), placement: 'per-task', types: {
49
52
  Unit: { description: 'Isolated behavior without external dependencies' },
50
53
  Integration: { description: 'Interaction between components or dependencies' },
51
54
  E2E: { description: 'Complete user or system workflow' }
@@ -61,8 +64,19 @@ function keys(o, allowed, label) {
61
64
  export function config(root) {
62
65
  const p = local(root, `${state}/config.yaml`);
63
66
  const raw = parse(read(p));
64
- keys(raw, ['docsRoot', 'learnings', 'writing', 'features', 'evidence', 'ac', 'testing'], 'config');
67
+ keys(raw, ['docsRoot', 'learnings', 'writing', 'features', 'evidence', 'ac', 'testing', 'contextSelection', 'documentationChecks', 'ciInspection', 'readiness'], 'config');
65
68
  const c = defaults();
69
+ c.documentationChecks = documentationSettings(raw.documentationChecks);
70
+ c.ciInspection = ciSettings(raw.ciInspection);
71
+ if (raw.readiness !== undefined) {
72
+ keys(raw.readiness, ['enabled', 'threshold'], 'readiness');
73
+ const { enabled = c.readiness.enabled, threshold = c.readiness.threshold } = raw.readiness;
74
+ if (typeof enabled !== 'boolean')
75
+ throw Error('readiness.enabled must be boolean');
76
+ if (!Number.isInteger(threshold) || threshold < 2 || threshold > 4)
77
+ throw Error('readiness.threshold must be an integer from 2 through 4');
78
+ c.readiness = { enabled, threshold };
79
+ }
66
80
  if (raw.learnings !== undefined) {
67
81
  keys(raw.learnings, ['enabled', 'directory'], 'learnings');
68
82
  if (raw.learnings.enabled !== undefined) {
@@ -153,6 +167,32 @@ export function config(root) {
153
167
  }
154
168
  if (!c.features.evidence && [c.testing.quality.coverage.mode, c.testing.quality.effectiveness.mode, c.testing.lifecycle.mode].includes('enforce'))
155
169
  throw Error('Test policy enforcement requires features.evidence: true; enable evidence or use review/off mode.');
170
+ if (raw.contextSelection !== undefined) {
171
+ keys(raw.contextSelection, ['mode', 'roots', 'exclude', 'maxFiles'], 'contextSelection');
172
+ const selection = raw.contextSelection;
173
+ if (selection.mode !== undefined) {
174
+ if (!['off', 'guided'].includes(selection.mode))
175
+ throw Error('contextSelection.mode must be off or guided');
176
+ c.contextSelection.mode = selection.mode;
177
+ }
178
+ for (const field of ['roots', 'exclude'])
179
+ if (selection[field] !== undefined) {
180
+ const paths = selection[field];
181
+ if (!Array.isArray(paths))
182
+ throw Error(`contextSelection.${field} must be an array of project-relative paths`);
183
+ for (const value of paths) {
184
+ if (typeof value !== 'string' || !value.trim() || value !== value.trim() || /[:?*\[\]{}\r\n]/.test(value))
185
+ throw Error(`contextSelection.${field} requires trimmed project-relative paths without glob syntax`);
186
+ local(root, value);
187
+ }
188
+ c.contextSelection[field] = paths;
189
+ }
190
+ if (selection.maxFiles !== undefined) {
191
+ if (!Number.isInteger(selection.maxFiles) || selection.maxFiles < 1 || selection.maxFiles > 100)
192
+ throw Error('contextSelection.maxFiles must be an integer from 1 to 100');
193
+ c.contextSelection.maxFiles = selection.maxFiles;
194
+ }
195
+ }
156
196
  local(root, c.docsRoot);
157
197
  if (c.learnings.enabled && c.features.documentation)
158
198
  local(root, `${c.docsRoot}/${c.learnings.directory}`);
@@ -160,6 +200,9 @@ export function config(root) {
160
200
  return c;
161
201
  }
162
202
  export function transaction(root, writes, dryRun = false) {
203
+ return dryRun ? transact(root, writes, true) : withStateLock(root, () => transact(root, writes, false));
204
+ }
205
+ function transact(root, writes, dryRun = false) {
163
206
  const jp = local(root, `${state}/transaction.json`);
164
207
  if (fs.existsSync(jp))
165
208
  throw Error('Interrupted transaction exists; run recover before writing.');
@@ -191,6 +234,9 @@ export function transaction(root, writes, dryRun = false) {
191
234
  return Object.keys(writes);
192
235
  }
193
236
  export function recover(root) {
237
+ return withStateLock(root, () => recoverState(root));
238
+ }
239
+ function recoverState(root) {
194
240
  const jp = local(root, `${state}/transaction.json`);
195
241
  if (!fs.existsSync(jp))
196
242
  return;
@@ -216,7 +262,7 @@ export function recover(root) {
216
262
  }
217
263
  fs.unlinkSync(jp);
218
264
  }
219
- function bundledFiles() { return { ...deliveryFiles(), ...discoveryFiles(), ...allFiles(), [`${state}/templates/learning.md`]: template('base/templates/learning.md'), [`${state}/planning.md`]: template('base/instructions/planning.md') + '\n## Work scoping\n\n' + template('base/instructions/work-scoping.md'), [`${state}/closure.md`]: template('base/instructions/closure.md'), [`${state}/prototyping.md`]: template('base/instructions/prototyping.md'), [`${state}/product-context.md`]: template('base/instructions/product-context.md') }; }
265
+ function bundledFiles() { return { ...deliveryFiles(), ...discoveryFiles(), ...allFiles(), [`${state}/templates/learning.md`]: template('base/templates/learning.md'), [`${state}/planning.md`]: template('base/instructions/planning.md') + '\n## Work scoping\n\n' + template('base/instructions/work-scoping.md'), [`${state}/closure.md`]: template('base/instructions/closure.md') + '\n## Writing policy\n\n' + template('base/instructions/humanizer.md'), [`${state}/prototyping.md`]: template('base/instructions/prototyping.md'), [`${state}/product-context.md`]: template('base/instructions/product-context.md'), [`${state}/context-selection.md`]: template('base/instructions/context-selection.md'), [`${state}/ci-inspection.md`]: template('base/instructions/ci-inspection.md') }; }
220
266
  function manifestText(files) {
221
267
  return JSON.stringify({ version, files: Object.fromEntries(Object.entries(files).map(([file, content]) => [file, hash(content)])) }, null, 2) + '\n';
222
268
  }
@@ -234,7 +280,7 @@ function ownedManifest(root, operation) {
234
280
  throw Error('Manifest files must be a nonempty ownership mapping');
235
281
  for (const [file, digest] of Object.entries(previous.files)) {
236
282
  local(root, file);
237
- const owned = [`${state}/templates/decision.md`, `${state}/templates/learning.md`, `${state}/planning.md`, `${state}/closure.md`, `${state}/prototyping.md`, `${state}/product-context.md`].includes(file) || /^openspec\/schemas\/cliewen-(delivery|discovery|all)\/(schema\.yaml|templates\/[a-z0-9][a-z0-9-]*\.md)$/.test(file);
283
+ const owned = [`${state}/templates/decision.md`, `${state}/templates/learning.md`, `${state}/planning.md`, `${state}/closure.md`, `${state}/prototyping.md`, `${state}/product-context.md`, `${state}/context-selection.md`, `${state}/ci-inspection.md`].includes(file) || /^openspec\/schemas\/cliewen-(delivery|discovery|all)\/(schema\.yaml|templates\/[a-z0-9][a-z0-9-]*\.md)$/.test(file);
238
284
  if (!owned || typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest))
239
285
  throw Error(`Invalid owned-file entry in manifest: ${file}`);
240
286
  }
@@ -280,6 +326,9 @@ function validateReplacementSchema(root, name) {
280
326
  }
281
327
  }
282
328
  export function uninstall(root, dryRun = false, replacement) {
329
+ return dryRun ? planUninstall(root, true, replacement) : withStateLock(root, () => planUninstall(root, false, replacement));
330
+ }
331
+ function planUninstall(root, dryRun, replacement) {
283
332
  if (!dryRun)
284
333
  recover(root);
285
334
  else if (fs.existsSync(local(root, `${state}/transaction.json`)))
@@ -458,8 +507,89 @@ function planInit(root, makeDefault) {
458
507
  writes[`${state}/manifest.json`] = manifest;
459
508
  return writes;
460
509
  }
461
- export function lifecycle(root, operation, dryRun = false, makeDefault = false) {
510
+ function requireLocalPlanning(root) {
511
+ const yaml = local(root, 'openspec/config.yaml');
512
+ const file = fs.existsSync(yaml) ? yaml : local(root, 'openspec/config.yml');
513
+ const doc = parseDocument(fs.existsSync(file) ? read(file) : '{}');
514
+ if (doc.errors.length)
515
+ throw Error(`Invalid OpenSpec config: ${doc.errors[0].message}`);
516
+ if (doc.contents !== null && !isMap(doc.contents))
517
+ throw Error('OpenSpec config must be a YAML mapping');
518
+ const pointer = doc.has('store');
519
+ const standalone = fs.existsSync(local(root, '.openspec-store/store.yaml'));
520
+ const localDirs = ['openspec/specs', 'openspec/changes'].every(p => {
521
+ const target = local(root, p);
522
+ return fs.existsSync(target) && fs.statSync(target).isDirectory();
523
+ });
524
+ if (standalone || (pointer && !localDirs))
525
+ throw Error('External OpenSpec stores are not supported by Cliewen init/update. Use a repository-local OpenSpec project with its own specs and changes; cross-repository acceptance identities and evidence require separate support. No files changed.');
526
+ }
527
+ export function setupProfile(value) {
528
+ if (value !== 'solo' && value !== 'team')
529
+ throw Error('Choose a solo or team profile');
530
+ return value;
531
+ }
532
+ const profileFile = `${state}/setup-profile.json`;
533
+ const settingsFile = `${state}/config.yaml`;
534
+ export function profileSnapshot(root, existingOnly = false) {
535
+ if (existingOnly) {
536
+ if (fs.existsSync(local(root, `${state}/transaction.json`)))
537
+ throw Error('Run recover before previewing a profile.');
538
+ ownedManifest(root, 'update');
539
+ if (!fs.existsSync(local(root, settingsFile)))
540
+ throw Error('Project settings are missing. Run init before switching profiles.');
541
+ }
542
+ const optional = (file) => {
543
+ const target = local(root, file);
544
+ return fs.existsSync(target) ? read(target) : undefined;
545
+ };
546
+ const settings = optional(settingsFile);
547
+ const stored = optional(profileFile);
548
+ const coordination = optional(`${state}/ac-coordination.json`);
549
+ const record = stored === undefined ? null : JSON.parse(stored);
550
+ if (stored !== undefined && (record?.version !== 1 || !['solo', 'team'].includes(record.profile)))
551
+ throw Error(`Invalid setup profile in ${profileFile}`);
552
+ return {
553
+ settings, stored, current: record?.profile,
554
+ review: settings === undefined ? defaults().features.review : config(root).features.review,
555
+ coordinated: coordination !== undefined && JSON.parse(coordination)?.mode === 'git'
556
+ };
557
+ }
558
+ function profileWrites(root, selection) {
559
+ const { profile, enableReview, basis } = selection;
560
+ if (!isDeepStrictEqual(profileSnapshot(root), basis))
561
+ throw Error('Project settings changed after preview. Preview the profile again.');
562
+ const writes = {};
563
+ if (basis.current !== profile)
564
+ writes[profileFile] = JSON.stringify({ version: 1, profile }, null, 2) + '\n';
565
+ if (enableReview && !basis.review) {
566
+ const doc = parseDocument(basis.settings ?? '{}');
567
+ const expected = doc.toJS();
568
+ expected.features.review = true;
569
+ doc.setIn(['features', 'review'], true);
570
+ if (!isDeepStrictEqual(doc.toJS(), expected))
571
+ throw Error('Enabling review would also change other YAML values. Resolve shared aliases first.');
572
+ writes[settingsFile] = doc.toString();
573
+ }
574
+ return writes;
575
+ }
576
+ export function applyProfile(root, selection) {
577
+ return withStateLock(root, () => {
578
+ if (fs.existsSync(local(root, `${state}/transaction.json`)))
579
+ throw Error('Run recover before applying a profile.');
580
+ ownedManifest(root, 'update');
581
+ const writes = profileWrites(root, selection);
582
+ transaction(root, writes);
583
+ return Object.keys(writes);
584
+ });
585
+ }
586
+ export function lifecycle(root, operation, dryRun = false, makeDefault = false, profile) {
462
587
  const tools = compatibility(root);
588
+ requireLocalPlanning(root);
589
+ const run = () => applyLifecycle(root, operation, dryRun, makeDefault, tools, profile);
590
+ return dryRun ? run() : withStateLock(root, run);
591
+ }
592
+ function applyLifecycle(root, operation, dryRun, makeDefault, tools, profile) {
463
593
  const pending = fs.existsSync(local(root, `${state}/transaction.json`));
464
594
  if (pending && dryRun)
465
595
  throw Error('Interrupted transaction exists; run recover before preview. No preview files changed.');
@@ -469,6 +599,8 @@ export function lifecycle(root, operation, dryRun = false, makeDefault = false)
469
599
  const mp = local(root, `${state}/manifest.json`);
470
600
  const installedVersion = fs.existsSync(mp) ? ownedManifest(root, 'update').version : null;
471
601
  const changes = operation === 'init' ? planInit(root, makeDefault) : planUpdate(root);
602
+ if (profile)
603
+ Object.assign(changes, profileWrites(root, profile));
472
604
  const writes = Object.keys(changes).filter(file => changes[file] !== null);
473
605
  const result = { writes, deletes: Object.keys(changes).filter(file => changes[file] === null), creates: writes.filter(file => !fs.existsSync(local(root, file))), replaces: writes.filter(file => fs.existsSync(local(root, file))), installedVersion, targetVersion: version, compatibility: tools, recoveredTransaction: pending };
474
606
  transaction(root, changes, dryRun);
@@ -492,7 +624,9 @@ export function markdowns(dir) {
492
624
  return [];
493
625
  return fs.readdirSync(dir, { withFileTypes: true }).flatMap(e => e.isDirectory() ? markdowns(path.join(dir, e.name)) : e.isFile() && e.name.endsWith('.md') ? [path.join(dir, e.name)] : []);
494
626
  }
495
- export function scenarios(root, change) {
627
+ export function scenarios(root, change, capability) {
628
+ if (change !== undefined && capability !== undefined)
629
+ throw Error('Choose either --change or --capability');
496
630
  if (change && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(change))
497
631
  throw Error('Change must be a kebab-case name');
498
632
  let folder = change ? local(root, `openspec/changes/${change}/specs`) : local(root, 'openspec/specs');
@@ -505,7 +639,18 @@ export function scenarios(root, change) {
505
639
  if (change && !fs.existsSync(folder))
506
640
  throw Error(`Change specs do not exist: ${change}`);
507
641
  const out = [];
508
- for (const file of markdowns(folder)) {
642
+ let files;
643
+ if (capability === undefined)
644
+ files = markdowns(folder);
645
+ else {
646
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(capability))
647
+ throw Error('Capability must be a kebab-case name');
648
+ const spec = local(root, `openspec/specs/${capability}/spec.md`);
649
+ if (!fs.existsSync(spec))
650
+ throw Error(`Permanent capability spec does not exist: ${capability}`);
651
+ files = [spec];
652
+ }
653
+ for (const file of files) {
509
654
  let fence = false, removed = false;
510
655
  let current;
511
656
  for (const line of read(file).split(/\r?\n/)) {
@@ -529,13 +674,16 @@ export function scenarios(root, change) {
529
674
  current.testTypes.push(type[1]);
530
675
  }
531
676
  }
677
+ if (capability !== undefined && !out.length)
678
+ throw Error(`No active scenarios in permanent capability: ${capability}`);
532
679
  return out;
533
680
  }
534
681
  export function git(root, args) { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
535
- export function check(root, change, failPending = false) {
682
+ export function check(root, change, failPending = false, capability) {
536
683
  const findings = [];
537
684
  const add = (code, message, severity = 'error') => findings.push({ code, severity, message });
538
685
  const c = config(root);
686
+ const selected = capability === undefined ? undefined : scenarios(root, change, capability);
539
687
  if (fs.existsSync(local(root, `${state}/transaction.json`)))
540
688
  add('interrupted-transaction', 'Run recover before continuing');
541
689
  const mp = local(root, `${state}/manifest.json`);
@@ -601,7 +749,7 @@ export function check(root, change, failPending = false) {
601
749
  add('quality-evidence-unavailable', 'Test policy review remains advisory: enable evidence for execution-backed assessment.', 'warning');
602
750
  return findings;
603
751
  }
604
- const specs = scenarios(root, change);
752
+ const specs = selected ?? scenarios(root, change);
605
753
  const ids = new Set();
606
754
  for (const s of specs) {
607
755
  if (!s.id)
@@ -627,14 +775,18 @@ export function check(root, change, failPending = false) {
627
775
  if (!report || report.version !== 1 || typeof report.revision !== 'string' || !/^[a-f0-9]{40,64}$/.test(report.revision) || !Array.isArray(report.results))
628
776
  throw Error('Invalid evidence report: expected version 1, full revision and results');
629
777
  if (report.scope !== undefined) {
630
- keys(report.scope, ['change'], 'evidence scope');
631
- if (typeof report.scope.change !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(report.scope.change))
632
- throw Error('Invalid evidence scope: expected a kebab-case change name');
633
- if (report.scope.change !== change)
634
- add('evidence-scope-mismatch', `Report is scoped to ${report.scope.change}; check ${change ? `requests ${change}` : 'requests permanent specs'}`);
778
+ keys(report.scope, ['change', 'capability'], 'evidence scope');
779
+ const entries = Object.entries(report.scope);
780
+ if (entries.length !== 1 || typeof entries[0][1] !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(entries[0][1]))
781
+ throw Error('Invalid evidence scope: expected one kebab-case change or capability name');
782
+ const [kind, name] = entries[0];
783
+ if (name !== (kind === 'change' ? change : capability))
784
+ add('evidence-scope-mismatch', `Report is scoped to ${kind} ${name}. Collect evidence for the requested scope.`);
635
785
  if (report.execution === undefined)
636
786
  throw Error('Scoped evidence requires the complete test runner exit code');
637
787
  }
788
+ else if (capability !== undefined)
789
+ add('evidence-scope-mismatch', `Collect evidence with --capability ${capability}.`);
638
790
  if (report.execution !== undefined && (!report.execution || !Number.isInteger(report.execution.exitCode)))
639
791
  throw Error('Invalid evidence execution result');
640
792
  if (report.execution?.exitCode !== undefined && report.execution.exitCode !== 0)
@@ -683,7 +835,7 @@ export function check(root, change, failPending = false) {
683
835
  for (const id of ids)
684
836
  if (!seen.has(id))
685
837
  add('missing-evidence', id);
686
- findings.push(...checkQuality(root, c, specs, report, change, local));
838
+ findings.push(...checkQuality(root, c, specs, report, change, local, capability));
687
839
  add('sufficiency-not-assessed', 'Execution and linkage do not prove assertion quality; review the assertions against the scenarios.', 'info');
688
840
  return findings;
689
841
  }
@@ -0,0 +1,16 @@
1
+ export declare const documentationCategories: readonly ['links', 'metadata', 'mermaid'];
2
+ export type DocumentationCategory = typeof documentationCategories[number];
3
+ export type DocumentationMode = 'off' | 'advisory' | 'enforce';
4
+ export type MetadataRule = {
5
+ path: string;
6
+ required: string[];
7
+ values: Record<string, string[]>;
8
+ };
9
+ export type DocumentationSettings = Record<DocumentationCategory, DocumentationMode> & {
10
+ roots: string[];
11
+ exclude: string[];
12
+ metadataRules: MetadataRule[];
13
+ };
14
+ export declare function documentationDefaults(): DocumentationSettings;
15
+ export declare function documentationPath(value: unknown, label: string): string;
16
+ export declare function documentationSettings(raw: unknown): DocumentationSettings;
@@ -0,0 +1,65 @@
1
+ import path from 'node:path';
2
+ export const documentationCategories = ['links', 'metadata', 'mermaid'];
3
+ export function documentationDefaults() {
4
+ return { roots: [], exclude: [], links: 'advisory', metadata: 'advisory', mermaid: 'advisory', metadataRules: [] };
5
+ }
6
+ function mapping(value, allowed, label) {
7
+ if (!value || typeof value !== 'object' || Array.isArray(value))
8
+ throw Error(`${label} must be a mapping`);
9
+ for (const key of Object.keys(value))
10
+ if (!allowed.includes(key))
11
+ throw Error(`Unknown ${label} key: ${key}`);
12
+ }
13
+ export function documentationPath(value, label) {
14
+ if (typeof value !== 'string' || !value || value !== value.trim() || /[:?*\[\]{}\x00-\x1f\x7f]/.test(value) || path.win32.parse(value).root || value.split(/[\\/]/).includes('..'))
15
+ throw Error(`${label} requires a trimmed project-relative path without traversal or glob syntax`);
16
+ return path.posix.normalize(value.replaceAll('\\', '/')).replace(/\/$/, '') || '.';
17
+ }
18
+ function fieldList(value, label) {
19
+ if (!Array.isArray(value) || value.some(v => typeof v !== 'string' || !v || v !== v.trim() || /[\x00-\x1f\x7f]/.test(v)))
20
+ throw Error(`${label} must be an array of nonempty trimmed strings`);
21
+ return [...new Set(value)];
22
+ }
23
+ export function documentationSettings(raw) {
24
+ const result = documentationDefaults();
25
+ if (raw === undefined)
26
+ return result;
27
+ mapping(raw, ['roots', 'exclude', ...documentationCategories, 'metadataRules'], 'documentationChecks');
28
+ for (const category of documentationCategories) {
29
+ const mode = raw[category];
30
+ if (mode === undefined)
31
+ continue;
32
+ if (!['off', 'advisory', 'enforce'].includes(mode))
33
+ throw Error(`documentationChecks.${category} must be off, advisory, or enforce`);
34
+ result[category] = mode;
35
+ }
36
+ for (const field of ['roots', 'exclude'])
37
+ if (raw[field] !== undefined) {
38
+ if (!Array.isArray(raw[field]))
39
+ throw Error(`documentationChecks.${field} must be an array`);
40
+ result[field] = [...new Set(raw[field].map(v => documentationPath(v, `documentationChecks.${field}`)))];
41
+ }
42
+ if (raw.metadataRules !== undefined) {
43
+ if (!Array.isArray(raw.metadataRules))
44
+ throw Error('documentationChecks.metadataRules must be an array');
45
+ result.metadataRules = raw.metadataRules.map((rule, i) => {
46
+ const label = `documentationChecks.metadataRules[${i}]`;
47
+ mapping(rule, ['path', 'required', 'values'], label);
48
+ const required = rule.required === undefined ? [] : fieldList(rule.required, `${label}.required`);
49
+ const values = Object.create(null);
50
+ if (rule.values !== undefined) {
51
+ if (!rule.values || typeof rule.values !== 'object' || Array.isArray(rule.values))
52
+ throw Error(`${label}.values must be a mapping`);
53
+ for (const [field, allowed] of Object.entries(rule.values)) {
54
+ fieldList([field], `${label}.values field`);
55
+ const list = fieldList(allowed, `${label}.values.${field}`);
56
+ if (!list.length)
57
+ throw Error(`${label}.values.${field} must not be empty`);
58
+ values[field] = list;
59
+ }
60
+ }
61
+ return { path: documentationPath(rule.path, `${label}.path`), required, values };
62
+ });
63
+ }
64
+ return result;
65
+ }
@@ -0,0 +1,47 @@
1
+ import { type DocumentationCategory, type DocumentationMode } from './documentation-settings.js';
2
+ type Status = 'passed' | 'issues' | 'incomplete' | 'off' | 'not-applicable';
3
+ type DocFinding = {
4
+ code: string;
5
+ category: DocumentationCategory;
6
+ severity: 'warning' | 'error';
7
+ path: string;
8
+ line?: number;
9
+ message: string;
10
+ incomplete: boolean;
11
+ };
12
+ export declare const documentationLimits: {
13
+ files: number;
14
+ fileBytes: number;
15
+ diagramBytes: number;
16
+ directoryEntries: number;
17
+ diagramMilliseconds: number;
18
+ };
19
+ export declare function checkDocumentation(root: string): Promise<{
20
+ ok: boolean;
21
+ exitCode: number;
22
+ scope: {
23
+ roots: string[];
24
+ exclude: string[];
25
+ selectedFiles: number;
26
+ readFiles: number;
27
+ excludedPaths: number;
28
+ reservedPaths: number;
29
+ nonLocalReferences: number;
30
+ };
31
+ limits: {
32
+ files: number;
33
+ fileBytes: number;
34
+ diagramBytes: number;
35
+ directoryEntries: number;
36
+ diagramMilliseconds: number;
37
+ };
38
+ categories: Record<"links" | "mermaid" | "metadata", {
39
+ mode: DocumentationMode;
40
+ status: Status;
41
+ checked: number;
42
+ }>;
43
+ anchorDialect: string;
44
+ mermaidParserVersion: string | null;
45
+ findings: DocFinding[];
46
+ }>;
47
+ export {};