@venizia/vulcan 0.4.9-3 → 0.4.9-5

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 (61) hide show
  1. package/base/ci-global.json +13 -0
  2. package/base/claude/commit-attribution.json +7 -0
  3. package/base/claude/events.json +60 -0
  4. package/base/commit-agents.json +41 -0
  5. package/base/hooks/event.ts +37 -0
  6. package/base/rules.md +1 -1
  7. package/base/templates/ci/github-actions.yml +75 -0
  8. package/base/templates/ci/gitlab-ci.yml +52 -0
  9. package/package.json +3 -3
  10. package/src/ci/affected.ts +176 -0
  11. package/src/ci/command.ts +166 -0
  12. package/src/ci/common/constants.ts +76 -0
  13. package/src/ci/common/index.ts +2 -0
  14. package/src/ci/common/types.ts +37 -0
  15. package/src/ci/git.ts +72 -0
  16. package/src/ci/global.ts +48 -0
  17. package/src/ci/graph.ts +43 -0
  18. package/src/ci/index.ts +7 -0
  19. package/src/ci/workspace.ts +119 -0
  20. package/src/commands/ci.command.ts +4 -0
  21. package/src/commands/clean.command.ts +3 -5
  22. package/src/commands/commit-check.command.ts +5 -0
  23. package/src/commands/event.command.ts +5 -0
  24. package/src/commands/help.command.ts +14 -2
  25. package/src/commands/index.ts +28 -27
  26. package/src/commands/sync.command.ts +2 -0
  27. package/src/commit/agents.ts +32 -0
  28. package/src/commit/check.ts +160 -0
  29. package/src/commit/common/constants.ts +28 -0
  30. package/src/commit/common/index.ts +2 -0
  31. package/src/commit/common/types.ts +57 -0
  32. package/src/commit/hook.ts +187 -0
  33. package/src/commit/index.ts +8 -0
  34. package/src/commit/message.ts +74 -0
  35. package/src/commit/policy.ts +110 -0
  36. package/src/commit/signature.ts +94 -0
  37. package/src/commit/subject.ts +40 -0
  38. package/src/common/constants.ts +13 -0
  39. package/src/config/common/constants.ts +1 -0
  40. package/src/config/schema.ts +102 -0
  41. package/src/doctor/checks.ts +129 -7
  42. package/src/doctor/common/constants.ts +2 -0
  43. package/src/doctor/runner.ts +3 -0
  44. package/src/events/actor.ts +116 -0
  45. package/src/events/command.ts +191 -0
  46. package/src/events/common/constants.ts +118 -0
  47. package/src/events/common/index.ts +2 -0
  48. package/src/events/common/types.ts +39 -0
  49. package/src/events/flow.ts +92 -0
  50. package/src/events/hook.ts +163 -0
  51. package/src/events/index.ts +8 -0
  52. package/src/events/log.ts +162 -0
  53. package/src/events/settings.ts +80 -0
  54. package/src/events/text.ts +49 -0
  55. package/src/local/constants.ts +36 -1
  56. package/src/local/scan.ts +256 -27
  57. package/src/manifest/render.ts +42 -0
  58. package/src/router.ts +47 -7
  59. package/src/sync/common/constants.ts +3 -0
  60. package/src/sync/local-choice.ts +3 -3
  61. package/src/sync/planner.ts +20 -1
