@jakobm/peacekeeper 0.25.1 → 0.26.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.
package/README.md CHANGED
@@ -23,7 +23,8 @@ as `src/modules/cli/types.ts` from the root `cmdabra.yaml`; `npm run typecheck`
23
23
  verifies that it is current before checking the TypeScript project.
24
24
 
25
25
  Generate the dependency views and SVG diagram with `npm run architecture`. The
26
- checked-in output lives in `architecture/`.
26
+ checked-in output lives in `architecture/`. Peacekeeper's configured
27
+ `generated-files` convention verifies that output during `npm test`.
27
28
 
28
29
  Checkpoint and session lifecycle hooks use the same Cmdabra and Portico composition
29
30
  as other CLI commands. Dependencies must therefore be installed in every worktree
@@ -188,9 +189,12 @@ git:
188
189
  tests:
189
190
  commands:
190
191
  - eslint .
192
+ - peacekeeper check-conventions
191
193
  - node --test
192
194
  receiptMaxAgeMinutes: 60
193
195
  npmTestUsesRunner: true
196
+ conventions:
197
+ rules: []
194
198
  loggingDirectory: tmp/logs
195
199
  loggingEnabled: true
196
200
  projectChecks:
@@ -350,6 +354,181 @@ are stored there and session cleanup reads that checkout's configuration.
350
354
  The hook definitions can then be reviewed and trusted in Codex; committing them
351
355
  does not grant trust automatically.
352
356
 
