@venizia/vulcan 0.3.13 → 0.4.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 (141) hide show
  1. package/base/claude/remote-hosts.json +1 -1
  2. package/base/claude/settings.json +75 -3
  3. package/base/hooks/guard-git.ts +55 -0
  4. package/base/hooks/guard-manifest.ts +1 -1
  5. package/base/hooks/guard-outside.ts +66 -0
  6. package/base/hooks/guard-package.ts +3 -2
  7. package/base/hooks/guard-remote-hosts.ts +3 -2
  8. package/base/hooks/guard-writes.ts +1 -1
  9. package/base/hooks/post-tool.ts +36 -0
  10. package/base/hooks/prompt-submit.ts +52 -0
  11. package/base/hooks/stop.ts +38 -0
  12. package/base/hooks/subagent-start.ts +18 -0
  13. package/base/references/delegation-brief.md +63 -0
  14. package/base/references/design-pass.md +39 -0
  15. package/base/references/evidence.md +36 -0
  16. package/base/references/phase-boundaries.md +20 -0
  17. package/base/references/testing.md +89 -0
  18. package/base/rules.md +11 -2
  19. package/base/skills/build-a-feature/SKILL.md +49 -23
  20. package/base/skills/docs-update/SKILL.md +12 -1
  21. package/base/skills/docs-writing/SKILL.md +2 -2
  22. package/base/skills/docs-writing/references/agent-documents.md +53 -0
  23. package/base/skills/fix-a-bug/SKILL.md +84 -0
  24. package/base/skills/fix-a-bug/evals/evals.json +17 -0
  25. package/base/skills/knowledge-sync/SKILL.md +4 -1
  26. package/base/skills/knowledge-sync/knowledge-sync.workflow.js +10 -10
  27. package/base/skills/plan-a-change/SKILL.md +95 -0
  28. package/base/skills/plan-a-change/evals/evals.json +23 -0
  29. package/base/skills/plan-a-change/references/spec-card.md +39 -0
  30. package/base/skills/report-back/SKILL.md +112 -0
  31. package/base/skills/report-back/evals/evals.json +23 -0
  32. package/base/skills/research/SKILL.md +64 -0
  33. package/base/skills/research/evals/evals.json +17 -0
  34. package/base/skills/retro/SKILL.md +69 -0
  35. package/base/skills/retro/evals/evals.json +17 -0
  36. package/base/skills/review-a-change/SKILL.md +90 -0
  37. package/base/skills/review-a-change/evals/evals.json +17 -0
  38. package/base/skills/ship/SKILL.md +82 -0
  39. package/base/skills/ship/evals/evals.json +23 -0
  40. package/base/skills/visualize-work/SKILL.md +87 -0
  41. package/base/skills/visualize-work/evals/evals.json +17 -0
  42. package/base/skills/visualize-work/references/spec.md +65 -0
  43. package/package.json +4 -4
  44. package/src/agents/common/schema.ts +2 -2
  45. package/src/agents/detect.ts +5 -5
  46. package/src/agents/exclude.ts +3 -3
  47. package/src/agents/local.ts +1 -1
  48. package/src/agents/prompt.ts +2 -2
  49. package/src/agents/render.ts +2 -2
  50. package/src/agents/resolve.ts +6 -6
  51. package/src/agents/table.ts +1 -1
  52. package/src/commands/agents.command.ts +4 -4
  53. package/src/commands/clean.command.ts +72 -0
  54. package/src/commands/help.command.ts +11 -0
  55. package/src/commands/index.ts +6 -0
  56. package/src/commands/init.command.ts +4 -1
  57. package/src/commands/profile.command.ts +255 -0
  58. package/src/commands/sync.command.ts +6 -4
  59. package/src/commands/upgrade.command.ts +1 -1
  60. package/src/commands/visualize.command.ts +107 -0
  61. package/src/common/constants.ts +23 -0
  62. package/src/config/common/constants.ts +2 -0
  63. package/src/config/loader.ts +4 -4
  64. package/src/config/packages.ts +1 -1
  65. package/src/config/schema.ts +16 -5
  66. package/src/create/add-app.ts +15 -15
  67. package/src/create/add-lib.ts +7 -7
  68. package/src/create/bunfig.ts +1 -1
  69. package/src/create/dockerignore.ts +4 -4
  70. package/src/create/init-monorepo.ts +3 -1
  71. package/src/create/lib-preset.ts +1 -1
  72. package/src/create/names.ts +7 -6
  73. package/src/create/next.ts +4 -4
  74. package/src/create/preset-menu.ts +4 -4
  75. package/src/create/preset.ts +3 -3
  76. package/src/create/scratch.ts +27 -6
  77. package/src/create/workspace.ts +11 -11
  78. package/src/doctor/checks.ts +231 -45
  79. package/src/doctor/common/constants.ts +4 -0
  80. package/src/doctor/makefile.ts +3 -3
  81. package/src/doctor/runner.ts +16 -1
  82. package/src/doctor/skills.ts +8 -8
  83. package/src/doctor/tags.ts +5 -5
  84. package/src/hooks/common/constants.ts +29 -0
  85. package/src/hooks/common/types.ts +20 -0
  86. package/src/hooks/decision.ts +15 -0
  87. package/src/hooks/guard-git.ts +288 -0
  88. package/src/hooks/guard-manifest.ts +1 -1
  89. package/src/hooks/guard-outside.ts +399 -0
  90. package/src/hooks/guard-package.ts +4 -4
  91. package/src/hooks/guard-writes.ts +5 -5
  92. package/src/hooks/index.ts +6 -0
  93. package/src/hooks/owner-reply.ts +148 -0
  94. package/src/hooks/post-tool.ts +137 -0
  95. package/src/hooks/remote-hosts.ts +25 -23
  96. package/src/hooks/session-digest.ts +24 -4
  97. package/src/hooks/shell.ts +325 -0
  98. package/src/hooks/subagent-card.ts +32 -0
  99. package/src/init/scaffold.ts +6 -6
  100. package/src/local/clean.ts +88 -0
  101. package/src/local/constants.ts +50 -0
  102. package/src/local/format.ts +25 -0
  103. package/src/local/index.ts +4 -0
  104. package/src/local/scan.ts +368 -0
  105. package/src/manifest/render.ts +1 -1
  106. package/src/owner/card.ts +85 -0
  107. package/src/owner/constants.ts +105 -0
  108. package/src/owner/index.ts +8 -0
  109. package/src/owner/profile.ts +123 -0
  110. package/src/owner/schema.ts +147 -0
  111. package/src/owner/shape.ts +380 -0
  112. package/src/owner/survey.ts +289 -0
  113. package/src/owner/view.ts +76 -0
  114. package/src/owner/violations.ts +202 -0
  115. package/src/router.ts +18 -1
  116. package/src/rules/base.ts +1 -1
  117. package/src/rules/parser.ts +5 -5
  118. package/src/signals/claims.ts +71 -0
  119. package/src/signals/classify.ts +132 -0
  120. package/src/signals/constants.ts +88 -0
  121. package/src/signals/index.ts +5 -0
  122. package/src/signals/loop.ts +46 -0
  123. package/src/signals/state.ts +276 -0
  124. package/src/sync/agent-files.ts +4 -4
  125. package/src/sync/agent-removal.ts +6 -6
  126. package/src/sync/atlas-block.ts +1 -1
  127. package/src/sync/base-rules.ts +1 -1
  128. package/src/sync/exclude.ts +9 -9
  129. package/src/sync/local-choice.ts +35 -5
  130. package/src/sync/planner.ts +16 -16
  131. package/src/sync/prune.ts +3 -3
  132. package/src/sync/settings.ts +15 -15
  133. package/src/ui/prompt.ts +3 -3
  134. package/src/visualize/assets.ts +80 -0
  135. package/src/visualize/constants.ts +126 -0
  136. package/src/visualize/index.ts +6 -0
  137. package/src/visualize/layout.ts +107 -0
  138. package/src/visualize/page.ts +211 -0
  139. package/src/visualize/render.ts +161 -0
  140. package/src/visualize/schema.ts +178 -0
  141. package/src/visualize/validate.ts +127 -0
