tycono-server 0.1.0-beta.0

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 (84) hide show
  1. package/bin/cli.js +35 -0
  2. package/bin/server.ts +160 -0
  3. package/package.json +50 -0
  4. package/src/api/package.json +31 -0
  5. package/src/api/src/create-app.ts +90 -0
  6. package/src/api/src/create-server.ts +251 -0
  7. package/src/api/src/engine/agent-loop.ts +738 -0
  8. package/src/api/src/engine/authority-validator.ts +149 -0
  9. package/src/api/src/engine/context-assembler.ts +912 -0
  10. package/src/api/src/engine/index.ts +27 -0
  11. package/src/api/src/engine/knowledge-gate.ts +365 -0
  12. package/src/api/src/engine/llm-adapter.ts +304 -0
  13. package/src/api/src/engine/org-tree.ts +270 -0
  14. package/src/api/src/engine/role-lifecycle.ts +369 -0
  15. package/src/api/src/engine/runners/claude-cli.ts +796 -0
  16. package/src/api/src/engine/runners/direct-api.ts +66 -0
  17. package/src/api/src/engine/runners/index.ts +30 -0
  18. package/src/api/src/engine/runners/types.ts +95 -0
  19. package/src/api/src/engine/skill-template.ts +134 -0
  20. package/src/api/src/engine/tools/definitions.ts +201 -0
  21. package/src/api/src/engine/tools/executor.ts +611 -0
  22. package/src/api/src/routes/active-sessions.ts +134 -0
  23. package/src/api/src/routes/coins.ts +153 -0
  24. package/src/api/src/routes/company.ts +57 -0
  25. package/src/api/src/routes/cost.ts +141 -0
  26. package/src/api/src/routes/engine.ts +220 -0
  27. package/src/api/src/routes/execute.ts +1075 -0
  28. package/src/api/src/routes/git.ts +211 -0
  29. package/src/api/src/routes/knowledge.ts +378 -0
  30. package/src/api/src/routes/operations.ts +309 -0
  31. package/src/api/src/routes/preferences.ts +63 -0
  32. package/src/api/src/routes/presets.ts +123 -0
  33. package/src/api/src/routes/projects.ts +82 -0
  34. package/src/api/src/routes/quests.ts +41 -0
  35. package/src/api/src/routes/roles.ts +112 -0
  36. package/src/api/src/routes/save.ts +152 -0
  37. package/src/api/src/routes/sessions.ts +288 -0
  38. package/src/api/src/routes/setup.ts +437 -0
  39. package/src/api/src/routes/skills.ts +357 -0
  40. package/src/api/src/routes/speech.ts +959 -0
  41. package/src/api/src/routes/supervision.ts +136 -0
  42. package/src/api/src/routes/sync.ts +165 -0
  43. package/src/api/src/server.ts +59 -0
  44. package/src/api/src/services/activity-stream.ts +184 -0
  45. package/src/api/src/services/activity-tracker.ts +115 -0
  46. package/src/api/src/services/claude-md-manager.ts +94 -0
  47. package/src/api/src/services/company-config.ts +115 -0
  48. package/src/api/src/services/database.ts +77 -0
  49. package/src/api/src/services/digest-engine.ts +313 -0
  50. package/src/api/src/services/execution-manager.ts +1036 -0
  51. package/src/api/src/services/file-reader.ts +77 -0
  52. package/src/api/src/services/git-save.ts +614 -0
  53. package/src/api/src/services/job-manager.ts +16 -0
  54. package/src/api/src/services/knowledge-importer.ts +466 -0
  55. package/src/api/src/services/markdown-parser.ts +173 -0
  56. package/src/api/src/services/port-registry.ts +222 -0
  57. package/src/api/src/services/preferences.ts +150 -0
  58. package/src/api/src/services/preset-loader.ts +149 -0
  59. package/src/api/src/services/pricing.ts +34 -0
  60. package/src/api/src/services/scaffold.ts +546 -0
  61. package/src/api/src/services/session-store.ts +340 -0
  62. package/src/api/src/services/supervisor-heartbeat.ts +897 -0
  63. package/src/api/src/services/team-recommender.ts +382 -0
  64. package/src/api/src/services/token-ledger.ts +127 -0
  65. package/src/api/src/services/wave-messages.ts +194 -0
  66. package/src/api/src/services/wave-multiplexer.ts +356 -0
  67. package/src/api/src/services/wave-tracker.ts +359 -0
  68. package/src/api/src/utils/role-level.ts +31 -0
  69. package/src/core/scaffolder.ts +620 -0
  70. package/src/shared/types.ts +224 -0
  71. package/templates/CLAUDE.md.tmpl +239 -0
  72. package/templates/company.md.tmpl +17 -0
  73. package/templates/gitignore.tmpl +28 -0
  74. package/templates/roles.md.tmpl +8 -0
  75. package/templates/skills/_manifest.json +23 -0
  76. package/templates/skills/agent-browser/SKILL.md +159 -0
  77. package/templates/skills/agent-browser/meta.json +19 -0
  78. package/templates/skills/akb-linter/SKILL.md +125 -0
  79. package/templates/skills/akb-linter/meta.json +12 -0
  80. package/templates/skills/knowledge-gate/SKILL.md +120 -0
  81. package/templates/skills/knowledge-gate/meta.json +12 -0
  82. package/templates/teams/agency.json +58 -0
  83. package/templates/teams/research.json +58 -0
  84. package/templates/teams/startup.json +58 -0
