@venizia/vulcan 0.4.8 → 0.4.9-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/base/extensions/vulcan-guards.ts +48 -41
  2. package/base/hooks/antigravity-guards.ts +4 -3
  3. package/base/hooks/codex-guards.ts +17 -6
  4. package/base/hooks/guard-git.ts +8 -8
  5. package/base/hooks/guard-manifest.ts +5 -5
  6. package/base/hooks/guard-outside.ts +8 -8
  7. package/base/hooks/guard-package.ts +6 -6
  8. package/base/hooks/guard-remote-hosts.ts +14 -9
  9. package/base/hooks/guard-scripting.ts +6 -6
  10. package/base/hooks/guard-writes.ts +20 -11
  11. package/base/hooks/post-tool.ts +4 -3
  12. package/base/hooks/prompt-submit.ts +4 -3
  13. package/base/hooks/session-start.ts +5 -3
  14. package/base/hooks/stop.ts +4 -3
  15. package/base/hooks/subagent-start.ts +2 -2
  16. package/base/make/vulcan.mk +1 -4
  17. package/base/skills/build-a-feature/SKILL.md +1 -1
  18. package/base/skills/docs-update/SKILL.md +11 -5
  19. package/base/skills/docs-update/evals/evals.json +1 -1
  20. package/base/skills/docs-writing/SKILL.md +1 -1
  21. package/base/skills/plan-a-change/references/spec-card.md +1 -1
  22. package/base/skills/ship/SKILL.md +1 -1
  23. package/base/skills/visualize-work/SKILL.md +29 -6
  24. package/base/skills/visualize-work/references/spec.md +16 -5
  25. package/package.json +5 -6
  26. package/src/agents/atlas-block.ts +43 -43
  27. package/src/agents/codex-hooks.ts +55 -52
  28. package/src/agents/common/types.ts +1 -1
  29. package/src/agents/detect.ts +19 -16
  30. package/src/agents/exclude.ts +97 -98
  31. package/src/agents/hooks-json.ts +41 -43
  32. package/src/agents/local.ts +46 -43
  33. package/src/agents/prompt.ts +45 -42
  34. package/src/agents/render.ts +203 -201
  35. package/src/agents/resolve.ts +133 -134
  36. package/src/agents/table.ts +12 -8
  37. package/src/cli.ts +3 -1
  38. package/src/commands/add.command.ts +2 -2
  39. package/src/commands/agents.command.ts +11 -17
  40. package/src/commands/clean.command.ts +6 -6
  41. package/src/commands/doctor.command.ts +6 -4
  42. package/src/commands/help.command.ts +11 -9
  43. package/src/commands/init.command.ts +14 -8
  44. package/src/commands/preset.command.ts +2 -2
  45. package/src/commands/profile.command.ts +43 -50
  46. package/src/commands/sync.command.ts +109 -111
  47. package/src/commands/upgrade.command.ts +85 -78
  48. package/src/commands/visualize.command.ts +20 -5
  49. package/src/commands/x.command.ts +55 -50
  50. package/src/common/format.ts +23 -21
  51. package/src/common/index.ts +2 -0
  52. package/src/common/json.ts +8 -5
  53. package/src/common/layout-folder.ts +96 -111
  54. package/src/common/paths.ts +14 -12
  55. package/src/common/record.ts +7 -0
  56. package/src/common/text.ts +7 -0
  57. package/src/config/common/constants.ts +13 -1
  58. package/src/config/common/types.ts +8 -1
  59. package/src/config/loader.ts +53 -48
  60. package/src/config/packages.ts +17 -11
  61. package/src/config/schema.ts +54 -7
  62. package/src/create/add-app.ts +604 -493
  63. package/src/create/add-lib.ts +249 -242
  64. package/src/create/bunfig.ts +26 -23
  65. package/src/create/checks.ts +36 -34
  66. package/src/create/common/constants.ts +1 -0
  67. package/src/create/common/failure.ts +10 -0
  68. package/src/create/common/index.ts +2 -0
  69. package/src/create/common/preset-path.ts +11 -0
  70. package/src/create/common/types.ts +7 -2
  71. package/src/create/diff.ts +21 -23
  72. package/src/create/dockerignore.ts +26 -24
  73. package/src/create/files.ts +7 -5
  74. package/src/create/init-monorepo.ts +78 -80
  75. package/src/create/lib-preset.ts +62 -61
  76. package/src/create/manifest-json.ts +10 -4
  77. package/src/create/names.ts +217 -210
  78. package/src/create/next.ts +27 -24
  79. package/src/create/plan.ts +15 -12
  80. package/src/create/preset-diff.ts +415 -240
  81. package/src/create/preset-menu.ts +40 -34
  82. package/src/create/preset.ts +207 -194
  83. package/src/create/process.ts +80 -71
  84. package/src/create/scratch.ts +49 -48
  85. package/src/create/workspace.ts +423 -398
  86. package/src/doctor/checks.ts +1069 -998
  87. package/src/doctor/makefile.ts +17 -13
  88. package/src/doctor/runner.ts +88 -116
  89. package/src/doctor/skills.ts +97 -95
  90. package/src/doctor/tags.ts +44 -41
  91. package/src/hooks/codex-patch.ts +27 -24
  92. package/src/hooks/command-view.ts +44 -39
  93. package/src/hooks/common/constants.ts +0 -3
  94. package/src/hooks/common/types.ts +15 -1
  95. package/src/hooks/decision.ts +38 -42
  96. package/src/hooks/guard-git.ts +52 -50
  97. package/src/hooks/guard-manifest.ts +58 -55
  98. package/src/hooks/guard-outside.ts +109 -88
  99. package/src/hooks/guard-package.ts +86 -77
  100. package/src/hooks/guard-scripting.ts +20 -15
  101. package/src/hooks/guard-writes.ts +169 -111
  102. package/src/hooks/owner-reply.ts +128 -128
  103. package/src/hooks/post-tool.ts +94 -93
  104. package/src/hooks/project-guards.ts +93 -55
  105. package/src/hooks/project-tmp.ts +27 -24
  106. package/src/hooks/remote-hosts.ts +157 -149
  107. package/src/hooks/session-digest.ts +99 -95
  108. package/src/hooks/shell.ts +519 -500
  109. package/src/hooks/subagent-card.ts +11 -7
  110. package/src/hooks/trusted-scripts.ts +158 -80
  111. package/src/init/common/types.ts +1 -1
  112. package/src/init/scaffold.ts +137 -134
  113. package/src/local/clean.ts +39 -37
  114. package/src/local/format.ts +21 -17
  115. package/src/local/scan.ts +146 -140
  116. package/src/manifest/render.ts +127 -112
  117. package/src/owner/card.ts +51 -46
  118. package/src/owner/profile.ts +100 -96
  119. package/src/owner/reply-switch.ts +9 -6
  120. package/src/owner/shape.ts +72 -70
  121. package/src/owner/survey.ts +175 -164
  122. package/src/owner/view.ts +62 -59
  123. package/src/owner/violations.ts +119 -123
  124. package/src/router.ts +4 -1
  125. package/src/rules/base.ts +15 -11
  126. package/src/rules/common/types.ts +1 -1
  127. package/src/rules/parser.ts +39 -32
  128. package/src/rules/slots.ts +8 -6
  129. package/src/signals/claims.ts +30 -28
  130. package/src/signals/classify.ts +36 -33
  131. package/src/signals/loop.ts +39 -37
  132. package/src/signals/state.ts +80 -85
  133. package/src/skills/frontmatter.ts +28 -28
  134. package/src/sync/agent-files.ts +217 -199
  135. package/src/sync/agent-removal.ts +62 -68
  136. package/src/sync/atlas-block.ts +45 -43
  137. package/src/sync/base-rules.ts +32 -30
  138. package/src/sync/claude-launch.ts +74 -37
  139. package/src/sync/common/constants.ts +4 -0
  140. package/src/sync/common/index.ts +1 -0
  141. package/src/sync/common/symlink.ts +9 -0
  142. package/src/sync/common/types.ts +2 -2
  143. package/src/sync/exclude.ts +77 -69
  144. package/src/sync/local-choice.ts +50 -47
  145. package/src/sync/planner.ts +64 -68
  146. package/src/sync/prune.ts +52 -48
  147. package/src/sync/settings.ts +167 -168
  148. package/src/ui/capability.ts +12 -7
  149. package/src/ui/keyboard.ts +35 -33
  150. package/src/ui/prompt.ts +81 -77
  151. package/src/visualize/assets.ts +379 -195
  152. package/src/visualize/charts.ts +188 -176
  153. package/src/visualize/compare-css.ts +31 -0
  154. package/src/visualize/compare-render.ts +196 -0
  155. package/src/visualize/compare-schema.ts +81 -0
  156. package/src/visualize/compare-validate.ts +126 -0
  157. package/src/visualize/constants.ts +29 -3
  158. package/src/visualize/diagrams.ts +189 -174
  159. package/src/visualize/gate.ts +136 -0
  160. package/src/visualize/grid-span.ts +34 -0
  161. package/src/visualize/icons.ts +9 -4
  162. package/src/visualize/index.ts +2 -0
  163. package/src/visualize/kinds-css.ts +54 -0
  164. package/src/visualize/kinds-render.ts +698 -0
  165. package/src/visualize/kinds-schema.ts +148 -0
  166. package/src/visualize/kinds-validate.ts +186 -0
  167. package/src/visualize/labels-vi.ts +109 -0
  168. package/src/visualize/labels.ts +53 -0
  169. package/src/visualize/layout.ts +112 -92
  170. package/src/visualize/page.ts +140 -114
  171. package/src/visualize/render.ts +158 -114
  172. package/src/visualize/schema.ts +21 -1
  173. package/src/visualize/sections.ts +401 -309
  174. package/src/visualize/sources.ts +270 -0
  175. package/src/visualize/theme.ts +474 -0
  176. package/src/visualize/validate.ts +15 -5
  177. package/src/wiki/anchors.ts +39 -37
  178. package/src/wiki/command.ts +4 -4
  179. package/src/wiki/source-links.ts +49 -49
