@aperant/framework 0.6.4 → 0.6.6

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 (241) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +54 -234
  3. package/agents/apt-improver.md +99 -0
  4. package/agents/apt-planner.md +115 -10
  5. package/dist/__test-helpers/run-cmd.d.mts +4 -2
  6. package/dist/__test-helpers/run-cmd.d.mts.map +1 -1
  7. package/dist/__test-helpers/run-cmd.mjs +56 -15
  8. package/dist/__test-helpers/run-cmd.mjs.map +1 -1
  9. package/dist/cli/ci-watch/lock.d.mts +53 -0
  10. package/dist/cli/ci-watch/lock.d.mts.map +1 -0
  11. package/dist/cli/ci-watch/lock.mjs +172 -0
  12. package/dist/cli/ci-watch/lock.mjs.map +1 -0
  13. package/dist/cli/ci-watch/state.d.mts +36 -0
  14. package/dist/cli/ci-watch/state.d.mts.map +1 -0
  15. package/dist/cli/ci-watch/state.mjs +103 -0
  16. package/dist/cli/ci-watch/state.mjs.map +1 -0
  17. package/dist/cli/ci-watch/stop-matrix.d.mts +58 -0
  18. package/dist/cli/ci-watch/stop-matrix.d.mts.map +1 -0
  19. package/dist/cli/ci-watch/stop-matrix.mjs +164 -0
  20. package/dist/cli/ci-watch/stop-matrix.mjs.map +1 -0
  21. package/dist/cli/cli-wrappers/ci-watch.d.mts +2 -0
  22. package/dist/cli/cli-wrappers/ci-watch.d.mts.map +1 -0
  23. package/dist/cli/cli-wrappers/ci-watch.mjs +9 -0
  24. package/dist/cli/cli-wrappers/ci-watch.mjs.map +1 -0
  25. package/dist/cli/commands/adr.d.mts +5 -0
  26. package/dist/cli/commands/adr.d.mts.map +1 -0
  27. package/dist/cli/commands/adr.mjs +228 -0
  28. package/dist/cli/commands/adr.mjs.map +1 -0
  29. package/dist/cli/commands/ci-watch.d.mts +7 -0
  30. package/dist/cli/commands/ci-watch.d.mts.map +1 -0
  31. package/dist/cli/commands/ci-watch.mjs +465 -0
  32. package/dist/cli/commands/ci-watch.mjs.map +1 -0
  33. package/dist/cli/commands/commit.d.mts.map +1 -1
  34. package/dist/cli/commands/commit.mjs +25 -8
  35. package/dist/cli/commands/commit.mjs.map +1 -1
  36. package/dist/cli/commands/context.d.mts +7 -0
  37. package/dist/cli/commands/context.d.mts.map +1 -0
  38. package/dist/cli/commands/context.mjs +224 -0
  39. package/dist/cli/commands/context.mjs.map +1 -0
  40. package/dist/cli/commands/event.d.mts.map +1 -1
  41. package/dist/cli/commands/event.mjs +125 -24
  42. package/dist/cli/commands/event.mjs.map +1 -1
  43. package/dist/cli/commands/host-detect.d.mts +1 -1
  44. package/dist/cli/commands/host-detect.d.mts.map +1 -1
  45. package/dist/cli/commands/host-detect.mjs +30 -3
  46. package/dist/cli/commands/host-detect.mjs.map +1 -1
  47. package/dist/cli/commands/modes.d.mts +13 -0
  48. package/dist/cli/commands/modes.d.mts.map +1 -0
  49. package/dist/cli/commands/modes.mjs +221 -0
  50. package/dist/cli/commands/modes.mjs.map +1 -0
  51. package/dist/cli/commands/route.mjs +1 -1
  52. package/dist/cli/commands/route.mjs.map +1 -1
  53. package/dist/cli/commands/task.d.mts.map +1 -1
  54. package/dist/cli/commands/task.mjs +393 -145
  55. package/dist/cli/commands/task.mjs.map +1 -1
  56. package/dist/cli/commands/tokens.d.mts.map +1 -1
  57. package/dist/cli/commands/tokens.mjs +150 -6
  58. package/dist/cli/commands/tokens.mjs.map +1 -1
  59. package/dist/cli/commands/triage.d.mts +8 -0
  60. package/dist/cli/commands/triage.d.mts.map +1 -0
  61. package/dist/cli/commands/triage.mjs +263 -0
  62. package/dist/cli/commands/triage.mjs.map +1 -0
  63. package/dist/cli/config/post-merge-sweep.d.mts +18 -0
  64. package/dist/cli/config/post-merge-sweep.d.mts.map +1 -1
  65. package/dist/cli/config/post-merge-sweep.mjs +48 -3
  66. package/dist/cli/config/post-merge-sweep.mjs.map +1 -1
  67. package/dist/cli/consistency/registry.d.mts +11 -0
  68. package/dist/cli/consistency/registry.d.mts.map +1 -1
  69. package/dist/cli/consistency/registry.mjs +13 -0
  70. package/dist/cli/consistency/registry.mjs.map +1 -1
  71. package/dist/cli/coordination/agent-identity.d.mts +9 -0
  72. package/dist/cli/coordination/agent-identity.d.mts.map +1 -1
  73. package/dist/cli/coordination/agent-identity.mjs +11 -0
  74. package/dist/cli/coordination/agent-identity.mjs.map +1 -1
  75. package/dist/cli/coordination/auto-emit-artifact-ready.d.mts +16 -0
  76. package/dist/cli/coordination/auto-emit-artifact-ready.d.mts.map +1 -0
  77. package/dist/cli/coordination/auto-emit-artifact-ready.mjs +88 -0
  78. package/dist/cli/coordination/auto-emit-artifact-ready.mjs.map +1 -0
  79. package/dist/cli/coordination/event-log.d.mts +27 -0
  80. package/dist/cli/coordination/event-log.d.mts.map +1 -1
  81. package/dist/cli/coordination/event-log.mjs +72 -2
  82. package/dist/cli/coordination/event-log.mjs.map +1 -1
  83. package/dist/cli/coordination/event-schema.d.mts +16 -0
  84. package/dist/cli/coordination/event-schema.d.mts.map +1 -0
  85. package/dist/cli/coordination/event-schema.mjs +161 -0
  86. package/dist/cli/coordination/event-schema.mjs.map +1 -0
  87. package/dist/cli/coordination/store.d.mts +6 -0
  88. package/dist/cli/coordination/store.d.mts.map +1 -1
  89. package/dist/cli/coordination/store.mjs +14 -0
  90. package/dist/cli/coordination/store.mjs.map +1 -1
  91. package/dist/cli/dispatch.d.mts.map +1 -1
  92. package/dist/cli/dispatch.mjs +14 -1
  93. package/dist/cli/dispatch.mjs.map +1 -1
  94. package/dist/cli/gate/registry.d.mts +11 -0
  95. package/dist/cli/gate/registry.d.mts.map +1 -1
  96. package/dist/cli/gate/registry.mjs +13 -0
  97. package/dist/cli/gate/registry.mjs.map +1 -1
  98. package/dist/cli/help.d.mts.map +1 -1
  99. package/dist/cli/help.mjs +3 -2
  100. package/dist/cli/help.mjs.map +1 -1
  101. package/dist/cli/host/detect.d.mts +1 -0
  102. package/dist/cli/host/detect.d.mts.map +1 -1
  103. package/dist/cli/host/detect.mjs +5 -0
  104. package/dist/cli/host/detect.mjs.map +1 -1
  105. package/dist/cli/roadmap/conductor-view.d.mts +13 -0
  106. package/dist/cli/roadmap/conductor-view.d.mts.map +1 -0
  107. package/dist/cli/roadmap/conductor-view.mjs +31 -0
  108. package/dist/cli/roadmap/conductor-view.mjs.map +1 -0
  109. package/dist/cli/route/envelope.d.mts +68 -4
  110. package/dist/cli/route/envelope.d.mts.map +1 -1
  111. package/dist/cli/route/envelope.mjs +140 -103
  112. package/dist/cli/route/envelope.mjs.map +1 -1
  113. package/dist/cli/route/skill-discover.d.mts +9 -0
  114. package/dist/cli/route/skill-discover.d.mts.map +1 -1
  115. package/dist/cli/route/skill-discover.mjs +13 -1
  116. package/dist/cli/route/skill-discover.mjs.map +1 -1
  117. package/dist/cli/skill-author/contract.d.mts +1 -0
  118. package/dist/cli/skill-author/contract.d.mts.map +1 -1
  119. package/dist/cli/skill-author/contract.mjs +7 -0
  120. package/dist/cli/skill-author/contract.mjs.map +1 -1
  121. package/dist/cli/task/ids.d.mts +7 -4
  122. package/dist/cli/task/ids.d.mts.map +1 -1
  123. package/dist/cli/task/ids.mjs +11 -10
  124. package/dist/cli/task/ids.mjs.map +1 -1
  125. package/dist/cli/task/worktree-cleanup.d.mts +9 -1
  126. package/dist/cli/task/worktree-cleanup.d.mts.map +1 -1
  127. package/dist/cli/task/worktree-cleanup.mjs +190 -9
  128. package/dist/cli/task/worktree-cleanup.mjs.map +1 -1
  129. package/dist/plugin/.claude-plugin/plugin.json +1 -1
  130. package/dist/plugin/agents/apt-planner.md +1 -1
  131. package/dist/plugin/skills/apt/SKILL.md +111 -5
  132. package/dist/plugin/skills/apt-author-skill/SKILL.md +11 -0
  133. package/dist/plugin/skills/apt-bootstrap/SKILL.md +1 -0
  134. package/dist/plugin/skills/apt-classify/SKILL.md +1 -0
  135. package/dist/plugin/skills/apt-close-task/SKILL.md +1 -0
  136. package/dist/plugin/skills/apt-create-docs/SKILL.md +1 -0
  137. package/dist/plugin/skills/apt-debug/SKILL.md +2 -0
  138. package/dist/plugin/skills/apt-design/SKILL.md +2 -0
  139. package/dist/plugin/skills/apt-discuss/SKILL.md +2 -0
  140. package/dist/plugin/skills/apt-docs/SKILL.md +2 -0
  141. package/dist/plugin/skills/apt-execute/SKILL.md +1 -0
  142. package/dist/plugin/skills/apt-mockup/SKILL.md +2 -0
  143. package/dist/plugin/skills/apt-pause/SKILL.md +1 -0
  144. package/dist/plugin/skills/apt-personas/SKILL.md +1 -0
  145. package/dist/plugin/skills/apt-plan/SKILL.md +2 -0
  146. package/dist/plugin/skills/apt-pr-review/SKILL.md +1 -0
  147. package/dist/plugin/skills/apt-quick/SKILL.md +2 -0
  148. package/dist/plugin/skills/apt-resume/SKILL.md +1 -0
  149. package/dist/plugin/skills/apt-review/SKILL.md +1 -0
  150. package/dist/plugin/skills/apt-roadmap/SKILL.md +1 -0
  151. package/dist/plugin/skills/apt-roundtable/SKILL.md +2 -0
  152. package/dist/plugin/skills/apt-run/SKILL.md +1 -0
  153. package/dist/plugin/skills/apt-scan/SKILL.md +1 -0
  154. package/dist/plugin/skills/apt-setup/SKILL.md +1 -0
  155. package/dist/plugin/skills/apt-ship/SKILL.md +6 -5
  156. package/dist/plugin/skills/apt-stress-test/SKILL.md +1 -0
  157. package/dist/plugin/skills/apt-terminal/SKILL.md +1 -0
  158. package/dist/plugin/skills/apt-update/SKILL.md +5 -0
  159. package/dist/plugin/skills/apt-verify/SKILL.md +1 -0
  160. package/dist/plugin/skills/apt-verify-proof/SKILL.md +1 -0
  161. package/dist/types/config.d.ts +85 -0
  162. package/dist/types/config.d.ts.map +1 -1
  163. package/package.json +9 -1
  164. package/prompts/coder.md +2 -0
  165. package/prompts/conductor-status-check.md +23 -0
  166. package/prompts/conductor-sub-agent.md +57 -0
  167. package/prompts/conductor-system.md +172 -0
  168. package/prompts/planner.md +12 -0
  169. package/prompts/spec_writer.md +9 -0
  170. package/skills/apt/SKILL.md +1 -0
  171. package/skills/apt-close-task/SKILL.md +32 -1
  172. package/skills/apt-debug/SKILL.md +39 -6
  173. package/skills/apt-debug/appendices/diagnose-discipline.md +119 -0
  174. package/skills/apt-diagram/SKILL.md +342 -0
  175. package/skills/apt-diagram/appendices/design-discipline.md +97 -0
  176. package/skills/apt-discuss/SKILL.md +25 -0
  177. package/skills/apt-discuss/appendices/grill-discipline.md +104 -0
  178. package/skills/apt-discuss/appendices/zoom-out-helper.md +79 -0
  179. package/skills/apt-execute/SKILL.md +48 -5
  180. package/skills/apt-execute/appendices/tdd-mode.md +107 -0
  181. package/skills/apt-improve/DEEPENING.md +84 -0
  182. package/skills/apt-improve/INTERFACE-DESIGN.md +97 -0
  183. package/skills/apt-improve/LANGUAGE.md +104 -0
  184. package/skills/apt-improve/SKILL.md +141 -0
  185. package/skills/apt-plan/SKILL.md +159 -4
  186. package/skills/apt-plan/adapters/conductor.md +98 -0
  187. package/skills/apt-planner.md +42 -1
  188. package/skills/apt-pr-review/SKILL.md +46 -16
  189. package/skills/apt-prototype/LOGIC.md +109 -0
  190. package/skills/apt-prototype/SKILL.md +143 -0
  191. package/skills/apt-prototype/UI.md +90 -0
  192. package/skills/apt-quick/SKILL.md +30 -0
  193. package/skills/apt-review/SKILL.md +2 -0
  194. package/skills/apt-run/SKILL.md +32 -4
  195. package/skills/apt-setup/SKILL.md +130 -2
  196. package/skills/apt-ship/SKILL.md +63 -1
  197. package/skills/apt-spar/SKILL.md +290 -0
  198. package/skills/apt-triage/AGENT-BRIEF.md +84 -0
  199. package/skills/apt-triage/OUT-OF-SCOPE.md +75 -0
  200. package/skills/apt-triage/SKILL.md +169 -0
  201. package/skills/apt-verify/SKILL.md +3 -0
  202. package/skills/apt-verify-proof/SKILL.md +3 -0
  203. package/skills/apt-watch-ci/SKILL.md +163 -0
  204. package/skills/apt-zoom-out/SKILL.md +130 -0
  205. package/src/cli/ci-watch/lock.mjs +178 -0
  206. package/src/cli/ci-watch/state.mjs +103 -0
  207. package/src/cli/ci-watch/stop-matrix.mjs +181 -0
  208. package/src/cli/cli-wrappers/ci-watch.mjs +9 -0
  209. package/src/cli/commands/adr.mjs +243 -0
  210. package/src/cli/commands/ci-watch.mjs +503 -0
  211. package/src/cli/commands/commit.mjs +27 -8
  212. package/src/cli/commands/context.mjs +244 -0
  213. package/src/cli/commands/event.mjs +131 -24
  214. package/src/cli/commands/host-detect.mjs +33 -7
  215. package/src/cli/commands/modes.mjs +216 -0
  216. package/src/cli/commands/route.mjs +1 -1
  217. package/src/cli/commands/task.mjs +430 -170
  218. package/src/cli/commands/tokens.mjs +157 -6
  219. package/src/cli/commands/triage.mjs +286 -0
  220. package/src/cli/config/post-merge-sweep.mjs +49 -3
  221. package/src/cli/consistency/registry.mjs +14 -0
  222. package/src/cli/coordination/agent-identity.mjs +12 -0
  223. package/src/cli/coordination/auto-emit-artifact-ready.mjs +96 -0
  224. package/src/cli/coordination/event-log.mjs +73 -2
  225. package/src/cli/coordination/event-schema.d.ts +13 -0
  226. package/src/cli/coordination/event-schema.mjs +174 -0
  227. package/src/cli/coordination/store.mjs +14 -0
  228. package/src/cli/dispatch.mjs +15 -1
  229. package/src/cli/gate/registry.mjs +14 -0
  230. package/src/cli/help.mjs +3 -2
  231. package/src/cli/host/detect.mjs +5 -0
  232. package/src/cli/roadmap/conductor-view.d.ts +10 -0
  233. package/src/cli/roadmap/conductor-view.mjs +31 -0
  234. package/src/cli/route/envelope.mjs +140 -106
  235. package/src/cli/route/skill-discover.mjs +14 -1
  236. package/src/cli/skill-author/contract.mjs +7 -0
  237. package/src/cli/task/ids.mjs +15 -13
  238. package/src/cli/task/worktree-cleanup.mjs +191 -9
  239. package/templates/adr-format.md +56 -0
  240. package/templates/config.json +4 -0
  241. package/templates/context-format.md +34 -0