@@ -0,0 +1,71 @@
1
+ import { ClaimClasses, ClaimWords } from './constants.ts';
2
+ import type { ISignalState } from './state.ts';
3
+
4
+ const LETTER_OR_DIGIT = String.raw`\p{L}\p{N}`;
5
+
6
+ const escaped = (opts: { text: string }): string =>
7
+ opts.text.replace(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
8
+
9
+ /** The sentences a reply asserts: code, quotes and questions are not assertions, and each sentence stands alone. */
10
+ const sentencesOf = (opts: { text: string }): string[] =>
11
+ opts.text
12
+ .normalize('NFC')
13
+ .replace(/```[\s\S]*?```/g, ' ')
14
+ .replace(/`[^`]*`/g, ' ')
15
+ .split('\n')
16
+ .filter((line) => !line.trimStart().startsWith('>'))
17
+ .join('\n')
18
+ .split(/(?<=[.!?…。!?])\s+|\n+/)
19
+ .map((sentence) => sentence.trim())
20
+ .filter((sentence) => sentence !== '' && !sentence.endsWith('?'));
21
+
22
+ const hasWord = (opts: { sentence: string; word: string }): boolean =>
23
+ new RegExp(
24
+ `(?<![${LETTER_OR_DIGIT}])${escaped({ text: opts.word.normalize('NFC') })}(?![${LETTER_OR_DIGIT}])`,
25
+ 'iu',
26
+ ).test(opts.sentence);
27
+
28
+ const isDenied = (opts: { sentence: string }): boolean =>
29
+ ClaimWords.NEGATIONS.some((word) =>
30
+ word === "n't"
31
+ ? opts.sentence.toLowerCase().includes(word)
32
+ : hasWord({ sentence: opts.sentence, word }),
33
+ );
34
+
35
+ /** Whether a sentence of the reply asserts one of the phrases, and does not deny it. */
36
+ const asserts = (opts: { text: string; words: string[] }): boolean =>
37
+ sentencesOf({ text: opts.text }).some(
38
+ (sentence) => !isDenied({ sentence }) && opts.words.some((word) => hasWord({ sentence, word })),
39
+ );
40
+
41
+ /**
42
+ * What the reply claims against what the turn's calls show. A claim that something is published, released
43
+ * or live needs a public-state probe in the turn; a claim that the checks pass is contradicted while a gate
44
+ * of the turn still failed on its latest run. Phrases match whole words in a sentence that does not deny,
45
+ * ask or quote; English plus any the project adds. Logged, never blocked: a match is a hint, not proof.
46
+ */
47
+ export const checkClaims = (opts: {
48
+ text: string;
49
+ state: ISignalState;
50
+ publicWords?: string[];
51
+ doneWords?: string[];
52
+ }): string[] => {
53
+ const classes: string[] = [];
54
+ const { state } = opts;
55
+
56
+ if (
57
+ asserts({ text: opts.text, words: [...ClaimWords.PUBLIC, ...(opts.publicWords ?? [])] }) &&
58
+ state.probeAt < state.turnAt
59
+ ) {
60
+ classes.push(ClaimClasses.PUBLIC_CLAIM_NO_PROBE);
61
+ }
62
+
63
+ if (
64
+ asserts({ text: opts.text, words: [...ClaimWords.DONE, ...(opts.doneWords ?? [])] }) &&
65
+ state.failedGates.length > 0
66
+ ) {
67
+ classes.push(ClaimClasses.CONTRADICTED_COMPLETION);
68
+ }
69
+
70
+ return classes;
71
+ };
@@ -0,0 +1,132 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { parseShell, programOf } from '../hooks/shell.ts';
3
+ import { SignalConstants, WatchedKinds } from './constants.ts';
4
+
5
+ const LOCAL_URL = /^https?:\/\/(?:localhost|127\.|0\.0\.0\.0|\[::1\])/;
6
+ const GATE_SCRIPTS = new Set(['test', 'lint', 'build', 'typecheck', 'check']);
7
+ const GATE_TOOLS = new Set(['tsc', 'vitest', 'jest', 'pytest', 'eslint', 'oxlint']);
8
+ const GATE_MAKE_TARGET = /^(?:test|lint|build|check|typecheck|docs|smoke)(?:[-:\w]*)$/;
9
+ const READ_VIEWS = new Set(['view', 'list', 'status', 'checks', 'watch']);
10
+ const SKILL_FILE =
11
+ /(?:^|\/)(?:\.agents\/skills|\.claude\/skills|packages\/[^/]+\/base\/skills)\/([^/]+)\/(?:SKILL\.md|references\/.+|evals\/.+)$/;
12
+ const RULES_FILE = /(?:^|\/)(?:\.agents\/rules\.md|packages\/[^/]+\/base\/rules\.md)$/;
13
+ const SCRATCH = /(?:^|\/)\.agents\/local\//;
14
+
15
+ /** The simple commands of a line as program and arguments; a line that cannot be parsed has none. */
16
+ const programsOf = (opts: { command: string }): { name: string; args: string[] }[] => {
17
+ try {
18
+ return parseShell({ command: opts.command }).map((simple) => {
19
+ const { name, args } = programOf({ command: simple });
20
+
21
+ return { name, args };
22
+ });
23
+ } catch {
24
+ return [];
25
+ }
26
+ };
27
+
28
+ /** The tool input as a short stable key: the same call twice has the same key. */
29
+ export const callKeyOf = (opts: { tool: string; input: unknown }): string =>
30
+ `${opts.tool}:${createHash('sha1')
31
+ .update(JSON.stringify(opts.input ?? null))
32
+ .digest('hex')
33
+ .slice(0, SignalConstants.EVENT_KEY_LENGTH)}`;
34
+
35
+ const isProbeProgram = (opts: { name: string; args: string[] }): boolean => {
36
+ const { name, args } = opts;
37
+
38
+ if (name === 'npm') {
39
+ return ['view', 'info', 'show', 'dist-tag'].includes(args[0] ?? '');
40
+ }
41
+
42
+ if (name === 'git') {
43
+ return args[0] === 'ls-remote';
44
+ }
45
+
46
+ if (name === 'gh') {
47
+ if (args[0] === 'api') {
48
+ return !args.some((arg) => /^(?:-X|--method|-f|-F|--field|--raw-field|--input)$/.test(arg));
49
+ }
50
+
51
+ return args.some((arg) => READ_VIEWS.has(arg)) && !args.includes('create');
52
+ }
53
+
54
+ if (name === 'curl') {
55
+ const url = args.find((arg) => /^https?:\/\//.test(arg));
56
+
57
+ return (
58
+ url !== undefined &&
59
+ !LOCAL_URL.test(url) &&
60
+ !args.some((arg) => /^(?:-X|--request|-d|--data.*|-F|--form|-T)$/.test(arg))
61
+ );
62
+ }
63
+
64
+ return false;
65
+ };
66
+
67
+ /** A command that asks public state: the registry, the forge, a remote, an outside URL; not a write. */
68
+ export const isPublicProbe = (opts: { command: string }): boolean =>
69
+ programsOf({ command: opts.command }).some((program) => isProbeProgram(program));
70
+
71
+ const isGateProgram = (opts: { name: string; args: string[] }): boolean => {
72
+ const { name, args } = opts;
73
+ const first = args.find((arg) => !arg.startsWith('-')) ?? '';
74
+
75
+ if (name === 'bun') {
76
+ return (
77
+ first === 'test' ||
78
+ (first === 'run' && GATE_SCRIPTS.has(args[args.indexOf('run') + 1] ?? '')) ||
79
+ (first === 'x' && args.includes('vulcan') && args.includes('doctor'))
80
+ );
81
+ }
82
+
83
+ if (name === 'bunx' || name === 'npx') {
84
+ return GATE_TOOLS.has(first);
85
+ }
86
+
87
+ if (name === 'make') {
88
+ return args.some((arg) => !arg.startsWith('-') && GATE_MAKE_TARGET.test(arg));
89
+ }
90
+
91
+ if (name === 'npm' || name === 'pnpm' || name === 'yarn') {
92
+ return (
93
+ GATE_SCRIPTS.has(first) ||
94
+ (first === 'run' && GATE_SCRIPTS.has(args[args.indexOf('run') + 1] ?? ''))
95
+ );
96
+ }
97
+
98
+ if (name === 'cargo' || name === 'go') {
99
+ return first === 'test';
100
+ }
101
+
102
+ if (name === 'vulcan') {
103
+ return first === 'doctor';
104
+ }
105
+
106
+ return GATE_TOOLS.has(name);
107
+ };
108
+
109
+ /** The gates a command line runs (tests, lint, build, the project's own gates), each as a short name. */
110
+ export const gatesOf = (opts: { command: string }): string[] =>
111
+ programsOf({ command: opts.command })
112
+ .filter((program) => isGateProgram(program))
113
+ .map((program) =>
114
+ [program.name, ...program.args].join(' ').slice(0, SignalConstants.GATE_KEY_LENGTH),
115
+ );
116
+
117
+ /** What an edited file is for the nudge: a skill (with its name), a rules file, or neither. */
118
+ export const watchedFileOf = (opts: {
119
+ path: string;
120
+ }): { kind: string; name: string } | undefined => {
121
+ if (SCRATCH.test(opts.path)) {
122
+ return undefined;
123
+ }
124
+
125
+ const skill = SKILL_FILE.exec(opts.path)?.[1];
126
+
127
+ if (skill !== undefined) {
128
+ return { kind: WatchedKinds.SKILL, name: skill };
129
+ }
130
+
131
+ return RULES_FILE.test(opts.path) ? { kind: WatchedKinds.RULES, name: opts.path } : undefined;
132
+ };
@@ -0,0 +1,88 @@
1
+ export class SignalConstants {
2
+ /** The turn's notes: one JSON line per call, appended, so parallel hook processes never overwrite each other. */
3
+ static readonly LOG_FILE = 'cache/signals.jsonl';
4
+ /** The log is rewritten smaller at a new turn once it grows past this. */
5
+ static readonly COMPACT_BYTES = 32 * 1024;
6
+ /** Only the end of an oversized log is read. */
7
+ static readonly READ_TAIL_BYTES = 256 * 1024;
8
+ static readonly MAX_EVENTS = 30;
9
+ /** The same advisory is not repeated inside this window. */
10
+ static readonly DEBOUNCE_MS = 5 * 60 * 1000;
11
+ static readonly SAME_CALL_LIMIT = 3;
12
+ /** Identical calls further apart than this are polling, not a loop. */
13
+ static readonly POLL_WINDOW_MS = 60 * 1000;
14
+ static readonly ALTERNATION_LENGTH = 6;
15
+ static readonly FAILURE_LIMIT = 3;
16
+ static readonly FAILURE_WINDOW = 6;
17
+ static readonly EVENT_KEY_LENGTH = 12;
18
+ static readonly GATE_KEY_LENGTH = 80;
19
+ }
20
+
21
+ export class EntryKinds {
22
+ static readonly TURN = 'turn';
23
+ static readonly CALL = 'call';
24
+ static readonly NOTE = 'note';
25
+ }
26
+
27
+ export class WatchedKinds {
28
+ static readonly SKILL = 'skill';
29
+ static readonly RULES = 'rules';
30
+ }
31
+
32
+ /** What a reply claimed that the turn's tool calls do not back. Both are logged, never blocking. */
33
+ export class ClaimClasses {
34
+ static readonly CONTRADICTED_COMPLETION = 'contradicted-completion';
35
+ static readonly PUBLIC_CLAIM_NO_PROBE = 'public-claim-no-probe';
36
+ static readonly SCHEME_SET = new Set<string>([
37
+ this.CONTRADICTED_COMPLETION,
38
+ this.PUBLIC_CLAIM_NO_PROBE,
39
+ ]);
40
+ static isValid(value: string): boolean {
41
+ return this.SCHEME_SET.has(value);
42
+ }
43
+ }
44
+
45
+ /** Phrases that say something is in public state, and that the work is complete and checked; English by default. */
46
+ export class ClaimWords {
47
+ static readonly PUBLIC = [
48
+ 'published',
49
+ 'released',
50
+ 'deployed',
51
+ 'is live',
52
+ 'went live',
53
+ 'now live',
54
+ ];
55
+ static readonly DONE = [
56
+ 'all tests pass',
57
+ 'tests pass',
58
+ 'tests are passing',
59
+ 'everything passes',
60
+ 'all checks pass',
61
+ 'all green',
62
+ 'build passes',
63
+ 'lint is clean',
64
+ 'gates pass',
65
+ ];
66
+ /** A sentence with one of these is not a claim: it denies, asks, or speaks of what is not yet so. */
67
+ static readonly NEGATIONS = [
68
+ 'not',
69
+ 'no',
70
+ 'nothing',
71
+ 'never',
72
+ 'yet',
73
+ 'whether',
74
+ 'if',
75
+ 'unless',
76
+ 'until',
77
+ 'when',
78
+ 'once',
79
+ 'will',
80
+ 'would',
81
+ 'should',
82
+ 'could',
83
+ 'might',
84
+ 'unpublished',
85
+ 'unreleased',
86
+ "n't",
87
+ ];
88
+ }
@@ -0,0 +1,5 @@
1
+ export * from './constants.ts';
2
+ export * from './classify.ts';
3
+ export * from './state.ts';
4
+ export * from './loop.ts';
5
+ export * from './claims.ts';
@@ -0,0 +1,46 @@
1
+ import { SignalConstants } from './constants.ts';
2
+ import type { ISignalEvent } from './state.ts';
3
+
4
+ /**
5
+ * What the last calls look like when an agent is going round in circles: the same call three times within
6
+ * a minute, two calls alternating for three rounds, or one call failing again and again. `undefined` when nothing looks stuck.
7
+ */
8
+ export const loopOf = (opts: { events: ISignalEvent[] }): string | undefined => {
9
+ const { events } = opts;
10
+ const last = events.slice(-SignalConstants.SAME_CALL_LIMIT);
11
+ const first = last[0];
12
+
13
+ if (
14
+ first !== undefined &&
15
+ last.length === SignalConstants.SAME_CALL_LIMIT &&
16
+ last.every((event) => event.key === first.key) &&
17
+ (last.at(-1)?.at ?? 0) - first.at < SignalConstants.POLL_WINDOW_MS
18
+ ) {
19
+ return `the same ${first.tool} call ${SignalConstants.SAME_CALL_LIMIT} times in a row`;
20
+ }
21
+
22
+ const cycle = events.slice(-SignalConstants.ALTERNATION_LENGTH);
23
+ const [one, two] = cycle;
24
+
25
+ if (
26
+ cycle.length === SignalConstants.ALTERNATION_LENGTH &&
27
+ one !== undefined &&
28
+ two !== undefined &&
29
+ one.key !== two.key &&
30
+ cycle.every((event, index) => event.key === (index % 2 === 0 ? one.key : two.key))
31
+ ) {
32
+ return `${one.tool} and ${two.tool} calls alternating without progress`;
33
+ }
34
+
35
+ const recent = events.slice(-SignalConstants.FAILURE_WINDOW);
36
+
37
+ for (const key of new Set(recent.map((event) => event.key))) {
38
+ const failures = recent.filter((event) => event.key === key && !event.isOk);
39
+
40
+ if (failures.length >= SignalConstants.FAILURE_LIMIT) {
41
+ return `${failures[0]?.tool ?? 'a tool'} failing ${SignalConstants.FAILURE_LIMIT} times with the same input in the last ${SignalConstants.FAILURE_WINDOW} calls`;
42
+ }
43
+ }
44
+
45
+ return undefined;
46
+ };
@@ -0,0 +1,276 @@
1
+ import {
2
+ appendFileSync,
3
+ closeSync,
4
+ fstatSync,
5
+ lstatSync,
6
+ mkdirSync,
7
+ openSync,
8
+ readSync,
9
+ renameSync,
10
+ rmSync,
11
+ writeFileSync,
12
+ } from 'node:fs';
13
+ import { randomBytes } from 'node:crypto';
14
+ import { dirname, join } from 'node:path';
15
+ import { localRootOf } from '../local/scan.ts';
16
+ import { EntryKinds, SignalConstants } from './constants.ts';
17
+
18
+ /** One line of the log. Only the fields of its kind are set. */
19
+ export interface ISignalEntry {
20
+ kind: string;
21
+ /** The session and the agent inside it ('' for the main agent) the line belongs to. */
22
+ session: string;
23
+ agent: string;
24
+ at: number;
25
+ tool: string;
26
+ key: string;
27
+ isOk: boolean;
28
+ isProbe: boolean;
29
+ /** The gate commands the call ran, as short names. */
30
+ gates: string[];
31
+ isEdit: boolean;
32
+ /** The name of an advisory already given. */
33
+ name: string;
34
+ }
35
+
36
+ export interface ISignalEvent {
37
+ tool: string;
38
+ key: string;
39
+ isOk: boolean;
40
+ at: number;
41
+ }
42
+
43
+ /** What the log says about the current turn of one session. */
44
+ export interface ISignalState {
45
+ turnAt: number;
46
+ /** The calls of the turn, for the agent asked about. */
47
+ events: ISignalEvent[];
48
+ /** The last public-state probe of the turn, by any agent. */
49
+ probeAt: number;
50
+ /** Gates whose latest run in the turn failed, by any agent. */
51
+ failedGates: string[];
52
+ editAt: number;
53
+ /** When each advisory was last given, by name. */
54
+ notedAt: Record<string, number>;
55
+ }
56
+
57
+ export const isRecord = (opts: { value: unknown }): opts is { value: Record<string, unknown> } =>
58
+ typeof opts.value === 'object' && opts.value !== null && !Array.isArray(opts.value);
59
+
60
+ const recordOf = (opts: { value: unknown }): Record<string, unknown> =>
61
+ typeof opts.value === 'object' && opts.value !== null && !Array.isArray(opts.value)
62
+ ? Object.fromEntries(Object.entries(opts.value))
63
+ : {};
64
+
65
+ const numberOf = (opts: { value: unknown }): number =>
66
+ typeof opts.value === 'number' && Number.isFinite(opts.value) ? opts.value : 0;
67
+
68
+ const stringOf = (opts: { value: unknown }): string =>
69
+ typeof opts.value === 'string' ? opts.value : '';
70
+
71
+ /** The log of a trusted `.agents/local/`; neither the cache folder nor the file may be a link, or not a plain file. */
72
+ const logFileOf = (opts: { root: string; create: boolean }): string | undefined => {
73
+ const local = localRootOf({ root: opts.root });
74
+
75
+ if (local === undefined) {
76
+ return undefined;
77
+ }
78
+
79
+ const file = join(local, SignalConstants.LOG_FILE);
80
+ const directory = dirname(file);
81
+
82
+ try {
83
+ const kind = lstatSync(directory, { throwIfNoEntry: false });
84
+
85
+ if (kind === undefined) {
86
+ if (!opts.create) {
87
+ return undefined;
88
+ }
89
+
90
+ mkdirSync(directory, { recursive: true });
91
+ } else if (!kind.isDirectory()) {
92
+ return undefined;
93
+ }
94
+
95
+ const entry = lstatSync(file, { throwIfNoEntry: false });
96
+
97
+ return entry === undefined || entry.isFile() ? file : undefined;
98
+ } catch {
99
+ return undefined;
100
+ }
101
+ };
102
+
103
+ const entryOf = (opts: { value: unknown }): ISignalEntry | undefined => {
104
+ const raw = recordOf({ value: opts.value });
105
+ const kind = stringOf({ value: raw.kind });
106
+
107
+ if (kind !== EntryKinds.TURN && kind !== EntryKinds.CALL && kind !== EntryKinds.NOTE) {
108
+ return undefined;
109
+ }
110
+
111
+ return {
112
+ kind,
113
+ session: stringOf({ value: raw.session }),
114
+ agent: stringOf({ value: raw.agent }),
115
+ at: numberOf({ value: raw.at }),
116
+ tool: stringOf({ value: raw.tool }),
117
+ key: stringOf({ value: raw.key }),
118
+ isOk: raw.isOk === true,
119
+ isProbe: raw.isProbe === true,
120
+ gates: Array.isArray(raw.gates)
121
+ ? raw.gates.filter((gate): gate is string => typeof gate === 'string')
122
+ : [],
123
+ isEdit: raw.isEdit === true,
124
+ name: stringOf({ value: raw.name }),
125
+ };
126
+ };
127
+
128
+ /** The log's lines, the end only when it is large; a damaged line is skipped. */
129
+ const readEntries = (opts: { file: string }): ISignalEntry[] => {
130
+ let text = '';
131
+
132
+ try {
133
+ const descriptor = openSync(opts.file, 'r');
134
+
135
+ try {
136
+ const { size } = fstatSync(descriptor);
137
+ const length = Math.min(size, SignalConstants.READ_TAIL_BYTES);
138
+ const buffer = Buffer.alloc(length);
139
+
140
+ readSync(descriptor, buffer, 0, length, size - length);
141
+ text = buffer.toString('utf8');
142
+ } finally {
143
+ closeSync(descriptor);
144
+ }
145
+ } catch {
146
+ return [];
147
+ }
148
+
149
+ const entries: ISignalEntry[] = [];
150
+
151
+ for (const line of text.split('\n')) {
152
+ try {
153
+ const entry = entryOf({ value: JSON.parse(line) });
154
+
155
+ if (entry !== undefined) {
156
+ entries.push(entry);
157
+ }
158
+ } catch {
159
+ // A damaged or cut line: the log is advisory.
160
+ }
161
+ }
162
+
163
+ return entries;
164
+ };
165
+
166
+ const EMPTY_STATE = (): ISignalState => ({
167
+ turnAt: 0,
168
+ events: [],
169
+ probeAt: 0,
170
+ failedGates: [],
171
+ editAt: 0,
172
+ notedAt: {},
173
+ });
174
+
175
+ /** The current turn of `session`: its last prompt, then the calls since. `agent` narrows the events only. */
176
+ export const readSignals = (opts: {
177
+ root: string;
178
+ session: string;
179
+ agent?: string;
180
+ }): ISignalState => {
181
+ const file = logFileOf({ root: opts.root, create: false });
182
+
183
+ if (file === undefined) {
184
+ return EMPTY_STATE();
185
+ }
186
+
187
+ const entries = readEntries({ file });
188
+ const state = EMPTY_STATE();
189
+ const gates = new Map<string, boolean>();
190
+ const mine = entries.filter(
191
+ (entry) => entry.kind === EntryKinds.NOTE || entry.session === opts.session,
192
+ );
193
+ const turnIndex = mine.findLastIndex((entry) => entry.kind === EntryKinds.TURN);
194
+
195
+ for (const entry of mine) {
196
+ if (entry.kind === EntryKinds.NOTE) {
197
+ state.notedAt[entry.name] = Math.max(state.notedAt[entry.name] ?? 0, entry.at);
198
+ }
199
+ }
200
+
201
+ state.turnAt = turnIndex === -1 ? 0 : (mine[turnIndex]?.at ?? 0);
202
+
203
+ for (const entry of mine.slice(turnIndex + 1)) {
204
+ if (entry.kind !== EntryKinds.CALL) {
205
+ continue;
206
+ }
207
+
208
+ if (opts.agent === undefined || entry.agent === opts.agent) {
209
+ state.events.push({ tool: entry.tool, key: entry.key, isOk: entry.isOk, at: entry.at });
210
+ }
211
+
212
+ if (entry.isProbe) {
213
+ state.probeAt = Math.max(state.probeAt, entry.at);
214
+ }
215
+
216
+ if (entry.isEdit) {
217
+ state.editAt = Math.max(state.editAt, entry.at);
218
+ }
219
+
220
+ for (const gate of entry.gates) {
221
+ gates.set(gate, entry.isOk);
222
+ }
223
+ }
224
+
225
+ state.events = state.events.slice(-SignalConstants.MAX_EVENTS);
226
+ state.failedGates = [...gates.entries()].filter(([, isOk]) => !isOk).map(([gate]) => gate);
227
+
228
+ return state;
229
+ };
230
+
231
+ /** Adds one line; appending a short line is atomic, so parallel hook processes lose nothing. */
232
+ export const appendSignal = (opts: {
233
+ root: string;
234
+ entry: Partial<ISignalEntry> & { kind: string; at: number };
235
+ }): void => {
236
+ const file = logFileOf({ root: opts.root, create: true });
237
+
238
+ if (file === undefined) {
239
+ return;
240
+ }
241
+
242
+ appendFileSync(file, `${JSON.stringify(opts.entry)}\n`, { mode: 0o600 });
243
+ };
244
+
245
+ /** A new turn for `session`: a marker line; a log grown past its size is first cut to what still matters. */
246
+ export const startTurn = (opts: { root: string; session: string; now?: number }): void => {
247
+ const file = logFileOf({ root: opts.root, create: true });
248
+
249
+ if (file === undefined) {
250
+ return;
251
+ }
252
+
253
+ const now = opts.now ?? Date.now();
254
+
255
+ if ((lstatSync(file, { throwIfNoEntry: false })?.size ?? 0) > SignalConstants.COMPACT_BYTES) {
256
+ const kept = readEntries({ file }).filter(
257
+ (entry) => entry.kind === EntryKinds.NOTE || now - entry.at < SignalConstants.DEBOUNCE_MS,
258
+ );
259
+ const partial = `${file}.${randomBytes(6).toString('hex')}.partial`;
260
+
261
+ try {
262
+ writeFileSync(partial, kept.map((entry) => `${JSON.stringify(entry)}\n`).join(''), {
263
+ mode: 0o600,
264
+ flag: 'wx',
265
+ });
266
+ renameSync(partial, file);
267
+ } finally {
268
+ rmSync(partial, { force: true });
269
+ }
270
+ }
271
+
272
+ appendSignal({
273
+ root: opts.root,
274
+ entry: { kind: EntryKinds.TURN, session: opts.session, at: now },
275
+ });
276
+ };
@@ -143,8 +143,8 @@ export const planAgentFiles = (opts: { root: string; agents: string[] }): ISyncA
143
143
  let sharedPlanned = false;
144
144
 
145
145
  return readAgentTable()
146
- .filter(entry => opts.agents.includes(entry.id))
147
- .flatMap(entry => {
146
+ .filter((entry) => opts.agents.includes(entry.id))
147
+ .flatMap((entry) => {
148
148
  if (entry.mcp.scope === AgentScopes.PROJECT) {
149
149
  return planAgentMcp({ root: opts.root, entry });
150
150
  }
@@ -162,5 +162,5 @@ export const planAgentFiles = (opts: { root: string; agents: string[] }): ISyncA
162
162
  /** One line per note of a chosen agent (a trust prompt only the user can answer). */
163
163
  export const agentNotes = (opts: { agents: string[] }): { agent: string; note: string }[] =>
164
164
  readAgentTable()
165
- .filter(entry => opts.agents.includes(entry.id))
166
- .flatMap(entry => entry.notes.map(note => ({ agent: entry.id, note })));
165
+ .filter((entry) => opts.agents.includes(entry.id))
166
+ .flatMap((entry) => entry.notes.map((note) => ({ agent: entry.id, note })));
@@ -65,7 +65,7 @@ const isSkillLink = (opts: { root: string; path: string }): boolean => {
65
65
  join(opts.root, '.agents', SyncConstants.SKILLS_DIRECTORY),
66
66
  ];
67
67
 
68
- return shipped.some(directory => target === directory || target.startsWith(`${directory}/`));
68
+ return shipped.some((directory) => target === directory || target.startsWith(`${directory}/`));
69
69
  };
70
70
 
71
71
  const removeFile = (opts: { path: string; note?: string; parent?: string }): ISyncAction => ({
@@ -191,8 +191,8 @@ const planSkillLinkRemoval = (opts: { root: string; directory: string }): ISyncA
191
191
  }
192
192
 
193
193
  const links = readdirSync(target)
194
- .map(name => join(target, name))
195
- .filter(path => isSkillLink({ root: opts.root, path }));
194
+ .map((name) => join(target, name))
195
+ .filter((path) => isSkillLink({ root: opts.root, path }));
196
196
 
197
197
  return links.map((path, index) => ({
198
198
  path,
@@ -261,16 +261,16 @@ export const planAgentRemoval = (opts: {
261
261
  }): ISyncAction[] => {
262
262
  const table = readAgentTable();
263
263
  const kept = new Set(
264
- table.filter(entry => opts.remaining.includes(entry.id)).map(entry => entry.skills.dir),
264
+ table.filter((entry) => opts.remaining.includes(entry.id)).map((entry) => entry.skills.dir),
265
265
  );
266
266
  const cleaned = new Set<string>();
267
267
  const actions: ISyncAction[] = [];
268
268
  const stillReadsShared = table.some(
269
- entry => opts.remaining.includes(entry.id) && entry.mcp.scope === AgentScopes.SHARED,
269
+ (entry) => opts.remaining.includes(entry.id) && entry.mcp.scope === AgentScopes.SHARED,
270
270
  );
271
271
  let sharedDone = false;
272
272
 
273
- for (const entry of table.filter(item => opts.removed.includes(item.id))) {
273
+ for (const entry of table.filter((item) => opts.removed.includes(item.id))) {
274
274
  if (entry.id === AgentConstants.DEFAULT_AGENT) {
275
275
  actions.push(...planClaudeRemoval({ root: opts.root }));
276
276
  }
@@ -25,7 +25,7 @@ export const mergedAtlasBlock = (opts: {
25
25
 
26
26
  const block = renderAtlasBlock({
27
27
  project: projectNameOf(opts),
28
- sources: opts.config.atlas.sources.map(source => source.name),
28
+ sources: opts.config.atlas.sources.map((source) => source.name),
29
29
  });
30
30
 
31
31
  return { path, ...mergeAtlasBlock({ text: readFileSync(path, 'utf8'), block }) };