@@ -1,12 +1,13 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { isAbsolute, join } from 'node:path';
1
+ import { existsSync, readFileSync, statSync } from 'node:fs';
2
+ import { isAbsolute, resolve } from 'node:path';
3
3
  import { HookConstants } from './common/index.ts';
4
4
  import { TrustStates } from './common/index.ts';
5
- import type { IHookCommand, IWriteCheck, IWriteHit } from './common/index.ts';
6
- import { commandTextsOf } from './command-view.ts';
7
- import { forHost } from './decision.ts';
5
+ import type { IHookCommand, IReadOnlyScript, IWriteCheck, IWriteHit } from './common/index.ts';
6
+ import { CommandView } from './command-view.ts';
7
+ import { HookDecision } from './decision.ts';
8
8
  import type { IProjectCommandCheck } from './project-guards.ts';
9
- import { listedScriptOf, trustOf } from './trusted-scripts.ts';
9
+ import { ShellParser } from './shell.ts';
10
+ import { ReadOnlyScripts, ScriptPaths, ScriptTrust } from './trusted-scripts.ts';
10
11
 
11
12
  const MUTATING_VERB = '(?:POST|PUT|PATCH|DELETE)';
12
13
 
@@ -72,125 +73,182 @@ const SCRIPT_CHECKS: IWriteCheck[] = [
72
73
  const extractScriptTargets = (opts: { command: string }): string[] =>
73
74
  [...opts.command.matchAll(/\bbun\s+(?:run\s+)?(\S+\.ts)\b/g)].map((match) => match[1]);
74
75
 
75
- const readScript = (opts: { target: string; cwd: string }): string | undefined => {
76
- const path = isAbsolute(opts.target) ? opts.target : join(opts.cwd, opts.target);
77
-
78
- return existsSync(path) ? readFileSync(path, 'utf8') : undefined;
79
- };
80
-
81
76
  /**
82
- * Every reason `command` looks like a write the base rules reserve for a human (V-W-02, V-W-03).
83
- * `trust` lists the scripts the project vouches for (`guard.writes.trustedScripts`, repo-relative, under
84
- * `root`): a listed script that is tracked and identical to HEAD skips the script checks only. The checks
85
- * on the command line itself always run, and a listed script that git says changed is checked like any other.
77
+ * The files a script word can mean. `bun x.ts` opens the path as the OS does, following a link before a `..`;
78
+ * `bun run x.ts` folds the `..` as text first. Both are read, so neither spelling hides the other.
86
79
  */
87
- export const inspectCommand = (opts: {
88
- command: string;
89
- cwd: string;
90
- trust?: { root: string; scripts: string[] };
91
- /** The project's own commands (`guard.writes.commands`), checked beside the fixed list. */
92
- extra?: IProjectCommandCheck[];
93
- }): IWriteHit[] => {
94
- // The patterns run on what the command runs, not on its text: a heredoc written to a file, the pattern
95
- // of an `rg` and a commit message are data.
96
- const texts = commandTextsOf({ command: opts.command, withMessages: true });
97
- const checks: IWriteCheck[] = [
98
- ...COMMAND_CHECKS,
99
- ...(opts.extra ?? []).map((check) => ({
100
- rule: check.rule,
101
- what: `${check.what} (this project's pattern)`,
102
- pattern: check.pattern,
103
- })),
104
- ];
105
- const hits: IWriteHit[] = checks
106
- .filter((check) => texts.some((text) => check.pattern.test(text)))
107
- .map((check) => ({
108
- rule: check.rule,
109
- message: check.what,
110
- }));
111
-
112
- for (const target of extractScriptTargets({ command: texts.join('\n') })) {
113
- const source = readScript({ target, cwd: opts.cwd });
114
-
115
- if (source === undefined) {
116
- continue;
117
- }
80
+ const scriptPathsOf = (opts: { target: string; cwd: string }): string[] => [
81
+ ...new Set([ScriptPaths.targetPath(opts), resolve(opts.cwd, opts.target)]),
82
+ ];
118
83
 
119
- const listed =
120
- opts.trust === undefined
121
- ? undefined
122
- : listedScriptOf({
123
- target,
124
- cwd: opts.cwd,
125
- root: opts.trust.root,
126
- scripts: opts.trust.scripts,
127
- });
128
- const trust =
129
- listed === undefined || opts.trust === undefined
130
- ? undefined
131
- : trustOf({ root: opts.trust.root, script: listed });
132
-
133
- if (trust?.state === TrustStates.TRUSTED) {
134
- continue;
135
- }
84
+ /** The text of a regular file; a folder, a pipe and a missing path read as nothing, so nothing is opened that can block. */
85
+ const readScript = (opts: { path: string }): string | undefined =>
86
+ existsSync(opts.path) && statSync(opts.path).isFile()
87
+ ? readFileSync(opts.path, 'utf8')
88
+ : undefined;
136
89
 
137
- for (const check of SCRIPT_CHECKS.filter((scriptCheck) => scriptCheck.pattern.test(source))) {
138
- hits.push({
90
+ const isRecord = (opts: { value: unknown }): opts is { value: Record<string, unknown> } =>
91
+ typeof opts.value === 'object' && opts.value !== null && !Array.isArray(opts.value);
92
+
93
+ export class WriteGuard {
94
+ /**
95
+ * Every reason `command` looks like a write the base rules reserve for a human (V-W-02, V-W-03).
96
+ * `trust` lists the scripts the project vouches for (`guard.writes.trustedScripts`, repo-relative, under
97
+ * `root`): a listed script that is tracked and identical to HEAD skips the script checks only. The checks
98
+ * on the command line itself always run, and a listed script that git says changed is checked like any other.
99
+ * `trust.readOnlyScripts` (`guard.writes.trustedScripts` objects, from the manifest) skips them for one call: the
100
+ * word right after the script is one of the entry's `readOnly` words and the script is tracked and equals HEAD.
101
+ */
102
+ static inspectCommand(opts: {
103
+ command: string;
104
+ cwd: string;
105
+ trust?: { root: string; scripts: string[]; readOnlyScripts?: IReadOnlyScript[] };
106
+ /** The project's own commands (`guard.writes.commands`), checked beside the fixed list. */
107
+ extra?: IProjectCommandCheck[];
108
+ }): IWriteHit[] {
109
+ // The patterns run on what the command runs, not on its text: a heredoc written to a file, the pattern
110
+ // of an `rg` and a commit message are data.
111
+ const texts = CommandView.commandTextsOf({ command: opts.command, withMessages: true });
112
+ const checks: IWriteCheck[] = [
113
+ ...COMMAND_CHECKS,
114
+ ...(opts.extra ?? []).map((check) => ({
139
115
  rule: check.rule,
140
- message: `${target} looks like it is ${check.what}${trust === undefined ? '' : ` (listed in guard.writes.trustedScripts, but not trusted: ${trust.reason})`}`,
141
- });
116
+ what: `${check.what} (this project's pattern)`,
117
+ pattern: check.pattern,
118
+ })),
119
+ ];
120
+ const hits: IWriteHit[] = checks
121
+ .filter((check) => texts.some((text) => check.pattern.test(text)))
122
+ .map((check) => ({
123
+ rule: check.rule,
124
+ message: check.what,
125
+ }));
126
+
127
+ const targets = extractScriptTargets({ command: texts.join('\n') });
128
+ const entries = opts.trust?.readOnlyScripts ?? [];
129
+ // A subcommand counts only when the shell's own words give the same scripts in the same order as the text
130
+ // does; any other line (a script named in an argument, a pipe into a runner) is read as a whole.
131
+ const invocations = ReadOnlyScripts.extractInvocations({ command: opts.command });
132
+ const isPaired =
133
+ invocations.length === targets.length &&
134
+ invocations.every((invocation, index) => invocation.script === targets[index]);
135
+ const hasMoving = texts.some((text) =>
136
+ ShellParser.parse({ command: text }).some((command) =>
137
+ ReadOnlyScripts.MOVING_COMMANDS.has(
138
+ ShellParser.basenameOf({ word: ShellParser.programOf({ command }).name }),
139
+ ),
140
+ ),
141
+ );
142
+
143
+ for (const [index, target] of targets.entries()) {
144
+ const sources = scriptPathsOf({ target, cwd: opts.cwd })
145
+ .map((path) => readScript({ path }))
146
+ .filter((text): text is string => text !== undefined);
147
+
148
+ if (sources.length === 0) {
149
+ continue;
150
+ }
151
+
152
+ const subcommand = isPaired ? invocations[index]?.subcommand : undefined;
153
+ // After a `cd` the hook does not know the folder a relative script word is from, so no entry covers it.
154
+ const isFromUnknownFolder =
155
+ !isAbsolute(target) && (isPaired ? invocations[index]?.moved === true : hasMoving);
156
+ // An entry covers the word only when both spellings of it (see `scriptPathsOf`) name that same entry.
157
+ const covered = (lookup: (spelling: { target: string }) => string | undefined) => {
158
+ const asWritten = lookup({ target });
159
+
160
+ return asWritten === lookup({ target: resolve(opts.cwd, target) }) ? asWritten : undefined;
161
+ };
162
+ const trusted = opts.trust;
163
+ const listed =
164
+ trusted === undefined || isFromUnknownFolder
165
+ ? undefined
166
+ : (covered((spelling) =>
167
+ ScriptTrust.listedOf({
168
+ target: spelling.target,
169
+ cwd: opts.cwd,
170
+ root: trusted.root,
171
+ scripts: trusted.scripts,
172
+ }),
173
+ ) ??
174
+ (subcommand === undefined
175
+ ? undefined
176
+ : covered((spelling) =>
177
+ ReadOnlyScripts.find({
178
+ target: spelling.target,
179
+ subcommand,
180
+ cwd: opts.cwd,
181
+ root: trusted.root,
182
+ entries,
183
+ }),
184
+ )));
185
+ const trust =
186
+ listed === undefined || opts.trust === undefined
187
+ ? undefined
188
+ : ScriptTrust.trustOf({ root: opts.trust.root, script: listed });
189
+
190
+ if (trust?.state === TrustStates.TRUSTED) {
191
+ continue;
192
+ }
193
+
194
+ for (const check of SCRIPT_CHECKS.filter((scriptCheck) =>
195
+ sources.some((text) => scriptCheck.pattern.test(text)),
196
+ )) {
197
+ hits.push({
198
+ rule: check.rule,
199
+ message: `${target} looks like it is ${check.what}${trust === undefined ? '' : ` (listed in guard.writes.trustedScripts, but not trusted: ${trust.reason})`}`,
200
+ });
201
+ }
142
202
  }
203
+
204
+ return hits;
143
205
  }
144
206
 
145
- return hits;
146
- };
207
+ /** The Bash command and cwd from the hook's JSON; `undefined` when it is not what Claude Code sends. */
208
+ static parseHookCommand(opts: { text: string }): IHookCommand | undefined {
209
+ let payload: unknown;
147
210
 
148
- const isRecord = (opts: { value: unknown }): opts is { value: Record<string, unknown> } =>
149
- typeof opts.value === 'object' && opts.value !== null && !Array.isArray(opts.value);
211
+ try {
212
+ payload = JSON.parse(opts.text);
213
+ } catch (error) {
214
+ console.error(
215
+ `[WriteGuard.parseHookCommand] unreadable hook input - letting the command through | ${error instanceof Error ? error.message : String(error)}`,
216
+ );
150
217
 
151
- /** The Bash command and cwd from the hook's JSON; `undefined` when it is not what Claude Code sends. */
152
- export const parseHookCommand = (opts: { text: string }): IHookCommand | undefined => {
153
- let payload: unknown;
218
+ return undefined;
219
+ }
154
220
 
155
- try {
156
- payload = JSON.parse(opts.text);
157
- } catch (error) {
158
- console.error(
159
- `[parseHookCommand] unreadable hook input - letting the command through | ${error instanceof Error ? error.message : String(error)}`,
160
- );
221
+ const holder = { value: payload };
161
222
 
162
- return undefined;
163
- }
223
+ if (!isRecord(holder)) {
224
+ return undefined;
225
+ }
164
226
 
165
- const holder = { value: payload };
227
+ // The wire names are snake_case; they stay behind string-literal access here, at the boundary (V-C-14).
228
+ const toolInput = { value: holder.value['tool_input'] };
229
+ const command = isRecord(toolInput) ? toolInput.value['command'] : undefined;
230
+ const cwd = holder.value['cwd'];
166
231
 
167
- if (!isRecord(holder)) {
168
- return undefined;
232
+ return typeof command === 'string' && command !== ''
233
+ ? { command, cwd: typeof cwd === 'string' ? cwd : undefined }
234
+ : undefined;
169
235
  }
170
236
 
171
- // The wire names are snake_case; they stay behind string-literal access here, at the boundary (V-C-14).
172
- const toolInput = { value: holder.value['tool_input'] };
173
- const command = isRecord(toolInput) ? toolInput.value['command'] : undefined;
174
- const cwd = holder.value['cwd'];
175
-
176
- return typeof command === 'string' && command !== ''
177
- ? { command, cwd: typeof cwd === 'string' ? cwd : undefined }
178
- : undefined;
179
- };
180
-
181
- export const buildGuardDecision = (opts: { hits: IWriteHit[] }) =>
182
- forHost({
183
- output: {
184
- hookSpecificOutput: {
185
- hookEventName: HookConstants.PRE_TOOL_USE,
186
- permissionDecision: HookConstants.GUARD_DECISION,
187
- permissionDecisionReason: [
188
- `This command looks like ${opts.hits.length === 1 ? 'an action' : 'actions'} the base rules reserve for a human:`,
189
- ...opts.hits.map((hit) => ` - ${hit.rule}: ${hit.message}`),
190
- '',
191
- 'The rules reject "it is only dev", "it is only a test row" and "it is reversible".',
192
- 'Produce the script, the SQL or the manifest and hand it over instead of running it.',
193
- ].join('\n'),
237
+ static buildDecision(opts: { hits: IWriteHit[] }) {
238
+ return HookDecision.forHost({
239
+ output: {
240
+ hookSpecificOutput: {
241
+ hookEventName: HookConstants.PRE_TOOL_USE,
242
+ permissionDecision: HookConstants.GUARD_DECISION,
243
+ permissionDecisionReason: [
244
+ `This command looks like ${opts.hits.length === 1 ? 'an action' : 'actions'} the base rules reserve for a human:`,
245
+ ...opts.hits.map((hit) => ` - ${hit.rule}: ${hit.message}`),
246
+ '',
247
+ 'The rules reject "it is only dev", "it is only a test row" and "it is reversible".',
248
+ 'Produce the script, the SQL or the manifest and hand it over instead of running it.',
249
+ ].join('\n'),
250
+ },
194
251
  },
195
- },
196
- });
252
+ });
253
+ }
254
+ }
@@ -1,19 +1,16 @@
1
- import { loadConfig } from '../config/index.ts';
1
+ import { ConfigLoader } from '../config/index.ts';
2
2
  import {
3
- checkOwnerShape,
3
+ OwnerShape,
4
4
  OWNER_SCHEMA,
5
5
  OwnerEnforcement,
6
- isOwnerReplyOff,
7
- readLastClasses,
8
- readProfile,
9
- markBlocked,
10
- recordReply,
11
- wasBlockedRecently,
12
- resolveOwnerView,
6
+ ReplySwitch,
7
+ ViolationLog,
8
+ OwnerProfile,
9
+ OwnerView,
13
10
  ShapeClasses,
14
11
  } from '../owner/index.ts';
15
12
  import type { IOwnerView } from '../owner/index.ts';
16
- import { checkClaims, readSignals, startTurn } from '../signals/index.ts';
13
+ import { ReplyClaims, SignalState } from '../signals/index.ts';
17
14
 
18
15
  /** What to do about each class, in the words of the block message. */
19
16
  const FIXES: Record<string, string> = {
@@ -33,130 +30,133 @@ const FIXES: Record<string, string> = {
33
30
  };
34
31
 
35
32
  /** The owner's view of the project in `projectRoot`; a project whose config cannot load gets the defaults. */
36
- export const loadOwnerView = async (opts: { projectRoot: string }): Promise<IOwnerView> => {
37
- const loaded = await loadConfig({ root: opts.projectRoot });
38
- const profile = readProfile({ root: opts.projectRoot });
33
+ const loadOwnerView = async (opts: { projectRoot: string }): Promise<IOwnerView> => {
34
+ const loaded = await ConfigLoader.load({ root: opts.projectRoot });
35
+ const profile = OwnerProfile.read({ root: opts.projectRoot });
39
36
 
40
- return resolveOwnerView({
37
+ return OwnerView.resolve({
41
38
  owner: loaded.ok ? loaded.config.owner : OWNER_SCHEMA.parse(undefined),
42
39
  profile: profile.ok ? profile.profile : undefined,
43
40
  });
44
41
  };
45
42
 
46
- /**
47
- * The Stop hook's answer for the last reply: it is checked and recorded (classes and date only), and
48
- * only under `block`, once per message and only for a structural fault, is it sent back to be restated.
49
- * Anything it cannot read passes: it never stops a session by failing. A session started with
50
- * `VULCAN_OWNER_REPLY=off` (a session whose reader is an agent) is not checked, logged or blocked at all.
51
- */
52
- export const buildStopOutput = async (opts: {
53
- projectRoot: string;
54
- input: unknown;
55
- /** The environment of the session; `VULCAN_OWNER_REPLY=off` exempts it. */
56
- env?: Record<string, string | undefined>;
57
- }): Promise<Record<string, unknown> | undefined> => {
58
- const { input } = opts;
59
-
60
- if (isOwnerReplyOff({ env: opts.env ?? process.env })) {
61
- return undefined;
43
+ export class OwnerReply {
44
+ /**
45
+ * The Stop hook's answer for the last reply: it is checked and recorded (classes and date only), and
46
+ * only under `block`, once per message and only for a structural fault, is it sent back to be restated.
47
+ * Anything it cannot read passes: it never stops a session by failing. A session started with
48
+ * `VULCAN_OWNER_REPLY=off` (a session whose reader is an agent) is not checked, logged or blocked at all.
49
+ */
50
+ static async buildStopOutput(opts: {
51
+ projectRoot: string;
52
+ input: unknown;
53
+ /** The environment of the session; `VULCAN_OWNER_REPLY=off` exempts it. */
54
+ env?: Record<string, string | undefined>;
55
+ }): Promise<Record<string, unknown> | undefined> {
56
+ const { input } = opts;
57
+
58
+ if (ReplySwitch.isOwnerOff({ env: opts.env ?? process.env })) {
59
+ return undefined;
60
+ }
61
+
62
+ if (typeof input !== 'object' || input === null || !('last_assistant_message' in input)) {
63
+ return undefined;
64
+ }
65
+
66
+ const { last_assistant_message: text } = input;
67
+ const isRetry = 'stop_hook_active' in input && input.stop_hook_active === true;
68
+ const session =
69
+ 'session_id' in input && typeof input.session_id === 'string' ? input.session_id : '';
70
+ const view = await loadOwnerView({ projectRoot: opts.projectRoot });
71
+
72
+ if (typeof text !== 'string' || view.enforce === OwnerEnforcement.OFF) {
73
+ return undefined;
74
+ }
75
+
76
+ const result = OwnerShape.check({ text, view });
77
+ // A claim is checked on every reply, a short one too: "Published." is the shortest wrong one.
78
+ const claims = ReplyClaims.check({
79
+ text,
80
+ state: SignalState.read({ root: opts.projectRoot, session }),
81
+ publicWords: view.claimWords.public,
82
+ doneWords: view.claimWords.done,
83
+ });
84
+ const classes = [...result.classes, ...claims];
85
+
86
+ // Every reply updates the note the next prompt reads, an exempt short one too; a write that fails never
87
+ // costs the decision below.
88
+ try {
89
+ ViolationLog.recordReply({ root: opts.projectRoot, classes, session });
90
+ } catch {
91
+ // The log is advisory.
92
+ }
93
+
94
+ if (!result.isChecked) {
95
+ return undefined;
96
+ }
97
+
98
+ const structural = result.classes.filter((name) => ShapeClasses.isStructural(name));
99
+
100
+ if (
101
+ view.enforce !== OwnerEnforcement.BLOCK ||
102
+ isRetry ||
103
+ structural.length === 0 ||
104
+ ViolationLog.wasBlockedRecently({ root: opts.projectRoot, session })
105
+ ) {
106
+ return undefined;
107
+ }
108
+
109
+ try {
110
+ ViolationLog.markBlocked({ root: opts.projectRoot, session });
111
+ } catch {
112
+ // Without the note the stop_hook_active flag is the only guard against a second block.
113
+ }
114
+
115
+ return {
116
+ decision: 'block',
117
+ reason: [
118
+ 'The reply to the owner breaks the report shape (see "How to answer the owner" in the session rules). Restate it once, in full:',
119
+ ...structural.map((name) => ` - ${name}: ${FIXES[name] ?? name}`),
120
+ ].join('\n'),
121
+ };
62
122
  }
63
123
 
64
- if (typeof input !== 'object' || input === null || !('last_assistant_message' in input)) {
65
- return undefined;
124
+ /**
125
+ * One line added to every prompt while the shape is held: the contract, and the faults of the reply
126
+ * before when it had any. Empty when the shape is not enforced.
127
+ */
128
+ static async buildPromptContract(opts: {
129
+ projectRoot: string;
130
+ /** The session the prompt belongs to; its turn begins here. */
131
+ session?: string;
132
+ /** The environment of the session; `VULCAN_OWNER_REPLY=off` exempts it. */
133
+ env?: Record<string, string | undefined>;
134
+ }): Promise<string> {
135
+ // A new turn begins with this prompt: the notes of the last one are forgotten, whatever is enforced.
136
+ try {
137
+ SignalState.startTurn({ root: opts.projectRoot, session: opts.session ?? '' });
138
+ } catch {
139
+ // The notes are advisory.
140
+ }
141
+
142
+ if (ReplySwitch.isOwnerOff({ env: opts.env ?? process.env })) {
143
+ return '';
144
+ }
145
+
146
+ const view = await loadOwnerView({ projectRoot: opts.projectRoot });
147
+
148
+ if (view.enforce === OwnerEnforcement.OFF) {
149
+ return '';
150
+ }
151
+
152
+ // A claim match is a hint, so it is logged but never said back to the model as a fault of the last reply.
153
+ const last = ViolationLog.readLastClasses({
154
+ root: opts.projectRoot,
155
+ session: opts.session,
156
+ }).filter((name) => ShapeClasses.isValid(name));
157
+
158
+ return last.length === 0
159
+ ? 'Owner reply contract: follow the report shape from the session rules.'
160
+ : `Owner reply contract: follow the report shape from the session rules. Your last reply broke it - ${last.map((name) => FIXES[name] ?? name).join('; ')}.`;
66
161
  }
67
-
68
- const { last_assistant_message: text } = input;
69
- const isRetry = 'stop_hook_active' in input && input.stop_hook_active === true;
70
- const session =
71
- 'session_id' in input && typeof input.session_id === 'string' ? input.session_id : '';
72
- const view = await loadOwnerView({ projectRoot: opts.projectRoot });
73
-
74
- if (typeof text !== 'string' || view.enforce === OwnerEnforcement.OFF) {
75
- return undefined;
76
- }
77
-
78
- const result = checkOwnerShape({ text, view });
79
- // A claim is checked on every reply, a short one too: "Published." is the shortest wrong one.
80
- const claims = checkClaims({
81
- text,
82
- state: readSignals({ root: opts.projectRoot, session }),
83
- publicWords: view.claimWords.public,
84
- doneWords: view.claimWords.done,
85
- });
86
- const classes = [...result.classes, ...claims];
87
-
88
- // Every reply updates the note the next prompt reads, an exempt short one too; a write that fails never
89
- // costs the decision below.
90
- try {
91
- recordReply({ root: opts.projectRoot, classes, session });
92
- } catch {
93
- // The log is advisory.
94
- }
95
-
96
- if (!result.isChecked) {
97
- return undefined;
98
- }
99
-
100
- const structural = result.classes.filter((name) => ShapeClasses.isStructural(name));
101
-
102
- if (
103
- view.enforce !== OwnerEnforcement.BLOCK ||
104
- isRetry ||
105
- structural.length === 0 ||
106
- wasBlockedRecently({ root: opts.projectRoot, session })
107
- ) {
108
- return undefined;
109
- }
110
-
111
- try {
112
- markBlocked({ root: opts.projectRoot, session });
113
- } catch {
114
- // Without the note the stop_hook_active flag is the only guard against a second block.
115
- }
116
-
117
- return {
118
- decision: 'block',
119
- reason: [
120
- 'The reply to the owner breaks the report shape (see "How to answer the owner" in the session rules). Restate it once, in full:',
121
- ...structural.map((name) => ` - ${name}: ${FIXES[name] ?? name}`),
122
- ].join('\n'),
123
- };
124
- };
125
-
126
- /**
127
- * One line added to every prompt while the shape is held: the contract, and the faults of the reply
128
- * before when it had any. Empty when the shape is not enforced.
129
- */
130
- export const buildPromptContract = async (opts: {
131
- projectRoot: string;
132
- /** The session the prompt belongs to; its turn begins here. */
133
- session?: string;
134
- /** The environment of the session; `VULCAN_OWNER_REPLY=off` exempts it. */
135
- env?: Record<string, string | undefined>;
136
- }): Promise<string> => {
137
- // A new turn begins with this prompt: the notes of the last one are forgotten, whatever is enforced.
138
- try {
139
- startTurn({ root: opts.projectRoot, session: opts.session ?? '' });
140
- } catch {
141
- // The notes are advisory.
142
- }
143
-
144
- if (isOwnerReplyOff({ env: opts.env ?? process.env })) {
145
- return '';
146
- }
147
-
148
- const view = await loadOwnerView({ projectRoot: opts.projectRoot });
149
-
150
- if (view.enforce === OwnerEnforcement.OFF) {
151
- return '';
152
- }
153
-
154
- // A claim match is a hint, so it is logged but never said back to the model as a fault of the last reply.
155
- const last = readLastClasses({ root: opts.projectRoot, session: opts.session }).filter((name) =>
156
- ShapeClasses.isValid(name),
157
- );
158
-
159
- return last.length === 0
160
- ? 'Owner reply contract: follow the report shape from the session rules.'
161
- : `Owner reply contract: follow the report shape from the session rules. Your last reply broke it - ${last.map((name) => FIXES[name] ?? name).join('; ')}.`;
162
- };
162
+ }