357
+ ## Configured repository conventions
358
+
359
+ Define general file conventions in `peacekeeper.config.yaml` and run:
360
+
361
+ ```sh
362
+ peacekeeper check-conventions
363
+ ```
364
+
365
+ Add `peacekeeper check-conventions` explicitly to `tests.commands` to include it
366
+ in the normal test run at the desired position. It is not added automatically.
367
+ Each rule is reported as a Node.js test. Violations, file errors, failed generators,
368
+ and invalid configuration cause a nonzero exit status; one failing rule does not
369
+ hide the results of later rules. A failed command in `run-tests` invalidates any
370
+ previous receipt and prevents a new passing receipt.
371
+
372
+ All configured paths and generator working directories are relative to the Git
373
+ root, even when the command is invoked from a subdirectory. Use forward slashes
374
+ on every platform. There is no separate conventions file. `conventions.rules: []`
375
+ is valid and reports that no rules are configured. Existing projects must run
376
+ `peacekeeper update-config` to add this field before ordinary commands can run;
377
+ existing rules and YAML comments are preserved.
378
+
379
+ Standalone checks always run and do not create or reuse test receipts. When
380
+ included in `tests.commands`, they follow `run-tests`' existing receipt reuse;
381
+ use `peacekeeper run-tests --force` to rerun the full configured test flow.
382
+ Run `check-conventions --update` separately from that flow when updating output.
383
+
384
+ The `testing` module owns rule execution and Node test reporting. The
385
+ `configuration` module owns the rule contract and strict validation, and `cli`
386
+ maps the command through the testing facade.
387
+
388
+ Peacekeeper's own configuration checks generated architecture output, kebab-case
389
+ TypeScript filenames, the two permitted files at the module root, test and fixture
390
+ files in the test tree, and sorted dependency lists. These rules run as an explicit
391
+ step in `npm test`; the architecture output check uses the same rule runner as
392
+ consumer projects.
393
+
394
+ ### Allowed files
395
+
396
+ ```yaml
397
+ conventions:
398
+ rules:
399
+ - check: allowed-files
400
+ files: "tests/acceptance/**/*"
401
+ allow:
402
+ - "tests/acceptance/**/*.case"
403
+ - "tests/acceptance/**/README.md"
404
+
405
+ - check: allowed-files
406
+ files: "scripts/*"
407
+ allow: []
408
+ ```
409
+
410
+ `files` selects existing files using glob patterns. `*` matches within one path
411
+ segment; `**` includes subdirectories. Directories themselves are not checked.
412
+ Hidden files are included. Symbolic directory links are not recursively followed.
413
+
414
+ Each selected file must match at least one `allow` pattern. The patterns in
415
+ `allow` are also relative to the repository root. An explicit empty
416
+ list forbids every selected file; omitting `allow` is a configuration error.
417
+ Overlapping rules must each pass independently.
418
+
419
+ The literal directory prefix before the first glob segment must exist. For
420
+ example, `scripts/*` fails when `scripts` is missing, but passes when it exists
421
+ and contains no direct files. These rules constrain existing files; they do not
422
+ require files to be present.
423
+
424
+ ### Corresponding files
425
+
426
+ ```yaml
427
+ conventions:
428
+ rules:
429
+ - check: corresponding-files
430
+ from: "tests/unit/src/{path}.test.ts"
431
+ to: "src/{path}.ts"
432
+ ```
433
+
434
+ Each matching `from` file must have an existing file at its corresponding `to`
435
+ path. `{path}` captures a nonempty relative path, including subdirectories, and
436
+ substitutes it unchanged into the target. Both templates must contain exactly
437
+ one `{path}` placeholder and no other glob patterns. The literal source
438
+ directory must exist; an existing empty source directory is allowed.
439
+
440
+ The check is one-way: extra target files are allowed. A directory at the target
441
+ path does not count as a corresponding file. Missing targets are reported with
442
+ both the source and expected target paths.
443
+
444
+ An empty `conventions.rules` list is valid. Unknown checks and fields,
445
+ absolute paths, parent traversal, and negated patterns are configuration errors.
446
+
447
+ ### Sorted YAML lists
448
+
449
+ ```yaml
450
+ conventions:
451
+ rules:
452
+ - check: sorted-yaml-lists
453
+ file: "src/modules/dependencies.yaml"
454
+ ```
455
+
456
+ Recursively checks every list containing only strings, including lists nested
457
+ inside mappings or other lists. Ordering uses JavaScript's case-sensitive
458
+ string sort, without locale rules. Empty lists and duplicate values are allowed.
459
+ Other lists are traversed for nested string lists, but are not themselves sorted.
460
+ Failures identify the file and the YAML value path. Missing files and invalid
461
+ YAML fail the check. `file` must be a literal relative path.
462
+
463
+ ### Document links
464
+
465
+ ```yaml
466
+ conventions:
467
+ rules:
468
+ - check: document-links
469
+ document: "README.md"
470
+ files: "docs/**/*"
471
+ ```
472
+
473
+ Every selected file must be the destination of an inline Markdown link in
474
+ `document`. Destinations are relative to the document's directory; URL-encoded
475
+ paths, fragments, query strings, and optional double-quoted titles are supported.
476
+ External URLs do not cover local files. Extra links are allowed. This simple
477
+ check recognizes inline link syntax only, not reference links or HTML links;
478
+ it does not parse Markdown blocks, so link-shaped text in code also counts.
479
+ The file selection has the same directory and glob semantics as `allowed-files`.
480
+ A missing document fails, and `document` must be a literal relative path.
481
+
482
+ ### File names
483
+
484
+ ```yaml
485
+ conventions:
486
+ rules:
487
+ - check: file-names
488
+ files: "{src,scripts,tests}/**/*.ts"
489
+ match: '^[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\.test|\.d)?\.ts$'
490
+ ```
491
+
492
+ `files` selects files using the same glob and directory semantics as
493
+ `allowed-files`. `match` is a case-sensitive JavaScript regular expression
494
+ using Unicode mode, applied to each file's basename including its extensions.
495
+ Directory names are not checked. Use `^` and `$` to require a full-name match;
496
+ without anchors, substring matches are allowed. Invalid expressions are
497
+ configuration errors. Failures report the file and expected expression.
498
+ YAML single quotes preserve regex backslashes without extra escaping.
499
+
500
+ The example requires kebab-case TypeScript filenames with optional `.test` or
501
+ `.d` suffixes. Adjust the expression to the calling project's naming conventions.
502
+
503
+ ### Generated files
504
+
505
+ ```yaml
506
+ conventions:
507
+ rules:
508
+ - check: generated-files
509
+ run: 'portico architecture --modules dist/src/modules --output "{output}"'
510
+ expected: architecture
511
+ ```
512
+
513
+ Runs a shell command from the repository root, with local
514
+ `node_modules/.bin` programs available. Quote `"{output}"` in the command:
515
+ the runner substitutes a temporary output directory and removes it afterward.
516
+ The command must succeed. The expected directory must exist and contain exactly
517
+ the same relative file paths and bytes, including hidden and nested files.
518
+ Empty directories are not compared. Generation must be deterministic.
519
+
520
+ Run `peacekeeper check-conventions --update` to regenerate all configured outputs.
521
+ This replaces each expected directory only after its generator succeeds, removing
522
+ stale files. Expected directories must contain only reproducible generated output;
523
+ review the diff before committing. Git metadata paths and expected paths containing
524
+ symbolic links are rejected. Temporary output is removed after each rule.
525
+
526
+ Other convention rules are still checked and are never automatically repaired.
527
+ The command does not sort YAML, rename files, create corresponding source files,
528
+ or insert document links. Updates happen per rule, so generated files may have
529
+ been updated even if another rule fails. A failed generator preserves that rule's
530
+ previous expected files and reports its exit status and output.
531
+
353
532
  ## Check project conventions locally
