opencastle 1.6.3 → 1.6.4

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 (155) hide show
  1. package/README.md +9 -9
  2. package/bin/cli.mjs +6 -4
  3. package/dist/cli/adapters/adapter-contract.test.js +1 -1
  4. package/dist/cli/adapters/single-file-base.d.ts.map +1 -1
  5. package/dist/cli/adapters/single-file-base.js +2 -12
  6. package/dist/cli/adapters/single-file-base.js.map +1 -1
  7. package/dist/cli/bootstrap.js +1 -1
  8. package/dist/cli/bootstrap.js.map +1 -1
  9. package/dist/cli/command-namespace.test.js +4 -21
  10. package/dist/cli/command-namespace.test.js.map +1 -1
  11. package/dist/cli/convoy/engine.js +2 -2
  12. package/dist/cli/convoy/engine.js.map +1 -1
  13. package/dist/cli/convoy/read-model.d.ts +8 -15
  14. package/dist/cli/convoy/read-model.d.ts.map +1 -1
  15. package/dist/cli/convoy/read-model.js +9 -68
  16. package/dist/cli/convoy/read-model.js.map +1 -1
  17. package/dist/cli/convoy/read-model.test.js +6 -25
  18. package/dist/cli/convoy/read-model.test.js.map +1 -1
  19. package/dist/cli/convoy/spec-builder.d.ts +2 -2
  20. package/dist/cli/convoy/spec-builder.d.ts.map +1 -1
  21. package/dist/cli/convoy/spec-builder.js +1 -1
  22. package/dist/cli/dashboard.js +1 -1
  23. package/dist/cli/dashboard.test.js +10 -2
  24. package/dist/cli/dashboard.test.js.map +1 -1
  25. package/dist/cli/dispatcher.test.js +5 -2
  26. package/dist/cli/dispatcher.test.js.map +1 -1
  27. package/dist/cli/docs-accuracy.test.js +5 -1
  28. package/dist/cli/docs-accuracy.test.js.map +1 -1
  29. package/dist/cli/doctor.d.ts.map +1 -1
  30. package/dist/cli/doctor.js +0 -25
  31. package/dist/cli/doctor.js.map +1 -1
  32. package/dist/cli/pipeline.d.ts +1 -1
  33. package/dist/cli/pipeline.flow.test.js +77 -77
  34. package/dist/cli/pipeline.flow.test.js.map +1 -1
  35. package/dist/cli/pipeline.js +24 -24
  36. package/dist/cli/pipeline.js.map +1 -1
  37. package/dist/cli/plan.d.ts +8 -2
  38. package/dist/cli/plan.d.ts.map +1 -1
  39. package/dist/cli/plan.js +18 -12
  40. package/dist/cli/plan.js.map +1 -1
  41. package/dist/cli/plan.test.js +17 -19
  42. package/dist/cli/plan.test.js.map +1 -1
  43. package/dist/cli/update.d.ts.map +1 -1
  44. package/dist/cli/update.js +1 -58
  45. package/dist/cli/update.js.map +1 -1
  46. package/package.json +1 -1
  47. package/src/cli/adapters/adapter-contract.test.ts +1 -1
  48. package/src/cli/adapters/single-file-base.ts +2 -11
  49. package/src/cli/bootstrap.ts +1 -1
  50. package/src/cli/command-namespace.test.ts +5 -22
  51. package/src/cli/convoy/engine.ts +2 -2
  52. package/src/{orchestrator/prompts/assess-complexity.prompt.md → cli/convoy/prompts/convoy-assess.prompt.md} +0 -3
  53. package/src/{orchestrator/prompts/fix-convoy.prompt.md → cli/convoy/prompts/convoy-plan-fix.prompt.md} +0 -3
  54. package/src/{orchestrator/prompts/validate-convoy.prompt.md → cli/convoy/prompts/convoy-plan-review.prompt.md} +0 -3
  55. package/src/{orchestrator/prompts/generate-convoy.prompt.md → cli/convoy/prompts/convoy-plan.prompt.md} +0 -2
  56. package/src/{orchestrator/prompts/fix-prd.prompt.md → cli/convoy/prompts/convoy-prd-fix.prompt.md} +0 -3
  57. package/src/{orchestrator/prompts/validate-prd.prompt.md → cli/convoy/prompts/convoy-prd-review.prompt.md} +0 -3
  58. package/src/{orchestrator/prompts/generate-prd.prompt.md → cli/convoy/prompts/convoy-prd.prompt.md} +0 -3
  59. package/src/cli/convoy/read-model.test.ts +5 -29
  60. package/src/cli/convoy/read-model.ts +11 -71
  61. package/src/cli/convoy/spec-builder.ts +2 -2
  62. package/src/cli/dashboard/dashboard.js +2 -4
  63. package/src/cli/dashboard.test.ts +10 -2
  64. package/src/cli/dashboard.ts +1 -1
  65. package/src/cli/dispatcher.test.ts +6 -2
  66. package/src/cli/docs-accuracy.test.ts +5 -1
  67. package/src/cli/doctor.ts +0 -26
  68. package/src/cli/pipeline.flow.test.ts +78 -78
  69. package/src/cli/pipeline.ts +25 -25
  70. package/src/cli/plan.test.ts +18 -20
  71. package/src/cli/plan.ts +18 -12
  72. package/src/cli/update.ts +1 -66
  73. package/src/orchestrator/agent-workflows/README.md +10 -18
  74. package/src/orchestrator/agent-workflows/data-pipeline.md +7 -140
  75. package/src/orchestrator/agent-workflows/database-migration.md +7 -153
  76. package/src/orchestrator/agent-workflows/performance-optimization.md +6 -119
  77. package/src/orchestrator/agent-workflows/refactoring.md +8 -137
  78. package/src/orchestrator/agent-workflows/schema-changes.md +8 -159
  79. package/src/orchestrator/agent-workflows/security-audit.md +7 -142
  80. package/src/orchestrator/agent-workflows/shared-delivery-phase.md +8 -25
  81. package/src/orchestrator/agents/architect.agent.md +2 -14
  82. package/src/orchestrator/agents/content-engineer.agent.md +8 -10
  83. package/src/orchestrator/agents/data-engineer.agent.md +8 -8
  84. package/src/orchestrator/agents/developer.agent.md +3 -10
  85. package/src/orchestrator/agents/devops-expert.agent.md +0 -3
  86. package/src/orchestrator/agents/performance-expert.agent.md +2 -3
  87. package/src/orchestrator/agents/security-expert.agent.md +10 -12
  88. package/src/orchestrator/agents/team-lead.agent.md +31 -75
  89. package/src/orchestrator/agents/testing-expert.agent.md +3 -6
  90. package/src/orchestrator/agents/ui-ux-expert.agent.md +1 -4
  91. package/src/orchestrator/agents/writer.agent.md +0 -3
  92. package/src/orchestrator/customizations/README.md +3 -4
  93. package/src/orchestrator/customizations/agents/agent-registry.md +3 -3
  94. package/src/orchestrator/customizations/agents/skill-matrix.json +6 -42
  95. package/src/orchestrator/instructions/general.instructions.md +10 -37
  96. package/src/orchestrator/prompts/bootstrap-customizations.prompt.md +4 -6
  97. package/src/orchestrator/prompts/brainstorm.prompt.md +7 -12
  98. package/src/orchestrator/prompts/bug-fix.prompt.md +19 -100
  99. package/src/orchestrator/prompts/convoy.prompt.md +20 -0
  100. package/src/orchestrator/prompts/create-skill.prompt.md +1 -5
  101. package/src/orchestrator/prompts/implement-feature.prompt.md +22 -93
  102. package/src/orchestrator/prompts/resolve-pr-comments.prompt.md +1 -5
  103. package/src/orchestrator/skills/api-patterns/SKILL.md +21 -18
  104. package/src/orchestrator/skills/deployment-infrastructure/SKILL.md +1 -1
  105. package/src/orchestrator/skills/fast-review/SKILL.md +28 -65
  106. package/src/orchestrator/skills/frontend-design/REFERENCE.md +0 -1
  107. package/src/orchestrator/skills/frontend-design/SKILL.md +3 -1
  108. package/src/orchestrator/skills/git-workflow/SKILL.md +18 -34
  109. package/src/orchestrator/skills/panel-majority-vote/SKILL.md +16 -46
  110. package/src/orchestrator/skills/security-hardening/SKILL.md +20 -19
  111. package/src/orchestrator/skills/self-improvement/LESSON-CATEGORIES.md +2 -2
  112. package/src/orchestrator/skills/self-improvement/SKILL.md +21 -46
  113. package/src/orchestrator/skills/technical-writing/SKILL.md +3 -1
  114. package/src/orchestrator/skills/technical-writing/TEMPLATES.md +23 -0
  115. package/src/orchestrator/skills/testing-workflow/SKILL.md +21 -23
  116. package/src/orchestrator/skills/validation-gates/REFERENCE.md +2 -14
  117. package/src/orchestrator/skills/validation-gates/SKILL.md +10 -88
  118. package/dist/cli/log.d.ts +0 -44
  119. package/dist/cli/log.d.ts.map +0 -1
  120. package/dist/cli/log.js +0 -336
  121. package/dist/cli/log.js.map +0 -1
  122. package/dist/cli/log.test.d.ts +0 -2
  123. package/dist/cli/log.test.d.ts.map +0 -1
  124. package/dist/cli/log.test.js +0 -208
  125. package/dist/cli/log.test.js.map +0 -1
  126. package/src/cli/log.test.ts +0 -228
  127. package/src/cli/log.ts +0 -374
  128. package/src/orchestrator/agent-workflows/bug-fix.md +0 -130
  129. package/src/orchestrator/agent-workflows/feature-implementation.md +0 -232
  130. package/src/orchestrator/instructions/ai-optimization.instructions.md +0 -17
  131. package/src/orchestrator/prompts/quick-refinement.prompt.md +0 -110
  132. package/src/orchestrator/skills/agent-hooks/HOOKS-REFERENCE.md +0 -44
  133. package/src/orchestrator/skills/agent-hooks/SKILL.md +0 -80
  134. package/src/orchestrator/skills/agent-memory/KNOWLEDGE-GRAPH.md +0 -49
  135. package/src/orchestrator/skills/agent-memory/SKILL.md +0 -50
  136. package/src/orchestrator/skills/code-commenting/SKILL.md +0 -18
  137. package/src/orchestrator/skills/context-map/REFERENCE.md +0 -67
  138. package/src/orchestrator/skills/context-map/SKILL.md +0 -71
  139. package/src/orchestrator/skills/decomposition/SKILL.md +0 -103
  140. package/src/orchestrator/skills/documentation-standards/SKILL.md +0 -33
  141. package/src/orchestrator/skills/fast-review/REFERENCE.md +0 -28
  142. package/src/orchestrator/skills/memory-merger/SKILL.md +0 -77
  143. package/src/orchestrator/skills/observability-logging/LOG-SCHEMA.md +0 -238
  144. package/src/orchestrator/skills/observability-logging/SKILL.md +0 -73
  145. package/src/orchestrator/skills/orchestration-protocols/REFERENCE.md +0 -38
  146. package/src/orchestrator/skills/orchestration-protocols/SKILL.md +0 -120
  147. package/src/orchestrator/skills/panel-majority-vote/REFERENCE.md +0 -49
  148. package/src/orchestrator/skills/panel-majority-vote/panel-report.template.md +0 -38
  149. package/src/orchestrator/skills/performance-optimization/SKILL.md +0 -23
  150. package/src/orchestrator/skills/project-consistency/SKILL.md +0 -80
  151. package/src/orchestrator/skills/project-consistency/TEMPLATES.md +0 -35
  152. package/src/orchestrator/skills/react-development/SKILL.md +0 -24
  153. package/src/orchestrator/skills/session-checkpoints/CHECKPOINT-TEMPLATE.md +0 -56
  154. package/src/orchestrator/skills/session-checkpoints/SKILL.md +0 -40
  155. package/src/orchestrator/skills/team-lead-reference/SKILL.md +0 -126