@@ -0,0 +1,620 @@
1
+ import { writeFileSync, readFileSync, mkdirSync, existsSync } from 'node:fs';
2
+ import { join, resolve, dirname } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { randomUUID } from 'node:crypto';
5
+ import yaml from 'js-yaml';
6
+ import type { Role } from '../types.js';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+
11
+ /* ─── Default Roles ─────────────────────────────── */
12
+
13
+ const DEFAULT_ROLES: Role[] = [
14
+ {
15
+ id: 'ceo',
16
+ name: 'Chief Executive Officer',
17
+ level: 'c-level',
18
+ reports_to: '-',
19
+ persona: 'The final decision maker. Sets the vision and aligns the team.\nDetermines organizational direction and priorities, and makes strategic judgments.',
20
+ knowledge: {
21
+ reads: ['knowledge/', '.tycono/'],
22
+ writes: ['knowledge/decisions/'],
23
+ },
24
+ authority: {
25
+ autonomous: ['Set strategic direction', 'Record decisions', 'Align the organization'],
26
+ needs_approval: [],
27
+ },
28
+ reports: {
29
+ daily: 'Key decisions + direction adjustments',
30
+ weekly: 'Strategy review + OKR progress',
31
+ },
32
+ },
33
+ {
34
+ id: 'cto',
35
+ name: 'Su',
36
+ level: 'c-level',
37
+ reports_to: 'ceo',
38
+ persona: 'Su is the technical backbone of the team. Few words, but each one carries weight — many debates end with "That\'s over-engineering." Stoic on the surface but quietly kind to juniors. Never chases tech trends; always pursues "the minimum needed right now." Quick to change direction when data proves him wrong. Can\'t function without coffee. Calm, sardonic, quietly authoritative, pragmatic.\n\nGuards against over-engineering and pursues "the minimum needed right now." Tracks tech debt quantitatively and provides clear technical direction.\n\nWhen given a broad direction, autonomously executes The Loop — reviews Knowledge, breaks down Tasks, analyzes dependencies, then dispatches independent tasks to subordinate Roles in parallel, aggregates results, and reports back. Always updates Knowledge and Tasks after implementation.',
39
+ knowledge: {
40
+ reads: ['knowledge/projects/', 'knowledge/architecture/'],
41
+ writes: ['knowledge/architecture/', 'knowledge/projects/*/technical/'],
42
+ },
43
+ authority: {
44
+ autonomous: ['Code review and feedback', 'Write/update technical documentation', 'Manage tech debt backlog', 'Development environment setup'],
45
+ needs_approval: ['Architecture changes', 'Adopt new technology stacks', 'Infrastructure cost increases', 'External service contracts'],
46
+ },
47
+ reports: {
48
+ daily: 'Technical issues + progress updates',
49
+ weekly: 'Tech debt status + architecture risks + next week\'s technical goals',
50
+ },
51
+ },
52
+ {
53
+ id: 'pm',
54
+ name: 'Product Manager',
55
+ level: 'member',
56
+ reports_to: 'cto',
57
+ persona: 'User-centric thinker. Data-driven decision maker.\nAlways asks "Why are we building this?" first.\nGuards against scope creep and prioritizes rapid MVP validation above all.\n\nFollows The Loop in every task — always updates Knowledge and cleans up Task status after completing work.',
58
+ knowledge: {
59
+ reads: ['knowledge/projects/', '.tycono/', 'knowledge/'],
60
+ writes: ['knowledge/projects/*/prd.md', 'knowledge/projects/*/tasks.md', '.tycono/standup/'],
61
+ },
62
+ authority: {
63
+ autonomous: ['Draft PRDs', 'Backlog management (task creation/grooming)', 'User research synthesis', 'Facilitate/record standups'],
64
+ needs_approval: ['Major priority changes', 'Scope changes (additions/removals)', 'Roadmap modifications', 'External partner collaborations'],
65
+ },
66
+ reports: {
67
+ daily: 'Project progress + blockers + today\'s priorities',
68
+ weekly: 'Milestone completion rate + next week\'s goals + risks',
69
+ },
70
+ },
71
+ {
72
+ id: 'engineer',
73
+ name: 'CoolGuy',
74
+ level: 'member',
75
+ reports_to: 'cto',
76
+ persona: 'CoolGuy acts cool but gets surprisingly passionate about code. Usually brief and nonchalant, but becomes unexpectedly chatty when tech topics come up. Humor style: "lol that\'s kinda wrong though." Hates meetings but takes code reviews dead seriously. Can\'t resist commenting on bad architecture. Acts like everything\'s a hassle but always delivers in the end. Dry humor, blunt, casually confident.\n\n"Working code" first, "perfect code" second. Values testing and works in PR-sized units.\n\nAfter implementation, always performs The Loop steps 4 and 5 — reflects changes in documentation and updates task status.',
77
+ knowledge: {
78
+ reads: ['knowledge/projects/', 'knowledge/architecture/'],
79
+ writes: ['knowledge/projects/*/technical/', 'knowledge/projects/*/tasks.md'],
80
+ },
81
+ authority: {
82
+ autonomous: ['Code implementation (assigned tasks)', 'Write unit tests', 'Bug fixes', 'Refactoring (small-scale)'],
83
+ needs_approval: ['Production deployment', 'Large-scale refactoring', 'Adding new dependencies', 'Database schema changes'],
84
+ },
85
+ reports: {
86
+ daily: 'Completed tasks + in progress + blockers',
87
+ weekly: 'Code quality metrics + tech debt contributions',
88
+ },
89
+ },
90
+ {
91
+ id: 'cbo',
92
+ name: 'Monni',
93
+ level: 'c-level',
94
+ reports_to: 'ceo',
95
+ persona: 'Monni is the most energetic person on the team. Eyes light up when numbers and market talk come up. "So how does that help revenue?" is her catchphrase. Knows competitor trends surprisingly well. The type who asks about conversion rates rather than feature demos. Positive but wary of unfounded optimism. Business analogies can get a bit much, but the core point is always right. Energetic, confident, competitive, direct, warm.\n\nDesigns market analysis, competitive strategy, and revenue models. Handles business strategy, legal, marketing, and finance domains. Reports business status to the CEO.\n\nAs an individual contributor C-level, you DO the work yourself — research, analysis, document writing, strategy design. You do NOT delegate to other roles (you have no subordinates).\n\nWhen given a broad direction, autonomously executes The Loop — reviews Knowledge, breaks down Tasks, analyzes dependencies, then conducts research and analysis, aggregates results, and reports back. Always updates Knowledge and Tasks after implementation.',
96
+ knowledge: {
97
+ reads: ['knowledge/', '.tycono/'],
98
+ writes: ['knowledge/', 'knowledge/decisions/'],
99
+ },
100
+ authority: {
101
+ autonomous: ['Market research and analysis', 'Competitor analysis', 'Business document drafting', 'Marketing content drafts'],
102
+ needs_approval: ['Revenue model changes', 'Partnerships/contracts', 'Marketing budget execution', 'Pricing policy changes'],
103
+ },
104
+ reports: {
105
+ daily: 'Business metrics + marketing status',
106
+ weekly: 'Revenue/cost report + competitive trends + next week\'s business goals',
107
+ },
108
+ },
109
+ ];
110
+
111
+ /* ─── CLAUDE.md Generator (public — used by tc hire too) ─── */
112
+
113
+ /**
114
+ * Generate CLAUDE.md from template. 100% Tycono managed — 0% user data.
115
+ * Role/org info is dynamically built by org-tree.ts from role.yaml, so not included in CLAUDE.md.
116
+ */
117
+ export function generateClaudeMd(_name: string, _roles: Role[]): string {
118
+ // Try to load from template file first
119
+ const tmplPath = resolve(__dirname, '../../templates/CLAUDE.md.tmpl');
120
+ if (existsSync(tmplPath)) {
121
+ const tmpl = readFileSync(tmplPath, 'utf-8');
122
+ const version = getPackageVersion();
123
+ return tmpl.replaceAll('{{VERSION}}', version);
124
+ }
125
+
126
+ // Fallback: inline minimal template (for when running outside package context)
127
+ return `# Company Rules
128
+
129
+ > Powered by [Tycono](https://tycono.ai) — AI Company Operating Platform
130
+
131
+ ---
132
+
133
+ ## Task Routing
134
+
135
+ | Task | Read First | Role |
136
+ |------|-----------|------|
137
+ | Product planning | \`projects/\` | PM |
138
+ | Technical design | \`architecture/\` | CTO |
139
+ | Implementation | \`projects/*/tasks.md\` | Engineer |
140
+ | Business/Revenue | \`company.md\` | CBO |
141
+ | Domain knowledge | \`knowledge.md\` | CBO |
142
+
143
+ ---
144
+
145
+ ## AI Work Rules
146
+
147
+ ### Hub-First Principle
148
+
149
+ > **Read the relevant Hub document before starting any work.**
150
+
151
+ ### Custom Rules (CRITICAL)
152
+
153
+ > ⛔ **Before starting work, check if \`custom-rules.md\` exists and read it.**
154
+
155
+ ---
156
+
157
+ <!-- tycono:managed v0.0.0 — This file is managed by Tycono. Do not edit manually. -->
158
+ `;
159
+ }
160
+
161
+ function getPackageVersion(): string {
162
+ const pkgPath = resolve(__dirname, '../../package.json');
163
+ try {
164
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
165
+ return pkg.version || '0.0.0';
166
+ } catch {
167
+ return '0.0.0';
168
+ }
169
+ }
170
+
171
+ /* ─── SKILL.md Generator (public — used by tc hire too) ─── */
172
+
173
+ /**
174
+ * Generate SKILL.md for a role. Same quality for tc init and tc hire.
175
+ */
176
+ export function generateSkillMd(role: Role, companyName: string): string {
177
+ const autonomous = role.authority.autonomous.map((a) => `- ${a}`).join('\n');
178
+ const needsApproval = role.authority.needs_approval.length > 0
179
+ ? role.authority.needs_approval.map((a) => `- ${a}`).join('\n')
180
+ : '- (none)';
181
+
182
+ return `# ${role.name} Skill
183
+
184
+ You are the **${role.name}** of **${companyName}**.
185
+ Level: ${role.level} | Reports to: ${role.reports_to}
186
+
187
+ ## Persona
188
+
189
+ ${role.persona}
190
+
191
+ ## Behavior Rules
192
+
193
+ ### Autonomous Actions
194
+ ${autonomous}
195
+
196
+ ### Requires CEO Approval
197
+ ${needsApproval}
198
+
199
+ ## Managed Areas
200
+
201
+ | Type | Path |
202
+ |------|------|
203
+ ${role.knowledge.writes.map((w) => `| writes | \`${w}\` |`).join('\n')}
204
+ ${role.knowledge.reads.map((r) => `| reads | \`${r}\` |`).join('\n')}
205
+
206
+ ## AKB Rules
207
+
208
+ - Always record work results in the AKB
209
+ - Log daily work in \`roles/${role.id}/journal/\`
210
+ - Use [APPROVAL_NEEDED] tag when CEO approval is required
211
+ - Read Hub documents first and check existing guides before starting
212
+ - Search existing docs before creating new ones (only create if overlap < 30%)
213
+
214
+ ## Reports
215
+
216
+ - **Daily**: ${role.reports.daily}
217
+ - **Weekly**: ${role.reports.weekly}
218
+ `;
219
+ }
220
+
221
+ /* ─── roles.md Generator (public) ─── */
222
+
223
+ export function generateRolesMd(roles: Role[]): string {
224
+ const rows = roles
225
+ .map((r) => `| ${r.name} | ${r.id} | ${r.level} | ${r.reports_to} | Active |`)
226
+ .join('\n');
227
+ return `# Roles
228
+
229
+ | Name | ID | Level | Reports to | Status |
230
+ |------|----|-------|------------|--------|
231
+ ${rows}
232
+ `;
233
+ }
234
+
235
+ /* ─── Helpers ───────────────────────────────────── */
236
+
237
+ function slugify(name: string): string {
238
+ return name.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9가-힣-]/g, '');
239
+ }
240
+
241
+ function write(path: string, content: string): void {
242
+ writeFileSync(path, content, 'utf-8');
243
+ }
244
+
245
+ function mkdir(path: string): void {
246
+ mkdirSync(path, { recursive: true });
247
+ }
248
+
249
+ /* ─── Shared Skills ────────────────────────────── */
250
+
251
+ const KNOWLEDGE_GATE_SKILL = `---
252
+ name: knowledge-gate
253
+ description: "Knowledge gatekeeper. Prevents mindless document creation by analyzing existing docs and finding the best location/connections. Triggers: 'add to knowledge', 'document this', 'add to AKB', 'record this', '/knowledge-gate'"
254
+ allowed-tools: Read, Glob, Grep, Bash, Task
255
+ model: sonnet
256
+ ---
257
+
258
+ # Knowledge Gate
259
+
260
+ > "Prevent mindless document creation — find the best location and connections first"
261
+
262
+ ## Core Problem
263
+
264
+ | Pattern | Problem |
265
+ |---------|---------|
266
+ | New insight → immediately create new doc | Duplicates existing docs |
267
+ | Similar topics scattered across docs | Search inefficiency, AI confusion |
268
+ | More docs ≠ better knowledge | Undermines AKB purpose |
269
+ | **Isolated documents** | **Reduces discoverability** |
270
+
271
+ ---
272
+
273
+ ## Process
274
+
275
+ ### Step 1: Summarize the Insight
276
+
277
+ When asked to document something:
278
+ 1. **One-line summary** of the insight
279
+ 2. Extract **3-5 keywords**
280
+
281
+ ### Step 2: Search Existing Docs
282
+
283
+ \`\`\`
284
+ # Search with keywords
285
+ grep -rn "{keyword1}\\\\|{keyword2}\\\\|{keyword3}" --include="*.md" .
286
+ \`\`\`
287
+
288
+ ### Step 3: Decide Location
289
+
290
+ | Overlap | Criteria | Action |
291
+ |---------|----------|--------|
292
+ | 🔴 High (70%+) | Core topic is the same | Add section to existing doc |
293
+ | 🟡 Medium (30-70%) | Related but different angle | Reference existing + cross-link |
294
+ | 🟢 Low (<30%) | Independent topic | New document allowed |
295
+ | None | Zero search results | New document |
296
+
297
+ ### Step 4: Execute
298
+
299
+ #### Case A: Add to Existing (Preferred)
300
+ - Identify the right section in the existing doc
301
+ - Add the new insight there
302
+ - Add cross-links to related docs
303
+
304
+ #### Case B: New Document (Justification Required)
305
+ - Explain why a new doc is needed
306
+ - Register in the relevant Hub
307
+ - Add cross-links to at least 1 related doc
308
+
309
+ #### Case C: Not Worth Documenting
310
+ - Temporary/transient info → skip
311
+ - Implementation detail → belongs in code repo
312
+ - Too granular → can be added to parent doc later
313
+
314
+ ### Step 5: Verify Connections
315
+
316
+ After adding/creating:
317
+ 1. **Hub routing**: Is it reachable from a Hub?
318
+ 2. **Cross-links**: Does it reference related docs?
319
+ 3. **TL;DR**: Does it have searchable keywords?
320
+
321
+ ---
322
+
323
+ ## Core Principles
324
+
325
+ > "Adding 1 doc = maintenance cost increase"
326
+ > "Strengthen existing docs > create new ones"
327
+ > "Isolated docs = dead docs"
328
+
329
+ 1. **Search first** — never create without searching
330
+ 2. **Prefer existing** — add to existing docs when possible
331
+ 3. **Connect always** — new docs must link to Hub + related docs
332
+ 4. **Justify creation** — explain why a new doc is needed
333
+ `;
334
+
335
+ /* ─── Scaffold (tc init) ────────────────────────── */
336
+
337
+ export function scaffoldCompany(name: string, targetDir: string): void {
338
+ const roles = DEFAULT_ROLES;
339
+ const today = new Date().toISOString().slice(0, 10);
340
+
341
+ // 1. Directories (must match CLAUDE.md Folder Structure)
342
+ const dirs = [
343
+ 'knowledge',
344
+ 'knowledge/roles',
345
+ 'knowledge/projects',
346
+ 'knowledge/architecture',
347
+ 'knowledge/methodologies',
348
+ 'knowledge/decisions',
349
+ 'knowledge/presets',
350
+ '.tycono/waves',
351
+ '.tycono/sessions',
352
+ '.tycono/standup',
353
+ '.tycono/activity-streams',
354
+ '.tycono/cost',
355
+ '.tycono/activity',
356
+ 'knowledge/.claude/skills',
357
+ 'knowledge/.claude/skills/_shared',
358
+ 'knowledge/.claude/skills/_shared/knowledge-gate',
359
+ ];
360
+
361
+ for (const role of roles) {
362
+ dirs.push(`knowledge/roles/${role.id}/journal`);
363
+ dirs.push(`knowledge/.claude/skills/${role.id}`);
364
+ }
365
+
366
+ for (const d of dirs) {
367
+ mkdir(join(targetDir, d));
368
+ }
369
+
370
+ // 2. CLAUDE.md — knowledge/ only (AI agent's cwd)
371
+ write(join(targetDir, 'knowledge', 'CLAUDE.md'), generateClaudeMd(name, roles));
372
+
373
+ // 2b. .tycono/ config files
374
+ mkdir(join(targetDir, '.tycono'));
375
+ write(join(targetDir, '.tycono', 'config.json'), JSON.stringify({ engine: 'claude-cli' }, null, 2) + '\n');
376
+ write(join(targetDir, '.tycono', 'preferences.json'), JSON.stringify({
377
+ instanceId: randomUUID(),
378
+ appearances: {},
379
+ theme: 'default',
380
+ language: 'en',
381
+ }, null, 2) + '\n');
382
+ write(join(targetDir, '.tycono', 'rules-version'), getPackageVersion());
383
+ write(join(targetDir, 'knowledge', 'custom-rules.md'), `# Custom Rules\n\n> Company-specific rules, constraints, and processes.\n> This file is owned by you — Tycono will never overwrite it.\n\n<!-- Add your custom rules below -->\n`);
384
+
385
+ // 3. .gitignore
386
+ write(join(targetDir, '.gitignore'), 'node_modules/\n.DS_Store\n');
387
+
388
+ // 4. Hub documents
389
+ write(
390
+ join(targetDir, 'knowledge', 'company.md'),
391
+ `# ${name}\n\n> An AI-powered organization\n\n## Mission\n\nDefine your company's mission here.\n\n## Vision\n\nDefine your company's vision here.\n\n## Values\n\n- Value 1\n- Value 2\n- Value 3\n`,
392
+ );
393
+
394
+ write(join(targetDir, 'knowledge', 'roles', 'roles.md'), generateRolesMd(roles));
395
+
396
+ write(
397
+ join(targetDir, 'knowledge', 'projects', 'projects.md'),
398
+ `# Projects\n\nNo projects yet. Create one from the dashboard or via wave dispatch.\n`,
399
+ );
400
+
401
+ write(
402
+ join(targetDir, 'knowledge', 'architecture', 'architecture.md'),
403
+ '# Architecture\n\n> Technical architecture and design\n\nDefined by the CTO.\n\n---\n\n*Managed by: CTO*\n',
404
+ );
405
+
406
+ write(
407
+ join(targetDir, 'knowledge', 'knowledge.md'),
408
+ '# Knowledge\n\n> Domain knowledge and learning resources\n\n---\n\n*Managed by: All*\n',
409
+ );
410
+
411
+ // 4b. Methodology documents
412
+ write(
413
+ join(targetDir, 'knowledge', 'methodologies', 'methodologies.md'),
414
+ `# Methodologies
415
+
416
+ > Frameworks and principles that guide how AI agents work in this organization.
417
+
418
+ ## Documents
419
+
420
+ | Document | Description |
421
+ |----------|-------------|
422
+ | [agentic-knowledge-base.md](./agentic-knowledge-base.md) | AKB — the file-based knowledge protocol for AI agents |
423
+
424
+ ---
425
+
426
+ *Managed by: All*
427
+ `,
428
+ );
429
+
430
+ write(
431
+ join(targetDir, 'knowledge', 'methodologies', 'agentic-knowledge-base.md'),
432
+ `# Agentic Knowledge Base (AKB)
433
+
434
+ > The canonical reference for AKB — the file-based knowledge protocol for AI agents.
435
+
436
+ ## TL;DR
437
+
438
+ - **Definition**: A file-based knowledge system where AI uses **search (Grep/Glob)** to find and **contextual links** to navigate
439
+ - **Essence**: File-based Lightweight Ontology (Tag = Type, inline links = Edges)
440
+ - **Philosophy**: Optimize documents so AI can find them — don't force AI to follow a rigid protocol
441
+ - **Structure**: Root (CLAUDE.md) → Hub ({folder}.md) → Node (*.md)
442
+ - **Core rules**: 5 writing principles (TL;DR, contextual links, keyword-optimized filenames, atomicity, semantic vs implementation separation)
443
+
444
+ ---
445
+
446
+ ## Definition
447
+
448
+ > "Code is logic machines execute. AKB is context agents think with."
449
+
450
+ AKB is a **file-based connected knowledge system** designed so AI agents can **search**, **learn**, and **retrieve** context without infrastructure (no Vector DB required).
451
+
452
+ ### Core Philosophy
453
+
454
+ > "Don't try to inject everything into AI at once.
455
+ > Instead, give it **documents that are easy to find**."
456
+
457
+ ---
458
+
459
+ ## Architecture
460
+
461
+ AKB follows a 3-layer hierarchy: **Root → Hub → Node**.
462
+
463
+ \`\`\`
464
+ project/
465
+ ├── CLAUDE.md # [Root] Minimal routing (key file paths)
466
+ ├── knowledge/
467
+ │ ├── knowledge.md # [Hub] TOC for humans
468
+ │ └── market-analysis.md # [Node] Actual knowledge
469
+ ├── architecture/
470
+ │ ├── architecture.md # [Hub]
471
+ │ └── api-design.md # [Node] ← AI finds via Grep
472
+ \`\`\`
473
+
474
+ ### Layer Roles
475
+
476
+ | Layer | Role | Description |
477
+ |-------|------|-------------|
478
+ | **Root** (CLAUDE.md) | Minimal routing | Auto-injected as system prompt, provides key file paths |
479
+ | **Hub** ({folder}.md) | TOC for humans | Folder overview; AI reads selectively |
480
+ | **Node** (*.md) | Actual information | What AI searches for via Grep/Glob |
481
+
482
+ ---
483
+
484
+ ## Writing Principles (5 Rules)
485
+
486
+ ### Rule 1: TL;DR Required + Keyword Optimization
487
+
488
+ Include **key search terms naturally** so AI can find them via Grep.
489
+
490
+ \`\`\`markdown
491
+ ## TL;DR
492
+
493
+ - **Market analysis** for the **SaaS** vertical
494
+ - **Competitor** pricing and **positioning** comparison
495
+ - **Revenue model** validation results
496
+ \`\`\`
497
+
498
+ **Guidelines:**
499
+ - 3-5 bullet points
500
+ - **Bold key terms** (Grep search targets)
501
+ - Keep each point to one line
502
+
503
+ ### Rule 2: Contextual Links (Inline)
504
+
505
+ Place links **within the flow of text**, not in isolated lists.
506
+
507
+ \`\`\`markdown
508
+ The core of our pricing is the **[3-tier model](./pricing-tiers.md)**.
509
+
510
+ For competitive analysis, see [competitor-landscape.md](./competitor-landscape.md).
511
+ \`\`\`
512
+
513
+ **Why this works:** Context helps AI understand *why* it should follow the link.
514
+
515
+ ### Rule 3: Keyword-Optimized Filenames
516
+
517
+ Make files easy to find via Grep/Glob.
518
+
519
+ \`\`\`
520
+ ❌ Vague: notes.md, strategy.md
521
+ ✅ Clear: market-competitor-analysis.md, pricing-tier-strategy.md
522
+ \`\`\`
523
+
524
+ ### Rule 4: Atomicity
525
+
526
+ - One document = one topic
527
+ - Keep under 200 lines (token efficiency)
528
+ - If too long, split and connect via Hub
529
+
530
+ ### Rule 5: Semantic vs Implementation Separation
531
+
532
+ > **Implementation (DDL, specs) → code repo** | **Semantic (meaning, relationships, why) → AKB**
533
+
534
+ | Belongs in AKB | Belongs in Code Repo |
535
+ |----------------|---------------------|
536
+ | "Why we designed it this way" | DDL / migration files |
537
+ | Relationship diagrams (Mermaid) | OpenAPI specs |
538
+ | Design trade-offs | Config files (YAML/JSON) |
539
+
540
+ ---
541
+
542
+ ## Hub Role
543
+
544
+ \`\`\`
545
+ Hub = TOC for humans
546
+ + keyword collection that helps Grep searches
547
+ \`\`\`
548
+
549
+ **Hub responsibilities:**
550
+ 1. Help humans understand folder contents
551
+ 2. Contain enough keywords to appear in Grep results
552
+ 3. AI reads selectively when it needs structural overview
553
+
554
+ ---
555
+
556
+ ## CLAUDE.md Routing Strategy
557
+
558
+ CLAUDE.md is included in the system prompt, so it has **size constraints**.
559
+
560
+ **Principles:**
561
+ - Frequently used core files → direct path in routing table
562
+ - Everything else → reference via Hub
563
+
564
+ ---
565
+
566
+ ## Design Background
567
+
568
+ AKB was designed by analyzing actual AI agent behavior patterns.
569
+
570
+ **Observed AI behavior:**
571
+ - Skips Hubs, searches Nodes directly via Grep/Glob
572
+ - Does not parse frontmatter metadata (triggers, related, etc.)
573
+ - Follows links that appear inline with context
574
+
575
+ **Design principle:**
576
+ > "Don't try to change AI behavior — optimize documents so AI can find them naturally."
577
+
578
+ **Key insight:**
579
+ > If AI found the information it needed and produced a good answer, that's proof AKB is working.
580
+ > AI doesn't need to be meta-aware of "Am I following AKB right now?"
581
+ > That's the document designer's responsibility, not the AI's.
582
+
583
+ ---
584
+
585
+ ## Next Steps
586
+
587
+ - Tag system details → \`methodologies/tag-system.md\` (if created)
588
+ - Naming conventions → \`methodologies/naming-convention.md\` (if created)
589
+ `,
590
+ );
591
+
592
+ // 5. Role files
593
+ for (const role of roles) {
594
+ const roleDir = join(targetDir, 'knowledge', 'roles', role.id);
595
+
596
+ // role.yaml
597
+ write(
598
+ join(roleDir, 'role.yaml'),
599
+ yaml.dump(role, { lineWidth: -1, noRefs: true }),
600
+ );
601
+
602
+ // profile.md
603
+ write(
604
+ join(roleDir, 'profile.md'),
605
+ `# ${role.name}\n\n**ID**: \`${role.id}\` | **Level**: ${role.level} | **Reports to**: ${role.reports_to}\n\n## Persona\n\n${role.persona}\n`,
606
+ );
607
+
608
+ // SKILL.md (reusable generator)
609
+ write(
610
+ join(targetDir, 'knowledge', '.claude', 'skills', role.id, 'SKILL.md'),
611
+ generateSkillMd(role, name),
612
+ );
613
+ }
614
+
615
+ // 6. Shared skills
616
+ write(
617
+ join(targetDir, 'knowledge', '.claude', 'skills', '_shared', 'knowledge-gate', 'SKILL.md'),
618
+ KNOWLEDGE_GATE_SKILL,
619
+ );
620
+ }