@@ -0,0 +1,13 @@
1
+ {
2
+ "files": [
3
+ "bun.lock",
4
+ "bun.lockb",
5
+ "package.json",
6
+ "bunfig.toml",
7
+ "tsconfig*.json",
8
+ ".configs/**",
9
+ ".github/workflows/**",
10
+ ".gitlab-ci.yml",
11
+ ".gitlab/**"
12
+ ]
13
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "attribution": {
3
+ "commit": "",
4
+ "pr": "",
5
+ "sessionUrl": false
6
+ }
7
+ }
@@ -0,0 +1,60 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "f=\"${CLAUDE_PROJECT_DIR:-$PWD}/node_modules/@venizia/vulcan/base/hooks/event.ts\"; if [ -f \"$f\" ] && command -v bun >/dev/null 2>&1; then bun \"$f\"; fi; exit 0",
9
+ "timeout": 5
10
+ }
11
+ ]
12
+ }
13
+ ],
14
+ "Stop": [
15
+ {
16
+ "hooks": [
17
+ {
18
+ "type": "command",
19
+ "command": "f=\"${CLAUDE_PROJECT_DIR:-$PWD}/node_modules/@venizia/vulcan/base/hooks/event.ts\"; if [ -f \"$f\" ] && command -v bun >/dev/null 2>&1; then bun \"$f\"; fi; exit 0",
20
+ "timeout": 5
21
+ }
22
+ ]
23
+ }
24
+ ],
25
+ "SubagentStop": [
26
+ {
27
+ "hooks": [
28
+ {
29
+ "type": "command",
30
+ "command": "f=\"${CLAUDE_PROJECT_DIR:-$PWD}/node_modules/@venizia/vulcan/base/hooks/event.ts\"; if [ -f \"$f\" ] && command -v bun >/dev/null 2>&1; then bun \"$f\"; fi; exit 0",
31
+ "timeout": 5
32
+ }
33
+ ]
34
+ }
35
+ ],
36
+ "Notification": [
37
+ {
38
+ "hooks": [
39
+ {
40
+ "type": "command",
41
+ "command": "f=\"${CLAUDE_PROJECT_DIR:-$PWD}/node_modules/@venizia/vulcan/base/hooks/event.ts\"; if [ -f \"$f\" ] && command -v bun >/dev/null 2>&1; then bun \"$f\"; fi; exit 0",
42
+ "timeout": 5
43
+ }
44
+ ]
45
+ }
46
+ ],
47
+ "PostToolUse": [
48
+ {
49
+ "matcher": "SendMessage",
50
+ "hooks": [
51
+ {
52
+ "type": "command",
53
+ "command": "f=\"${CLAUDE_PROJECT_DIR:-$PWD}/node_modules/@venizia/vulcan/base/hooks/event.ts\"; if [ -f \"$f\" ] && command -v bun >/dev/null 2>&1; then bun \"$f\"; fi; exit 0",
54
+ "timeout": 5
55
+ }
56
+ ]
57
+ }
58
+ ]
59
+ }
60
+ }
@@ -0,0 +1,41 @@
1
+ {
2
+ "products": [
3
+ "claude code",
4
+ "claude opus",
5
+ "claude sonnet",
6
+ "claude haiku",
7
+ "claude agent",
8
+ "chatgpt",
9
+ "gpt",
10
+ "openai codex",
11
+ "codex",
12
+ "github copilot",
13
+ "copilot",
14
+ "cursor agent",
15
+ "gemini code assist",
16
+ "gemini cli",
17
+ "google gemini"
18
+ ],
19
+ "mentions": [
20
+ "claude",
21
+ "anthropic",
22
+ "codex",
23
+ "openai",
24
+ "chatgpt",
25
+ "gpt",
26
+ "gemini",
27
+ "copilot",
28
+ "cursor"
29
+ ],
30
+ "addressNames": [
31
+ "claude",
32
+ "codex",
33
+ "copilot",
34
+ "chatgpt",
35
+ "cursoragent",
36
+ "gemini-code-assist[bot]"
37
+ ],
38
+ "addressDomains": ["anthropic.com", "openai.com", "google.com", "cursor.com", "github.com"],
39
+ "noreplyDomains": ["anthropic.com", "openai.com", "google.com"],
40
+ "generatedPhrases": ["generated with", "generated by"]
41
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Event log hook (SessionStart, Stop, SubagentStop, Notification, PostToolUse on SendMessage): appends one
3
+ * line to the agent event log (src/events/hook.ts) when the manifest says `events.log` is on. It stores
4
+ * names and short labels only - never a message body, the last reply, a command or a file path.
5
+ *
6
+ * It fails OPEN and says nothing on stdout: input it cannot read, a missing module or a write that fails
7
+ * pass with a note on stderr, and the agent is never held. It imports only the events module, no config and
8
+ * no zod, because it runs on every session event. `VULCAN_GUARDS=off` switches it off.
9
+ */
10
+
11
+ // A module, so the awaits below are top-level; it has no static import, by design.
12
+ export {};
13
+
14
+ if (process.env.VULCAN_GUARDS === 'off') {
15
+ process.exit(0);
16
+ }
17
+
18
+ try {
19
+ const { EventHook } = await import('../../src/events/hook.ts');
20
+ const stdin = await Bun.stdin.text();
21
+
22
+ EventHook.run({
23
+ root: process.env.CLAUDE_PROJECT_DIR ?? process.cwd(),
24
+ input: JSON.parse(stdin),
25
+ env: process.env,
26
+ });
27
+ } catch (error) {
28
+ // Input that is not JSON is not echoed: Bun's parse error quotes it.
29
+ const reason =
30
+ error instanceof SyntaxError
31
+ ? 'unreadable input'
32
+ : error instanceof Error
33
+ ? error.message
34
+ : String(error);
35
+
36
+ console.error(`vulcan: the event hook failed (${reason}) - the event is not logged`);
37
+ }
package/base/rules.md CHANGED
@@ -74,7 +74,7 @@ An ID the base drops is never reused.
74
74
  | V-C-06 | **Never a silent catch - log it.** Always braces. Early return. `switch` with `default` over a long if-else chain. Strict TypeScript; no `any` where a type exists. | LINT (braces, floating promises) + SOFT |
75
75
  | V-C-07 | **A function name opens with its verb** - `generate` `build` `to` `is` `has` `assert` `extract` `enrich` `get` `resolve`. `is*` returns a boolean and leaves the branch to the caller; `assert*` throws and returns `void`, so the code after it needs none - reach for `assert*` when every caller would throw on `false` anyway. `has*` is the ownership question (`hasBucket`, never `isBucketExists`). That list is for UTILITY functions; service methods lean on a wider set. **Arrow functions, not `function` declarations** (do not churn existing ones). State plus the operations on it live in a class with static members - the `LoggerFactory` shape - never module-level `let` plus exported arrows. | SOFT |
76
76
  | V-C-08 | **Enumerable strings are a const class plus `TConstValue`,** never a raw string-literal union. When something validates against such a class, it carries `static readonly SCHEME_SET = new Set([...])` over its values and `static isValid(value: string): boolean` reading it, so a runtime check exists wherever a value crosses a boundary (`IsolationLevels` in connectors is the model; a subclass redeclares `SCHEME_SET` with `...Parent.SCHEME_SET` first); a class nothing validates against needs neither. The `T`/`I` prefix follows the declaration keyword: `type` gets `T`, `interface` gets `I`; an interface turned into a type alias is renamed, and no tool catches it - grep both directions. | SOFT |
77
- | V-C-09 | **Comments state only a constraint the code cannot show** - one to three lines; no history, no dates, no decision notes, no restating the code - the one exception is the `// SHORTCUT:` marker of V-B-07. Most code needs none. | SOFT |
77
+ | V-C-09 | **Comments state only a lasting fact the code cannot show** - a constraint, an external contract, a non-obvious invariant; one to three lines; no history, no dates, no decision or review notes, no restating the code. An exported declaration may carry a short JSDoc: one summary line, `@param`/`@returns` without `{type}`. Machine directives stay. The one other exception is the `// SHORTCUT:` marker of V-B-07. Most code needs none; remove a meaningless comment in the lines you touch. | SOFT |
78
78
  | V-C-10 | **No explicit cast in new code.** `as X`, `as any`, `as unknown as X` and `as never` assert nothing; they silence the compiler where the type is wrong. Fix the type instead: a generic on the setter, a narrower parameter, a typed helper, `satisfies`. A pre-existing cast is removed when the line is touched, never copied. Generic parameters are full words (`ApplicationType`, `TDocument`), never `App` or `TDoc` (V-C-04). | SOFT |
79
79
  | V-C-11 | **SIMPLE FIRST, in code and in prose.** Fewest concepts, plainest words, smallest surface. Complexity must buy correctness, speed or safety the simple version cannot, and the artifact says what it bought. Something a reader cannot follow in one pass is a defect even when it works. Fix the root cause with the smallest change; never layer an abstraction on a misdiagnosed problem. Small means the code holds only what the task needs - not golfed: no clever one-liners to save lines, and no code for a need nobody has yet. | SOFT |
80
80
  | V-C-12 | **Consistent, never self-invented.** Before writing anything new - a constant, file, binding key, error shape - find the nearest precedent in this repo and copy its shape. Binding keys are namespaced (`controllers.X`, `services.X`, `repositories.X`, `datasources.X`). Every scope is one folder with nested `common/{types,constants}.ts` and an index barrel (`inversion` is the model). A second style for something that already has one is a defect. | SOFT |
@@ -0,0 +1,75 @@
1
+ # Runs, for each package a change touches, only the checks that package has.
2
+ # `vulcan ci affected` lists the packages: the ones whose files changed, and every package that depends on them.
3
+ # A change to a lockfile, bunfig.toml, a root tsconfig, .configs/ or a workflow file runs everything.
4
+ name: Checks
5
+
6
+ on:
7
+ pull_request:
8
+ branches: [develop, main]
9
+ push:
10
+ branches: [develop]
11
+
12
+ permissions:
13
+ contents: read
14
+
15
+ concurrency:
16
+ group: checks-${{ github.event.pull_request.number || github.ref }}
17
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
18
+
19
+ jobs:
20
+ affected:
21
+ name: Affected packages
22
+ runs-on: ubuntu-latest
23
+ outputs:
24
+ matrix: ${{ steps.affected.outputs.matrix }}
25
+ steps:
26
+ - name: Checkout
27
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
28
+ with:
29
+ # The base commit must be in the clone; a shallow one has not got it.
30
+ fetch-depth: 0
31
+
32
+ - name: Setup Bun
33
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
34
+
35
+ - name: Install
36
+ run: bun install --frozen-lockfile
37
+
38
+ - name: List the affected packages
39
+ id: affected
40
+ # bash, so that a failing command in the pipe below fails the step.
41
+ shell: bash
42
+ env:
43
+ # A pull request compares with its base; a push compares with the commit before it.
44
+ BASE: ${{ github.event.pull_request.base.sha || github.event.before }}
45
+ run: |
46
+ matrix=$(bun x --no-install vulcan ci affected --base "$BASE" --json \
47
+ | jq -c '{include: [.packages[] | .name as $package | .checks | to_entries[] | {package: $package, check: .key}]}')
48
+ echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
49
+ echo "$matrix"
50
+
51
+ check:
52
+ name: ${{ matrix.package }} ${{ matrix.check }}
53
+ needs: affected
54
+ # A matrix with no entry is an error, so a change that touches no package skips this job.
55
+ if: ${{ fromJSON(needs.affected.outputs.matrix).include[0] != null }}
56
+ runs-on: ubuntu-latest
57
+ strategy:
58
+ fail-fast: false
59
+ matrix: ${{ fromJSON(needs.affected.outputs.matrix) }}
60
+ steps:
61
+ - name: Checkout
62
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
63
+
64
+ - name: Setup Bun
65
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
66
+
67
+ - name: Install
68
+ run: bun install --frozen-lockfile
69
+
70
+ - name: Run the check
71
+ # The package name comes from a pull request: it reaches the shell as a variable, never as text of the script.
72
+ env:
73
+ PKG: ${{ matrix.package }}
74
+ CHECK: ${{ matrix.check }}
75
+ run: bun run --filter "$PKG" "$CHECK"
@@ -0,0 +1,52 @@
1
+ # Runs, for each package a change touches, only the checks that package has.
2
+ # `vulcan ci affected` lists the packages: the ones whose files changed, and every package that depends on them.
3
+ # A change to a lockfile, bunfig.toml, a root tsconfig, .configs/ or a workflow file runs everything.
4
+
5
+ workflow:
6
+ rules:
7
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event"
8
+ - if: $CI_COMMIT_BRANCH == "develop"
9
+
10
+ variables:
11
+ # The base commit must be in the clone; a shallow one has not got it.
12
+ GIT_DEPTH: '0'
13
+
14
+ .affected:
15
+ image: oven/bun:1
16
+ rules:
17
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event"
18
+ - if: $CI_COMMIT_BRANCH == "develop"
19
+ variables:
20
+ CHECK: ''
21
+ before_script:
22
+ - command -v git >/dev/null || (apt-get update -qq && apt-get install -y -qq git)
23
+ - bun install --frozen-lockfile
24
+ script:
25
+ # A merge request compares with the commit it branched from; a push to develop with the commit before it.
26
+ - base="${CI_MERGE_REQUEST_DIFF_BASE_SHA:-$CI_COMMIT_BEFORE_SHA}"
27
+ - |
28
+ names=$(bun x --no-install vulcan ci affected --base "$base" --check "$CHECK" --names)
29
+ if [ -z "$names" ]; then echo "no affected package has $CHECK"; exit 0; fi
30
+ printf '%s\n' "$names" | while IFS= read -r name; do
31
+ bun run --filter "$name" "$CHECK" || exit 1
32
+ done
33
+
34
+ typecheck:
35
+ extends: .affected
36
+ variables:
37
+ CHECK: typecheck
38
+
39
+ lint:
40
+ extends: .affected
41
+ variables:
42
+ CHECK: lint
43
+
44
+ test:
45
+ extends: .affected
46
+ variables:
47
+ CHECK: test
48
+
49
+ compile:
50
+ extends: .affected
51
+ variables:
52
+ CHECK: compile
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/vulcan",
3
- "version": "0.4.9-3",
3
+ "version": "0.4.9-5",
4
4
  "description": "VULCAN - one setup, one workflow for every project: init, sync, doctor, upgrade, and `vulcan x` for the shipped tools. Bun-only.",
5
5
  "homepage": "https://github.com/VENIZIA-AI/vulcan/tree/main/packages/cli",
6
6
  "bugs": {
@@ -44,8 +44,8 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@clack/prompts": "1.8.1",
47
- "@venizia/vulcan-atlas": "0.4.9-3",
48
- "@venizia/vulcan-okf": "0.4.9-3",
47
+ "@venizia/vulcan-atlas": "0.4.9-5",
48
+ "@venizia/vulcan-okf": "0.4.9-5",
49
49
  "zod": "^4.6.7"
50
50
  },
51
51
  "devDependencies": {
@@ -0,0 +1,176 @@
1
+ import { AffectedReasons, CiChecks, CiConstants } from './common/index.ts';
2
+ import type {
3
+ IAffectedPackage,
4
+ IAffectedResult,
5
+ IWorkspacePackage,
6
+ TAffectedReason,
7
+ TCiCheck,
8
+ } from './common/index.ts';
9
+ import { CiGit } from './git.ts';
10
+ import { CiGlobal } from './global.ts';
11
+ import { CiGraph } from './graph.ts';
12
+ import { CiWorkspace } from './workspace.ts';
13
+
14
+ type TAffectedRun = { ok: true; result: IAffectedResult } | { ok: false; error: string };
15
+
16
+ /** Which packages a change touches. */
17
+ export class CiAffected {
18
+ /**
19
+ * Reads the workspace of the checked-out tree and the files that differ between `base` and `head`,
20
+ * and says which packages are affected. `head` must be the commit that is checked out, because the
21
+ * packages and their dependencies are read from the files on disk. A base of only zeros, what a
22
+ * pipeline passes for a branch with no parent, has nothing to compare with: every package is affected.
23
+ */
24
+ static run(opts: { root: string; base: string; head: string }): TAffectedRun {
25
+ const workspace = CiWorkspace.read({ root: opts.root });
26
+
27
+ if (!workspace.ok) {
28
+ return workspace;
29
+ }
30
+
31
+ const globs = CiGlobal.read({ root: opts.root });
32
+
33
+ if (CiConstants.EMPTY_BASE.test(opts.base)) {
34
+ return {
35
+ ok: true,
36
+ result: CiAffected.build({
37
+ base: opts.base,
38
+ head: opts.head,
39
+ packages: workspace.packages,
40
+ selection: {
41
+ all: true,
42
+ because: 'the base is empty (a new branch): nothing to compare with',
43
+ reached: new Map(),
44
+ },
45
+ }),
46
+ };
47
+ }
48
+
49
+ const head = CiGit.resolve({ root: opts.root, ref: opts.head });
50
+ const base = CiGit.resolve({ root: opts.root, ref: opts.base });
51
+ const checkedOut = CiGit.resolve({ root: opts.root, ref: 'HEAD' });
52
+
53
+ if (!head.ok || !base.ok || !checkedOut.ok) {
54
+ return {
55
+ ok: false,
56
+ error:
57
+ [head, base, checkedOut].flatMap((step) => (step.ok ? [] : [step.error]))[0] ??
58
+ 'git failed',
59
+ };
60
+ }
61
+
62
+ if (head.stdout !== checkedOut.stdout) {
63
+ return {
64
+ ok: false,
65
+ error: `--head ${opts.head} is not the checked-out commit: the packages are read from the files on disk, so check ${opts.head} out first`,
66
+ };
67
+ }
68
+
69
+ const changes = CiGit.changedFiles({ root: opts.root, base: base.stdout, head: head.stdout });
70
+
71
+ if (!changes.ok) {
72
+ return changes;
73
+ }
74
+
75
+ return {
76
+ ok: true,
77
+ result: CiAffected.build({
78
+ base: base.stdout,
79
+ head: head.stdout,
80
+ packages: workspace.packages,
81
+ selection: CiAffected.select({
82
+ packages: workspace.packages,
83
+ files: changes.files,
84
+ globs,
85
+ }),
86
+ }),
87
+ };
88
+ }
89
+
90
+ /**
91
+ * The packages a set of changed files touches. Everything is affected when a file matches `globs` or the
92
+ * otherwise a package is affected when one of its files changed or when a package it depends on is.
93
+ */
94
+ static select(opts: { packages: IWorkspacePackage[]; files: string[]; globs: string[] }): {
95
+ all: boolean;
96
+ because?: string;
97
+ reached: Map<string, TAffectedReason>;
98
+ } {
99
+ const hit = CiGlobal.firstHit({ files: opts.files, globs: opts.globs });
100
+
101
+ if (hit !== undefined) {
102
+ return { all: true, because: hit, reached: new Map() };
103
+ }
104
+
105
+ const seeds = new Map<string, TAffectedReason>();
106
+
107
+ for (const file of opts.files) {
108
+ const owner = CiAffected.ownerOf({ packages: opts.packages, file });
109
+
110
+ if (owner !== undefined) {
111
+ seeds.set(owner.name, AffectedReasons.CHANGED);
112
+ }
113
+ }
114
+
115
+ return { all: false, reached: CiGraph.closure({ packages: opts.packages, seeds }) };
116
+ }
117
+
118
+ /** The package whose folder holds `file`: the deepest one when folders nest. */
119
+ private static ownerOf(opts: {
120
+ packages: IWorkspacePackage[];
121
+ file: string;
122
+ }): IWorkspacePackage | undefined {
123
+ let owner: IWorkspacePackage | undefined;
124
+
125
+ for (const entry of opts.packages) {
126
+ const isInside = opts.file === entry.dir || opts.file.startsWith(`${entry.dir}/`);
127
+
128
+ if (isInside && (owner === undefined || entry.dir.length > owner.dir.length)) {
129
+ owner = entry;
130
+ }
131
+ }
132
+
133
+ return owner;
134
+ }
135
+
136
+ private static build(opts: {
137
+ base: string;
138
+ head: string;
139
+ packages: IWorkspacePackage[];
140
+ selection: { all: boolean; because?: string; reached: Map<string, TAffectedReason> };
141
+ }): IAffectedResult {
142
+ const { selection } = opts;
143
+ const listed: IAffectedPackage[] = opts.packages
144
+ .filter((entry) => selection.all || selection.reached.has(entry.name))
145
+ .map((entry) => ({
146
+ name: entry.name,
147
+ dir: entry.dir,
148
+ reason: selection.all
149
+ ? AffectedReasons.GLOBAL
150
+ : (selection.reached.get(entry.name) ?? AffectedReasons.CHANGED),
151
+ checks: CiAffected.checksOf({ scripts: entry.scripts }),
152
+ }))
153
+ .sort((left, right) => left.name.localeCompare(right.name));
154
+
155
+ return {
156
+ base: opts.base,
157
+ head: opts.head,
158
+ all: selection.all,
159
+ ...(selection.all && selection.because !== undefined
160
+ ? { allBecause: selection.because }
161
+ : {}),
162
+ packages: listed,
163
+ };
164
+ }
165
+
166
+ /** The checks a package has: each standard script it defines, by the name that runs it. */
167
+ private static checksOf(opts: {
168
+ scripts: Record<string, string>;
169
+ }): Partial<Record<TCiCheck, string>> {
170
+ return Object.fromEntries(
171
+ [...CiChecks.SCHEME_SET]
172
+ .filter((check) => Object.hasOwn(opts.scripts, check))
173
+ .map((check) => [check, check]),
174
+ );
175
+ }
176
+ }
@@ -0,0 +1,166 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { BASE_DIRECTORY } from '../common/paths.ts';
4
+ import { ExitCodes } from '../common/index.ts';
5
+ import type { ICommandContext } from '../common/index.ts';
6
+ import { CiAffected } from './affected.ts';
7
+ import { CiChecks, CiConstants, CiFlags, CiSubcommands, CiTemplates } from './common/index.ts';
8
+ import type { IAffectedResult, TCiCheck } from './common/index.ts';
9
+
10
+ const USAGE = `usage: vulcan ci affected ${CiFlags.BASE} <ref> [${CiFlags.HEAD} <ref>] [${CiFlags.CHECK} <check>] [${CiFlags.JSON} | ${CiFlags.NAMES}]
11
+ vulcan ci template <${[...CiTemplates.SCHEME_SET].join('|')}>
12
+ checks: ${[...CiChecks.SCHEME_SET].join(', ')}`;
13
+
14
+ /** `vulcan ci`: which packages a change touches, and the CI templates that call it. */
15
+ export class CiCommand {
16
+ static async run(opts: ICommandContext): Promise<number> {
17
+ const [subcommand, ...rest] = opts.args;
18
+
19
+ if (subcommand === CiSubcommands.TEMPLATE) {
20
+ return CiCommand.template({ args: rest });
21
+ }
22
+
23
+ if (subcommand === CiSubcommands.AFFECTED) {
24
+ return CiCommand.affected({ cwd: opts.cwd, args: rest });
25
+ }
26
+
27
+ process.stderr.write(`ci: ${USAGE}\n`);
28
+
29
+ return ExitCodes.USAGE;
30
+ }
31
+
32
+ private static template(opts: { args: string[] }): number {
33
+ const [name, ...extra] = opts.args;
34
+
35
+ if (name === undefined || extra.length > 0 || !CiTemplates.isValid(name)) {
36
+ process.stderr.write(`ci: ${USAGE}\n`);
37
+
38
+ return ExitCodes.USAGE;
39
+ }
40
+
41
+ process.stdout.write(
42
+ readFileSync(
43
+ join(BASE_DIRECTORY, CiConstants.TEMPLATE_FOLDER, CiTemplates.FILES[name]),
44
+ 'utf8',
45
+ ),
46
+ );
47
+
48
+ return ExitCodes.OK;
49
+ }
50
+
51
+ private static affected(opts: { cwd: string; args: string[] }): number {
52
+ const parsed = CiCommand.parse({ args: opts.args });
53
+
54
+ if (!parsed.ok) {
55
+ process.stderr.write(`ci: ${parsed.error}\n${USAGE}\n`);
56
+
57
+ return ExitCodes.USAGE;
58
+ }
59
+
60
+ const { base, head, check, json, names } = parsed;
61
+ const run = CiAffected.run({ root: opts.cwd, base, head });
62
+
63
+ if (!run.ok) {
64
+ process.stderr.write(`ci: ${run.error}\n`);
65
+
66
+ return ExitCodes.USAGE;
67
+ }
68
+
69
+ const result: IAffectedResult =
70
+ check === undefined
71
+ ? run.result
72
+ : {
73
+ ...run.result,
74
+ packages: run.result.packages.filter((entry) => entry.checks[check] !== undefined),
75
+ };
76
+
77
+ if (json) {
78
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
79
+ } else if (names) {
80
+ process.stdout.write(result.packages.map((entry) => `${entry.name}\n`).join(''));
81
+ } else {
82
+ process.stdout.write(CiCommand.format({ result }));
83
+ }
84
+
85
+ return ExitCodes.OK;
86
+ }
87
+
88
+ private static parse(opts: { args: string[] }):
89
+ | {
90
+ ok: true;
91
+ base: string;
92
+ head: string;
93
+ check: TCiCheck | undefined;
94
+ json: boolean;
95
+ names: boolean;
96
+ }
97
+ | { ok: false; error: string } {
98
+ const values: Record<string, string> = {};
99
+ let json = false;
100
+ let names = false;
101
+
102
+ for (let index = 0; index < opts.args.length; index++) {
103
+ const arg = opts.args[index];
104
+
105
+ if (arg === CiFlags.JSON) {
106
+ json = true;
107
+ continue;
108
+ }
109
+
110
+ if (arg === CiFlags.NAMES) {
111
+ names = true;
112
+ continue;
113
+ }
114
+
115
+ const value = opts.args[index + 1];
116
+
117
+ if (value === undefined || Object.hasOwn(values, arg) || value.startsWith('-')) {
118
+ return { ok: false, error: `${arg} needs a value, once` };
119
+ }
120
+
121
+ values[arg] = value;
122
+ index++;
123
+ }
124
+
125
+ const base = values[CiFlags.BASE];
126
+ const check = values[CiFlags.CHECK];
127
+
128
+ if (base === undefined) {
129
+ return { ok: false, error: `${CiFlags.BASE} is required` };
130
+ }
131
+
132
+ if (json && names) {
133
+ return { ok: false, error: `${CiFlags.JSON} and ${CiFlags.NAMES} cannot be combined` };
134
+ }
135
+
136
+ if (check !== undefined && !CiChecks.isValid(check)) {
137
+ return {
138
+ ok: false,
139
+ error: `${CiFlags.CHECK} must be one of ${[...CiChecks.SCHEME_SET].join(', ')}`,
140
+ };
141
+ }
142
+
143
+ return {
144
+ ok: true,
145
+ base,
146
+ head: values[CiFlags.HEAD] ?? 'HEAD',
147
+ check: check as TCiCheck | undefined,
148
+ json,
149
+ names,
150
+ };
151
+ }
152
+
153
+ private static format(opts: { result: IAffectedResult }): string {
154
+ const { result } = opts;
155
+ const header =
156
+ result.all && result.allBecause !== undefined
157
+ ? `all packages are affected: ${result.allBecause}\n`
158
+ : '';
159
+ const rows = result.packages.map(
160
+ (entry) =>
161
+ `${entry.name} ${entry.dir} ${entry.reason} ${Object.keys(entry.checks).join(',') || '-'}\n`,
162
+ );
163
+
164
+ return `${header}${rows.join('')}`;
165
+ }
166
+ }