354
533
 
355
534
  Run `peacekeeper check-project` to check the local project configuration.
@@ -675,7 +854,9 @@ It never uses an administrator bypass or pushes directly to the default branch.
675
854
  After merge, the command verifies the package files at the PR's actual merge
676
855
  commit, tags that commit with `v<version>`, and pushes the tag. The existing
677
856
  workflow publishes through npm trusted publishing. The command then waits for
678
- the publish job and for the version to appear on npm. Git and an authenticated
857
+ the publish job and for the version to appear on npm. Monitoring reads the run
858
+ status before its jobs so a job finishing between requests does not produce a
859
+ false publication failure. Git and an authenticated
679
860
  GitHub CLI (`gh`) with Contents read/write, Pull requests read/write, Actions
680
861
  read and the policy-reading access described above are required. Registry checks
681
862
  use a temporary npm cache and request current metadata.
package/dist/cmdabra.yaml CHANGED
@@ -60,6 +60,12 @@ commands:
60
60
  choices: [major, minor, patch]
61
61
  assess-release:
62
62
  description: Assess unpublished changes with Codex and return a JSON recommendation.
63
+ check-conventions:
64
+ description: Test configured repository conventions.
65
+ named-options:
66
+ update:
67
+ description: Replace generated output directories after successful generation; check other rules.
68
+ type: boolean
63
69
  run-tests:
64
70
  description: Run configured tests, reusing a valid test receipt.
65
71
  named-options:
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jakobm/peacekeeper",
3
- "version": "0.25.1",
3
+ "version": "0.26.0",
4
4
  "description": "Shared repository test, Git worktree, and Codex hook commands",
5
5
  "license": "MIT",
6
6
  "author": "Jakob Mattsson",
@@ -43,6 +43,7 @@
43
43
  "@iarna/toml": "^2.2.5",
44
44
  "@jakobm/cmdabra": "^0.7.0",
45
45
  "@jakobm/portico": "^0.8.1",
46
+ "glob": "^14.0.4",
46
47
  "semver": "^7.8.5",
47
48
  "yaml": "^2.9.1"
48
49
  },
@@ -17,6 +17,7 @@ export default ({ configuration, lifecycle, maintenance, projects, releases, tes
17
17
  }),
18
18
  generateGithubSetup: options => projects.generateGithubSetup({ repository: options.repository }),
19
19
  installHooks: options => projects.installHooks({ dryRun: options.dryRun }),
20
+ checkConventions: options => testing.checkConventions({ update: options.update }),
20
21
  checkTestReceipt: () => testing.checkTestReceipt(),
21
22
  recordTestReceipt: () => testing.recordTestReceipt(),
22
23
  runTests: options => testing.runTests({ force: options.force }),