@@ -0,0 +1,244 @@
1
+ /**
2
+ * commands/context.mjs — `apt-tools context write` (Pocock adoption ST-5, AC4).
3
+ *
4
+ * Upserts a term-block into the project's CONTEXT.md (the persistent
5
+ * project glossary). Format ported from Pocock's CONTEXT-FORMAT.md
6
+ * (see packages/framework/templates/context-format.md for the MIT
7
+ * attribution + field semantics).
8
+ *
9
+ * Idempotent: re-running with the same `--term` updates the existing
10
+ * block in place. Fields not explicitly overridden via flags are
11
+ * preserved from the prior block.
12
+ *
13
+ * CLI:
14
+ * apt-tools context write <project-dir>
15
+ * --term <bold-term>
16
+ * --definition <one-line>
17
+ * [--aliases-to-avoid alias1,alias2]
18
+ * [--cardinality 'one-to-many' | 'one-to-one' | 'many-to-many']
19
+ * [--flagged-ambiguity 'note']
20
+ * [--example-dialogue 'example']
21
+ *
22
+ * Output: JSON envelope { status: 'ok' | 'error',
23
+ * command: 'context-write',
24
+ * file: <absolute path>,
25
+ * term: <term>,
26
+ * operation: 'created' | 'updated' }.
27
+ */
28
+
29
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
30
+ import { resolve } from 'node:path'
31
+ import { parseFlags } from '../util/args.mjs'
32
+ import { err, ok } from '../util/result.mjs'
33
+
34
+ const HEADER = '# Project glossary (CONTEXT.md)'
35
+ const HEADER_NOTE =
36
+ '<!-- Managed by `apt-tools context write`. Hand-edits are preserved across upserts. -->'
37
+
38
+ /**
39
+ * Parse a single term-block out of CONTEXT.md.
40
+ *
41
+ * A block looks like:
42
+ * ## {Term}
43
+ *
44
+ * {Definition line}
45
+ *
46
+ * - **Aliases to avoid:** ...
47
+ * - **Cardinality:** ...
48
+ * - **Flagged ambiguities:** ...
49
+ * - **Example dialogue:** ...
50
+ *
51
+ * Returns `{ definition, aliasesToAvoid, cardinality, flaggedAmbiguity, exampleDialogue }`
52
+ * with each field as a string or null.
53
+ *
54
+ * @param {string} blockText
55
+ */
56
+ function parseBlock(blockText) {
57
+ const lines = blockText.split('\n')
58
+ // First non-empty line after the ## header is the definition.
59
+ let definition = ''
60
+ let i = 0
61
+ while (i < lines.length && lines[i].trim() === '') i++
62
+ if (i < lines.length && !lines[i].startsWith('- ')) {
63
+ definition = lines[i].trim()
64
+ i++
65
+ }
66
+ const fields = {
67
+ aliasesToAvoid: null,
68
+ cardinality: null,
69
+ flaggedAmbiguity: null,
70
+ exampleDialogue: null,
71
+ }
72
+ for (; i < lines.length; i++) {
73
+ const line = lines[i]
74
+ const m = line.match(/^- \*\*([^*]+):\*\*\s*(.*)$/)
75
+ if (!m) continue
76
+ const key = m[1].trim()
77
+ const value = m[2].trim()
78
+ switch (key) {
79
+ case 'Aliases to avoid':
80
+ fields.aliasesToAvoid = value
81
+ break
82
+ case 'Cardinality':
83
+ fields.cardinality = value
84
+ break
85
+ case 'Flagged ambiguities':
86
+ fields.flaggedAmbiguity = value
87
+ break
88
+ case 'Example dialogue':
89
+ fields.exampleDialogue = value
90
+ break
91
+ }
92
+ }
93
+ return { definition, ...fields }
94
+ }
95
+
96
+ /**
97
+ * Render a term-block to markdown.
98
+ *
99
+ * @param {string} term
100
+ * @param {{
101
+ * definition: string,
102
+ * aliasesToAvoid: string|null,
103
+ * cardinality: string|null,
104
+ * flaggedAmbiguity: string|null,
105
+ * exampleDialogue: string|null,
106
+ * }} block
107
+ */
108
+ function renderBlock(term, block) {
109
+ const lines = [`## ${term}`, '', block.definition, '']
110
+ const fields = [
111
+ ['Aliases to avoid', block.aliasesToAvoid],
112
+ ['Cardinality', block.cardinality],
113
+ ['Flagged ambiguities', block.flaggedAmbiguity],
114
+ ['Example dialogue', block.exampleDialogue],
115
+ ]
116
+ for (const [key, value] of fields) {
117
+ if (value !== null && value !== undefined && value !== '') {
118
+ lines.push(`- **${key}:** ${value}`)
119
+ }
120
+ }
121
+ return lines.join('\n')
122
+ }
123
+
124
+ /**
125
+ * Find an existing block by term in the source markdown.
126
+ * Returns `{ start, end, prior }` or `null` if no such block exists.
127
+ * `start` and `end` are inclusive/exclusive offsets into `source`.
128
+ *
129
+ * @param {string} source
130
+ * @param {string} term
131
+ */
132
+ function findBlock(source, term) {
133
+ const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
134
+ const headerRe = new RegExp(`^##\\s+${escaped}\\s*$`, 'm')
135
+ const m = headerRe.exec(source)
136
+ if (!m) return null
137
+ const start = m.index
138
+ // Find the next ## or # header or EOF. LOG-004: including H1 prevents a
139
+ // manually-inserted `# Heading` from being absorbed into the block's content.
140
+ const tail = source.slice(m.index + m[0].length)
141
+ const nextRe = /^#{1,2}\s+/m
142
+ const nextMatch = nextRe.exec(tail)
143
+ const end = nextMatch ? m.index + m[0].length + nextMatch.index : source.length
144
+ const blockText = source.slice(m.index + m[0].length, end)
145
+ return { start, end, prior: parseBlock(blockText) }
146
+ }
147
+
148
+ /**
149
+ * CLI entry: `apt-tools context <subcommand> <project-dir> [flags]`.
150
+ *
151
+ * Only `write` is supported in v1; other subcommands return a usage error.
152
+ */
153
+ export function cmdContext(subcommand, projectDir, extraArgs) {
154
+ if (subcommand !== 'write') {
155
+ return err(
156
+ 'Usage: apt-tools context write <project-dir> --term <term> --definition <line> [--aliases-to-avoid ...] [--cardinality ...] [--flagged-ambiguity ...] [--example-dialogue ...]',
157
+ 1,
158
+ { command: 'context' },
159
+ )
160
+ }
161
+ if (!projectDir) {
162
+ return err(
163
+ 'Usage: apt-tools context write <project-dir> --term <term> --definition <line>',
164
+ 1,
165
+ {
166
+ command: 'context-write',
167
+ },
168
+ )
169
+ }
170
+
171
+ const flags = parseFlags(extraArgs ?? [])
172
+ const term = flags.get('term')
173
+ const definition = flags.get('definition')
174
+ if (typeof term !== 'string' || term.trim() === '') {
175
+ return err('--term <bold-term> is required', 1, { command: 'context-write' })
176
+ }
177
+ if (typeof definition !== 'string' || definition.trim() === '') {
178
+ return err('--definition <one-line> is required', 1, { command: 'context-write' })
179
+ }
180
+
181
+ const absProjectDir = resolve(projectDir)
182
+ if (!existsSync(absProjectDir)) {
183
+ return err(`project directory not found: ${absProjectDir}`, 1, {
184
+ command: 'context-write',
185
+ })
186
+ }
187
+
188
+ const contextPath = resolve(absProjectDir, 'CONTEXT.md')
189
+ let source = ''
190
+ if (existsSync(contextPath)) {
191
+ source = readFileSync(contextPath, 'utf-8')
192
+ } else {
193
+ source = `${HEADER}\n\n${HEADER_NOTE}\n\n`
194
+ }
195
+ // Ensure the file starts with the header even if it existed pre-Pocock.
196
+ if (!source.startsWith(HEADER)) {
197
+ source = `${HEADER}\n\n${HEADER_NOTE}\n\n${source}`
198
+ }
199
+
200
+ const existing = findBlock(source, term)
201
+ const incoming = {
202
+ definition,
203
+ aliasesToAvoid:
204
+ typeof flags.get('aliases-to-avoid') === 'string' ? flags.get('aliases-to-avoid') : null,
205
+ cardinality: typeof flags.get('cardinality') === 'string' ? flags.get('cardinality') : null,
206
+ flaggedAmbiguity:
207
+ typeof flags.get('flagged-ambiguity') === 'string' ? flags.get('flagged-ambiguity') : null,
208
+ exampleDialogue:
209
+ typeof flags.get('example-dialogue') === 'string' ? flags.get('example-dialogue') : null,
210
+ }
211
+
212
+ // Merge: prior block fields are preserved unless explicitly overridden.
213
+ const merged = existing
214
+ ? {
215
+ definition: incoming.definition, // definition always overrides
216
+ aliasesToAvoid: incoming.aliasesToAvoid ?? existing.prior.aliasesToAvoid,
217
+ cardinality: incoming.cardinality ?? existing.prior.cardinality,
218
+ flaggedAmbiguity: incoming.flaggedAmbiguity ?? existing.prior.flaggedAmbiguity,
219
+ exampleDialogue: incoming.exampleDialogue ?? existing.prior.exampleDialogue,
220
+ }
221
+ : incoming
222
+
223
+ const rendered = renderBlock(term, merged)
224
+ let updated
225
+ if (existing) {
226
+ // Replace the existing block (header + body) with the rendered one.
227
+ const before = source.slice(0, existing.start).replace(/\n+$/, '')
228
+ const after = source.slice(existing.end).replace(/^\n+/, '')
229
+ updated = `${before}\n\n${rendered}\n${after.length > 0 ? `\n${after}` : ''}`
230
+ } else {
231
+ // Append a new block at the end.
232
+ updated = `${source.replace(/\n+$/, '')}\n\n${rendered}\n`
233
+ }
234
+
235
+ writeFileSync(contextPath, updated)
236
+
237
+ return ok({
238
+ status: 'ok',
239
+ command: 'context-write',
240
+ file: contextPath,
241
+ term,
242
+ operation: existing ? 'updated' : 'created',
243
+ })
244
+ }
@@ -2,15 +2,86 @@
2
2
  * commands/event.mjs — append-only event log for coordination history (C29).