@@ -1,228 +0,0 @@
1
- import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
2
- import { tmpdir } from 'node:os'
3
- import { join, resolve } from 'node:path'
4
- import { afterEach, describe, expect, it, vi } from 'vitest'
5
- import log, { LOG_RECORDS, parseLogArgs } from './log.js'
6
-
7
- const repoRoot = resolve(import.meta.dirname, '..', '..')
8
- const README = join(repoRoot, 'src', 'orchestrator', 'skills', 'observability-logging', 'LOG-SCHEMA.md')
9
- const SKILL = join(repoRoot, 'src', 'orchestrator', 'skills', 'observability-logging', 'SKILL.md')
10
-
11
- /** The `opencastle log …` command lines in a document's sh blocks, continuation lines joined. */
12
- function examples(path: string): string[] {
13
- const text = readFileSync(path, 'utf8')
14
- const out: string[] = []
15
- for (const block of text.matchAll(/```sh\n([\s\S]*?)```/g)) {
16
- const joined = block[1].replace(/\\\n\s*/g, ' ')
17
- for (const line of joined.split('\n')) if (line.trim().startsWith('opencastle log')) out.push(line.trim())
18
- }
19
- return out
20
- }
21
-
22
- /** Split a shell line into words, as a POSIX shell would for these examples: double quotes and $MODEL. */
23
- function words(line: string, model: string): string[] {
24
- const out: string[] = []
25
- for (const m of line.matchAll(/"((?:[^"\\]|\\.)*)"|(\S+)/g)) out.push((m[1] ?? m[2]).replace(/\$MODEL/g, model))
26
- return out.slice(2) // drop "opencastle log"
27
- }
28
-
29
- /** The same line with `--model "$MODEL"` (or `--reviewer_model`) left out, as the README says to when none was reported. */
30
- function withoutModel(args: string[]): string[] {
31
- const out: string[] = []
32
- for (let i = 0; i < args.length; i++) {
33
- if (args[i] === '--model' || args[i] === '--reviewer_model') { i++; continue }
34
- out.push(args[i])
35
- }
36
- return out
37
- }
38
-
39
- function errorsOf(args: string[]): string[] {
40
- const parsed = parseLogArgs(args)
41
- return parsed.ok ? [] : parsed.errors
42
- }
43
-
44
- function recordOf(args: string[]): Record<string, unknown> {
45
- const parsed = parseLogArgs(args)
46
- if (!parsed.ok) throw new Error(parsed.errors.join('\n'))
47
- if (parsed.help) throw new Error('help')
48
- return parsed.record
49
- }
50
-
51
- const SESSION = ['--type', 'session', '--agent', 'Developer', '--task', 'Fix it', '--outcome', 'success']
52
-
53
- describe('the documented examples', () => {
54
- const documented = [...examples(README), ...examples(SKILL)]
55
-
56
- it('finds every record type in the README', () => {
57
- const types = examples(README).map((l) => /--type[= ](\w+)/.exec(l)?.[1])
58
- expect(types.sort()).toEqual(Object.keys(LOG_RECORDS).sort())
59
- })
60
-
61
- it.each(documented)('accepts %s', (line) => {
62
- expect(errorsOf(words(line, 'some-model'))).toEqual([])
63
- expect(errorsOf(withoutModel(words(line, 'some-model')))).toEqual([])
64
- })
65
-
66
- it('refuses the examples when $MODEL is empty, as the README warns', () => {
67
- const line = examples(README).find((l) => l.includes('--model'))!
68
- expect(errorsOf(words(line, ''))).toEqual(['--model cannot be empty. Leave it out instead when there is nothing to record.'])
69
- })
70
- })
71
-
72
- describe('the schema is the README schema', () => {
73
- const text = readFileSync(README, 'utf8')
74
- const KIND_TYPE = { text: 'string', count: 'number', number: 'number', boolean: 'boolean', list: 'string[]' }
75
-
76
- it.each(Object.keys(LOG_RECORDS))('%s record: same fields, required flags, types and allowed values', (type) => {
77
- const at = text.indexOf(`(\`type: "${type}"\`)`)
78
- expect(at, `README section for ${type}`).toBeGreaterThan(-1)
79
- const section = text.slice(at, text.indexOf('\n## ', at + 1) === -1 ? undefined : text.indexOf('\n## ', at + 1))
80
- const rows = [...section.matchAll(/^\| `(\w+)` \| `([^`]+)` \| (Yes|No[^|]*) \| ([^\n]*)\|$/gm)]
81
- .filter((m) => m[1] !== 'type' && m[1] !== 'timestamp')
82
- const schema = LOG_RECORDS[type]
83
- expect(rows.map((m) => m[1]).sort()).toEqual(Object.keys(schema).sort())
84
- for (const [, field, docType, required, description] of rows) {
85
- const f = schema[field]
86
- expect(f.required, `${type}.${field} required`).toBe(required === 'Yes')
87
- expect(KIND_TYPE[f.kind], `${type}.${field} type`).toBe(docType)
88
- if (f.values) {
89
- const documentedValues = [...description.matchAll(/`([^`]+)`/g)].map((m) => m[1])
90
- expect([...f.values].sort(), `${type}.${field} values`).toEqual(documentedValues.sort())
91
- }
92
- }
93
- })
94
- })
95
-
96
- describe('what it refuses', () => {
97
- it('a record with none of its required fields', () => {
98
- expect(errorsOf(['--type', 'session'])).toEqual([
99
- '--agent is required.',
100
- '--task is required.',
101
- '--outcome is required: one of success, partial, failed.',
102
- ])
103
- })
104
-
105
- it('values outside an enum', () => {
106
- expect(errorsOf([...SESSION.slice(0, -1), 'banana'])).toEqual(['--outcome must be one of success, partial, failed, not "banana".'])
107
- const review = ['--type', 'review', '--agent', 'D', '--verdict', 'maybe', '--attempt', '1', '--issues_critical', '0',
108
- '--issues_major', '0', '--issues_minor', '0', '--confidence', 'high', '--escalated', 'false']
109
- expect(errorsOf(review)).toEqual(['--verdict must be one of pass, fail, not "maybe".'])
110
- const delegation = ['--type', 'delegation', '--session_id', 's', '--agent', 'D', '--tier', 'utility',
111
- '--mechanism', 'sub-agent', '--outcome', 'success']
112
- expect(errorsOf(delegation)).toEqual(['--tier must be one of premium, standard, economy, not "utility".'])
113
- })
114
-
115
- it('a timestamp from the caller', () => {
116
- expect(errorsOf([...SESSION, '--timestamp', 'yesterday'])).toEqual([
117
- '--timestamp is not accepted: opencastle log sets the timestamp itself.',
118
- ])
119
- })
120
-
121
- it('a flag with no value, instead of storing true', () => {
122
- expect(errorsOf([...SESSION, '--model'])).toEqual(['--model needs a value.'])
123
- expect(errorsOf(['--type', 'session', '--model', '--agent', 'D', '--task', 't', '--outcome', 'success'])).toEqual(['--model needs a value.'])
124
- const panel = ['--type', 'panel', '--panel_key', 'k', '--verdict', 'pass', '--pass_count', '3', '--block_count', '0',
125
- '--must_fix', '0', '--should_fix', '0', '--attempt', '1', '--weighted']
126
- expect(errorsOf(panel)).toEqual(['--weighted needs a value.'])
127
- })
128
-
129
- it('an unknown flag, naming the nearest known one', () => {
130
- expect(errorsOf([...SESSION, '--agnet', 'x'])).toEqual(['Unknown option --agnet for a session record. Did you mean --agent?'])
131
- expect(errorsOf([...SESSION, '--dryRun'])).toEqual(['Unknown option --dryRun for a session record. Did you mean --dry-run?'])
132
- // A field of another record type is unknown here.
133
- expect(errorsOf([...SESSION, '--verdict', 'pass'])[0]).toMatch(/^Unknown option --verdict for a session record/)
134
- expect(errorsOf([...SESSION, '--__proto__', 'x'])[0]).toMatch(/^Unknown option --__proto__/)
135
- })
136
-
137
- it('an unknown or missing type', () => {
138
- expect(errorsOf(['--type', 'sesion'])[0]).toBe('--type "sesion" is not a record type: one of session, delegation, review, panel, dispute. Did you mean session?')
139
- expect(errorsOf(['--agent', 'D'])[0]).toBe('--type is required: one of session, delegation, review, panel, dispute.')
140
- })
141
-
142
- it('numbers that are not numbers, and counts that are not counts', () => {
143
- expect(errorsOf([...SESSION, '--duration_min', 'twelve'])).toEqual(['--duration_min must be a number, 0 or more, not "twelve".'])
144
- expect(errorsOf([...SESSION, '--files_changed', '-1'])).toEqual(['--files_changed must be a whole number, 0 or more, not "-1".'])
145
- expect(errorsOf([...SESSION, '--files_changed', '2.5'])).toEqual(['--files_changed must be a whole number, 0 or more, not "2.5".'])
146
- })
147
-
148
- it('a boolean that is not true or false', () => {
149
- const review = ['--type', 'review', '--agent', 'D', '--verdict', 'pass', '--attempt', '0', '--issues_critical', '0',
150
- '--issues_major', '0', '--issues_minor', '0', '--confidence', 'high', '--escalated', 'yes']
151
- expect(errorsOf(review)).toEqual([
152
- '--attempt must be a whole number, at least 1, not "0".',
153
- '--escalated must be true or false, not "yes".',
154
- ])
155
- })
156
-
157
- it('a stray word, the sign of an unquoted value', () => {
158
- expect(errorsOf(['--type', 'session', '--agent', 'D', '--task', 'Fix', 'bug', '--outcome', 'success'])).toEqual([
159
- 'Unexpected "bug". Every value follows its --field; quote values that contain spaces.',
160
- ])
161
- })
162
-
163
- it('the same field twice', () => {
164
- expect(errorsOf([...SESSION, '--agent', 'Other'])).toEqual(['--agent is given twice.'])
165
- })
166
- })
167
-
168
- describe('what it records', () => {
169
- it('keeps ids and text as typed: no numeric coercion', () => {
170
- const rec = recordOf(['--type', 'delegation', '--session_id', '2024', '--agent', 'D', '--tier', 'standard',
171
- '--mechanism', 'sub-agent', '--outcome', 'success', '--tracker_issue', '007'])
172
- expect(rec.session_id).toBe('2024')
173
- expect(rec.tracker_issue).toBe('007')
174
- expect(recordOf([...SESSION.slice(0, 4), '--task', '007', '--outcome', 'success']).task).toBe('007')
175
- })
176
-
177
- it('converts numbers, booleans and lists by field', () => {
178
- const rec = recordOf(['--type', 'dispute', '--dispute_id', 'DSP-1', '--priority', 'high', '--trigger', 'panel-3x-block',
179
- '--implementing_agent', 'Developer', '--reviewing_agents', 'Reviewer, Panel (3x)', '--total_attempts', '6', '--status', 'pending'])
180
- expect(rec.reviewing_agents).toEqual(['Reviewer', 'Panel (3x)'])
181
- expect(rec.total_attempts).toBe(6)
182
- const review = recordOf(['--type', 'review', '--agent', 'D', '--verdict', 'pass', '--attempt', '1', '--issues_critical', '0',
183
- '--issues_major', '0', '--issues_minor', '2', '--confidence', 'high', '--escalated', 'false', '--duration_sec', '4.5'])
184
- expect(review).toMatchObject({ escalated: false, issues_minor: 2, duration_sec: 4.5 })
185
- })
186
-
187
- it('sets the timestamp itself, first after the type', () => {
188
- const now = new Date('2026-10-03T07:49:09.383Z')
189
- const parsed = parseLogArgs(SESSION, now)
190
- expect(parsed.ok && !parsed.help && Object.entries(parsed.record).slice(0, 2)).toEqual([
191
- ['type', 'session'],
192
- ['timestamp', '2026-10-03T07:49:09.383Z'],
193
- ])
194
- })
195
-
196
- it('treats --help anywhere as a request for help', () => {
197
- expect(parseLogArgs(['--type', 'session', '--help'])).toEqual({ ok: true, help: true })
198
- })
199
- })
200
-
201
- describe('the command', () => {
202
- let dir: string | undefined
203
- afterEach(() => {
204
- vi.restoreAllMocks()
205
- if (dir) rmSync(dir, { recursive: true, force: true })
206
- dir = undefined
207
- })
208
-
209
- it('appends one valid line', async () => {
210
- dir = mkdtempSync(join(tmpdir(), 'log-'))
211
- vi.spyOn(console, 'log').mockImplementation(() => {})
212
- await log({ pkgRoot: repoRoot, args: [...SESSION, '--logs-dir', dir] })
213
- await log({ pkgRoot: repoRoot, args: [...SESSION, '--logs-dir', dir, '--duration_min', '3'] })
214
- const lines = readFileSync(join(dir, 'events.ndjson'), 'utf8').trim().split('\n').map((l) => JSON.parse(l))
215
- expect(lines).toHaveLength(2)
216
- expect(lines[1]).toMatchObject({ type: 'session', agent: 'Developer', duration_min: 3 })
217
- })
218
-
219
- it('writes nothing and exits 1 for a record it refuses', async () => {
220
- dir = mkdtempSync(join(tmpdir(), 'log-'))
221
- const errors: string[] = []
222
- vi.spyOn(console, 'error').mockImplementation((m: string) => { errors.push(m) })
223
- vi.spyOn(process, 'exit').mockImplementation(((code: number) => { throw new Error(`exit ${code}`) }) as never)
224
- await expect(log({ pkgRoot: repoRoot, args: ['--type', 'session', '--logs-dir', dir] })).rejects.toThrow('exit 1')
225
- expect(errors[0]).toBe(' ✗ opencastle log refused a session record:')
226
- expect(() => readFileSync(join(dir!, 'events.ndjson'))).toThrow()
227
- })
228
- })
package/src/cli/log.ts DELETED
@@ -1,374 +0,0 @@
1
- import { mkdir, appendFile, readFile, stat } from 'node:fs/promises'
2
- import { join, dirname } from 'node:path'
3
- import * as v from 'valibot'
4
- import { TIER_IDS } from './tiers.js'
5
- import { nearest } from './nearest.js'
6
- import type { CliContext } from './types.js'
7
-
8
- /**
9
- * `opencastle log` — append one agent record to `.opencastle/logs/events.ndjson`.
10
- *
11
- * Agents call this from generated instructions, so a record it accepts is a
12
- * record every reader of the log has to cope with. It used to accept anything:
13
- * `--type session` with no fields, `--outcome banana`, a value-less `--model`
14
- * stored as `true`, `--task 007` stored as the number 7, `--agnet`, and a
15
- * caller-supplied `--timestamp yesterday`. Each record type is now checked
16
- * against the schema in `skills/observability-logging/LOG-SCHEMA.md`, field by field, and a
17
- * record that does not match is refused with every reason at once.
18
- */
19
-
20
- type Kind = 'text' | 'count' | 'number' | 'boolean' | 'list'
21
-
22
- interface Field {
23
- kind: Kind
24
- required: boolean
25
- /** The only values a text field may take. */
26
- values?: readonly string[]
27
- /** Smallest value of a count. */
28
- min?: number
29
- }
30
-
31
- const req = (kind: Kind, values?: readonly string[]): Field => ({ kind, required: true, values })
32
- const opt = (kind: Kind, values?: readonly string[]): Field => ({ kind, required: false, values })
33
- const attempt: Field = { kind: 'count', required: true, min: 1 }
34
-
35
- const OUTCOMES = ['success', 'partial', 'failed'] as const
36
-
37
- /** The record schemas, as `skills/observability-logging/LOG-SCHEMA.md` documents them. `log.test.ts` holds the two together. */
38
- export const LOG_RECORDS: Record<string, Record<string, Field>> = {
39
- session: {
40
- agent: req('text'),
41
- model: opt('text'),
42
- task: req('text'),
43
- tracker_issue: opt('text'),
44
- outcome: req('text', OUTCOMES),
45
- duration_min: opt('number'),
46
- files_changed: opt('count'),
47
- retries: opt('count'),
48
- lessons_added: opt('list'),
49
- discoveries: opt('list'),
50
- },
51
- delegation: {
52
- session_id: req('text'),
53
- agent: req('text'),
54
- model: opt('text'),
55
- tier: req('text', TIER_IDS),
56
- mechanism: req('text', ['sub-agent', 'background']),
57
- tracker_issue: opt('text'),
58
- outcome: req('text', [...OUTCOMES, 'redirected']),
59
- retries: opt('count'),
60
- phase: opt('count'),
61
- file_partition: opt('list'),
62
- },
63
- review: {
64
- tracker_issue: opt('text'),
65
- agent: req('text'),
66
- reviewer_model: opt('text'),
67
- verdict: req('text', ['pass', 'fail']),
68
- attempt,
69
- issues_critical: req('count'),
70
- issues_major: req('count'),
71
- issues_minor: req('count'),
72
- confidence: req('text', ['low', 'medium', 'high']),
73
- escalated: req('boolean'),
74
- duration_sec: opt('number'),
75
- },
76
- panel: {
77
- panel_key: req('text'),
78
- verdict: req('text', ['pass', 'block']),
79
- pass_count: req('count'),
80
- block_count: req('count'),
81
- must_fix: req('count'),
82
- should_fix: req('count'),
83
- reviewer_model: opt('text'),
84
- weighted: req('boolean'),
85
- attempt,
86
- tracker_issue: opt('text'),
87
- artifacts_count: opt('count'),
88
- report_path: opt('text'),
89
- },
90
- dispute: {
91
- dispute_id: req('text'),
92
- tracker_issue: opt('text'),
93
- priority: req('text', ['critical', 'high', 'medium', 'low']),
94
- trigger: req('text', ['panel-3x-block', 'approach-conflict', 'criteria-conflict', 'architectural-ambiguity', 'external-dependency']),
95
- implementing_agent: req('text'),
96
- reviewing_agents: req('list'),
97
- total_attempts: req('count'),
98
- est_tokens_spent: opt('count'),
99
- status: req('text', ['pending', 'resolved', 'deferred']),
100
- resolution_option_chosen: opt('text'),
101
- resolved_at: opt('text'),
102
- },
103
- }
104
-
105
- const TYPES = Object.keys(LOG_RECORDS)
106
-
107
- type AnySchema = v.GenericSchema<unknown>
108
-
109
- function schemaFor(field: Field): AnySchema {
110
- const text = v.pipe(v.string(), v.nonEmpty())
111
- const base: AnySchema =
112
- field.kind === 'text'
113
- ? field.values ? v.picklist(field.values as string[]) : text
114
- : field.kind === 'count'
115
- ? v.pipe(v.number(), v.integer(), v.minValue(field.min ?? 0))
116
- : field.kind === 'number'
117
- ? v.pipe(v.number(), v.minValue(0))
118
- : field.kind === 'boolean'
119
- ? v.boolean()
120
- : v.pipe(v.array(text), v.minLength(1))
121
- return field.required ? base : v.optional(base)
122
- }
123
-
124
- const SCHEMAS: Record<string, AnySchema> = Object.fromEntries(
125
- Object.entries(LOG_RECORDS).map(([type, fields]) => [
126
- type,
127
- v.strictObject(Object.fromEntries(Object.entries(fields).map(([k, f]) => [k, schemaFor(f)]))),
128
- ]),
129
- )
130
-
131
- /** What a field accepts, in words, for error messages and help. */
132
- function describe(field: Field): string {
133
- if (field.values) return `one of ${field.values.join(', ')}`
134
- switch (field.kind) {
135
- case 'count': return field.min ? `a whole number, at least ${field.min}` : 'a whole number, 0 or more'
136
- case 'number': return 'a number, 0 or more'
137
- case 'boolean': return 'true or false'
138
- case 'list': return 'a comma-separated list'
139
- default: return 'text'
140
- }
141
- }
142
-
143
- const OWN_FLAGS = ['--type', '--logs-dir', '--dry-run', '--help']
144
-
145
- /**
146
- * Turn one argv value into the field's type.
147
- *
148
- * Only numeric fields become numbers. Every id and text field stays exactly as
149
- * typed, so `--session_id 2024` and `--task 007` are the strings "2024" and "007".
150
- */
151
- function convert(raw: string, field: Field | undefined): unknown {
152
- switch (field?.kind) {
153
- case 'count':
154
- case 'number':
155
- return /^-?\d+(\.\d+)?$/.test(raw) ? Number(raw) : raw
156
- case 'boolean':
157
- return raw === 'true' ? true : raw === 'false' ? false : raw
158
- case 'list':
159
- return raw.split(',').map((s) => s.trim()).filter(Boolean)
160
- default:
161
- return raw
162
- }
163
- }
164
-
165
- export type ParsedLog =
166
- | { ok: true; help: true }
167
- | { ok: true; help: false; record: Record<string, unknown>; logsDir: string | null; dryRun: boolean }
168
- | { ok: false; errors: string[]; type: string | null }
169
-
170
- /** Read `opencastle log` arguments into a checked record, or every reason it is not one. */
171
- export function parseLogArgs(args: string[], now: Date = new Date()): ParsedLog {
172
- const errors: string[] = []
173
- const given = new Map<string, string>()
174
- // Fields already reported for how they were passed; the schema check need not repeat them.
175
- const reported = new Set<string>()
176
- let type: string | null = null
177
- let logsDir: string | null = null
178
- let dryRun = false
179
-
180
- // First pass: the type decides which fields are known, wherever --type appears.
181
- const typeAt = args.indexOf('--type')
182
- const typeGuess = typeAt >= 0 ? args[typeAt + 1] : undefined
183
- const fields = typeGuess && typeGuess in LOG_RECORDS ? LOG_RECORDS[typeGuess] : null
184
- const knownFields = fields ? Object.keys(fields) : [...new Set(Object.values(LOG_RECORDS).flatMap((f) => Object.keys(f)))]
185
-
186
- for (let i = 0; i < args.length; i++) {
187
- const arg = args[i]
188
- if (arg === '--help' || arg === '-h') return { ok: true, help: true }
189
- if (arg === '--dry-run') { dryRun = true; continue }
190
- if (!arg.startsWith('--')) {
191
- errors.push(`Unexpected "${arg}". Every value follows its --field; quote values that contain spaces.`)
192
- continue
193
- }
194
- const key = arg.slice(2)
195
- const value = args[i + 1]
196
- // A flag needs a value. One followed by another flag, or by nothing, used to
197
- // be stored as `true` — a `--model` whose variable was empty became a model
198
- // named true.
199
- const missing = value === undefined || value.startsWith('--')
200
- if (!missing) i++
201
-
202
- if (key === 'timestamp') {
203
- errors.push('--timestamp is not accepted: opencastle log sets the timestamp itself.')
204
- continue
205
- }
206
- const isOwn = key === 'type' || key === 'logs-dir'
207
- if (!isOwn && !knownFields.includes(key)) {
208
- const suggestion = nearest(key, [...knownFields, ...OWN_FLAGS.map((f) => f.slice(2))])
209
- const where = fields ? `a ${typeGuess} record` : 'any record type'
210
- errors.push(`Unknown option --${key} for ${where}.${suggestion ? ` Did you mean --${suggestion}?` : ''}`)
211
- continue
212
- }
213
- if (missing) {
214
- errors.push(`--${key} needs a value.`)
215
- reported.add(key)
216
- continue
217
- }
218
- if (value.trim() === '') {
219
- errors.push(`--${key} cannot be empty. Leave it out instead when there is nothing to record.`)
220
- reported.add(key)
221
- continue
222
- }
223
- if (key === 'type') type = value
224
- else if (key === 'logs-dir') logsDir = value
225
- else if (given.has(key)) errors.push(`--${key} is given twice.`)
226
- else given.set(key, value)
227
- }
228
-
229
- if (!type) {
230
- errors.unshift(`--type is required: one of ${TYPES.join(', ')}.`)
231
- return { ok: false, errors, type: null }
232
- }
233
- if (!(type in LOG_RECORDS)) {
234
- const suggestion = nearest(type, TYPES)
235
- errors.unshift(`--type "${type}" is not a record type: one of ${TYPES.join(', ')}.${suggestion ? ` Did you mean ${suggestion}?` : ''}`)
236
- return { ok: false, errors, type: null }
237
- }
238
-
239
- const schema = LOG_RECORDS[type]
240
- const values: Record<string, unknown> = {}
241
- for (const [key, raw] of given) values[key] = convert(raw, schema[key])
242
-
243
- const result = v.safeParse(SCHEMAS[type], values)
244
- if (!result.success) {
245
- for (const issue of result.issues) {
246
- const key = String(issue.path?.[0]?.key ?? '')
247
- if (!key || reported.has(key)) continue
248
- reported.add(key)
249
- const field = schema[key]
250
- if (!field) continue
251
- errors.push(
252
- given.has(key)
253
- ? `--${key} must be ${describe(field)}, not "${given.get(key)}".`
254
- : `--${key} is required${field.kind === 'text' && !field.values ? '' : `: ${describe(field)}`}.`,
255
- )
256
- }
257
- }
258
- if (errors.length > 0) return { ok: false, errors, type }
259
-
260
- // Fields in the order they were given, after the two every record starts with.
261
- const record: Record<string, unknown> = { type, timestamp: now.toISOString() }
262
- for (const key of given.keys()) record[key] = values[key]
263
- return { ok: true, help: false, record, logsDir, dryRun }
264
- }
265
-
266
- function fieldList(fields: Record<string, Field>): string {
267
- const words = Object.entries(fields).map(([k, f]) => `${f.required ? '*' : ''}${k}${f.values ? `=${f.values.join('|')}` : ''}`)
268
- const lines: string[] = []
269
- let line = ''
270
- for (const w of words) {
271
- if (line && line.length + w.length + 1 > 62) {
272
- lines.push(line)
273
- line = w
274
- } else {
275
- line = line ? `${line} ${w}` : w
276
- }
277
- }
278
- if (line) lines.push(line)
279
- return lines.join('\n ')
280
- }
281
-
282
- const HELP = `
283
- opencastle log --type <type> --<field> <value> ...
284
-
285
- Append one record to .opencastle/logs/events.ndjson. Each record is checked
286
- against its schema; a record that does not match is refused, with every
287
- reason. opencastle log sets the timestamp itself.
288
-
289
- Options:
290
- --type <type> ${TYPES.join(' | ')}
291
- --<field> <value> A field of that record type (below)
292
- --logs-dir <path> Write to another logs directory
293
- --dry-run Print the record without writing it
294
- --help, -h Show this help
295
-
296
- Fields (* required):
297
- ${Object.entries(LOG_RECORDS).map(([t, f]) => ` ${t.padEnd(12)} ${fieldList(f)}`).join('\n')}
298
-
299
- Lists are comma-separated. Booleans are true or false. Leave out a field you
300
- have no value for; an empty value is refused.
301
-
302
- Examples:
303
- opencastle log --type session --agent Developer --task "Fix bug" --outcome success
304
- opencastle log --type delegation --session_id feat/prj-1 --agent Developer --tier standard --mechanism sub-agent --outcome success
305
- `
306
-
307
- /** Resolve the path to the logs directory (walks up to find .opencastle/). */
308
- async function resolveLogsDir(override?: string | null): Promise<string> {
309
- if (override) return override
310
- let dir = process.cwd()
311
- for (;;) {
312
- try {
313
- const s = await stat(join(dir, '.opencastle'))
314
- if (s.isDirectory()) return join(dir, '.opencastle', 'logs')
315
- } catch {
316
- // .opencastle not in this directory, walk up
317
- }
318
- const parent = dirname(dir)
319
- if (parent === dir) break
320
- dir = parent
321
- }
322
- return join(process.cwd(), '.opencastle', 'logs')
323
- }
324
-
325
- /** Append a structured event record to events.ndjson. */
326
- export async function appendEvent(
327
- record: Record<string, unknown>,
328
- logsDir?: string | null,
329
- ): Promise<void> {
330
- const resolvedDir = await resolveLogsDir(logsDir ?? null)
331
- const eventsFile = join(resolvedDir, 'events.ndjson')
332
- await mkdir(resolvedDir, { recursive: true })
333
- const line = JSON.stringify(record)
334
- // Ensure file ends with a newline before appending to prevent record concatenation
335
- let prefix = ''
336
- try {
337
- const existing = await readFile(eventsFile, 'utf8')
338
- if (existing.length > 0 && !existing.endsWith('\n')) {
339
- prefix = '\n'
340
- }
341
- } catch {
342
- // File doesn't exist yet — no prefix needed
343
- }
344
- await appendFile(eventsFile, prefix + line + '\n', 'utf8')
345
- }
346
-
347
- export default async function log({ args }: CliContext): Promise<void> {
348
- const parsed = parseLogArgs(args)
349
- if (parsed.ok && parsed.help) {
350
- console.log(HELP)
351
- return
352
- }
353
- if (!parsed.ok) {
354
- const what = parsed.type ? `a ${parsed.type} record` : 'this record'
355
- console.error(` ✗ opencastle log refused ${what}:`)
356
- for (const e of parsed.errors) console.error(` ${e}`)
357
- console.error(' Run "opencastle log --help" for the fields of each record type.')
358
- process.exit(1)
359
- }
360
-
361
- if (parsed.dryRun) {
362
- console.log(` [dry-run] Would append to events.ndjson:`)
363
- console.log(JSON.stringify(parsed.record))
364
- return
365
- }
366
-
367
- try {
368
- await appendEvent(parsed.record, parsed.logsDir)
369
- console.log(JSON.stringify(parsed.record))
370
- } catch (err: unknown) {
371
- console.error(` ✗ Failed to write log: ${(err as Error).message}`)
372
- process.exit(1)
373
- }
374
- }