@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,160 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { ExitCodes } from '../common/index.ts';
4
+ import type { ICommandContext } from '../common/index.ts';
5
+ import { AgentSignaturePolicies, CommitCheckFlags } from './common/index.ts';
6
+ import type { ICommentStyle, ICommitPolicy } from './common/index.ts';
7
+ import { CommitMessage } from './message.ts';
8
+ import { CommitPolicy } from './policy.ts';
9
+ import { AgentSignature } from './signature.ts';
10
+ import { SubjectShape } from './subject.ts';
11
+
12
+ const USAGE = `usage: vulcan commit-check <message-file> | ${CommitCheckFlags.RANGE} <revs> | ${CommitCheckFlags.TEXT} <message>`;
13
+
14
+ interface ICheckedMessage {
15
+ label: string;
16
+ message: string;
17
+ }
18
+
19
+ type TSource =
20
+ | { kind: 'file'; value: string }
21
+ | { kind: 'text'; value: string }
22
+ | { kind: 'range'; value: string };
23
+
24
+ type TMessages = { ok: true; messages: ICheckedMessage[] } | { ok: false; error: string };
25
+
26
+ export class CommitCheck {
27
+ static async run(opts: ICommandContext): Promise<number> {
28
+ const source = CommitCheck.sourceOf({ args: opts.args });
29
+
30
+ if (source === undefined) {
31
+ process.stderr.write(`commit-check: ${USAGE}\n`);
32
+
33
+ return ExitCodes.USAGE;
34
+ }
35
+
36
+ const input = CommitCheck.readMessages({ cwd: opts.cwd, source });
37
+
38
+ if (!input.ok) {
39
+ process.stderr.write(`commit-check: ${input.error}\n`);
40
+
41
+ return ExitCodes.USAGE;
42
+ }
43
+
44
+ const policy = CommitPolicy.read({ root: opts.cwd });
45
+
46
+ if (policy === undefined) {
47
+ process.stderr.write(
48
+ 'commit-check: no commit check is configured (commit.message in .configs/vulcan.config.mts); nothing checked\n',
49
+ );
50
+
51
+ return ExitCodes.OK;
52
+ }
53
+
54
+ const comment = CommitMessage.commentStyleOf({ cwd: opts.cwd });
55
+ const problems = input.messages.flatMap((checked) =>
56
+ CommitCheck.problemsOf({ checked, policy, comment }),
57
+ );
58
+
59
+ if (problems.length === 0) {
60
+ return ExitCodes.OK;
61
+ }
62
+
63
+ process.stderr.write(
64
+ `commit-check: ${problems.length} problem(s) in the commit message:\n${problems.join('\n')}\n`,
65
+ );
66
+
67
+ return ExitCodes.FAILURE;
68
+ }
69
+
70
+ private static sourceOf(opts: { args: string[] }): TSource | undefined {
71
+ const [first, second, ...rest] = opts.args;
72
+
73
+ if (first === CommitCheckFlags.TEXT && second !== undefined && rest.length === 0) {
74
+ return { kind: 'text', value: second };
75
+ }
76
+
77
+ if (first === CommitCheckFlags.RANGE && second !== undefined && rest.length === 0) {
78
+ return { kind: 'range', value: second };
79
+ }
80
+
81
+ return first !== undefined && !first.startsWith('--') && second === undefined
82
+ ? { kind: 'file', value: first }
83
+ : undefined;
84
+ }
85
+
86
+ private static problemsOf(opts: {
87
+ checked: ICheckedMessage;
88
+ policy: ICommitPolicy;
89
+ comment: ICommentStyle;
90
+ }): string[] {
91
+ const { checked, policy, comment } = opts;
92
+ const signed =
93
+ policy.agentSignature === AgentSignaturePolicies.DENY
94
+ ? AgentSignature.find({ message: checked.message, agents: policy.agents, comment }).map(
95
+ (hit) =>
96
+ ` ${checked.label} line ${hit.line}: "${hit.text}" signs the commit as an agent; remove the line`,
97
+ )
98
+ : [];
99
+ const shape =
100
+ policy.subject === undefined
101
+ ? undefined
102
+ : SubjectShape.problemOf({ message: checked.message, subject: policy.subject, comment });
103
+
104
+ return shape === undefined
105
+ ? signed
106
+ : [
107
+ ...signed,
108
+ ` ${checked.label} line ${shape.line}: "${shape.text}" does not match the shape ${policy.subject?.pattern}${shape.hint === undefined ? '' : ` (${shape.hint})`}`,
109
+ ];
110
+ }
111
+
112
+ private static readMessages(opts: { cwd: string; source: TSource }): TMessages {
113
+ const { kind, value } = opts.source;
114
+
115
+ if (kind === 'text') {
116
+ return { ok: true, messages: [{ label: 'message,', message: value }] };
117
+ }
118
+
119
+ if (kind === 'range') {
120
+ return CommitCheck.readRange({ cwd: opts.cwd, range: value });
121
+ }
122
+
123
+ try {
124
+ return {
125
+ ok: true,
126
+ messages: [{ label: 'commit message,', message: readFileSync(value, 'utf8') }],
127
+ };
128
+ } catch (error) {
129
+ return {
130
+ ok: false,
131
+ error: `cannot read ${value}: ${error instanceof Error ? error.message : String(error)}`,
132
+ };
133
+ }
134
+ }
135
+
136
+ private static readRange(opts: { cwd: string; range: string }): TMessages {
137
+ const result = spawnSync(
138
+ 'git',
139
+ ['log', '--format=%h%x01%B%x00', '--end-of-options', opts.range],
140
+ { cwd: opts.cwd, encoding: 'utf8' },
141
+ );
142
+
143
+ if (result.status !== 0) {
144
+ return { ok: false, error: `git log ${opts.range} failed: ${result.stderr.trim()}` };
145
+ }
146
+
147
+ return {
148
+ ok: true,
149
+ messages: result.stdout
150
+ .split('\x00')
151
+ .map((chunk) => chunk.replace(/^\n/, ''))
152
+ .filter((chunk) => chunk.trim() !== '')
153
+ .map((chunk) => {
154
+ const [id, ...body] = chunk.split('\x01');
155
+
156
+ return { label: `commit ${id},`, message: body.join('\x01') };
157
+ }),
158
+ };
159
+ }
160
+ }
@@ -0,0 +1,28 @@
1
+ export class AgentSignaturePolicies {
2
+ static readonly ALLOW = 'allow';
3
+ static readonly DENY = 'deny';
4
+
5
+ static readonly SCHEME_SET = new Set<string>([this.ALLOW, this.DENY]);
6
+
7
+ static isValid(value: string): boolean {
8
+ return this.SCHEME_SET.has(value);
9
+ }
10
+ }
11
+
12
+ export class CommitCheckFlags {
13
+ static readonly RANGE = '--range';
14
+ static readonly TEXT = '--text';
15
+ }
16
+
17
+ export class CommitHookStates {
18
+ static readonly OFF = 'off';
19
+ static readonly NOT_GIT = 'not-git';
20
+ static readonly MISSING = 'missing';
21
+ /** The hook calls `vulcan commit-check`: ours and current, or the developer's own wiring. */
22
+ static readonly WIRED = 'wired';
23
+ static readonly STALE = 'stale';
24
+ /** A hook that is not ours and does not call the check: the developer adds the line. */
25
+ static readonly UNWIRED = 'unwired';
26
+ /** Our hook, and the project turned every check off: sync takes it back. */
27
+ static readonly LEFTOVER = 'leftover';
28
+ }
@@ -0,0 +1,2 @@
1
+ export * from './constants.ts';
2
+ export * from './types.ts';
@@ -0,0 +1,57 @@
1
+ import type { TConstValue } from '../../common/index.ts';
2
+ import type { AgentSignaturePolicies, CommitHookStates } from './constants.ts';
3
+
4
+ export type TAgentSignaturePolicy = TConstValue<typeof AgentSignaturePolicies>;
5
+
6
+ export interface ICommitAgents {
7
+ /** Names that begin a co-author's name when an agent made the commit: "Claude Code", "Cursor Agent". */
8
+ products: string[];
9
+ /** Words a "generated with" line names an agent by: "Claude", "Gemini". */
10
+ mentions: string[];
11
+ /** Local parts that name an agent: `cursoragent`, on an address at one of `addressDomains`. */
12
+ addressNames: string[];
13
+ addressDomains: string[];
14
+ noreplyDomains: string[];
15
+ generatedPhrases: string[];
16
+ /** Names the project says are never an agent (a person called Claude). */
17
+ allow: string[];
18
+ }
19
+
20
+ /** `line` counts from 1. */
21
+ export interface ISignatureHit {
22
+ line: number;
23
+ text: string;
24
+ }
25
+
26
+ /** `pattern` is a regular expression source. */
27
+ export interface ICommitSubject {
28
+ pattern: string;
29
+ hint?: string;
30
+ }
31
+
32
+ export interface ISubjectProblem {
33
+ line: number;
34
+ text: string;
35
+ hint: string | undefined;
36
+ }
37
+
38
+ export interface ICommitPolicy {
39
+ agentSignature: TAgentSignaturePolicy;
40
+ agents: ICommitAgents;
41
+ subject?: ICommitSubject;
42
+ }
43
+
44
+ export type TCommitHookState = TConstValue<typeof CommitHookStates>;
45
+
46
+ export interface ICommitHookStatus {
47
+ state: TCommitHookState;
48
+ /** Empty when the folder is not a git repository. */
49
+ path: string;
50
+ /** What the developer does when sync cannot: the line to add to a hook that is theirs. */
51
+ note?: string;
52
+ }
53
+
54
+ /** The prefixes git treats as comment lines, and as the start of the scissors line. */
55
+ export interface ICommentStyle {
56
+ prefixes: string[];
57
+ }
@@ -0,0 +1,187 @@
1
+ import { chmodSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname, resolve } from 'node:path';
3
+ import type { TResolvedConfig } from '../config/index.ts';
4
+ import type { ISyncAction } from '../sync/common/index.ts';
5
+ import { SyncStatuses } from '../sync/common/index.ts';
6
+ import { AgentSignaturePolicies, CommitHookStates } from './common/index.ts';
7
+ import type { ICommitHookStatus } from './common/index.ts';
8
+
9
+ const HOOK_NAME = 'commit-msg';
10
+ const MARKER = '# vulcan:commit-msg';
11
+ const CALL = /vulcan\s+commit-check/;
12
+ const COMMAND = 'bun x --no-install vulcan commit-check "$1"';
13
+
14
+ const git = (opts: { root: string; args: string[] }): string | undefined => {
15
+ try {
16
+ const result = Bun.spawnSync(['git', ...opts.args], {
17
+ cwd: opts.root,
18
+ stdout: 'pipe',
19
+ stderr: 'ignore',
20
+ });
21
+
22
+ return result.exitCode === 0 ? result.stdout.toString().trim() : undefined;
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ };
27
+
28
+ export class CommitHook {
29
+ static isWanted(opts: { config: TResolvedConfig }): boolean {
30
+ const { agent, subject } = opts.config.commit.message;
31
+
32
+ return agent.signature === AgentSignaturePolicies.DENY || subject !== undefined;
33
+ }
34
+
35
+ /**
36
+ * The hook file: a POSIX shell script that hands the message to `vulcan commit-check` from the
37
+ * project folder. A commit goes through, with a note on stderr, when bun is not installed, no
38
+ * `node_modules/@venizia/vulcan` is found from the project folder up to the git top level, or the installed vulcan has
39
+ * no `commit-check` command (an older branch).
40
+ */
41
+ static template(opts: { prefix: string }): string {
42
+ const folder = opts.prefix.replace(/\/$/, '');
43
+ const enter = folder === '' ? '' : `cd ${CommitHook.quote({ text: folder })} || exit 0\n`;
44
+
45
+ return `#!/bin/sh
46
+ ${MARKER} - written by vulcan sync from commit.message in .configs/vulcan.config.mts; do not edit
47
+ message="$1"
48
+ case "$message" in /*) ;; *) message="$PWD/$message" ;; esac
49
+ top="$(git rev-parse --show-toplevel)"
50
+ cd "$top" || exit 0
51
+ ${enter}if ! command -v bun >/dev/null 2>&1; then
52
+ echo "vulcan: the commit-msg hook is skipped - bun is not installed" >&2
53
+ exit 0
54
+ fi
55
+ dir="$PWD"
56
+ while [ ! -d "$dir/node_modules/@venizia/vulcan" ]; do
57
+ if [ "$dir" = "$top" ] || [ "$dir" = "/" ]; then
58
+ echo "vulcan: the commit-msg hook is skipped - run bun install" >&2
59
+ exit 0
60
+ fi
61
+ dir="$(dirname "$dir")"
62
+ done
63
+ output="$(${COMMAND.replace('"$1"', '"$message"')} 2>&1)"
64
+ status=$?
65
+ if [ "$status" -eq 1 ] && printf '%s\n' "$output" | grep -q "^vulcan: unknown command 'commit-check'"; then
66
+ echo "vulcan: the commit-msg hook is skipped - the installed vulcan has no commit-check command" >&2
67
+ exit 0
68
+ fi
69
+ [ -z "$output" ] || printf '%s\n' "$output" >&2
70
+ exit "$status"
71
+ `;
72
+ }
73
+
74
+ private static quote(opts: { text: string }): string {
75
+ return `'${opts.text.replaceAll("'", "'\\''")}'`;
76
+ }
77
+
78
+ /** A project that sets `core.hooksPath` owns its hooks: this only reads them. */
79
+ static stateOf(opts: { root: string; config: TResolvedConfig }): ICommitHookStatus {
80
+ const location = git({
81
+ root: opts.root,
82
+ args: ['rev-parse', '--git-path', `hooks/${HOOK_NAME}`],
83
+ });
84
+ const prefix = git({ root: opts.root, args: ['rev-parse', '--show-prefix'] });
85
+ const isWanted = CommitHook.isWanted({ config: opts.config });
86
+
87
+ if (location === undefined || location === '' || prefix === undefined) {
88
+ return { state: isWanted ? CommitHookStates.NOT_GIT : CommitHookStates.OFF, path: '' };
89
+ }
90
+
91
+ const path = resolve(opts.root, location);
92
+ const hooksPath = git({ root: opts.root, args: ['config', '--get', 'core.hooksPath'] });
93
+ const entry = lstatSync(path, { throwIfNoEntry: false });
94
+ const text = entry?.isFile() === true ? readFileSync(path, 'utf8') : undefined;
95
+ const isOurs = hooksPath === undefined && text?.split('\n')[1]?.startsWith(MARKER) === true;
96
+
97
+ if (!isWanted) {
98
+ return { state: isOurs ? CommitHookStates.LEFTOVER : CommitHookStates.OFF, path };
99
+ }
100
+
101
+ const addLine = `add '${COMMAND}' to its ${HOOK_NAME} hook`;
102
+
103
+ if (hooksPath !== undefined) {
104
+ return text !== undefined && CALL.test(text)
105
+ ? { state: CommitHookStates.WIRED, path }
106
+ : {
107
+ state: CommitHookStates.UNWIRED,
108
+ path,
109
+ note: `core.hooksPath is ${hooksPath}: ${addLine}`,
110
+ };
111
+ }
112
+
113
+ if (entry === undefined) {
114
+ return { state: CommitHookStates.MISSING, path };
115
+ }
116
+
117
+ if (text === undefined) {
118
+ return {
119
+ state: CommitHookStates.UNWIRED,
120
+ path,
121
+ note: `a symbolic link or folder, not touched: ${addLine}`,
122
+ };
123
+ }
124
+
125
+ if (isOurs) {
126
+ const isCurrent = text === CommitHook.template({ prefix }) && (entry.mode & 0o111) !== 0;
127
+
128
+ return { state: isCurrent ? CommitHookStates.WIRED : CommitHookStates.STALE, path };
129
+ }
130
+
131
+ return CALL.test(text)
132
+ ? { state: CommitHookStates.WIRED, path }
133
+ : {
134
+ state: CommitHookStates.UNWIRED,
135
+ path,
136
+ note: `a hook of yours is there, not touched: ${addLine}`,
137
+ };
138
+ }
139
+
140
+ static write(opts: { path: string; prefix: string }): void {
141
+ mkdirSync(dirname(opts.path), { recursive: true });
142
+ writeFileSync(opts.path, CommitHook.template({ prefix: opts.prefix }));
143
+ chmodSync(opts.path, 0o755);
144
+ }
145
+ }
146
+
147
+ export class CommitHookPlan {
148
+ static plan(opts: { root: string; config: TResolvedConfig }): ISyncAction[] {
149
+ const status = CommitHook.stateOf(opts);
150
+ const prefix = git({ root: opts.root, args: ['rev-parse', '--show-prefix'] }) ?? '';
151
+ const { path } = status;
152
+ const write = (): void => CommitHook.write({ path, prefix });
153
+
154
+ switch (status.state) {
155
+ case CommitHookStates.MISSING: {
156
+ return [{ path, status: SyncStatuses.CREATED, apply: write }];
157
+ }
158
+
159
+ case CommitHookStates.STALE: {
160
+ return [{ path, status: SyncStatuses.REPLACED, apply: write }];
161
+ }
162
+
163
+ case CommitHookStates.WIRED: {
164
+ return [{ path, status: SyncStatuses.UNCHANGED, apply: () => {} }];
165
+ }
166
+
167
+ case CommitHookStates.UNWIRED: {
168
+ return [{ path, status: SyncStatuses.SKIPPED, note: status.note, apply: () => {} }];
169
+ }
170
+
171
+ case CommitHookStates.LEFTOVER: {
172
+ return [
173
+ {
174
+ path,
175
+ status: SyncStatuses.REMOVED,
176
+ note: 'no commit check is turned on',
177
+ apply: () => rmSync(path),
178
+ },
179
+ ];
180
+ }
181
+
182
+ default: {
183
+ return [];
184
+ }
185
+ }
186
+ }
187
+ }
@@ -0,0 +1,8 @@
1
+ export * from './common/index.ts';
2
+ export * from './agents.ts';
3
+ export * from './signature.ts';
4
+ export * from './subject.ts';
5
+ export * from './policy.ts';
6
+ export * from './check.ts';
7
+ export * from './hook.ts';
8
+ export * from './message.ts';
@@ -0,0 +1,74 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { TextValue } from '../common/index.ts';
3
+ import type { ICommentStyle } from './common/index.ts';
4
+
5
+ const INVISIBLE = /[\p{Cf}︎️]/gu;
6
+ const DASHES = /[\p{Pd}−]/gu;
7
+ /** The characters git picks from when `core.commentChar` is `auto`. */
8
+ const AUTO_PREFIXES = ['#', ';', '@', '!', '$', '%', '^', '&', '|', ':'];
9
+ const DEFAULT_STYLE: ICommentStyle = { prefixes: ['#'] };
10
+ /** A camel-case word, an acronym, a number, or any other run of letters. */
11
+ const TOKEN = /\p{Lu}+(?!\p{Ll})|\p{Lu}?\p{Ll}+|\p{N}+|\p{L}+/gu;
12
+
13
+ export class CommitMessage {
14
+ /** The comment style of the repository at `cwd`: `core.commentString` or `core.commentChar`, `#` by default. */
15
+ static commentStyleOf(opts: { cwd: string }): ICommentStyle {
16
+ for (const key of ['core.commentString', 'core.commentChar']) {
17
+ const result = spawnSync('git', ['config', '--get', key], {
18
+ cwd: opts.cwd,
19
+ encoding: 'utf8',
20
+ });
21
+ const value = result.status === 0 ? result.stdout.replace(/\r?\n$/, '') : '';
22
+
23
+ if (value === 'auto') {
24
+ return { prefixes: AUTO_PREFIXES };
25
+ }
26
+
27
+ if (value !== '') {
28
+ return { prefixes: [value] };
29
+ }
30
+ }
31
+
32
+ return DEFAULT_STYLE;
33
+ }
34
+
35
+ static isComment(opts: { line: string; comment?: ICommentStyle }): boolean {
36
+ return (opts.comment ?? DEFAULT_STYLE).prefixes.some((prefix) => opts.line.startsWith(prefix));
37
+ }
38
+
39
+ /** A lone carriage return is a line break too. Nothing below the scissors line of `git commit -v` is the message. */
40
+ static linesOf(opts: { message: string; comment?: ICommentStyle }): string[] {
41
+ const lines = opts.message.split(/\r\n|\r|\n/);
42
+ const scissors = (opts.comment ?? DEFAULT_STYLE).prefixes.map(
43
+ (prefix) => new RegExp(`^${TextValue.escapeLiteral({ text: prefix })} -+ >8 -+$`),
44
+ );
45
+ const cut = lines.findIndex((text) => scissors.some((pattern) => pattern.test(text)));
46
+
47
+ return cut === -1 ? lines : lines.slice(0, cut);
48
+ }
49
+
50
+ static cleanOf(opts: { text: string }): string {
51
+ return opts.text.replace(INVISIBLE, '').replace(DASHES, '-');
52
+ }
53
+
54
+ /** Letters and digits only, lower case: "Claude Code", "ClaudeCode" and "claude-code" read alike. */
55
+ static compactOf(opts: { text: string }): string {
56
+ return opts.text
57
+ .normalize('NFKC')
58
+ .toLowerCase()
59
+ .replace(/[^\p{L}\p{N}]/gu, '');
60
+ }
61
+
62
+ /** The words of `text`, split at punctuation, at camel-case boundaries and between letters and digits. */
63
+ static tokensOf(opts: { text: string }): string[] {
64
+ return opts.text.normalize('NFKC').match(TOKEN) ?? [];
65
+ }
66
+
67
+ /** Whether the words of `text` begin with one of `forms`, whole words only: "Claude Code 4" does, "Claude Coderre" does not. */
68
+ static beginsWithForm(opts: { text: string; forms: string[] }): boolean {
69
+ const tokens = CommitMessage.tokensOf({ text: opts.text }).map((token) => token.toLowerCase());
70
+ const forms = new Set(opts.forms.map((form) => CommitMessage.compactOf({ text: form })));
71
+
72
+ return tokens.some((_, index) => forms.has(tokens.slice(0, index + 1).join('')));
73
+ }
74
+ }
@@ -0,0 +1,110 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { RecordValue } from '../common/record.ts';
4
+ import { CommitAgents } from './agents.ts';
5
+ import { AgentSignaturePolicies } from './common/index.ts';
6
+ import type { ICommitPolicy, ICommitSubject, TAgentSignaturePolicy } from './common/index.ts';
7
+
8
+ const MANIFEST_FILE = '.agents/vulcan.manifest.json';
9
+
10
+ export class CommitPolicy {
11
+ /**
12
+ * The checks the project turned on, from the manifest `vulcan sync` wrote; undefined when the
13
+ * project turned none on, or when the block is not what sync writes (a note says so, and nothing is checked).
14
+ */
15
+ static read(opts: { root: string }): ICommitPolicy | undefined {
16
+ const file = join(opts.root, MANIFEST_FILE);
17
+
18
+ if (!existsSync(file)) {
19
+ return undefined;
20
+ }
21
+
22
+ let manifest: unknown;
23
+
24
+ try {
25
+ manifest = JSON.parse(readFileSync(file, 'utf8'));
26
+ } catch (error) {
27
+ console.error(
28
+ `[CommitPolicy.read] ${MANIFEST_FILE} is not JSON | ${error instanceof Error ? error.message : String(error)}`,
29
+ );
30
+
31
+ return undefined;
32
+ }
33
+
34
+ const commit = RecordValue.isRecord(manifest) ? manifest.commit : undefined;
35
+ const block = RecordValue.isRecord(commit) ? commit.message : undefined;
36
+
37
+ if (block === undefined) {
38
+ return undefined;
39
+ }
40
+
41
+ const policy = CommitPolicy.parse({ block });
42
+
43
+ if (policy === undefined) {
44
+ console.error(
45
+ `[CommitPolicy.read] ignoring commit.message in ${MANIFEST_FILE}: not the shape vulcan sync writes - run vulcan sync`,
46
+ );
47
+ }
48
+
49
+ return policy;
50
+ }
51
+
52
+ private static parse(opts: { block: unknown }): ICommitPolicy | undefined {
53
+ if (!RecordValue.isRecord(opts.block) || !RecordValue.isRecord(opts.block.agent)) {
54
+ return undefined;
55
+ }
56
+
57
+ const { signature, names, allow } = opts.block.agent;
58
+ const { subject } = opts.block;
59
+
60
+ if (typeof signature !== 'string' || !AgentSignaturePolicies.isValid(signature)) {
61
+ return undefined;
62
+ }
63
+
64
+ const extra = CommitPolicy.namesOf({ value: names });
65
+ const allowed = CommitPolicy.namesOf({ value: allow });
66
+
67
+ if (extra === undefined || allowed === undefined) {
68
+ return undefined;
69
+ }
70
+
71
+ const shape = CommitPolicy.subjectOf({ value: subject });
72
+
73
+ if (subject !== undefined && shape === undefined) {
74
+ return undefined;
75
+ }
76
+
77
+ return {
78
+ agentSignature: CommitPolicy.policyOf({ value: signature }),
79
+ agents: CommitAgents.read({ extra, allow: allowed }),
80
+ ...(shape === undefined ? {} : { subject: shape }),
81
+ };
82
+ }
83
+
84
+ private static namesOf(opts: { value: unknown }): string[] | undefined {
85
+ if (opts.value === undefined) {
86
+ return [];
87
+ }
88
+
89
+ return Array.isArray(opts.value) &&
90
+ opts.value.every((name) => typeof name === 'string' && /[\p{L}\p{N}]/u.test(name))
91
+ ? opts.value
92
+ : undefined;
93
+ }
94
+
95
+ private static policyOf(opts: { value: string }): TAgentSignaturePolicy {
96
+ return opts.value === AgentSignaturePolicies.DENY
97
+ ? AgentSignaturePolicies.DENY
98
+ : AgentSignaturePolicies.ALLOW;
99
+ }
100
+
101
+ private static subjectOf(opts: { value: unknown }): ICommitSubject | undefined {
102
+ if (!RecordValue.isRecord(opts.value) || typeof opts.value.pattern !== 'string') {
103
+ return undefined;
104
+ }
105
+
106
+ const { pattern, hint } = opts.value;
107
+
108
+ return typeof hint === 'string' ? { pattern, hint } : { pattern };
109
+ }
110
+ }