3
3
  */
4
4
 
5
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
5
+ import { appendFileSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
6
6
  import { hostname } from 'node:os'
7
7
  import { join, resolve } from 'node:path'
8
8
  import { readLifecycleEventsForDay } from '../coordination/event-log.mjs'
9
+ import { validateConductorEvent } from '../coordination/event-schema.mjs'
9
10
  import { createCoordinationStore } from '../coordination/store.mjs'
10
11
  import { detectWorktree } from '../git/worktree-detect.mjs'
11
12
  import { parseFlags } from '../util/args.mjs'
12
13
  import { err, ok } from '../util/result.mjs'
13
14
 
15
+ // QUA-003 / PRF-002 — single source of truth for valid event types.
16
+ // VALID_EVENT_TYPES is the authoritative list; CI_WATCH_EVENT_TYPES is the O(1)
17
+ // membership Set used to short-circuit ci-watch.* events to the JSONL path (D-04).
18
+ const VALID_EVENT_TYPES = [
19
+ 'task-claimed',
20
+ 'task-completed',
21
+ 'task-failed',
22
+ 'wave-started',
23
+ 'wave-completed',
24
+ 'install.started',
25
+ 'install.ok',
26
+ 'install.failed',
27
+ 'ci-watch.armed',
28
+ 'ci-watch.tick',
29
+ 'ci-watch.fix-pushed',
30
+ 'ci-watch.stopped',
31
+ // Phase 2.5 — Conductor-readable ops emitted by APT skills so the
32
+ // Conductor's readEventLog tool can drive its observe loop. These
33
+ // events route to JSONL (like ci-watch.*) and carry terminal_id
34
+ // auto-stamped from APERANT_TERMINAL_ID when present.
35
+ 'phase.changed',
36
+ 'artifact.ready',
37
+ 'awaiting-input',
38
+ 'input-rescinded',
39
+ 'heartbeat',
40
+ 'budget.exceeded',
41
+ 'terminal.enrolled',
42
+ 'terminal.unenrolled',
43
+ 'conductor.intent',
44
+ 'conductor.cross_check',
45
+ 'conductor.realignment',
46
+ ]
47
+
48
+ const CI_WATCH_EVENT_TYPES = new Set([
49
+ 'ci-watch.armed',
50
+ 'ci-watch.tick',
51
+ 'ci-watch.fix-pushed',
52
+ 'ci-watch.stopped',
53
+ ])
54
+
55
+ const CONDUCTOR_EVENT_TYPES = new Set([
56
+ 'phase.changed',
57
+ 'artifact.ready',
58
+ 'awaiting-input',
59
+ 'input-rescinded',
60
+ 'heartbeat',
61
+ 'budget.exceeded',
62
+ 'terminal.enrolled',
63
+ 'terminal.unenrolled',
64
+ 'conductor.intent',
65
+ 'conductor.cross_check',
66
+ 'conductor.realignment',
67
+ ])
68
+
69
+ /**
70
+ * Append a ci-watch event to the per-day JSONL file (D-04).
71
+ * O(1) — no directory scan. Creates the events dir if missing.
72
+ * @param {string} eventsDir
73
+ * @param {object} payload
74
+ * @returns {{ jsonlFile: string, jsonlPath: string }}
75
+ */
76
+ function appendToJsonl(eventsDir, payload) {
77
+ mkdirSync(eventsDir, { recursive: true })
78
+ const today = new Date().toISOString().slice(0, 10)
79
+ const jsonlFile = `${today}.jsonl`
80
+ const jsonlPath = join(eventsDir, jsonlFile)
81
+ appendFileSync(jsonlPath, `${JSON.stringify(payload)}\n`, 'utf-8')
82
+ return { jsonlFile, jsonlPath }
83
+ }
84
+
14
85
  export function cmdEvent(subcommand, projectDir, extraArgs) {
15
86
  if (!subcommand)
16
87
  return err('Usage: apt-tools event <append|list|rebuild-state> <project-dir> [flags]')
@@ -38,18 +109,12 @@ export function cmdEvent(subcommand, projectDir, extraArgs) {
38
109
  // install.started — { task_id, ecosystem, pid, started_at, log_path }
39
110
  // install.ok — { task_id, ecosystem, duration_ms, log_path }
40
111
  // install.failed — { task_id, ecosystem, exit_code, duration_ms, reason, log_path }
41
- const validTypes = [
42
- 'task-claimed',
43
- 'task-completed',
44
- 'task-failed',
45
- 'wave-started',
46
- 'wave-completed',
47
- 'install.started',
48
- 'install.ok',
49
- 'install.failed',
50
- ]
51
- if (!validTypes.includes(type)) {
52
- return err(`Invalid event type: ${type}. Valid types: ${validTypes.join(', ')}`)
112
+ // C28 (post-ship CI watcher D-04) — added ci-watch.{armed,tick,fix-pushed,stopped}
113
+ // so /apt:watch-ci tick / start / stop can stream events into
114
+ // .aperant/events/{today}.jsonl. The rebuild-state switch below
115
+ // silently ignores them (they're informational, not task-lifecycle).
116
+ if (!VALID_EVENT_TYPES.includes(type)) {
117
+ return err(`Invalid event type: ${type}. Valid types: ${VALID_EVENT_TYPES.join(', ')}`)
53
118
  }
54
119
 
55
120
  let data = {}
@@ -61,6 +126,58 @@ export function cmdEvent(subcommand, projectDir, extraArgs) {
61
126
  }
62
127
  }
63
128
 
129
+ // PRF-002 — ci-watch.* events go to the per-day JSONL path (D-04).
130
+ // O(1) append; no directory scan needed.
131
+ if (CI_WATCH_EVENT_TYPES.has(type)) {
132
+ const event = {
133
+ type,
134
+ subtask,
135
+ worker: `${hostname()}-${process.pid}`,
136
+ timestamp: new Date().toISOString(),
137
+ data,
138
+ }
139
+ const { jsonlFile } = appendToJsonl(eventsDir, event)
140
+ return ok({ status: 'ok', command: 'event-append', event_file: jsonlFile, event })
141
+ }
142
+
143
+ // Phase 2.5 — Conductor-readable events route to the per-day JSONL
144
+ // path with the canonical envelope the Conductor's readEventLog
145
+ // expects: { t, agent, pid, hostname, incarnation, op, task, data }.
146
+ // terminal_id is auto-stamped from APERANT_TERMINAL_ID env when set,
147
+ // so APT skills running in a Conductor-spawned PTY automatically
148
+ // tag their events with the originating terminal.
149
+ if (CONDUCTOR_EVENT_TYPES.has(type)) {
150
+ const terminalId = process.env.APERANT_TERMINAL_ID
151
+ if (terminalId && data && typeof data === 'object' && !data.terminal_id) {
152
+ data.terminal_id = terminalId
153
+ }
154
+ // Step 1 — schema gate: reject payloads that violate the per-op
155
+ // contract before the line lands on disk. The same validator
156
+ // runs at the framework store seam and the core conductor
157
+ // writer; gating here catches CLI emitters (APT skills).
158
+ const validation = validateConductorEvent(type, data)
159
+ if (!validation.ok) {
160
+ return err(`Schema violation for ${type}: ${validation.error}`)
161
+ }
162
+ const envelope = {
163
+ t: new Date().toISOString(),
164
+ agent: `${hostname()}-${process.pid}`,
165
+ pid: process.pid,
166
+ hostname: hostname(),
167
+ incarnation: 1,
168
+ op: type,
169
+ task: subtask || null,
170
+ data: data || {},
171
+ }
172
+ const { jsonlFile } = appendToJsonl(eventsDir, envelope)
173
+ return ok({
174
+ status: 'ok',
175
+ command: 'event-append',
176
+ event_file: jsonlFile,
177
+ event: envelope,
178
+ })
179
+ }
180
+
64
181
  // Find next sequence number — scan existing files for highest number
65
182
  const existingFiles = readdirSync(eventsDir).filter((f) => f.endsWith('.json'))
66
183
  let maxId = 0
@@ -169,17 +286,7 @@ export function cmdEvent(subcommand, projectDir, extraArgs) {
169
286
  const event = JSON.parse(readFileSync(join(eventsDir, f), 'utf-8'))
170
287
 
171
288
  // Validate event type before processing (T-11-04 mitigation)
172
- const validTypes = [
173
- 'task-claimed',
174
- 'task-completed',
175
- 'task-failed',
176
- 'wave-started',
177
- 'wave-completed',
178
- 'install.started',
179
- 'install.ok',
180
- 'install.failed',
181
- ]
182
- if (!validTypes.includes(event.type)) continue
289
+ if (!VALID_EVENT_TYPES.includes(event.type)) continue
183
290
 
184
291
  eventsProcessed++
185
292
 
@@ -22,14 +22,30 @@ export function cmdHostDetect() {
22
22
  })
23
23
  }
24
24
 
25
- export function cmdReconcile(projectDir) {
26
- if (!projectDir) return err('Usage: apt-tools reconcile <project-dir>')
25
+ /**
26
+ * Parse `--track <quick|standard|deep>` from positional args. Returns the
27
+ * lowercased track or null when the flag is absent. Unknown values are
28
+ * silently ignored to preserve backward-compat — the caller falls back to
29
+ * global phase_delegation in that case.
30
+ */
31
+ function parseTrackFlag(args) {
32
+ if (!Array.isArray(args)) return null
33
+ const idx = args.indexOf('--track')
34
+ if (idx === -1 || idx === args.length - 1) return null
35
+ const val = String(args[idx + 1]).toLowerCase()
36
+ return val === 'quick' || val === 'standard' || val === 'deep' ? val : null
37
+ }
38
+
39
+ export function cmdReconcile(projectDir, extraArgs = []) {
40
+ if (!projectDir)
41
+ return err('Usage: apt-tools reconcile <project-dir> [--track quick|standard|deep]')
27
42
  const targetDir = resolve(projectDir)
28
43
 
29
44
  if (!existsSync(targetDir)) return err(`Directory does not exist: ${targetDir}`)
30
45
 
31
46
  const host = detectHost()
32
47
  const { capabilities } = host
48
+ const track = parseTrackFlag(extraArgs)
33
49
 
34
50
  // Read orchestration config — default all fields to 'auto' if missing
35
51
  let orchestrationConfig = {
@@ -37,6 +53,7 @@ export function cmdReconcile(projectDir) {
37
53
  review_mode: 'auto',
38
54
  debate_mode: 'auto',
39
55
  }
56
+ let perTrack = null
40
57
 
41
58
  const configPath = join(targetDir, '.aperant', 'config.json')
42
59
  if (existsSync(configPath)) {
@@ -48,18 +65,22 @@ export function cmdReconcile(projectDir) {
48
65
  review_mode: cfg.orchestration.review_mode ?? 'auto',
49
66
  debate_mode: cfg.orchestration.debate_mode ?? 'auto',
50
67
  }
68
+ perTrack = cfg.orchestration.per_track ?? null
51
69
  }
52
70
  } catch {
53
71
  // Malformed config — use defaults
54
72
  }
55
73
  }
56
74
 
75
+ // Per-track phase_delegation override (roundtable 2026-05-14 R7):
76
+ // when --track is passed AND per_track[track] is set, use that as
77
+ // the requested mode for phase_delegation. Otherwise fall back to
78
+ // the global value. review_mode and debate_mode are not track-scoped.
79
+ const requestedPhaseDelegation =
80
+ track && perTrack?.[track] ? perTrack[track] : orchestrationConfig.phase_delegation
81
+
57
82
  // Resolve each dimension
58
- const pdResult = resolveMode(
59
- orchestrationConfig.phase_delegation,
60
- capabilities,
61
- 'phase_delegation',
62
- )
83
+ const pdResult = resolveMode(requestedPhaseDelegation, capabilities, 'phase_delegation')
63
84
  const rmResult = resolveMode(orchestrationConfig.review_mode, capabilities, 'review_mode')
64
85
  const dmResult = resolveMode(orchestrationConfig.debate_mode, capabilities, 'debate_mode')
65
86
 
@@ -79,6 +100,11 @@ export function cmdReconcile(projectDir) {
79
100
  resolved,
80
101
  }
81
102
 
103
+ if (track) {
104
+ result.track = track
105
+ result.track_source = perTrack && perTrack[track] ? 'per_track' : 'fallback'
106
+ }
107
+
82
108
  if (downgrades.length > 0) {
83
109
  result.downgrades = downgrades
84
110
  }