@@ -0,0 +1,93 @@
1
+ export default ({ external: { hasMagic, path } }) => {
2
+ function invalid(location, message) {
3
+ throw new Error(`Invalid conventions configuration: ${location} ${message}`);
4
+ }
5
+ function nonempty(value, location) {
6
+ if (typeof value !== 'string' || !value.trim())
7
+ invalid(location, 'must be a nonempty string');
8
+ }
9
+ function relative(value, location) {
10
+ nonempty(value, location);
11
+ if (path.posix.isAbsolute(value) || path.win32.isAbsolute(value) || value.includes('\\')
12
+ || value.split(/[/{},]/u).some(part => part === '..' || part === '.') || value.startsWith('!')) {
13
+ invalid(location, 'must be a relative path using forward slashes without traversal or negation');
14
+ }
15
+ }
16
+ function literal(value, location) {
17
+ relative(value, location);
18
+ if (hasMagic(`./${value}`, { magicalBraces: true }))
19
+ invalid(location, 'must be a literal path');
20
+ }
21
+ function template(value, location) {
22
+ relative(value, location);
23
+ const text = value;
24
+ const replaced = text.replace('{path}', 'placeholder');
25
+ if (text.split('{path}').length !== 2 || /[{}]/u.test(replaced) || hasMagic(replaced)) {
26
+ invalid(location, 'must contain exactly one {path} placeholder and no other glob patterns');
27
+ }
28
+ }
29
+ function validate(rules) {
30
+ if (!Array.isArray(rules))
31
+ invalid('conventions.rules', 'must be an array');
32
+ const fields = {
33
+ 'allowed-files': ['files', 'allow'],
34
+ 'corresponding-files': ['from', 'to'],
35
+ 'sorted-yaml-lists': ['file'],
36
+ 'document-links': ['document', 'files'],
37
+ 'file-names': ['files', 'match'],
38
+ 'generated-files': ['run', 'expected'],
39
+ };
40
+ for (const [index, rule] of rules.entries()) {
41
+ const location = `conventions.rules[${index}]`;
42
+ if (!rule || typeof rule !== 'object' || Array.isArray(rule))
43
+ invalid(location, 'must be an object');
44
+ if (typeof rule.check !== 'string' || !Object.hasOwn(fields, rule.check))
45
+ invalid(`${location}.check`, 'is unknown');
46
+ const required = ['check', ...fields[rule.check]];
47
+ for (const key of Object.keys(rule))
48
+ if (!required.includes(key))
49
+ invalid(`${location}.${key}`, 'is unknown');
50
+ for (const key of required)
51
+ if (!Object.hasOwn(rule, key))
52
+ invalid(`${location}.${key}`, 'is missing');
53
+ switch (rule.check) {
54
+ case 'allowed-files':
55
+ relative(rule.files, `${location}.files`);
56
+ if (!Array.isArray(rule.allow))
57
+ invalid(`${location}.allow`, 'must be an array');
58
+ rule.allow.forEach((value, i) => relative(value, `${location}.allow[${i}]`));
59
+ break;
60
+ case 'corresponding-files':
61
+ template(rule.from, `${location}.from`);
62
+ template(rule.to, `${location}.to`);
63
+ break;
64
+ case 'sorted-yaml-lists':
65
+ literal(rule.file, `${location}.file`);
66
+ break;
67
+ case 'document-links':
68
+ literal(rule.document, `${location}.document`);
69
+ relative(rule.files, `${location}.files`);
70
+ break;
71
+ case 'file-names':
72
+ relative(rule.files, `${location}.files`);
73
+ nonempty(rule.match, `${location}.match`);
74
+ try {
75
+ new RegExp(rule.match, 'u');
76
+ }
77
+ catch {
78
+ invalid(`${location}.match`, 'must be a valid regular expression');
79
+ }
80
+ break;
81
+ case 'generated-files':
82
+ literal(rule.expected, `${location}.expected`);
83
+ if (rule.expected.split('/').includes('.git'))
84
+ invalid(`${location}.expected`, 'must not target Git metadata');
85
+ nonempty(rule.run, `${location}.run`);
86
+ if (!rule.run.includes('{output}'))
87
+ invalid(`${location}.run`, 'must contain an {output} placeholder');
88
+ break;
89
+ }
90
+ }
91
+ }
92
+ return { validate };
93
+ };
@@ -18,6 +18,9 @@
18
18
  "receiptMaxAgeMinutes": 60,
19
19
  "npmTestUsesRunner": false
20
20
  },
21
+ "conventions": {
22
+ "rules": []
23
+ },
21
24
  "loggingEnabled": true,
22
25
  "loggingDirectory": "tmp/logs",
23
26
  "projectChecks": {
@@ -1,4 +1,4 @@
1
- export default ({ external: { execFileSync, fs, path, projectConfigDefaults, runtime, YAML, } }) => {
1
+ export default ({ conventionRules, external: { execFileSync, fs, path, projectConfigDefaults, runtime, YAML, } }) => {
2
2
  const CONFIG_FILE = 'peacekeeper.config.yaml';
3
3
  const LEGACY_CONFIG_FILE = 'peacekeeper.config.json';
4
4
  function repositoryRoot(cwd = runtime.cwd()) {
@@ -14,6 +14,7 @@ export default ({ external: { execFileSync, fs, path, projectConfigDefaults, run
14
14
  checkpointPushRemotes: true, releaseMergeMethod: true,
15
15
  releaseRequiredChecks: true, releaseTestWorkflow: true },
16
16
  tests: { commands: true, receiptMaxAgeMinutes: true, npmTestUsesRunner: true },
17
+ conventions: { rules: true },
17
18
  loggingDirectory: true,
18
19
  loggingEnabled: true,
19
20
  projectChecks: { testWorkflow: true, requiredJobs: true },
@@ -45,6 +46,12 @@ export default ({ external: { execFileSync, fs, path, projectConfigDefaults, run
45
46
  validateShape(config, CONFIG_SCHEMA, 'config', errors);
46
47
  if (errors.length)
47
48
  throw new Error(`${file}: ${errors.join('; ')}. Run peacekeeper update-config to add missing fields.`);
49
+ try {
50
+ conventionRules.validate(config.conventions.rules);
51
+ }
52
+ catch (error) {
53
+ throw new Error(`${file}: ${error instanceof Error ? error.message : String(error)}`);
54
+ }
48
55
  if (typeof config.projectChecks.testWorkflow !== 'string' || !/^[A-Za-z0-9_-]+\.ya?ml$/u.test(config.projectChecks.testWorkflow)) {
49
56
  throw new Error(`${file}: projectChecks.testWorkflow must be a workflow filename`);
50
57
  }
@@ -8,9 +8,9 @@ allowed-modules:
8
8
  testing: [configuration, projects]
9
9
  allowed-external:
10
10
  cli: [cliConfigPath, runCli, runtime]
11
- configuration: [execFileSync, fs, isDeepStrictEqual, output, path, projectConfigDefaults, runtime, YAML]
11
+ configuration: [YAML, execFileSync, fs, hasMagic, isDeepStrictEqual, output, path, projectConfigDefaults, runtime]
12
12
  lifecycle: [buffer, clock, executablePath, fs, output, path, runtime, spawn, spawnSync]
13
13
  maintenance: [execFileSync, fs, output, path, runtime, spawnSync]
14
- projects: [buffer, fs, isDeepStrictEqual, modulesRoot, output, packageVersion, path, projectConfigDefaults, runtime, semver, spawnSync, structuredClone, TOML, url, YAML]
15
- releases: [assessReleaseSchema, clock, execFileSync, fs, modulesRoot, os, output, path, runtime, semver, spawnSync, structuredClone, url, YAML]
16
- testing: [clock, crypto, execFileSync, fs, modulesRoot, os, output, path, runtime, spawnSync]
14
+ projects: [TOML, YAML, buffer, fs, isDeepStrictEqual, modulesRoot, output, packageVersion, path, projectConfigDefaults, runtime, semver, spawnSync, structuredClone, url]
15
+ releases: [YAML, assessReleaseSchema, clock, execFileSync, fs, modulesRoot, os, output, path, runtime, semver, spawnSync, structuredClone, url]
16
+ testing: [YAML, clock, crypto, execFileSync, fs, globSync, hasMagic, modulesRoot, os, output, path, runtime, spawnSync, test]
@@ -4,6 +4,8 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { isDeepStrictEqual } from 'node:util';
7
+ import test from 'node:test';
8
+ import { globSync, hasMagic } from 'glob';
7
9
  import { fileURLToPath } from 'node:url';
8
10
  import TOML from '@iarna/toml';
9
11
  import semver from 'semver';
@@ -30,6 +32,8 @@ export default () => ({
30
32
  crypto,
31
33
  execFileSync,
32
34
  fs,
35
+ globSync,
36
+ hasMagic,
33
37
  isDeepStrictEqual,
34
38
  modulesRoot: moduleDirectory,
35
39
  os,
@@ -43,6 +47,7 @@ export default () => ({
43
47
  spawn,
44
48
  spawnSync,
45
49
  structuredClone,
50
+ test,
46
51
  TOML,
47
52
  url: URL,
48
53
  YAML,
@@ -298,6 +298,9 @@ export default ({ configuration, releaseProtection, external: { clock, fs, os, p
298
298
  }
299
299
  }
300
300
  if (runId) {
301
+ // Read the run first: it can finish while we fetch jobs. A completed
302
+ // run must be checked against a newer job snapshot, never an older one.
303
+ const runStatus = github(exec, cwd, details.host, `repos/${details.slug}/actions/runs/${runId}`, {});
301
304
  const jobs = github(exec, cwd, details.host, `repos/${details.slug}/actions/runs/${runId}/jobs`, {
302
305
  per_page: '100',
303
306
  }).jobs || [];
@@ -307,7 +310,6 @@ export default ({ configuration, releaseProtection, external: { clock, fs, os, p
307
310
  if (matching.length === 1 && matching[0].status === 'completed' && matching[0].conclusion !== 'success') {
308
311
  throw new ReleaseError(`Publish job in GitHub run ${runId} ended as ${matching[0].conclusion}.`);
309
312
  }
310
- const runStatus = github(exec, cwd, details.host, `repos/${details.slug}/actions/runs/${runId}`, {});
311
313
  if (runStatus.status === 'completed') {
312
314
  if (matching.length !== 1 || matching[0].status !== 'completed' || matching[0].conclusion !== 'success') {
313
315
  throw new ReleaseError(`Workflow run ${runId} completed without a successful publish job.`);
@@ -0,0 +1,41 @@
1
+ export default ({ configuration, conventions, external: { output, runtime, test } }) => {
2
+ function name(rule) {
3
+ switch (rule.check) {
4
+ case 'allowed-files':
5
+ case 'file-names': return `${rule.check}: ${rule.files}`;
6
+ case 'corresponding-files': return `${rule.check}: ${rule.from} -> ${rule.to}`;
7
+ case 'sorted-yaml-lists': return `${rule.check}: ${rule.file}`;
8
+ case 'document-links': return `${rule.check}: ${rule.document} -> ${rule.files}`;
9
+ case 'generated-files': return `${rule.check}: ${rule.expected}`;
10
+ }
11
+ }
12
+ async function run({ update = false } = {}) {
13
+ try {
14
+ const config = configuration.projectConfig();
15
+ if (!config.conventions.rules.length) {
16
+ output.log('No convention rules configured.');
17
+ return;
18
+ }
19
+ await test('repository conventions', async (context) => {
20
+ for (const rule of config.conventions.rules) {
21
+ await context.test(name(rule), () => {
22
+ try {
23
+ const violations = conventions.checkRule(config.root, rule, update);
24
+ if (violations.length)
25
+ throw new Error(violations.join('\n'));
26
+ }
27
+ catch (error) {
28
+ runtime.exitCode = 1;
29
+ throw error;
30
+ }
31
+ });
32
+ }
33
+ });
34
+ }
35
+ catch (error) {
36
+ output.error(error instanceof Error ? error.message : String(error));
37
+ runtime.exitCode = 1;
38
+ }
39
+ }
40
+ return { run };
41
+ };
@@ -0,0 +1,168 @@
1
+ export default ({ external: { fs, os, spawnSync, path, globSync, hasMagic, runtime, YAML } }) => {
2
+ function selectedFiles(root, pattern) {
3
+ return globSync(pattern, {
4
+ cwd: root, nodir: true, dot: true, follow: false,
5
+ ignore: {
6
+ childrenIgnored: entry => entry.isSymbolicLink(),
7
+ ignored: entry => entry.isSymbolicLink()
8
+ && !fs.statSync(entry.fullpath(), { throwIfNoEntry: false })?.isFile(),
9
+ },
10
+ })
11
+ .map((fileName) => fileName.split(path.sep).join('/')).sort();
12
+ }
13
+ function selectionDirectory(pattern) {
14
+ const segments = pattern.split('/');
15
+ const firstPattern = segments.findIndex((segment) => hasMagic(`./${segment}`, { magicalBraces: true }));
16
+ return segments.slice(0, firstPattern === -1 ? -1 : firstPattern).join('/') || '.';
17
+ }
18
+ function missingDirectory(root, pattern) {
19
+ const directory = selectionDirectory(pattern);
20
+ return fs.existsSync(path.join(root, directory)) && fs.statSync(path.join(root, directory)).isDirectory()
21
+ ? [] : [`Selection directory does not exist: ${directory}`];
22
+ }
23
+ function allowedFiles(root, rule) {
24
+ const violations = missingDirectory(root, rule.files);
25
+ if (violations.length === 0) {
26
+ const allowed = new Set(rule.allow.flatMap((pattern) => selectedFiles(root, pattern)));
27
+ for (const fileName of selectedFiles(root, rule.files)) {
28
+ if (!allowed.has(fileName))
29
+ violations.push(`Unexpected file: ${fileName}`);
30
+ }
31
+ }
32
+ return violations;
33
+ }
34
+ function fileNames(root, rule) {
35
+ const pattern = new RegExp(rule.match, 'u');
36
+ const violations = missingDirectory(root, rule.files);
37
+ if (violations.length === 0) {
38
+ for (const fileName of selectedFiles(root, rule.files)) {
39
+ if (!pattern.test(path.posix.basename(fileName))) {
40
+ violations.push(`Unexpected file name: ${fileName} (expected ${rule.match})`);
41
+ }
42
+ }
43
+ }
44
+ return violations;
45
+ }
46
+ function correspondingFiles(root, rule) {
47
+ const [prefix, suffix] = rule.from.split('{path}');
48
+ const directory = path.posix.dirname(`${prefix}placeholder`);
49
+ const pattern = directory === '.' ? '**/*' : `${directory}/**/*`;
50
+ const violations = missingDirectory(root, pattern);
51
+ if (violations.length === 0) {
52
+ for (const fileName of selectedFiles(root, pattern)) {
53
+ if (!fileName.startsWith(prefix) || !fileName.endsWith(suffix) ||
54
+ fileName.length <= prefix.length + suffix.length)
55
+ continue;
56
+ const captured = fileName.slice(prefix.length, suffix.length === 0 ? undefined : -suffix.length);
57
+ const counterpart = rule.to.replace('{path}', () => captured);
58
+ const destination = path.join(root, counterpart);
59
+ if (!fs.existsSync(destination) || !fs.statSync(destination).isFile()) {
60
+ violations.push(`Missing corresponding file: ${fileName} -> ${counterpart}`);
61
+ }
62
+ }
63
+ }
64
+ return violations;
65
+ }
66
+ function sortedYamlLists(root, rule) {
67
+ const violations = [];
68
+ function visit(value, location) {
69
+ if (Array.isArray(value)) {
70
+ if (value.every((entry) => typeof entry === 'string')) {
71
+ const sorted = [...value].sort();
72
+ if (value.some((entry, index) => entry !== sorted[index])) {
73
+ violations.push(`Unsorted list: ${rule.file} at ${location}`);
74
+ }
75
+ }
76
+ else {
77
+ value.forEach((entry, index) => visit(entry, `${location}[${index}]`));
78
+ }
79
+ }
80
+ else if (value !== null && typeof value === 'object') {
81
+ for (const [key, entry] of Object.entries(value))
82
+ visit(entry, `${location}.${key}`);
83
+ }
84
+ }
85
+ visit(YAML.parse(fs.readFileSync(path.join(root, rule.file), 'utf8')), '$');
86
+ return violations;
87
+ }
88
+ function documentLinks(root, rule) {
89
+ const document = fs.readFileSync(path.join(root, rule.document), 'utf8');
90
+ const links = new Set();
91
+ for (const match of document.matchAll(/\]\(([^\s)]+)(?:\s+"[^"\n]*")?\)/gu)) {
92
+ const target = match[1].split(/[?#]/u)[0];
93
+ if (!target || /^(?:[a-z][a-z\d+.-]*:|\/)/iu.test(target))
94
+ continue;
95
+ links.add(path.resolve(root, path.dirname(rule.document), decodeURIComponent(target)));
96
+ }
97
+ const violations = missingDirectory(root, rule.files);
98
+ if (violations.length === 0) {
99
+ for (const fileName of selectedFiles(root, rule.files)) {
100
+ if (!links.has(path.resolve(root, fileName))) {
101
+ violations.push(`Missing document link: ${rule.document} -> ${fileName}`);
102
+ }
103
+ }
104
+ }
105
+ return violations;
106
+ }
107
+ function generatedFiles(root, rule, update) {
108
+ const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'conventions-generated-'));
109
+ const output = path.join(temporary, 'output');
110
+ const expected = path.join(root, rule.expected);
111
+ const violations = [];
112
+ try {
113
+ // Updating through a directory symlink could replace files outside this repository.
114
+ let target = root;
115
+ for (const segment of rule.expected.split('/')) {
116
+ target = path.join(target, segment);
117
+ if (fs.lstatSync(target, { throwIfNoEntry: false })?.isSymbolicLink()) {
118
+ throw new Error(`Generated output path must not contain symbolic links: ${rule.expected}`);
119
+ }
120
+ }
121
+ fs.mkdirSync(output);
122
+ const result = spawnSync(rule.run.replaceAll('{output}', () => output), {
123
+ cwd: root, shell: true, encoding: 'utf8',
124
+ env: { ...runtime.env, PATH: path.join(root, 'node_modules/.bin') + path.delimiter + (runtime.env.PATH ?? '') },
125
+ });
126
+ if (result.error)
127
+ throw result.error;
128
+ if (result.status !== 0) {
129
+ violations.push(`Generation failed (exit ${result.status}, signal ${result.signal}): ${result.stdout}${result.stderr}`);
130
+ }
131
+ else if (update) {
132
+ fs.rmSync(expected, { recursive: true, force: true });
133
+ fs.cpSync(output, expected, { recursive: true });
134
+ }
135
+ else if (!fs.existsSync(expected) || !fs.statSync(expected).isDirectory()) {
136
+ violations.push(`Missing expected directory: ${rule.expected}`);
137
+ }
138
+ else {
139
+ const generated = new Set(selectedFiles(output, '**/*'));
140
+ const committed = new Set(selectedFiles(expected, '**/*'));
141
+ for (const name of [...new Set([...generated, ...committed])].sort()) {
142
+ if (!generated.has(name))
143
+ violations.push(`Unexpected expected file: ${rule.expected}/${name}`);
144
+ else if (!committed.has(name))
145
+ violations.push(`Missing expected file: ${rule.expected}/${name}`);
146
+ else if (!fs.readFileSync(path.join(output, name)).equals(fs.readFileSync(path.join(expected, name)))) {
147
+ violations.push(`Generated file differs: ${rule.expected}/${name}`);
148
+ }
149
+ }
150
+ }
151
+ }
152
+ finally {
153
+ fs.rmSync(temporary, { recursive: true, force: true });
154
+ }
155
+ return violations;
156
+ }
157
+ function checkRule(root, rule, update) {
158
+ switch (rule.check) {
159
+ case 'generated-files': return generatedFiles(root, rule, update);
160
+ case 'allowed-files': return allowedFiles(root, rule);
161
+ case 'corresponding-files': return correspondingFiles(root, rule);
162
+ case 'sorted-yaml-lists': return sortedYamlLists(root, rule);
163
+ case 'document-links': return documentLinks(root, rule);
164
+ case 'file-names': return fileNames(root, rule);
165
+ }
166
+ }
167
+ return { checkRule };
168
+ };
@@ -1,4 +1,5 @@
1
- export const porticoFacade = ({ checkTestReceipt, recordTestReceipt, runTests }) => ({
1
+ export const porticoFacade = ({ checkConventions, checkTestReceipt, recordTestReceipt, runTests }) => ({
2
+ checkConventions: checkConventions.run,
2
3
  checkTestReceipt: checkTestReceipt.run,
3
4
  recordTestReceipt: recordTestReceipt.run,
4
5
  runTests: runTests.run,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jakobm/peacekeeper",
3
- "version": "0.25.1",
3
+ "version": "0.26.0",
4
4
  "description": "Shared repository test, Git worktree, and Codex hook commands",
5
5
  "license": "MIT",
6
6
  "author": "Jakob Mattsson",
@@ -43,6 +43,7 @@
43
43
  "@iarna/toml": "^2.2.5",
44
44
  "@jakobm/cmdabra": "^0.7.0",
45
45
  "@jakobm/portico": "^0.8.1",
46
+ "glob": "^14.0.4",
46
47
  "semver": "^7.8.5",
47
48
  "yaml": "^2.9.1"
48
49
  },