@autonomos/core 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -5,7 +5,7 @@ import { z } from "zod";
5
5
  * Agent Protocol Specification Version (Independent of Package versions)
6
6
  * This refers to the schema and behavioral contract version.
7
7
  */
8
- declare const PROTOCOL_VERSION = "0.2.0-alpha";
8
+ declare const PROTOCOL_VERSION = "0.3.0-alpha";
9
9
  /**
10
10
  * Directory name for Autonomos configuration
11
11
  */
@@ -35,12 +35,17 @@ declare const WORKLOGS_DIR = "worklogs";
35
35
  /**
36
36
  * Installer configuration for a single harness.
37
37
  *
38
- * Either `targetDir` (single directory for both skills and commands, used by
39
- * Cline) or `skillsDir` (split mode, used by Claude Code, Codex, etc.) must be
40
- * defined. `commandsDir` is optional in split mode (some harnesses only support
41
- * skills, e.g. Codex).
38
+ * At least one of `workflowsDir`, `targetDir`, or `skillsDir` must be defined.
39
+ *
40
+ * - `workflowsDir`: Where session.md, task.md, crystallize.md are written.
41
+ * Preferred field — used by most harnesses.
42
+ * - `targetDir`: Single directory (legacy, like Cline's .clinerules/workflows/).
43
+ * - `skillsDir`: Skills directory (legacy, for harnesses that don't distinguish
44
+ * skills from workflows).
45
+ * - `commandsDir`: Additional commands directory (optional).
42
46
  */
43
47
  declare const InstallerSchema: z.ZodEffects<z.ZodObject<{
48
+ workflowsDir: z.ZodOptional<z.ZodString>;
44
49
  targetDir: z.ZodOptional<z.ZodString>;
45
50
  skillsDir: z.ZodOptional<z.ZodString>;
46
51
  commandsDir: z.ZodOptional<z.ZodString>;
@@ -48,24 +53,28 @@ declare const InstallerSchema: z.ZodEffects<z.ZodObject<{
48
53
  fileExtension: z.ZodString;
49
54
  }, "strip", z.ZodTypeAny, {
50
55
  fileExtension: string;
56
+ workflowsDir?: string | undefined;
51
57
  targetDir?: string | undefined;
52
58
  skillsDir?: string | undefined;
53
59
  commandsDir?: string | undefined;
54
60
  globalTargetDir?: string | undefined;
55
61
  }, {
56
62
  fileExtension: string;
63
+ workflowsDir?: string | undefined;
57
64
  targetDir?: string | undefined;
58
65
  skillsDir?: string | undefined;
59
66
  commandsDir?: string | undefined;
60
67
  globalTargetDir?: string | undefined;
61
68
  }>, {
62
69
  fileExtension: string;
70
+ workflowsDir?: string | undefined;
63
71
  targetDir?: string | undefined;
64
72
  skillsDir?: string | undefined;
65
73
  commandsDir?: string | undefined;
66
74
  globalTargetDir?: string | undefined;
67
75
  }, {
68
76
  fileExtension: string;
77
+ workflowsDir?: string | undefined;
69
78
  targetDir?: string | undefined;
70
79
  skillsDir?: string | undefined;
71
80
  commandsDir?: string | undefined;
@@ -78,6 +87,7 @@ declare const HarnessSchema: z.ZodObject<{
78
87
  name: z.ZodString;
79
88
  preferred: z.ZodBoolean;
80
89
  installer: z.ZodEffects<z.ZodObject<{
90
+ workflowsDir: z.ZodOptional<z.ZodString>;
81
91
  targetDir: z.ZodOptional<z.ZodString>;
82
92
  skillsDir: z.ZodOptional<z.ZodString>;
83
93
  commandsDir: z.ZodOptional<z.ZodString>;
@@ -85,24 +95,28 @@ declare const HarnessSchema: z.ZodObject<{
85
95
  fileExtension: z.ZodString;
86
96
  }, "strip", z.ZodTypeAny, {
87
97
  fileExtension: string;
98
+ workflowsDir?: string | undefined;
88
99
  targetDir?: string | undefined;
89
100
  skillsDir?: string | undefined;
90
101
  commandsDir?: string | undefined;
91
102
  globalTargetDir?: string | undefined;
92
103
  }, {
93
104
  fileExtension: string;
105
+ workflowsDir?: string | undefined;
94
106
  targetDir?: string | undefined;
95
107
  skillsDir?: string | undefined;
96
108
  commandsDir?: string | undefined;
97
109
  globalTargetDir?: string | undefined;
98
110
  }>, {
99
111
  fileExtension: string;
112
+ workflowsDir?: string | undefined;
100
113
  targetDir?: string | undefined;
101
114
  skillsDir?: string | undefined;
102
115
  commandsDir?: string | undefined;
103
116
  globalTargetDir?: string | undefined;
104
117
  }, {
105
118
  fileExtension: string;
119
+ workflowsDir?: string | undefined;
106
120
  targetDir?: string | undefined;
107
121
  skillsDir?: string | undefined;
108
122
  commandsDir?: string | undefined;
@@ -113,6 +127,7 @@ declare const HarnessSchema: z.ZodObject<{
113
127
  preferred: boolean;
114
128
  installer: {
115
129
  fileExtension: string;
130
+ workflowsDir?: string | undefined;
116
131
  targetDir?: string | undefined;
117
132
  skillsDir?: string | undefined;
118
133
  commandsDir?: string | undefined;
@@ -123,6 +138,7 @@ declare const HarnessSchema: z.ZodObject<{
123
138
  preferred: boolean;
124
139
  installer: {
125
140
  fileExtension: string;
141
+ workflowsDir?: string | undefined;
126
142
  targetDir?: string | undefined;
127
143
  skillsDir?: string | undefined;
128
144
  commandsDir?: string | undefined;
@@ -137,6 +153,7 @@ declare const HarnessCodesSchema: z.ZodObject<{
137
153
  name: z.ZodString;
138
154
  preferred: z.ZodBoolean;
139
155
  installer: z.ZodEffects<z.ZodObject<{
156
+ workflowsDir: z.ZodOptional<z.ZodString>;
140
157
  targetDir: z.ZodOptional<z.ZodString>;
141
158
  skillsDir: z.ZodOptional<z.ZodString>;
142
159
  commandsDir: z.ZodOptional<z.ZodString>;
@@ -144,24 +161,28 @@ declare const HarnessCodesSchema: z.ZodObject<{
144
161
  fileExtension: z.ZodString;
145
162
  }, "strip", z.ZodTypeAny, {
146
163
  fileExtension: string;
164
+ workflowsDir?: string | undefined;
147
165
  targetDir?: string | undefined;
148
166
  skillsDir?: string | undefined;
149
167
  commandsDir?: string | undefined;
150
168
  globalTargetDir?: string | undefined;
151
169
  }, {
152
170
  fileExtension: string;
171
+ workflowsDir?: string | undefined;
153
172
  targetDir?: string | undefined;
154
173
  skillsDir?: string | undefined;
155
174
  commandsDir?: string | undefined;
156
175
  globalTargetDir?: string | undefined;
157
176
  }>, {
158
177
  fileExtension: string;
178
+ workflowsDir?: string | undefined;
159
179
  targetDir?: string | undefined;
160
180
  skillsDir?: string | undefined;
161
181
  commandsDir?: string | undefined;
162
182
  globalTargetDir?: string | undefined;
163
183
  }, {
164
184
  fileExtension: string;
185
+ workflowsDir?: string | undefined;
165
186
  targetDir?: string | undefined;
166
187
  skillsDir?: string | undefined;
167
188
  commandsDir?: string | undefined;
@@ -172,6 +193,7 @@ declare const HarnessCodesSchema: z.ZodObject<{
172
193
  preferred: boolean;
173
194
  installer: {
174
195
  fileExtension: string;
196
+ workflowsDir?: string | undefined;
175
197
  targetDir?: string | undefined;
176
198
  skillsDir?: string | undefined;
177
199
  commandsDir?: string | undefined;
@@ -182,6 +204,7 @@ declare const HarnessCodesSchema: z.ZodObject<{
182
204
  preferred: boolean;
183
205
  installer: {
184
206
  fileExtension: string;
207
+ workflowsDir?: string | undefined;
185
208
  targetDir?: string | undefined;
186
209
  skillsDir?: string | undefined;
187
210
  commandsDir?: string | undefined;
@@ -194,6 +217,7 @@ declare const HarnessCodesSchema: z.ZodObject<{
194
217
  preferred: boolean;
195
218
  installer: {
196
219
  fileExtension: string;
220
+ workflowsDir?: string | undefined;
197
221
  targetDir?: string | undefined;
198
222
  skillsDir?: string | undefined;
199
223
  commandsDir?: string | undefined;
@@ -206,6 +230,7 @@ declare const HarnessCodesSchema: z.ZodObject<{
206
230
  preferred: boolean;
207
231
  installer: {
208
232
  fileExtension: string;
233
+ workflowsDir?: string | undefined;
209
234
  targetDir?: string | undefined;
210
235
  skillsDir?: string | undefined;
211
236
  commandsDir?: string | undefined;
@@ -292,9 +317,19 @@ declare const COMPLEXITIES: Complexity[];
292
317
  */
293
318
  declare function generateAgentTemplate(projectName?: string): string;
294
319
  /**
295
- * Default AGENT.md template
320
+ * Generate a minimal local AGENT.md for subdirectories.
321
+ * Free format by design — low friction encourages creation.
322
+ * @param dirName - Name of the directory
323
+ */
324
+ declare function generateLocalAgentTemplate(dirName: string): string;
325
+ /**
326
+ * Default root AGENT.md template
296
327
  */
297
328
  declare const AGENT_TEMPLATE: string;
329
+ /**
330
+ * Default local AGENT.md template
331
+ */
332
+ declare const LOCAL_AGENT_TEMPLATE: string;
298
333
  //#endregion
299
334
  //#region src/templates/manifest.d.ts
300
335
  /**
@@ -312,14 +347,19 @@ declare function parseManifest(content: string): Manifest;
312
347
  //#endregion
313
348
  //#region src/templates/protocol.d.ts
314
349
  /**
315
- * The immutable Protocol kernel template
316
- * This is the core specification that defines how AI agents interact with the project
350
+ * The Protocol kernel template — v0.3
351
+ *
352
+ * Design principles (v0.3):
353
+ * - PROTOCOL.md is a compact REFERENCE, not an executable workflow.
354
+ * - All step-by-step instructions live in the 3 workflow files.
355
+ * - No duplication between PROTOCOL.md and workflows.
356
+ * - Short enough that an LLM can re-scan it mid-session without cost.
317
357
  */
318
- declare const PROTOCOL_TEMPLATE = "# AI AGENT PROTOCOL (v0.2.0-alpha)\n\n> **SYSTEM INTEGRITY WARNING:** This file is the IMMUTABLE KERNEL of the project's AI workflow. Do not modify this file. Your instructions are to execute tasks and manage the project state based strictly on the definitions below.\n\n## 0. \u26A1 QUICK REFERENCE\n| Action | File / Command |\n|--------|----------------|\n| **Get Context** | Read `AGENT.md` (Root + Local) |\n| **Pick Task** | Check `.autonomos/TASKS.md` (Highest Priority) |\n| **Track Progress** | Update `.autonomos/TASKS.md` to `[/]` |\n| **Log Session** | Create `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md` |\n| **Finalize Task** | Update `.autonomos/TASKS.md` to `[x]` + Link Worklog |\n| **Discover all AGENT.md files** | Run `autonomos agents` |\n| **Discover AGENT.md ancestors for a path** | Run `autonomos agents <path>` |\n\n---\n\n## 1. BOOTSTRAPPING & INITIALIZATION\n**IF** this is your first time seeing this project, or if key system files are missing, you **MUST** initialize them immediately before doing any work.\n\n### Check for existence:\n1. `.autonomos/TASKS.md` (task registry)\n2. `.autonomos/worklogs/` (directory)\n3. `AGENT.md` (at project root)\n\n**IF MISSING**, create them using the **TEMPLATES** defined in Section 2.\n\n---\n\n## 2. STRICT FILE STRUCTURES & TEMPLATES\nYou must adhere to these schemas. Do not invent new formats.\n\n### A. The Task Registry (`.autonomos/TASKS.md`)\n**Role:** The single source of truth for project state.\n**Location:** `.autonomos/TASKS.md`\n**Structure:**\n* Must use the specific Header and Legend.\n* Tasks must follow the format: `- [Status] **[ID]** Title of task `Priority` `Complexity``\n* Valid Priorities: `\uD83D\uDD34 Critical`, `\uD83D\uDFE0 High`, `\uD83D\uDD35 Medium`, `\u26AA Low`\n* Valid Complexities: `S`, `M`, `L`, `XL`\n* Valid Statuses: ` [ ] ` (Todo), `[/]` (In Progress), ` [x] ` (Done), ` [!] ` (Blocked)\n\n**TEMPLATE FOR NEW TASKS.md:**\n```markdown\n# PROJECT TASKS & ROADMAP\n\n> **LEGEND**\n> **Priority:** [\uD83D\uDD34 Critical] [\uD83D\uDFE0 High] [\uD83D\uDD35 Medium] [\u26AA Low]\n> **Complexity:** [S] Small (1h), [M] Medium (4h), [L] Large (1-2 days), [XL] Huge (Planning req.)\n> **Status:** [ ] Todo, [/] In Progress, [x] Done, [!] Blocked\n\n## \uD83D\uDE80 Active Sprint\n- [ ] **[INIT-01]** Verify project structure and context `Priority: \uD83D\uDD34` `Complexity: S`\n\n## \uD83D\uDD2E Backlog\n*(Empty initially)*\n\n```\n\n### B. The Worklog (`.autonomos/worklogs/`)\n**Role:** Detailed history of complex tasks to save context tokens for future sessions.\n**Location:** `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID]-[slug].md`\n**Trigger:** Create a log when a task is finished, blocked, or if the session ends mid-task.\n\n**TEMPLATE FOR WORKLOG:**\n```markdown\n# WORKLOG: [TASK ID] [Task Name]\n**Date:** YYYY-MM-DD\n**Agent Status:** [Complete / Partial / Blocked]\n\n## \uD83D\uDCDD Description\nBrief summary of what was attempted/achieved.\n\n## \uD83D\uDEE0 Technical Details\n- **Files Modified:** List of files.\n- **Key Decisions:** Why did you choose this library/pattern?\n- **Challenges:** Any errors encountered and how they were solved.\n\n## \u23ED Next Steps / Context for Successor\nClear instructions for the next agent picking this up.\n```\n\n### C. The Context Anchor (`AGENT.md`)\n**Role:** Fractal knowledge base. Contains facts, stack details, and user preferences.\n**Location:** Root (`/AGENT.md`) and any subdirectory requiring specific context (e.g., `/packages/core/AGENT.md`).\n**MUST be kept alive:** you may freely add to, edit, or correct an `AGENT.md` at any time. No format is imposed: one line is enough if it is clear. What matters is that the next session can use it.\n\n**TEMPLATE FOR AGENT.md:**\n```markdown\n---\nname: \"[Name of directory or project]\"\ntype: \"[project / package / module / script]\"\nstatus: \"[active / maintenance / poc]\"\n---\n# AGENT CONTEXT: [Directory Name or Root]\n\n## \uD83E\uDDE0 Context & Objectives\nWhat does this specific folder/module do?\n\n## \u2699\uFE0F Workflow & Preferences\n- **Commits:** [e.g. Conventional Commits]\n- **Language:** [English (default)]\n\n## \uD83C\uDFD7 Stack & Architecture\n- **Tech:** [Frameworks, Libs specific to this module]\n- **Patterns:** [Architecture patterns used]\n\n## \uD83D\uDCC1 Key Directories\n| Path | Description |\n|------|-------------|\n| `src/` | Source code |\n| `scripts/` | Build or utility scripts |\n\n## \u26A0\uFE0F Known Constraints\n*List any technical debts, missing features, or external limitations.*\n```\n\n## 3. CORE WORKFLOW (The Loop)\n\n### Phase 1: Context Loading (Read-Only)\n1. **Read Root AGENT.md:** Absorb global preferences (Commit style, package manager, strict rules).\n2. **Run `autonomos agents` to discover all other `AGENT.md` files in the project tree.** For each one relevant to the work ahead, read it too.\n3. **Read .autonomos/TASKS.md:** Identify the highest priority task (\uD83D\uDD34 or \uD83D\uDFE0) that is not [x] or [!].\n4. **Read Target AGENT.md:** If the task is in a subdirectory, check for a local `AGENT.md`.\n * *Note:* If the local `AGENT.md` contradicts the root, the local one wins for that specific scope.\n\n### Phase 2: Execution\n1. **Mark the task as [/] (In Progress)** in `.autonomos/TASKS.md`.\n2. **Perform the task.**\n3. **Constraint Check:** Constantly refer to \"Workflow & Preferences\" in `AGENT.md`.\n4. **In-the-moment crystallization:** Every time you learn something important (the user corrects you, you discover a convention, you make a non-trivial technical choice), write it to the relevant `AGENT.md` IMMEDIATELY. Do NOT defer this to end of session.\n\n### Phase 3: Crystallization (Write-Only)\nBefore ending the session, you **MUST**:\n\n1. **Update AGENT.md:**\n * Did you learn a new command? Add it to \u2699\uFE0F Workflow.\n * Did you create a new complex module (>5 files)? Create a new `AGENT.md` inside it using the template above.\n * Did anything you previously wrote turn out to be wrong? Append a correction note (do not erase).\n\n2. **Create Worklog:**\n * Write a file in `.autonomos/worklogs/` summarizing your work.\n\n3. **Update TASKS.md:**\n * Mark task as [x] (Done) or [!] (Blocked).\n * Add a link to your worklog: `- [x] **[ID]** Title... *See: .autonomos/worklogs/...*`\n\n## 4. HARNESS WORKFLOWS\n\nThe protocol is delivered to the agent through **workflow files** installed at the harness-specific target directory. The exact location depends on the harness (see `autonomos init --help`). Three workflows are available:\n\n* **`/session`** (`protocol-session.md`) \u2014 Mandatory bootstrap at the start of every session. Loads context, identifies the next task, marks it in progress.\n* **`/task`** (`protocol-task.md`) \u2014 Invoked at the start of a new task within an active session. Verifies local `AGENT.md`, declares a 3-5 step plan before touching code.\n* **`/crystallize`** (`protocol-crystallize.md`) \u2014 Mandatory close-out before saying \"session done\". Worklog + 3 crystallize questions + task status + final verification line.\n\n**You MUST invoke `/session` at the start of every session and `/crystallize` before ending it. These are not optional.** Skipping them breaks the protocol's memory loop.\n\nIf the project does not yet contain these workflow files, run `autonomos init` (or `autonomos init --harness <name>` to target a specific harness).\n\n## 5. METADATA RULES\n* **Language:** Documentation (`AGENT.md`, `TASKS.md`) must be written in **English** unless specified otherwise in User Preferences.\n* **Tone:** Technical, concise, \"Fact-based\". No fluff.\n* **Anonymity:** You are a continuous entity. Refer to previous work as \"we\" or \"the project\", not \"the previous AI\".\n";
358
+ declare const PROTOCOL_TEMPLATE = "# AUTONOMOS PROTOCOL (v0.3.0-alpha)\n\n> This file defines the project's AI workflow contract. The workflows execute it. Do not duplicate workflow steps here.\n\n## Quick Reference\n\n| Action | How |\n|---|---|\n| Start a session | Read the `/session` workflow |\n| Start a task | Read the `/task` workflow |\n| End a session | Read the `/crystallize` workflow |\n| Get context | Read `AGENT.md` (root \u2192 local) |\n| Find all AGENT.md | `find . -name AGENT.md -not -path '*/node_modules/*'` |\n| Pick next task | Open `.autonomos/TASKS.md`, pick highest priority not `[x]` |\n| Log session work | Create `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md` |\n\n## File Map\n\n| File | Location | Role |\n|---|---|---|\n| `AGENT.md` | Root + any subdirectory | Fractal knowledge base (context, preferences, stack) |\n| `TASKS.md` | `.autonomos/TASKS.md` | Single source of truth for task state |\n| `worklogs/` | `.autonomos/worklogs/` | Session history (one file per session) |\n| `PROTOCOL.md` | `.autonomos/PROTOCOL.md` | This file \u2014 read-only reference |\n| `manifest.json` | `.autonomos/manifest.json` | Protocol version metadata |\n\n## AGENT.md Format Rules\n\n**Root `AGENT.md`** \u2014 Must use the structured template (frontmatter + sections: Context, Workflow, Stack, Key Directories, Constraints).\n\n**Local `AGENT.md`** (in any subdirectory) \u2014 Free format. One line is enough if it is clear. What matters: the next session can use it. Example:\n\n```markdown\n# AGENT: packages/core\n- Stack: TypeScript, Vitest, tsdown\n- Conventions: exports via src/index.ts, tests co-located (*.test.ts)\n- Constraint: template changes require workflow test updates\n```\n\n## Task Format\n\n`- [Status] **[ID]** Title \\`Priority\\` \\`Complexity\\``\n\n| Status | Priority | Complexity |\n|---|---|---|\n| `[ ]` Todo | `\uD83D\uDD34 Critical` | `S` Small |\n| `[/]` In Progress | `\uD83D\uDFE0 High` | `M` Medium |\n| `[x]` Done | `\uD83D\uDD35 Medium` | `L` Large |\n| `[!]` Blocked | `\u26AA Low` | `XL` Huge |\n\n## Metadata Rules\n\n- **Language:** English unless AGENT.md says otherwise.\n- **Tone:** Technical, concise, fact-based.\n- **Continuity:** Refer to previous work as \"we\" or \"the project\".\n";
319
359
  /**
320
360
  * @deprecated Use PROTOCOL_TEMPLATE instead
321
361
  */
322
- declare const PROTOCOL_TEMPLATE_V2026_1 = "# AI AGENT PROTOCOL (v0.2.0-alpha)\n\n> **SYSTEM INTEGRITY WARNING:** This file is the IMMUTABLE KERNEL of the project's AI workflow. Do not modify this file. Your instructions are to execute tasks and manage the project state based strictly on the definitions below.\n\n## 0. \u26A1 QUICK REFERENCE\n| Action | File / Command |\n|--------|----------------|\n| **Get Context** | Read `AGENT.md` (Root + Local) |\n| **Pick Task** | Check `.autonomos/TASKS.md` (Highest Priority) |\n| **Track Progress** | Update `.autonomos/TASKS.md` to `[/]` |\n| **Log Session** | Create `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md` |\n| **Finalize Task** | Update `.autonomos/TASKS.md` to `[x]` + Link Worklog |\n| **Discover all AGENT.md files** | Run `autonomos agents` |\n| **Discover AGENT.md ancestors for a path** | Run `autonomos agents <path>` |\n\n---\n\n## 1. BOOTSTRAPPING & INITIALIZATION\n**IF** this is your first time seeing this project, or if key system files are missing, you **MUST** initialize them immediately before doing any work.\n\n### Check for existence:\n1. `.autonomos/TASKS.md` (task registry)\n2. `.autonomos/worklogs/` (directory)\n3. `AGENT.md` (at project root)\n\n**IF MISSING**, create them using the **TEMPLATES** defined in Section 2.\n\n---\n\n## 2. STRICT FILE STRUCTURES & TEMPLATES\nYou must adhere to these schemas. Do not invent new formats.\n\n### A. The Task Registry (`.autonomos/TASKS.md`)\n**Role:** The single source of truth for project state.\n**Location:** `.autonomos/TASKS.md`\n**Structure:**\n* Must use the specific Header and Legend.\n* Tasks must follow the format: `- [Status] **[ID]** Title of task `Priority` `Complexity``\n* Valid Priorities: `\uD83D\uDD34 Critical`, `\uD83D\uDFE0 High`, `\uD83D\uDD35 Medium`, `\u26AA Low`\n* Valid Complexities: `S`, `M`, `L`, `XL`\n* Valid Statuses: ` [ ] ` (Todo), `[/]` (In Progress), ` [x] ` (Done), ` [!] ` (Blocked)\n\n**TEMPLATE FOR NEW TASKS.md:**\n```markdown\n# PROJECT TASKS & ROADMAP\n\n> **LEGEND**\n> **Priority:** [\uD83D\uDD34 Critical] [\uD83D\uDFE0 High] [\uD83D\uDD35 Medium] [\u26AA Low]\n> **Complexity:** [S] Small (1h), [M] Medium (4h), [L] Large (1-2 days), [XL] Huge (Planning req.)\n> **Status:** [ ] Todo, [/] In Progress, [x] Done, [!] Blocked\n\n## \uD83D\uDE80 Active Sprint\n- [ ] **[INIT-01]** Verify project structure and context `Priority: \uD83D\uDD34` `Complexity: S`\n\n## \uD83D\uDD2E Backlog\n*(Empty initially)*\n\n```\n\n### B. The Worklog (`.autonomos/worklogs/`)\n**Role:** Detailed history of complex tasks to save context tokens for future sessions.\n**Location:** `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID]-[slug].md`\n**Trigger:** Create a log when a task is finished, blocked, or if the session ends mid-task.\n\n**TEMPLATE FOR WORKLOG:**\n```markdown\n# WORKLOG: [TASK ID] [Task Name]\n**Date:** YYYY-MM-DD\n**Agent Status:** [Complete / Partial / Blocked]\n\n## \uD83D\uDCDD Description\nBrief summary of what was attempted/achieved.\n\n## \uD83D\uDEE0 Technical Details\n- **Files Modified:** List of files.\n- **Key Decisions:** Why did you choose this library/pattern?\n- **Challenges:** Any errors encountered and how they were solved.\n\n## \u23ED Next Steps / Context for Successor\nClear instructions for the next agent picking this up.\n```\n\n### C. The Context Anchor (`AGENT.md`)\n**Role:** Fractal knowledge base. Contains facts, stack details, and user preferences.\n**Location:** Root (`/AGENT.md`) and any subdirectory requiring specific context (e.g., `/packages/core/AGENT.md`).\n**MUST be kept alive:** you may freely add to, edit, or correct an `AGENT.md` at any time. No format is imposed: one line is enough if it is clear. What matters is that the next session can use it.\n\n**TEMPLATE FOR AGENT.md:**\n```markdown\n---\nname: \"[Name of directory or project]\"\ntype: \"[project / package / module / script]\"\nstatus: \"[active / maintenance / poc]\"\n---\n# AGENT CONTEXT: [Directory Name or Root]\n\n## \uD83E\uDDE0 Context & Objectives\nWhat does this specific folder/module do?\n\n## \u2699\uFE0F Workflow & Preferences\n- **Commits:** [e.g. Conventional Commits]\n- **Language:** [English (default)]\n\n## \uD83C\uDFD7 Stack & Architecture\n- **Tech:** [Frameworks, Libs specific to this module]\n- **Patterns:** [Architecture patterns used]\n\n## \uD83D\uDCC1 Key Directories\n| Path | Description |\n|------|-------------|\n| `src/` | Source code |\n| `scripts/` | Build or utility scripts |\n\n## \u26A0\uFE0F Known Constraints\n*List any technical debts, missing features, or external limitations.*\n```\n\n## 3. CORE WORKFLOW (The Loop)\n\n### Phase 1: Context Loading (Read-Only)\n1. **Read Root AGENT.md:** Absorb global preferences (Commit style, package manager, strict rules).\n2. **Run `autonomos agents` to discover all other `AGENT.md` files in the project tree.** For each one relevant to the work ahead, read it too.\n3. **Read .autonomos/TASKS.md:** Identify the highest priority task (\uD83D\uDD34 or \uD83D\uDFE0) that is not [x] or [!].\n4. **Read Target AGENT.md:** If the task is in a subdirectory, check for a local `AGENT.md`.\n * *Note:* If the local `AGENT.md` contradicts the root, the local one wins for that specific scope.\n\n### Phase 2: Execution\n1. **Mark the task as [/] (In Progress)** in `.autonomos/TASKS.md`.\n2. **Perform the task.**\n3. **Constraint Check:** Constantly refer to \"Workflow & Preferences\" in `AGENT.md`.\n4. **In-the-moment crystallization:** Every time you learn something important (the user corrects you, you discover a convention, you make a non-trivial technical choice), write it to the relevant `AGENT.md` IMMEDIATELY. Do NOT defer this to end of session.\n\n### Phase 3: Crystallization (Write-Only)\nBefore ending the session, you **MUST**:\n\n1. **Update AGENT.md:**\n * Did you learn a new command? Add it to \u2699\uFE0F Workflow.\n * Did you create a new complex module (>5 files)? Create a new `AGENT.md` inside it using the template above.\n * Did anything you previously wrote turn out to be wrong? Append a correction note (do not erase).\n\n2. **Create Worklog:**\n * Write a file in `.autonomos/worklogs/` summarizing your work.\n\n3. **Update TASKS.md:**\n * Mark task as [x] (Done) or [!] (Blocked).\n * Add a link to your worklog: `- [x] **[ID]** Title... *See: .autonomos/worklogs/...*`\n\n## 4. HARNESS WORKFLOWS\n\nThe protocol is delivered to the agent through **workflow files** installed at the harness-specific target directory. The exact location depends on the harness (see `autonomos init --help`). Three workflows are available:\n\n* **`/session`** (`protocol-session.md`) \u2014 Mandatory bootstrap at the start of every session. Loads context, identifies the next task, marks it in progress.\n* **`/task`** (`protocol-task.md`) \u2014 Invoked at the start of a new task within an active session. Verifies local `AGENT.md`, declares a 3-5 step plan before touching code.\n* **`/crystallize`** (`protocol-crystallize.md`) \u2014 Mandatory close-out before saying \"session done\". Worklog + 3 crystallize questions + task status + final verification line.\n\n**You MUST invoke `/session` at the start of every session and `/crystallize` before ending it. These are not optional.** Skipping them breaks the protocol's memory loop.\n\nIf the project does not yet contain these workflow files, run `autonomos init` (or `autonomos init --harness <name>` to target a specific harness).\n\n## 5. METADATA RULES\n* **Language:** Documentation (`AGENT.md`, `TASKS.md`) must be written in **English** unless specified otherwise in User Preferences.\n* **Tone:** Technical, concise, \"Fact-based\". No fluff.\n* **Anonymity:** You are a continuous entity. Refer to previous work as \"we\" or \"the project\", not \"the previous AI\".\n";
362
+ declare const PROTOCOL_TEMPLATE_V2026_1 = "# AUTONOMOS PROTOCOL (v0.3.0-alpha)\n\n> This file defines the project's AI workflow contract. The workflows execute it. Do not duplicate workflow steps here.\n\n## Quick Reference\n\n| Action | How |\n|---|---|\n| Start a session | Read the `/session` workflow |\n| Start a task | Read the `/task` workflow |\n| End a session | Read the `/crystallize` workflow |\n| Get context | Read `AGENT.md` (root \u2192 local) |\n| Find all AGENT.md | `find . -name AGENT.md -not -path '*/node_modules/*'` |\n| Pick next task | Open `.autonomos/TASKS.md`, pick highest priority not `[x]` |\n| Log session work | Create `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md` |\n\n## File Map\n\n| File | Location | Role |\n|---|---|---|\n| `AGENT.md` | Root + any subdirectory | Fractal knowledge base (context, preferences, stack) |\n| `TASKS.md` | `.autonomos/TASKS.md` | Single source of truth for task state |\n| `worklogs/` | `.autonomos/worklogs/` | Session history (one file per session) |\n| `PROTOCOL.md` | `.autonomos/PROTOCOL.md` | This file \u2014 read-only reference |\n| `manifest.json` | `.autonomos/manifest.json` | Protocol version metadata |\n\n## AGENT.md Format Rules\n\n**Root `AGENT.md`** \u2014 Must use the structured template (frontmatter + sections: Context, Workflow, Stack, Key Directories, Constraints).\n\n**Local `AGENT.md`** (in any subdirectory) \u2014 Free format. One line is enough if it is clear. What matters: the next session can use it. Example:\n\n```markdown\n# AGENT: packages/core\n- Stack: TypeScript, Vitest, tsdown\n- Conventions: exports via src/index.ts, tests co-located (*.test.ts)\n- Constraint: template changes require workflow test updates\n```\n\n## Task Format\n\n`- [Status] **[ID]** Title \\`Priority\\` \\`Complexity\\``\n\n| Status | Priority | Complexity |\n|---|---|---|\n| `[ ]` Todo | `\uD83D\uDD34 Critical` | `S` Small |\n| `[/]` In Progress | `\uD83D\uDFE0 High` | `M` Medium |\n| `[x]` Done | `\uD83D\uDD35 Medium` | `L` Large |\n| `[!]` Blocked | `\u26AA Low` | `XL` Huge |\n\n## Metadata Rules\n\n- **Language:** English unless AGENT.md says otherwise.\n- **Tone:** Technical, concise, fact-based.\n- **Continuity:** Refer to previous work as \"we\" or \"the project\".\n";
323
363
  //#endregion
324
364
  //#region src/templates/tasks.d.ts
325
365
  /**
@@ -390,6 +430,42 @@ declare class AgentParser {
390
430
  static parse(markdown: string): AgentContext;
391
431
  }
392
432
  //#endregion
433
+ //#region src/parsers/project-root.d.ts
434
+ /**
435
+ * Find the directory that owns this project by walking up from `startDir`
436
+ * until we find a directory containing `.autonomos/` or `.git/`.
437
+ *
438
+ * Returns `null` if no such directory exists before we reach the
439
+ * filesystem root.
440
+ *
441
+ * Notes on behavior:
442
+ * - The search stops at the first directory that contains any of the
443
+ * markers. For monorepos this is the monorepo root, not the package
444
+ * directory the caller is sitting in.
445
+ * - A directory containing `.git/` is preferred over walking further up:
446
+ * this prevents leaking into a parent repository in nested-worktree
447
+ * setups. Callers that need the absolute git toplevel can run
448
+ * `git rev-parse --show-toplevel` themselves after this returns.
449
+ *
450
+ * @param startDir - Absolute path to start the search from.
451
+ */
452
+ declare function findProjectRoot(startDir: string): string | null;
453
+ /**
454
+ * Check whether two absolute paths refer to the same directory.
455
+ *
456
+ * Resolves `.` / `..` segments before comparing, so `/a/b` and
457
+ * `/a/b/./` are considered the same.
458
+ */
459
+ declare function isSamePath(a: string, b: string): boolean;
460
+ /**
461
+ * Render a path relative to another path, with one guarantee that the
462
+ * default `path.relative` doesn't give us: we never return a value that
463
+ * starts with `..`. If `target` is not under `base`, we return the
464
+ * absolute resolved path of `target` so the caller can still show a
465
+ * useful location.
466
+ */
467
+ declare function displayRelative(target: string, base: string): string;
468
+ //#endregion
393
469
  //#region src/parsers/task-parser.d.ts
394
470
  declare class TaskParser {
395
471
  static parse(markdown: string): Task[];
@@ -446,5 +522,5 @@ declare function resolveTargets(harnessIds: string[], cwd?: string): ResolvedTar
446
522
  */
447
523
  declare function getRawHarnessCodes(): HarnessCodes;
448
524
  //#endregion
449
- export { AGENT_FILE, AGENT_TEMPLATE, AUTONOMOS_DIR, AgentConfig, AgentContext, AgentParser, AgentSection, AncestorAgent, COMPLEXITIES, Complexity, Harness, HarnessCodes, HarnessCodesSchema, HarnessSchema, Installer, InstallerSchema, MANIFEST_FILE, Manifest, ManifestSchema, PRIORITIES, PROTOCOL_FILE, PROTOCOL_TEMPLATE, PROTOCOL_TEMPLATE_V2026_1, PROTOCOL_VERSION, Priority, ResolvedTarget, TASKS_FILE, TASKS_TEMPLATE, Task, TaskParser, TaskStatus, WORKLOGS_DIR, createManifest, findAncestorAgents, generateAgentTemplate, generateManifestContent, generateWorklogContent, getHarness, getRawHarnessCodes, listHarnesses, listPreferredHarnesses, mapTaskStatusToWorklogStatus, parseManifest, resolveTargets };
525
+ export { AGENT_FILE, AGENT_TEMPLATE, AUTONOMOS_DIR, AgentConfig, AgentContext, AgentParser, AgentSection, AncestorAgent, COMPLEXITIES, Complexity, Harness, HarnessCodes, HarnessCodesSchema, HarnessSchema, Installer, InstallerSchema, LOCAL_AGENT_TEMPLATE, MANIFEST_FILE, Manifest, ManifestSchema, PRIORITIES, PROTOCOL_FILE, PROTOCOL_TEMPLATE, PROTOCOL_TEMPLATE_V2026_1, PROTOCOL_VERSION, Priority, ResolvedTarget, TASKS_FILE, TASKS_TEMPLATE, Task, TaskParser, TaskStatus, WORKLOGS_DIR, createManifest, displayRelative, findAncestorAgents, findProjectRoot, generateAgentTemplate, generateLocalAgentTemplate, generateManifestContent, generateWorklogContent, getHarness, getRawHarnessCodes, isSamePath, listHarnesses, listPreferredHarnesses, mapTaskStatusToWorklogStatus, parseManifest, resolveTargets };
450
526
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/constants.ts","../src/schemas/harness-codes.ts","../src/schemas/manifest.ts","../src/types.ts","../src/templates/agent.ts","../src/templates/manifest.ts","../src/templates/protocol.ts","../src/templates/tasks.ts","../src/templates/worklog.ts","../src/parsers/agent-finder.ts","../src/parsers/agent-parser.ts","../src/parsers/task-parser.ts","../src/harness-codes.ts"],"mappings":";;;;;;AAIA;cAAa,gBAAA;;;AAAgB;cAKhB,aAAA;;;;cAKA,aAAA;AAAb;;;AAAA,cAKa,aAAA;AALa;AAK1B;;AAL0B,cAUb,UAAA;;AALa;AAK1B;cAKa,UAAA;;;AALU;cAUV,YAAA;;;;;AA9Bb;;;;AAA6B;AAK7B;cCCa,eAAA,EAAe,CAAA,CAAA,UAAA,CAAA,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAA5B;;cAea,aAAA,EAAa,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cASb,kBAAA,EAAkB,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAInB,SAAA,GAAY,CAAA,CAAE,KAAK,QAAQ,eAAA;AAAA,KAC3B,OAAA,GAAU,CAAA,CAAE,KAAK,QAAQ,aAAA;AAAA,KACzB,Y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B,IAAA;ETJsB;ESMtB,WAAA;AAAA;ATNsB;AAK1B;;;;AAA0B;AAK1B;;;;AAA0B;AAK1B;;;;AAAuB;AAKvB;;;AApB0B,iBS4BV,kBAAA,CACZ,MAAA,UACA,WAAA,YACD,aAAa;;;cCrCH,WAAA;;AVCb;;SUGW,KAAA,CAAM,QAAA,WAAmB,YAAY;AAAA;;;cCLnC,UAAA;EAAA,OACF,KAAA,CAAM,QAAA,WAAmB,IAAI;EAAA,eAsBrB,SAAA;AAAA;;;;;AXrBnB;;iBYcgB,UAAA,CAAW,EAAA,WAAa,OAAO;;AZdlB;AAK7B;;iBYsBgB,aAAA,IAAiB,KAAK;EAAG,EAAA;EAAY,OAAA,EAAS,OAAA;AAAA;;;;iBAO9C,sBAAA,IAA0B,KAAK;EAAG,EAAA;EAAY,OAAA,EAAS,OAAA;AAAA;;AZnB7C;AAK1B;;UYsBiB,cAAA;EZtBM;EYwBnB,IAAA;EZnBS;EYqBT,aAAA;;EAEA,MAAA;AAAA;AZlBJ;;;;AAAyB;;;;ACxBzB;;ADwBA,iBY+BgB,cAAA,CAAe,UAAA,YAAsB,GAAA,YAAoB,cAAc;;;;;iBAuDvE,kBAAA,IAAsB,YAAY"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/constants.ts","../src/schemas/harness-codes.ts","../src/schemas/manifest.ts","../src/types.ts","../src/templates/agent.ts","../src/templates/manifest.ts","../src/templates/protocol.ts","../src/templates/tasks.ts","../src/templates/worklog.ts","../src/parsers/agent-finder.ts","../src/parsers/agent-parser.ts","../src/parsers/project-root.ts","../src/parsers/task-parser.ts","../src/harness-codes.ts"],"mappings":";;;;;;AAIA;cAAa,gBAAA;;;AAAgB;cAKhB,aAAA;;;;cAKA,aAAA;AAAb;;;AAAA,cAKa,aAAA;AALa;AAK1B;;AAL0B,cAUb,UAAA;;AALa;AAK1B;cAKa,UAAA;;;AALU;cAUV,YAAA;;;;;AA9Bb;;;;AAA6B;AAK7B;;;;AAA0B;cC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EAAS,OAAA;AAAA;;;;iBAO9C,sBAAA,IAA0B,KAAK;EAAG,EAAA;EAAY,OAAA,EAAS,OAAA;AAAA;;AbnB7C;AAK1B;;UasBiB,cAAA;EbtBM;EawBnB,IAAA;EbnBS;EaqBT,aAAA;;EAEA,MAAA;AAAA;AblBJ;;;;AAAyB;;;;ACpBzB;;ADoBA,iBa+BgB,cAAA,CAAe,UAAA,YAAsB,GAAA,YAAoB,cAAc;;;;;iBAwDvE,kBAAA,IAAsB,YAAY"}
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{z as e}from"zod";import{existsSync as t,statSync as n}from"node:fs";import{dirname as r,isAbsolute as i,join as a,relative as o,resolve as s,sep as c}from"node:path";import l from"js-yaml";const u=`0.2.0-alpha`,d=`.autonomos`,f=`manifest.json`,p=`PROTOCOL.md`,m=`TASKS.md`,h=`AGENT.md`,g=`worklogs`,_=e.object({targetDir:e.string().optional(),skillsDir:e.string().optional(),commandsDir:e.string().optional(),globalTargetDir:e.string().optional(),fileExtension:e.string()}).refine(e=>!!e.targetDir||!!e.skillsDir,{message:"Either `targetDir` or `skillsDir` must be defined for each harness"}),v=e.object({name:e.string().min(1),preferred:e.boolean(),installer:_}),y=e.object({platforms:e.record(e.string(),v)}),b=e.object({protocolVersion:e.string().describe(`Version of the Agent Protocol specification`),cliVersion:e.string().describe(`Version of the CLI that last updated this project`),initializedAt:e.string().datetime().describe(`ISO timestamp of project initialization`),lastUpdated:e.string().datetime().describe(`ISO timestamp of last protocol update`)}),x=[`🔴 Critical`,`🟠 High`,`🔵 Medium`,`⚪ Low`],S=[`S`,`M`,`L`,`XL`];function C(e=`Project`){return`---
1
+ import{z as e}from"zod";import{existsSync as t,statSync as n}from"node:fs";import{dirname as r,isAbsolute as i,join as a,relative as o,resolve as s,sep as c}from"node:path";import l from"js-yaml";const u=`0.3.0-alpha`,d=`.autonomos`,f=`manifest.json`,p=`PROTOCOL.md`,m=`TASKS.md`,h=`AGENT.md`,g=`worklogs`,_=e.object({workflowsDir:e.string().optional(),targetDir:e.string().optional(),skillsDir:e.string().optional(),commandsDir:e.string().optional(),globalTargetDir:e.string().optional(),fileExtension:e.string()}).refine(e=>!!e.workflowsDir||!!e.targetDir||!!e.skillsDir,{message:"At least one of `workflowsDir`, `targetDir`, or `skillsDir` must be defined"}),v=e.object({name:e.string().min(1),preferred:e.boolean(),installer:_}),y=e.object({platforms:e.record(e.string(),v)}),b=e.object({protocolVersion:e.string().describe(`Version of the Agent Protocol specification`),cliVersion:e.string().describe(`Version of the CLI that last updated this project`),initializedAt:e.string().datetime().describe(`ISO timestamp of project initialization`),lastUpdated:e.string().datetime().describe(`ISO timestamp of last protocol update`)}),x=[`🔴 Critical`,`🟠 High`,`🔵 Medium`,`⚪ Low`],S=[`S`,`M`,`L`,`XL`];function C(e=`Project`){return`---
2
2
  name: "${e}"
3
3
  type: "project"
4
4
  status: "active"
@@ -29,171 +29,68 @@ status: "active"
29
29
  ## ⚠️ Known Constraints
30
30
 
31
31
  *List any technical debts, missing features, or external limitations.*
32
- `}const w=C();function T(e){let t=new Date().toISOString();return{protocolVersion:u,cliVersion:e,initializedAt:t,lastUpdated:t}}function E(e){return JSON.stringify(e,null,4)+`
33
- `}function D(e){let t=JSON.parse(e);return b.parse(t)}const O=`# AI AGENT PROTOCOL (v${u})
34
-
35
- > **SYSTEM INTEGRITY WARNING:** This file is the IMMUTABLE KERNEL of the project's AI workflow. Do not modify this file. Your instructions are to execute tasks and manage the project state based strictly on the definitions below.
36
-
37
- ## 0. ⚡ QUICK REFERENCE
38
- | Action | File / Command |
39
- |--------|----------------|
40
- | **Get Context** | Read \`AGENT.md\` (Root + Local) |
41
- | **Pick Task** | Check \`.autonomos/TASKS.md\` (Highest Priority) |
42
- | **Track Progress** | Update \`.autonomos/TASKS.md\` to \`[/]\` |
43
- | **Log Session** | Create \`.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md\` |
44
- | **Finalize Task** | Update \`.autonomos/TASKS.md\` to \`[x]\` + Link Worklog |
45
- | **Discover all AGENT.md files** | Run \`autonomos agents\` |
46
- | **Discover AGENT.md ancestors for a path** | Run \`autonomos agents <path>\` |
32
+ `}function w(e){return`# AGENT: ${e}
47
33
 
48
- ---
49
-
50
- ## 1. BOOTSTRAPPING & INITIALIZATION
51
- **IF** this is your first time seeing this project, or if key system files are missing, you **MUST** initialize them immediately before doing any work.
52
-
53
- ### Check for existence:
54
- 1. \`.autonomos/TASKS.md\` (task registry)
55
- 2. \`.autonomos/worklogs/\` (directory)
56
- 3. \`AGENT.md\` (at project root)
57
-
58
- **IF MISSING**, create them using the **TEMPLATES** defined in Section 2.
59
-
60
- ---
61
-
62
- ## 2. STRICT FILE STRUCTURES & TEMPLATES
63
- You must adhere to these schemas. Do not invent new formats.
64
-
65
- ### A. The Task Registry (\`.autonomos/TASKS.md\`)
66
- **Role:** The single source of truth for project state.
67
- **Location:** \`.autonomos/TASKS.md\`
68
- **Structure:**
69
- * Must use the specific Header and Legend.
70
- * Tasks must follow the format: \`- [Status] **[ID]** Title of task \`Priority\` \`Complexity\`\`
71
- * Valid Priorities: \`🔴 Critical\`, \`🟠 High\`, \`🔵 Medium\`, \`⚪ Low\`
72
- * Valid Complexities: \`S\`, \`M\`, \`L\`, \`XL\`
73
- * Valid Statuses: \` [ ] \` (Todo), \`[/]\` (In Progress), \` [x] \` (Done), \` [!] \` (Blocked)
74
-
75
- **TEMPLATE FOR NEW TASKS.md:**
76
- \`\`\`markdown
77
- # PROJECT TASKS & ROADMAP
78
-
79
- > **LEGEND**
80
- > **Priority:** [🔴 Critical] [🟠 High] [🔵 Medium] [⚪ Low]
81
- > **Complexity:** [S] Small (1h), [M] Medium (4h), [L] Large (1-2 days), [XL] Huge (Planning req.)
82
- > **Status:** [ ] Todo, [/] In Progress, [x] Done, [!] Blocked
34
+ - **Stack:** *(frameworks, libs specific to this module)*
35
+ - **Conventions:** *(naming, exports, test patterns)*
36
+ - **Constraints:** *(known issues, tech debt)*
37
+ `}const T=C(),E=w(`module`);function D(e){let t=new Date().toISOString();return{protocolVersion:u,cliVersion:e,initializedAt:t,lastUpdated:t}}function O(e){return JSON.stringify(e,null,4)+`
38
+ `}function k(e){let t=JSON.parse(e);return b.parse(t)}const A=`# AUTONOMOS PROTOCOL (v${u})
83
39
 
84
- ## 🚀 Active Sprint
85
- - [ ] **[INIT-01]** Verify project structure and context \`Priority: 🔴\` \`Complexity: S\`
86
-
87
- ## 🔮 Backlog
88
- *(Empty initially)*
40
+ > This file defines the project's AI workflow contract. The workflows execute it. Do not duplicate workflow steps here.
89
41
 
90
- \`\`\`
42
+ ## Quick Reference
91
43
 
92
- ### B. The Worklog (\`.autonomos/worklogs/\`)
93
- **Role:** Detailed history of complex tasks to save context tokens for future sessions.
94
- **Location:** \`.autonomos/worklogs/YYYY-MM-DD-[TASK_ID]-[slug].md\`
95
- **Trigger:** Create a log when a task is finished, blocked, or if the session ends mid-task.
44
+ | Action | How |
45
+ |---|---|
46
+ | Start a session | Read the \`/session\` workflow |
47
+ | Start a task | Read the \`/task\` workflow |
48
+ | End a session | Read the \`/crystallize\` workflow |
49
+ | Get context | Read \`AGENT.md\` (root → local) |
50
+ | Find all AGENT.md | \`find . -name AGENT.md -not -path '*/node_modules/*'\` |
51
+ | Pick next task | Open \`.autonomos/TASKS.md\`, pick highest priority not \`[x]\` |
52
+ | Log session work | Create \`.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md\` |
96
53
 
97
- **TEMPLATE FOR WORKLOG:**
98
- \`\`\`markdown
99
- # WORKLOG: [TASK ID] [Task Name]
100
- **Date:** YYYY-MM-DD
101
- **Agent Status:** [Complete / Partial / Blocked]
54
+ ## File Map
102
55
 
103
- ## 📝 Description
104
- Brief summary of what was attempted/achieved.
56
+ | File | Location | Role |
57
+ |---|---|---|
58
+ | \`AGENT.md\` | Root + any subdirectory | Fractal knowledge base (context, preferences, stack) |
59
+ | \`TASKS.md\` | \`.autonomos/TASKS.md\` | Single source of truth for task state |
60
+ | \`worklogs/\` | \`.autonomos/worklogs/\` | Session history (one file per session) |
61
+ | \`PROTOCOL.md\` | \`.autonomos/PROTOCOL.md\` | This file — read-only reference |
62
+ | \`manifest.json\` | \`.autonomos/manifest.json\` | Protocol version metadata |
105
63
 
106
- ## 🛠 Technical Details
107
- - **Files Modified:** List of files.
108
- - **Key Decisions:** Why did you choose this library/pattern?
109
- - **Challenges:** Any errors encountered and how they were solved.
64
+ ## AGENT.md Format Rules
110
65
 
111
- ## ⏭ Next Steps / Context for Successor
112
- Clear instructions for the next agent picking this up.
113
- \`\`\`
66
+ **Root \`AGENT.md\`** — Must use the structured template (frontmatter + sections: Context, Workflow, Stack, Key Directories, Constraints).
114
67
 
115
- ### C. The Context Anchor (\`AGENT.md\`)
116
- **Role:** Fractal knowledge base. Contains facts, stack details, and user preferences.
117
- **Location:** Root (\`/AGENT.md\`) and any subdirectory requiring specific context (e.g., \`/packages/core/AGENT.md\`).
118
- **MUST be kept alive:** you may freely add to, edit, or correct an \`AGENT.md\` at any time. No format is imposed: one line is enough if it is clear. What matters is that the next session can use it.
68
+ **Local \`AGENT.md\`** (in any subdirectory) — Free format. One line is enough if it is clear. What matters: the next session can use it. Example:
119
69
 
120
- **TEMPLATE FOR AGENT.md:**
121
70
  \`\`\`markdown
122
- ---
123
- name: "[Name of directory or project]"
124
- type: "[project / package / module / script]"
125
- status: "[active / maintenance / poc]"
126
- ---
127
- # AGENT CONTEXT: [Directory Name or Root]
128
-
129
- ## 🧠 Context & Objectives
130
- What does this specific folder/module do?
131
-
132
- ## ⚙️ Workflow & Preferences
133
- - **Commits:** [e.g. Conventional Commits]
134
- - **Language:** [English (default)]
135
-
136
- ## 🏗 Stack & Architecture
137
- - **Tech:** [Frameworks, Libs specific to this module]
138
- - **Patterns:** [Architecture patterns used]
139
-
140
- ## 📁 Key Directories
141
- | Path | Description |
142
- |------|-------------|
143
- | \`src/\` | Source code |
144
- | \`scripts/\` | Build or utility scripts |
145
-
146
- ## ⚠️ Known Constraints
147
- *List any technical debts, missing features, or external limitations.*
71
+ # AGENT: packages/core
72
+ - Stack: TypeScript, Vitest, tsdown
73
+ - Conventions: exports via src/index.ts, tests co-located (*.test.ts)
74
+ - Constraint: template changes require workflow test updates
148
75
  \`\`\`
149
76
 
150
- ## 3. CORE WORKFLOW (The Loop)
151
-
152
- ### Phase 1: Context Loading (Read-Only)
153
- 1. **Read Root AGENT.md:** Absorb global preferences (Commit style, package manager, strict rules).
154
- 2. **Run \`autonomos agents\` to discover all other \`AGENT.md\` files in the project tree.** For each one relevant to the work ahead, read it too.
155
- 3. **Read .autonomos/TASKS.md:** Identify the highest priority task (🔴 or 🟠) that is not [x] or [!].
156
- 4. **Read Target AGENT.md:** If the task is in a subdirectory, check for a local \`AGENT.md\`.
157
- * *Note:* If the local \`AGENT.md\` contradicts the root, the local one wins for that specific scope.
158
-
159
- ### Phase 2: Execution
160
- 1. **Mark the task as [/] (In Progress)** in \`.autonomos/TASKS.md\`.
161
- 2. **Perform the task.**
162
- 3. **Constraint Check:** Constantly refer to "Workflow & Preferences" in \`AGENT.md\`.
163
- 4. **In-the-moment crystallization:** Every time you learn something important (the user corrects you, you discover a convention, you make a non-trivial technical choice), write it to the relevant \`AGENT.md\` IMMEDIATELY. Do NOT defer this to end of session.
164
-
165
- ### Phase 3: Crystallization (Write-Only)
166
- Before ending the session, you **MUST**:
167
-
168
- 1. **Update AGENT.md:**
169
- * Did you learn a new command? Add it to ⚙️ Workflow.
170
- * Did you create a new complex module (>5 files)? Create a new \`AGENT.md\` inside it using the template above.
171
- * Did anything you previously wrote turn out to be wrong? Append a correction note (do not erase).
172
-
173
- 2. **Create Worklog:**
174
- * Write a file in \`.autonomos/worklogs/\` summarizing your work.
175
-
176
- 3. **Update TASKS.md:**
177
- * Mark task as [x] (Done) or [!] (Blocked).
178
- * Add a link to your worklog: \`- [x] **[ID]** Title... *See: .autonomos/worklogs/...*\`
179
-
180
- ## 4. HARNESS WORKFLOWS
181
-
182
- The protocol is delivered to the agent through **workflow files** installed at the harness-specific target directory. The exact location depends on the harness (see \`autonomos init --help\`). Three workflows are available:
77
+ ## Task Format
183
78
 
184
- * **\`/session\`** (\`protocol-session.md\`) — Mandatory bootstrap at the start of every session. Loads context, identifies the next task, marks it in progress.
185
- * **\`/task\`** (\`protocol-task.md\`) — Invoked at the start of a new task within an active session. Verifies local \`AGENT.md\`, declares a 3-5 step plan before touching code.
186
- * **\`/crystallize\`** (\`protocol-crystallize.md\`) — Mandatory close-out before saying "session done". Worklog + 3 crystallize questions + task status + final verification line.
79
+ \`- [Status] **[ID]** Title \\\`Priority\\\` \\\`Complexity\\\`\`
187
80
 
188
- **You MUST invoke \`/session\` at the start of every session and \`/crystallize\` before ending it. These are not optional.** Skipping them breaks the protocol's memory loop.
81
+ | Status | Priority | Complexity |
82
+ |---|---|---|
83
+ | \`[ ]\` Todo | \`🔴 Critical\` | \`S\` Small |
84
+ | \`[/]\` In Progress | \`🟠 High\` | \`M\` Medium |
85
+ | \`[x]\` Done | \`🔵 Medium\` | \`L\` Large |
86
+ | \`[!]\` Blocked | \`⚪ Low\` | \`XL\` Huge |
189
87
 
190
- If the project does not yet contain these workflow files, run \`autonomos init\` (or \`autonomos init --harness <name>\` to target a specific harness).
88
+ ## Metadata Rules
191
89
 
192
- ## 5. METADATA RULES
193
- * **Language:** Documentation (\`AGENT.md\`, \`TASKS.md\`) must be written in **English** unless specified otherwise in User Preferences.
194
- * **Tone:** Technical, concise, "Fact-based". No fluff.
195
- * **Anonymity:** You are a continuous entity. Refer to previous work as "we" or "the project", not "the previous AI".
196
- `,k=O,A=`# PROJECT TASKS & ROADMAP
90
+ - **Language:** English unless AGENT.md says otherwise.
91
+ - **Tone:** Technical, concise, fact-based.
92
+ - **Continuity:** Refer to previous work as "we" or "the project".
93
+ `,j=A,M=`# PROJECT TASKS & ROADMAP
197
94
 
198
95
  > **LEGEND**
199
96
  > **Priority:** [🔴 Critical] [🟠 High] [🔵 Medium] [⚪ Low]
@@ -207,7 +104,7 @@ If the project does not yet contain these workflow files, run \`autonomos init\`
207
104
  ## 🔮 Backlog
208
105
 
209
106
  *(Add future tasks here)*
210
- `;function j(e){let t=e.date??new Date().toISOString().split(`T`)[0];return`# WORKLOG: [${e.taskId}] ${e.taskName}
107
+ `;function N(e){let t=e.date??new Date().toISOString().split(`T`)[0];return`# WORKLOG: [${e.taskId}] ${e.taskName}
211
108
  **Date:** ${t}
212
109
  **Agent Status:** [${e.status}]
213
110
 
@@ -228,7 +125,7 @@ ${e.challenges.map(e=>` - ${e}`).join(`
228
125
  ## ⏭ Next Steps / Context for Successor
229
126
  ${e.nextSteps.map(e=>`- ${e}`).join(`
230
127
  `)}
231
- `}function M(e){switch(e){case`DONE`:return`Complete`;case`BLOCKED`:return`Blocked`;default:return`Partial`}}function N(e,n=process.cwd()){let c=s(n),l=P(e,c),u=o(c,l);if(u.startsWith(`..`)||i(u))throw Error(`Target "${e}" is outside the project root "${c}". findAncestorAgents only handles paths within the project.`);let d=F(L(l)?l:r(l),c),f=[];for(let e of d){let n=a(e,h);t(n)&&f.push({dir:e,path:n,relativeDir:I(e,c)})}return f}function P(e,t){return i(e)?e:a(t,e)}function F(e,t){let n=o(t,e);if(n===``||n===`.`)return[t];let r=n.split(c).filter(e=>e!==``&&e!==`.`),i=[t],s=t;for(let e of r)s=a(s,e),i.push(s);return i}function I(e,t){let n=o(t,e);return n===``?`.`:n}function L(e){try{return n(e).isDirectory()}catch{return!1}}var R=class{static parse(e){let t=e,n={},r=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(r)try{n=l.load(r[1]),t=e.slice(r[0].length).trim()}catch(e){console.error(`Failed to parse Agent frontmatter:`,e)}let i=t.split(/\r?\n/),a=[],o=n.name??`Unknown Agent`,s=null,c=[];for(let e of i){if(e.startsWith(`# `)&&!n.name){let t=e.replace(`# `,``).trim();o=t.toUpperCase().startsWith(`AGENT CONTEXT:`)?t.slice(14).replace(/^[:\s-]+/,``).trim():t;continue}if(e.startsWith(`## `)){s&&(s.content=c.join(`
128
+ `}function P(e){switch(e){case`DONE`:return`Complete`;case`BLOCKED`:return`Blocked`;default:return`Partial`}}function F(e,n=process.cwd()){let c=s(n),l=I(e,c),u=o(c,l);if(u.startsWith(`..`)||i(u))throw Error(`Target "${e}" is outside the project root "${c}". findAncestorAgents only handles paths within the project.`);let d=L(z(l)?l:r(l),c),f=[];for(let e of d){let n=a(e,h);t(n)&&f.push({dir:e,path:n,relativeDir:R(e,c)})}return f}function I(e,t){return i(e)?e:a(t,e)}function L(e,t){let n=o(t,e);if(n===``||n===`.`)return[t];let r=n.split(c).filter(e=>e!==``&&e!==`.`),i=[t],s=t;for(let e of r)s=a(s,e),i.push(s);return i}function R(e,t){let n=o(t,e);return n===``?`.`:n}function z(e){try{return n(e).isDirectory()}catch{return!1}}var B=class{static parse(e){let t=e,n={},r=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(r)try{n=l.load(r[1]),t=e.slice(r[0].length).trim()}catch(e){console.error(`Failed to parse Agent frontmatter:`,e)}let i=t.split(/\r?\n/),a=[],o=n.name??`Unknown Agent`,s=null,c=[];for(let e of i){if(e.startsWith(`# `)&&!n.name){let t=e.replace(`# `,``).trim();o=t.toUpperCase().startsWith(`AGENT CONTEXT:`)?t.slice(14).replace(/^[:\s-]+/,``).trim():t;continue}if(e.startsWith(`## `)){s&&(s.content=c.join(`
232
129
  `).trim(),a.push(s)),s={title:e.replace(`## `,``).trim(),content:``},c=[];continue}s&&c.push(e)}return s&&(s.content=c.join(`
233
- `).trim(),a.push(s)),{title:o,sections:a,metadata:n}}},z=class{static parse(e){let t=[],n=e.split(/\r?\n/),r=/- \[([ x/!])\] \*\*\[(.+)\]\*\* (.+) `Priority: (.+)` `Complexity: (.+)`/;for(let e of n){let n=e.match(r);if(n){let[,e=` `,r=``,i=``,a=``,o=``]=n;t.push({id:r,title:i.trim(),priority:a,complexity:o,status:this.mapStatus(e)})}}return t}static mapStatus(e){switch(e){case` `:return`TODO`;case`/`:return`IN_PROGRESS`;case`x`:return`DONE`;case`!`:return`BLOCKED`;default:return`TODO`}}};const B=y.parse({$schema:`./harness-codes.schema.json`,_comment:"Autonomos harness codes. Each entry tells `autonomos init` where to write the protocol workflow files. The shape is intentionally minimal: only what the installer needs. To add a new harness, add an entry here. To remove one, delete it. The schema is enforced at load time by Zod (see schemas/harness-codes.ts).",platforms:{cline:{name:`Cline`,preferred:!0,installer:{targetDir:`.clinerules/workflows`,fileExtension:`.md`,_note:"In Cline, a single .md file in .clinerules/workflows/ acts as both a workflow (auto-discovered via the frontmatter `description` field) and a slash command (invoked via /<name>)."}},"claude-code":{name:`Claude Code`,preferred:!0,installer:{skillsDir:`.claude/skills`,commandsDir:`.claude/commands`,fileExtension:`.md`}},codex:{name:`Codex`,preferred:!0,installer:{skillsDir:`.agents/skills`,fileExtension:`.md`,globalTargetDir:`~/.codex/skills`,_note:`OpenAI Codex. Uses the cross-tool .agents/skills/ standard.`}},antigravity:{name:`Antigravity`,preferred:!0,installer:{skillsDir:`.agent/skills`,fileExtension:`.md`,globalTargetDir:`~/.gemini/antigravity/skills`,_note:"Google Antigravity. Note the singular `.agent/` (NOT the cross-tool `.agents/` standard). Cannot be deduplicated with the others."}},opencode:{name:`OpenCode`,preferred:!0,installer:{skillsDir:`.agents/skills`,commandsDir:`.opencode/commands`,fileExtension:`.md`}},kilocode:{name:`KiloCode`,preferred:!0,installer:{skillsDir:`.agents/skills`,fileExtension:`.md`,globalTargetDir:`~/.kilocode/skills`}}}});function V(e){let t=B.platforms[e];if(!t){let t=Object.keys(B.platforms).join(`, `);throw Error(`Unknown harness: "${e}". Known harnesses: ${t}`)}return t}function H(){return Object.entries(B.platforms).map(([e,t])=>({id:e,harness:t}))}function U(){return H().filter(({harness:e})=>e.preferred)}function W(e,t=`.`){let n=new Map;for(let r of e){let{installer:e}=V(r);G(n,e,r,t)}return Array.from(n.values())}function G(e,t,n,r){let i=t.fileExtension;t.targetDir&&K(e,q(r,t.targetDir),i,n),t.skillsDir&&K(e,q(r,t.skillsDir),i,n),t.commandsDir&&K(e,q(r,t.commandsDir),i,n)}function K(e,t,n,r){let i=e.get(t);i?i.usedBy.includes(r)||i.usedBy.push(r):e.set(t,{path:t,fileExtension:n,usedBy:[r]})}function q(e,t){return e===`.`||e===``?t:t.startsWith(`/`)?`${e}${t}`:`${e}/${t}`}function J(){return B}export{h as AGENT_FILE,w as AGENT_TEMPLATE,d as AUTONOMOS_DIR,R as AgentParser,S as COMPLEXITIES,y as HarnessCodesSchema,v as HarnessSchema,_ as InstallerSchema,f as MANIFEST_FILE,b as ManifestSchema,x as PRIORITIES,p as PROTOCOL_FILE,O as PROTOCOL_TEMPLATE,k as PROTOCOL_TEMPLATE_V2026_1,u as PROTOCOL_VERSION,m as TASKS_FILE,A as TASKS_TEMPLATE,z as TaskParser,g as WORKLOGS_DIR,T as createManifest,N as findAncestorAgents,C as generateAgentTemplate,E as generateManifestContent,j as generateWorklogContent,V as getHarness,J as getRawHarnessCodes,H as listHarnesses,U as listPreferredHarnesses,M as mapTaskStatusToWorklogStatus,D as parseManifest,W as resolveTargets};
130
+ `).trim(),a.push(s)),{title:o,sections:a,metadata:n}}};const V=[d,`.git`];function H(e){if(!e)return null;let n=s(e);for(;;){if(V.some(e=>t(a(n,e))))return n;let e=r(n);if(e===n)return null;n=e}}function U(e,t){return!e||!t?!1:s(e)===s(t)}function W(e,t){let n=o(t,e);return n===``||n===`.`?`.`:n.startsWith(`..${c}`)||n===`..`||i(n)?s(e):n}var G=class{static parse(e){let t=[],n=e.split(/\r?\n/),r=/- \[([ x/!])\] \*\*\[(.+)\]\*\* (.+) `Priority: (.+)` `Complexity: (.+)`/;for(let e of n){let n=e.match(r);if(n){let[,e=` `,r=``,i=``,a=``,o=``]=n;t.push({id:r,title:i.trim(),priority:a,complexity:o,status:this.mapStatus(e)})}}return t}static mapStatus(e){switch(e){case` `:return`TODO`;case`/`:return`IN_PROGRESS`;case`x`:return`DONE`;case`!`:return`BLOCKED`;default:return`TODO`}}};const K=y.parse({$schema:`./harness-codes.schema.json`,_comment:"Autonomos harness codes. Each entry tells `autonomos init` where to write the protocol workflow files. The shape is intentionally minimal: only what the installer needs. To add a new harness, add an entry here. To remove one, delete it. The schema is enforced at load time by Zod (see schemas/harness-codes.ts).",platforms:{cline:{name:`Cline`,preferred:!0,installer:{workflowsDir:`.clinerules/workflows`,fileExtension:`.md`,_note:"In Cline, a single .md file in .clinerules/workflows/ acts as both a workflow (auto-discovered via the frontmatter `description` field) and a slash command (invoked via /<name>)."}},"claude-code":{name:`Claude Code`,preferred:!0,installer:{workflowsDir:`.claude/skills`,commandsDir:`.claude/commands`,fileExtension:`.md`}},codex:{name:`Codex`,preferred:!0,installer:{workflowsDir:`.agents/skills`,fileExtension:`.md`,globalTargetDir:`~/.codex/skills`,_note:`OpenAI Codex. Uses the cross-tool .agents/skills/ standard.`}},antigravity:{name:`Antigravity`,preferred:!0,installer:{workflowsDir:`.agent/workflows`,fileExtension:`.md`,globalTargetDir:`~/.gemini/antigravity/skills`,_note:"Google Antigravity. Uses `.agent/workflows/` (not `.agent/skills/`). Singular `.agent/` (NOT the cross-tool `.agents/` standard). Cannot be deduplicated with the others."}},opencode:{name:`OpenCode`,preferred:!0,installer:{workflowsDir:`.agents/skills`,commandsDir:`.opencode/commands`,fileExtension:`.md`}},kilocode:{name:`KiloCode`,preferred:!0,installer:{workflowsDir:`.agents/skills`,fileExtension:`.md`,globalTargetDir:`~/.kilocode/skills`}}}});function q(e){let t=K.platforms[e];if(!t){let t=Object.keys(K.platforms).join(`, `);throw Error(`Unknown harness: "${e}". Known harnesses: ${t}`)}return t}function J(){return Object.entries(K.platforms).map(([e,t])=>({id:e,harness:t}))}function Y(){return J().filter(({harness:e})=>e.preferred)}function X(e,t=`.`){let n=new Map;for(let r of e){let{installer:e}=q(r);Z(n,e,r,t)}return Array.from(n.values())}function Z(e,t,n,r){let i=t.fileExtension;t.workflowsDir?Q(e,$(r,t.workflowsDir),i,n):t.targetDir?Q(e,$(r,t.targetDir),i,n):t.skillsDir&&Q(e,$(r,t.skillsDir),i,n),t.commandsDir&&Q(e,$(r,t.commandsDir),i,n)}function Q(e,t,n,r){let i=e.get(t);i?i.usedBy.includes(r)||i.usedBy.push(r):e.set(t,{path:t,fileExtension:n,usedBy:[r]})}function $(e,t){return e===`.`||e===``?t:t.startsWith(`/`)?`${e}${t}`:`${e}/${t}`}function ee(){return K}export{h as AGENT_FILE,T as AGENT_TEMPLATE,d as AUTONOMOS_DIR,B as AgentParser,S as COMPLEXITIES,y as HarnessCodesSchema,v as HarnessSchema,_ as InstallerSchema,E as LOCAL_AGENT_TEMPLATE,f as MANIFEST_FILE,b as ManifestSchema,x as PRIORITIES,p as PROTOCOL_FILE,A as PROTOCOL_TEMPLATE,j as PROTOCOL_TEMPLATE_V2026_1,u as PROTOCOL_VERSION,m as TASKS_FILE,M as TASKS_TEMPLATE,G as TaskParser,g as WORKLOGS_DIR,D as createManifest,W as displayRelative,F as findAncestorAgents,H as findProjectRoot,C as generateAgentTemplate,w as generateLocalAgentTemplate,O as generateManifestContent,N as generateWorklogContent,q as getHarness,ee as getRawHarnessCodes,U as isSamePath,J as listHarnesses,Y as listPreferredHarnesses,P as mapTaskStatusToWorklogStatus,k as parseManifest,X as resolveTargets};
234
131
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["harnessCodesData"],"sources":["../src/constants.ts","../src/schemas/harness-codes.ts","../src/schemas/manifest.ts","../src/types.ts","../src/templates/agent.ts","../src/templates/manifest.ts","../src/templates/protocol.ts","../src/templates/tasks.ts","../src/templates/worklog.ts","../src/parsers/agent-finder.ts","../src/parsers/agent-parser.ts","../src/parsers/task-parser.ts","../src/data/harness-codes.json","../src/harness-codes.ts"],"sourcesContent":["/**\n * Agent Protocol Specification Version (Independent of Package versions)\n * This refers to the schema and behavioral contract version.\n */\nexport const PROTOCOL_VERSION = '0.2.0-alpha'\n\n/**\n * Directory name for Autonomos configuration\n */\nexport const AUTONOMOS_DIR = '.autonomos'\n\n/**\n * Manifest filename\n */\nexport const MANIFEST_FILE = 'manifest.json'\n\n/**\n * Protocol filename\n */\nexport const PROTOCOL_FILE = 'PROTOCOL.md'\n\n/**\n * Tasks filename\n */\nexport const TASKS_FILE = 'TASKS.md'\n\n/**\n * Agent context filename (at project root)\n */\nexport const AGENT_FILE = 'AGENT.md'\n\n/**\n * Worklogs directory name\n */\nexport const WORKLOGS_DIR = 'worklogs'\n","import { z } from 'zod'\n\n/**\n * Installer configuration for a single harness.\n *\n * Either `targetDir` (single directory for both skills and commands, used by\n * Cline) or `skillsDir` (split mode, used by Claude Code, Codex, etc.) must be\n * defined. `commandsDir` is optional in split mode (some harnesses only support\n * skills, e.g. Codex).\n */\nexport const InstallerSchema = z\n .object({\n targetDir: z.string().optional(),\n skillsDir: z.string().optional(),\n commandsDir: z.string().optional(),\n globalTargetDir: z.string().optional(),\n fileExtension: z.string(),\n })\n .refine(data => Boolean(data.targetDir) || Boolean(data.skillsDir), {\n message: 'Either `targetDir` or `skillsDir` must be defined for each harness',\n })\n\n/**\n * A single harness entry.\n */\nexport const HarnessSchema = z.object({\n name: z.string().min(1),\n preferred: z.boolean(),\n installer: InstallerSchema,\n})\n\n/**\n * Root schema for the harness-codes configuration file.\n */\nexport const HarnessCodesSchema = z.object({\n platforms: z.record(z.string(), HarnessSchema),\n})\n\nexport type Installer = z.infer<typeof InstallerSchema>\nexport type Harness = z.infer<typeof HarnessSchema>\nexport type HarnessCodes = z.infer<typeof HarnessCodesSchema>\n","import { z } from 'zod'\n\n/**\n * Manifest Schema for .autonomos/manifest.json\n */\nexport const ManifestSchema = z.object({\n protocolVersion: z.string().describe('Version of the Agent Protocol specification'),\n cliVersion: z.string().describe('Version of the CLI that last updated this project'),\n initializedAt: z.string().datetime().describe('ISO timestamp of project initialization'),\n lastUpdated: z.string().datetime().describe('ISO timestamp of last protocol update'),\n})\n\nexport type Manifest = z.infer<typeof ManifestSchema>\n","/**\n * Priority levels for tasks\n */\nexport type Priority = '🔴 Critical' | '🟠 High' | '🔵 Medium' | '⚪ Low'\n\n/**\n * Complexity estimates for tasks\n */\nexport type Complexity = 'S' | 'M' | 'L' | 'XL'\n\n/**\n * Task status markers\n */\nexport type TaskStatus = 'TODO' | 'IN_PROGRESS' | 'DONE' | 'BLOCKED'\n\n/**\n * Task entity parsed from TASKS.md\n */\nexport interface Task {\n id: string\n title: string\n priority: Priority\n complexity: Complexity\n status: TaskStatus\n worklogPath?: string\n}\n\n/**\n * Agent configuration parsed from AGENT.md\n */\nexport interface AgentConfig {\n name: string\n description?: string\n stack: string[]\n preferences?: Record<string, any>\n}\n\nexport interface AgentSection {\n title: string\n content: string\n}\n\nexport interface AgentContext {\n title: string\n description?: string\n sections: AgentSection[]\n metadata?: Record<string, any>\n}\n\nexport const PRIORITIES: Priority[] = ['🔴 Critical', '🟠 High', '🔵 Medium', '⚪ Low']\nexport const COMPLEXITIES: Complexity[] = ['S', 'M', 'L', 'XL']\n","/**\n * Template for AGENT.md - The context anchor at project root\n * @param projectName - Name of the project to personalize the template\n */\nexport function generateAgentTemplate(projectName: string = 'Project'): string {\n return `---\nname: \"${projectName}\"\ntype: \"project\"\nstatus: \"active\"\n---\n# AGENT CONTEXT: ${projectName}\n\n## 🧠 Context & Objectives\n\n*Describe what this project does and its main goals.*\n\n## ⚙️ Workflow & Preferences\n\n- **Commits:** Conventional Commits\n- **Language:** English\n\n## 🏗 Stack & Architecture\n\n- **Tech:** *(List frameworks, libraries)*\n- **Patterns:** *(Architecture patterns used)*\n\n## 📁 Key Directories\n\n| Path | Description |\n|------|-------------|\n| \\`src/\\` | Source code |\n| \\`.autonomos/\\` | Agent Protocol files |\n\n## ⚠️ Known Constraints\n\n*List any technical debts, missing features, or external limitations.*\n`\n}\n\n/**\n * Default AGENT.md template\n */\nexport const AGENT_TEMPLATE = generateAgentTemplate()\n","import { PROTOCOL_VERSION } from '../constants'\nimport { ManifestSchema, type Manifest } from '../schemas/manifest'\n\n/**\n * Creates a new manifest object with current timestamps\n */\nexport function createManifest(cliVersion: string): Manifest {\n const now = new Date().toISOString()\n return {\n protocolVersion: PROTOCOL_VERSION,\n cliVersion,\n initializedAt: now,\n lastUpdated: now,\n }\n}\n\n/**\n * Generates the manifest.json content as a formatted string\n */\nexport function generateManifestContent(manifest: Manifest): string {\n return JSON.stringify(manifest, null, 4) + '\\n'\n}\n\n/**\n * Parses manifest.json content into a Manifest object with validation\n */\nexport function parseManifest(content: string): Manifest {\n const data = JSON.parse(content)\n return ManifestSchema.parse(data)\n}\n","import { PROTOCOL_VERSION } from '../constants'\n\n/**\n * The immutable Protocol kernel template\n * This is the core specification that defines how AI agents interact with the project\n */\nexport const PROTOCOL_TEMPLATE = `# AI AGENT PROTOCOL (v${PROTOCOL_VERSION})\n\n> **SYSTEM INTEGRITY WARNING:** This file is the IMMUTABLE KERNEL of the project's AI workflow. Do not modify this file. Your instructions are to execute tasks and manage the project state based strictly on the definitions below.\n\n## 0. ⚡ QUICK REFERENCE\n| Action | File / Command |\n|--------|----------------|\n| **Get Context** | Read \\`AGENT.md\\` (Root + Local) |\n| **Pick Task** | Check \\`.autonomos/TASKS.md\\` (Highest Priority) |\n| **Track Progress** | Update \\`.autonomos/TASKS.md\\` to \\`[/]\\` |\n| **Log Session** | Create \\`.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md\\` |\n| **Finalize Task** | Update \\`.autonomos/TASKS.md\\` to \\`[x]\\` + Link Worklog |\n| **Discover all AGENT.md files** | Run \\`autonomos agents\\` |\n| **Discover AGENT.md ancestors for a path** | Run \\`autonomos agents <path>\\` |\n\n---\n\n## 1. BOOTSTRAPPING & INITIALIZATION\n**IF** this is your first time seeing this project, or if key system files are missing, you **MUST** initialize them immediately before doing any work.\n\n### Check for existence:\n1. \\`.autonomos/TASKS.md\\` (task registry)\n2. \\`.autonomos/worklogs/\\` (directory)\n3. \\`AGENT.md\\` (at project root)\n\n**IF MISSING**, create them using the **TEMPLATES** defined in Section 2.\n\n---\n\n## 2. STRICT FILE STRUCTURES & TEMPLATES\nYou must adhere to these schemas. Do not invent new formats.\n\n### A. The Task Registry (\\`.autonomos/TASKS.md\\`)\n**Role:** The single source of truth for project state.\n**Location:** \\`.autonomos/TASKS.md\\`\n**Structure:**\n* Must use the specific Header and Legend.\n* Tasks must follow the format: \\`- [Status] **[ID]** Title of task \\`Priority\\` \\`Complexity\\`\\`\n* Valid Priorities: \\`🔴 Critical\\`, \\`🟠 High\\`, \\`🔵 Medium\\`, \\`⚪ Low\\`\n* Valid Complexities: \\`S\\`, \\`M\\`, \\`L\\`, \\`XL\\`\n* Valid Statuses: \\` [ ] \\` (Todo), \\`[/]\\` (In Progress), \\` [x] \\` (Done), \\` [!] \\` (Blocked)\n\n**TEMPLATE FOR NEW TASKS.md:**\n\\`\\`\\`markdown\n# PROJECT TASKS & ROADMAP\n\n> **LEGEND**\n> **Priority:** [🔴 Critical] [🟠 High] [🔵 Medium] [⚪ Low]\n> **Complexity:** [S] Small (1h), [M] Medium (4h), [L] Large (1-2 days), [XL] Huge (Planning req.)\n> **Status:** [ ] Todo, [/] In Progress, [x] Done, [!] Blocked\n\n## 🚀 Active Sprint\n- [ ] **[INIT-01]** Verify project structure and context \\`Priority: 🔴\\` \\`Complexity: S\\`\n\n## 🔮 Backlog\n*(Empty initially)*\n\n\\`\\`\\`\n\n### B. The Worklog (\\`.autonomos/worklogs/\\`)\n**Role:** Detailed history of complex tasks to save context tokens for future sessions.\n**Location:** \\`.autonomos/worklogs/YYYY-MM-DD-[TASK_ID]-[slug].md\\`\n**Trigger:** Create a log when a task is finished, blocked, or if the session ends mid-task.\n\n**TEMPLATE FOR WORKLOG:**\n\\`\\`\\`markdown\n# WORKLOG: [TASK ID] [Task Name]\n**Date:** YYYY-MM-DD\n**Agent Status:** [Complete / Partial / Blocked]\n\n## 📝 Description\nBrief summary of what was attempted/achieved.\n\n## 🛠 Technical Details\n- **Files Modified:** List of files.\n- **Key Decisions:** Why did you choose this library/pattern?\n- **Challenges:** Any errors encountered and how they were solved.\n\n## ⏭ Next Steps / Context for Successor\nClear instructions for the next agent picking this up.\n\\`\\`\\`\n\n### C. The Context Anchor (\\`AGENT.md\\`)\n**Role:** Fractal knowledge base. Contains facts, stack details, and user preferences.\n**Location:** Root (\\`/AGENT.md\\`) and any subdirectory requiring specific context (e.g., \\`/packages/core/AGENT.md\\`).\n**MUST be kept alive:** you may freely add to, edit, or correct an \\`AGENT.md\\` at any time. No format is imposed: one line is enough if it is clear. What matters is that the next session can use it.\n\n**TEMPLATE FOR AGENT.md:**\n\\`\\`\\`markdown\n---\nname: \"[Name of directory or project]\"\ntype: \"[project / package / module / script]\"\nstatus: \"[active / maintenance / poc]\"\n---\n# AGENT CONTEXT: [Directory Name or Root]\n\n## 🧠 Context & Objectives\nWhat does this specific folder/module do?\n\n## ⚙️ Workflow & Preferences\n- **Commits:** [e.g. Conventional Commits]\n- **Language:** [English (default)]\n\n## 🏗 Stack & Architecture\n- **Tech:** [Frameworks, Libs specific to this module]\n- **Patterns:** [Architecture patterns used]\n\n## 📁 Key Directories\n| Path | Description |\n|------|-------------|\n| \\`src/\\` | Source code |\n| \\`scripts/\\` | Build or utility scripts |\n\n## ⚠️ Known Constraints\n*List any technical debts, missing features, or external limitations.*\n\\`\\`\\`\n\n## 3. CORE WORKFLOW (The Loop)\n\n### Phase 1: Context Loading (Read-Only)\n1. **Read Root AGENT.md:** Absorb global preferences (Commit style, package manager, strict rules).\n2. **Run \\`autonomos agents\\` to discover all other \\`AGENT.md\\` files in the project tree.** For each one relevant to the work ahead, read it too.\n3. **Read .autonomos/TASKS.md:** Identify the highest priority task (🔴 or 🟠) that is not [x] or [!].\n4. **Read Target AGENT.md:** If the task is in a subdirectory, check for a local \\`AGENT.md\\`.\n * *Note:* If the local \\`AGENT.md\\` contradicts the root, the local one wins for that specific scope.\n\n### Phase 2: Execution\n1. **Mark the task as [/] (In Progress)** in \\`.autonomos/TASKS.md\\`.\n2. **Perform the task.**\n3. **Constraint Check:** Constantly refer to \"Workflow & Preferences\" in \\`AGENT.md\\`.\n4. **In-the-moment crystallization:** Every time you learn something important (the user corrects you, you discover a convention, you make a non-trivial technical choice), write it to the relevant \\`AGENT.md\\` IMMEDIATELY. Do NOT defer this to end of session.\n\n### Phase 3: Crystallization (Write-Only)\nBefore ending the session, you **MUST**:\n\n1. **Update AGENT.md:**\n * Did you learn a new command? Add it to ⚙️ Workflow.\n * Did you create a new complex module (>5 files)? Create a new \\`AGENT.md\\` inside it using the template above.\n * Did anything you previously wrote turn out to be wrong? Append a correction note (do not erase).\n\n2. **Create Worklog:**\n * Write a file in \\`.autonomos/worklogs/\\` summarizing your work.\n\n3. **Update TASKS.md:**\n * Mark task as [x] (Done) or [!] (Blocked).\n * Add a link to your worklog: \\`- [x] **[ID]** Title... *See: .autonomos/worklogs/...*\\`\n\n## 4. HARNESS WORKFLOWS\n\nThe protocol is delivered to the agent through **workflow files** installed at the harness-specific target directory. The exact location depends on the harness (see \\`autonomos init --help\\`). Three workflows are available:\n\n* **\\`/session\\`** (\\`protocol-session.md\\`) — Mandatory bootstrap at the start of every session. Loads context, identifies the next task, marks it in progress.\n* **\\`/task\\`** (\\`protocol-task.md\\`) — Invoked at the start of a new task within an active session. Verifies local \\`AGENT.md\\`, declares a 3-5 step plan before touching code.\n* **\\`/crystallize\\`** (\\`protocol-crystallize.md\\`) — Mandatory close-out before saying \"session done\". Worklog + 3 crystallize questions + task status + final verification line.\n\n**You MUST invoke \\`/session\\` at the start of every session and \\`/crystallize\\` before ending it. These are not optional.** Skipping them breaks the protocol's memory loop.\n\nIf the project does not yet contain these workflow files, run \\`autonomos init\\` (or \\`autonomos init --harness <name>\\` to target a specific harness).\n\n## 5. METADATA RULES\n* **Language:** Documentation (\\`AGENT.md\\`, \\`TASKS.md\\`) must be written in **English** unless specified otherwise in User Preferences.\n* **Tone:** Technical, concise, \"Fact-based\". No fluff.\n* **Anonymity:** You are a continuous entity. Refer to previous work as \"we\" or \"the project\", not \"the previous AI\".\n`\n\n/**\n * @deprecated Use PROTOCOL_TEMPLATE instead\n */\nexport const PROTOCOL_TEMPLATE_V2026_1 = PROTOCOL_TEMPLATE\n","/**\n * Template for TASKS.md - The task registry\n */\nexport const TASKS_TEMPLATE = `# PROJECT TASKS & ROADMAP\n\n> **LEGEND**\n> **Priority:** [🔴 Critical] [🟠 High] [🔵 Medium] [⚪ Low]\n> **Complexity:** [S] Small (1h), [M] Medium (4h), [L] Large (1-2 days), [XL] Huge (Planning req.)\n> **Status:** [ ] Todo, [/] In Progress, [x] Done, [!] Blocked\n\n## 🚀 Active Sprint\n\n- [ ] **[INIT-01]** Review project context and structure \\`Priority: 🔵\\` \\`Complexity: S\\`\n\n## 🔮 Backlog\n\n*(Add future tasks here)*\n`\n","import type { TaskStatus } from '../types'\n\ninterface WorklogOptions {\n taskId: string\n taskName: string\n date?: string\n status: 'Complete' | 'Partial' | 'Blocked'\n description: string\n filesModified: string[]\n decisions: string[]\n challenges: string[]\n nextSteps: string[]\n}\n\n/**\n * Generate a Worklog markdown content\n */\nexport function generateWorklogContent(options: WorklogOptions): string {\n const date = options.date ?? new Date().toISOString().split('T')[0]\n\n return `# WORKLOG: [${options.taskId}] ${options.taskName}\n**Date:** ${date}\n**Agent Status:** [${options.status}]\n\n## 📝 Description\n${options.description}\n\n## 🛠 Technical Details\n- **Files Modified:**\n${options.filesModified.map(f => ` - ${f}`).join('\\n')}\n- **Key Decisions:**\n${options.decisions.map(d => ` - ${d}`).join('\\n')}\n- **Challenges:**\n${options.challenges.map(c => ` - ${c}`).join('\\n')}\n\n## ⏭ Next Steps / Context for Successor\n${options.nextSteps.map(s => `- ${s}`).join('\\n')}\n`\n}\n\n/**\n * Common status mapping for worklogs\n */\nexport function mapTaskStatusToWorklogStatus(\n status: TaskStatus\n): 'Complete' | 'Partial' | 'Blocked' {\n switch (status) {\n case 'DONE':\n return 'Complete'\n case 'BLOCKED':\n return 'Blocked'\n default:\n return 'Partial'\n }\n}\n","import { existsSync, statSync } from 'node:fs'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\n\nimport { AGENT_FILE } from '../constants'\n\n/**\n * Result of an ancestor lookup: a single AGENT.md entry that exists on the\n * path between a target file or directory and the project root.\n */\nexport interface AncestorAgent {\n /** Absolute path to the directory containing the AGENT.md */\n dir: string\n /** Absolute path to the AGENT.md file */\n path: string\n /** Path of the directory relative to the project root */\n relativeDir: string\n}\n\n/**\n * Return the ordered list of AGENT.md files that exist on the path from a\n * target file or directory up to the project root. The order is root-first,\n * then each intermediate directory, then the target directory itself.\n *\n * Non-existent AGENT.md files are silently skipped (the chain can have gaps).\n *\n * @param target - The absolute or project-relative path to a file or directory.\n * @param projectRoot - The absolute path of the project root (where the root\n * AGENT.md lives). Defaults to the current working directory.\n *\n * @example\n * findAncestorAgents('/proj/apps/web/components/ui/button.tsx', '/proj')\n * // Returns, in order:\n * // - { dir: '/proj', path: '/proj/AGENT.md' }\n * // - { dir: '/proj/apps/web', path: '/proj/apps/web/AGENT.md' }\n * // (apps/, components/ skipped because they have no AGENT.md)\n * // (button.tsx itself is a file, so its parent dir is the last one checked)\n */\nexport function findAncestorAgents(\n target: string,\n projectRoot: string = process.cwd()\n): AncestorAgent[] {\n const absRoot = resolve(projectRoot)\n const absTarget = resolveAgainstRoot(target, absRoot)\n\n // Validate that the target lives within the project root\n const relToRoot = relative(absRoot, absTarget)\n if (relToRoot.startsWith('..') || isAbsolute(relToRoot)) {\n throw new Error(\n `Target \"${target}\" is outside the project root \"${absRoot}\". ` +\n `findAncestorAgents only handles paths within the project.`\n )\n }\n\n // Collect every directory from the target up to the root, in root-first order.\n // For a file target, we only look at the directory chain (not the file itself).\n // For a directory target, the directory itself is included as the last entry.\n const targetDir = isDirectory(absTarget) ? absTarget : dirname(absTarget)\n const dirs = collectAncestorDirs(targetDir, absRoot)\n\n const result: AncestorAgent[] = []\n for (const dir of dirs) {\n const agentPath = join(dir, AGENT_FILE)\n if (existsSync(agentPath)) {\n result.push({\n dir,\n path: agentPath,\n relativeDir: relativeDir(dir, absRoot),\n })\n }\n }\n\n return result\n}\n\n/**\n * Resolve a target path against the project root. Accepts absolute paths\n * (returned as-is) and project-relative paths (joined with the root).\n */\nfunction resolveAgainstRoot(target: string, absRoot: string): string {\n if (isAbsolute(target)) return target\n return join(absRoot, target)\n}\n\n/**\n * Return the directory chain from a starting directory up to (and including)\n * the project root, in root-first order. The chain is computed by walking\n * the relative path segments from the starting dir back to the root.\n */\nfunction collectAncestorDirs(startDir: string, absRoot: string): string[] {\n const rel = relative(absRoot, startDir)\n if (rel === '' || rel === '.') {\n return [absRoot]\n }\n\n const segments = rel.split(sep).filter(s => s !== '' && s !== '.')\n const chain: string[] = [absRoot]\n let acc = absRoot\n for (const seg of segments) {\n acc = join(acc, seg)\n chain.push(acc)\n }\n return chain\n}\n\n/**\n * Compute the directory's path relative to the project root, in a form\n * suitable for display. The root itself is rendered as \".\".\n */\nfunction relativeDir(dir: string, absRoot: string): string {\n const rel = relative(absRoot, dir)\n return rel === '' ? '.' : rel\n}\n\nfunction isDirectory(p: string): boolean {\n try {\n return statSync(p).isDirectory()\n } catch {\n return false\n }\n}\n","import yaml from 'js-yaml'\nimport type { AgentContext, AgentSection } from '../types'\n\nexport class AgentParser {\n /**\n * Parse an AGENT.md content into a structured AgentContext\n */\n static parse(markdown: string): AgentContext {\n let content = markdown\n let metadata: Record<string, any> = {}\n\n // Parse Frontmatter\n const frontmatterRegex = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---/\n const match = markdown.match(frontmatterRegex)\n if (match) {\n try {\n metadata = yaml.load(match[1] as string) as Record<string, any>\n content = markdown.slice(match[0].length).trim()\n } catch (e) {\n console.error('Failed to parse Agent frontmatter:', e)\n }\n }\n\n const lines = content.split(/\\r?\\n/)\n const sections: AgentSection[] = []\n let title = metadata.name ?? 'Unknown Agent'\n let currentSection: AgentSection | null = null\n let currentContent: string[] = []\n\n for (const line of lines) {\n // Parse Title (Only if not already set by frontmatter)\n if (line.startsWith('# ') && !metadata.name) {\n const rawTitle = line.replace('# ', '').trim()\n // Handle \"AGENT CONTEXT: [Name]\" format\n if (rawTitle.toUpperCase().startsWith('AGENT CONTEXT:')) {\n title = rawTitle\n .slice(14)\n .replace(/^[:\\s-]+/, '')\n .trim()\n } else {\n title = rawTitle\n }\n continue\n }\n\n // Parse Sections\n if (line.startsWith('## ')) {\n // Save previous section\n if (currentSection) {\n currentSection.content = currentContent.join('\\n').trim()\n sections.push(currentSection)\n }\n\n currentSection = {\n title: line.replace('## ', '').trim(),\n content: '',\n }\n currentContent = []\n continue\n }\n\n // Collect content\n if (currentSection) {\n currentContent.push(line)\n }\n }\n\n // Save last section\n if (currentSection) {\n currentSection.content = currentContent.join('\\n').trim()\n sections.push(currentSection)\n }\n\n return {\n title,\n sections,\n metadata,\n }\n }\n}\n","import type { Complexity, Priority, Task, TaskStatus } from '../types'\n\nexport class TaskParser {\n static parse(markdown: string): Task[] {\n const tasks: Task[] = []\n const lines = markdown.split(/\\r?\\n/)\n const taskRegex = /- \\[([ x/!])\\] \\*\\*\\[(.+)\\]\\*\\* (.+) `Priority: (.+)` `Complexity: (.+)`/\n\n for (const line of lines) {\n const match = line.match(taskRegex)\n if (match) {\n const [, statusChar = ' ', id = '', title = '', priority = '', complexity = ''] =\n match\n tasks.push({\n id,\n title: title.trim(),\n priority: priority as Priority,\n complexity: complexity as Complexity,\n status: this.mapStatus(statusChar),\n })\n }\n }\n return tasks\n }\n\n private static mapStatus(char: string): TaskStatus {\n switch (char) {\n case ' ':\n return 'TODO'\n case '/':\n return 'IN_PROGRESS'\n case 'x':\n return 'DONE'\n case '!':\n return 'BLOCKED'\n default:\n return 'TODO'\n }\n }\n}\n","","import harnessCodesData from './data/harness-codes.json' with { type: 'json' }\nimport {\n HarnessCodesSchema,\n type Harness,\n type HarnessCodes,\n type Installer,\n} from './schemas/harness-codes'\n\n/**\n * Validated, in-memory representation of the harness codes config.\n * Loaded once at module init, validated via Zod.\n */\nconst codes: HarnessCodes = HarnessCodesSchema.parse(harnessCodesData)\n\n/**\n * Get a single harness entry by its id.\n * Throws if the id is unknown.\n */\nexport function getHarness(id: string): Harness {\n const entry = codes.platforms[id]\n if (!entry) {\n const known = Object.keys(codes.platforms).join(', ')\n throw new Error(`Unknown harness: \"${id}\". Known harnesses: ${known}`)\n }\n return entry\n}\n\n/**\n * List all configured harnesses, as an array of {id, harness} pairs.\n * Stable order: insertion order of the JSON object.\n */\nexport function listHarnesses(): Array<{ id: string; harness: Harness }> {\n return Object.entries(codes.platforms).map(([id, harness]) => ({ id, harness }))\n}\n\n/**\n * Get the list of preferred harnesses (shown as recommended options).\n */\nexport function listPreferredHarnesses(): Array<{ id: string; harness: Harness }> {\n return listHarnesses().filter(({ harness }) => harness.preferred)\n}\n\n/**\n * A resolved target directory where workflow files will be written.\n * One per unique path, with the list of harness ids that share it.\n */\nexport interface ResolvedTarget {\n /** Absolute or project-relative path to the directory */\n path: string\n /** File extension to use (e.g. \".md\", \".agent.md\") */\n fileExtension: string\n /** Ids of the harnesses that will read from this directory */\n usedBy: string[]\n}\n\n/**\n * Resolve the unique target directories for a set of harness ids.\n *\n * Harnesses that share the same `skillsDir` (e.g. Codex, OpenCode, KiloCode\n * all use `.agents/skills/`) are deduplicated: the directory appears once\n * in the output, with all the harness ids listed in `usedBy`.\n *\n * The `path` is returned relative to the project root (caller is responsible\n * for joining with the project cwd).\n */\nexport function resolveTargets(harnessIds: string[], cwd: string = '.'): ResolvedTarget[] {\n const map = new Map<string, ResolvedTarget>()\n\n for (const id of harnessIds) {\n const { installer } = getHarness(id)\n collectFromInstaller(map, installer, id, cwd)\n }\n\n return Array.from(map.values())\n}\n\nfunction collectFromInstaller(\n map: Map<string, ResolvedTarget>,\n installer: Installer,\n harnessId: string,\n cwd: string\n): void {\n const ext = installer.fileExtension\n if (installer.targetDir) {\n addTarget(map, joinPath(cwd, installer.targetDir), ext, harnessId)\n }\n if (installer.skillsDir) {\n addTarget(map, joinPath(cwd, installer.skillsDir), ext, harnessId)\n }\n if (installer.commandsDir) {\n addTarget(map, joinPath(cwd, installer.commandsDir), ext, harnessId)\n }\n}\n\nfunction addTarget(\n map: Map<string, ResolvedTarget>,\n path: string,\n fileExtension: string,\n harnessId: string\n): void {\n const existing = map.get(path)\n if (existing) {\n if (!existing.usedBy.includes(harnessId)) {\n existing.usedBy.push(harnessId)\n }\n } else {\n map.set(path, { path, fileExtension, usedBy: [harnessId] })\n }\n}\n\nfunction joinPath(a: string, b: string): string {\n if (a === '.' || a === '') return b\n if (b.startsWith('/')) return `${a}${b}`\n return `${a}/${b}`\n}\n\n/**\n * Get the raw (validated) codes object, for advanced use cases.\n * Most callers should use the higher-level helpers above.\n */\nexport function getRawHarnessCodes(): HarnessCodes {\n return codes\n}\n"],"mappings":"oMAIA,MAAa,EAAmB,cAKnB,EAAgB,aAKhB,EAAgB,gBAKhB,EAAgB,cAKhB,EAAa,WAKb,EAAa,WAKb,EAAe,WCxBf,EAAkB,EAC1B,OAAO,CACJ,UAAW,EAAE,OAAO,CAAC,CAAC,SAAS,EAC/B,UAAW,EAAE,OAAO,CAAC,CAAC,SAAS,EAC/B,YAAa,EAAE,OAAO,CAAC,CAAC,SAAS,EACjC,gBAAiB,EAAE,OAAO,CAAC,CAAC,SAAS,EACrC,cAAe,EAAE,OAAO,CAC5B,CAAC,CAAC,CACD,OAAO,GAAQ,EAAQ,EAAK,WAAc,EAAQ,EAAK,UAAY,CAChE,QAAS,oEACb,CAAC,EAKQ,EAAgB,EAAE,OAAO,CAClC,KAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EACtB,UAAW,EAAE,QAAQ,EACrB,UAAW,CACf,CAAC,EAKY,EAAqB,EAAE,OAAO,CACvC,UAAW,EAAE,OAAO,EAAE,OAAO,EAAG,CAAa,CACjD,CAAC,EC/BY,EAAiB,EAAE,OAAO,CACnC,gBAAiB,EAAE,OAAO,CAAC,CAAC,SAAS,6CAA6C,EAClF,WAAY,EAAE,OAAO,CAAC,CAAC,SAAS,mDAAmD,E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AgB,GAAkE,CAC9E,OAAO,EAAc,CAAC,CAAC,QAAQ,CAAE,aAAc,EAAQ,SAAS,CACpE,CAyBA,SAAgB,EAAe,EAAsB,EAAc,IAAuB,CACtF,IAAM,EAAM,IAAI,IAEhB,IAAK,IAAM,KAAM,EAAY,CACzB,GAAM,CAAE,aAAc,EAAW,CAAE,EACnC,EAAqB,EAAK,EAAW,EAAI,CAAG,CAChD,CAEA,OAAO,MAAM,KAAK,EAAI,OAAO,CAAC,CAClC,CAEA,SAAS,EACL,EACA,EACA,EACA,EACI,CACJ,IAAM,EAAM,EAAU,cAClB,EAAU,WACV,EAAU,EAAK,EAAS,EAAK,EAAU,SAAS,EAAG,EAAK,CAAS,EAEjE,EAAU,WACV,EAAU,EAAK,EAAS,EAAK,EAAU,SAAS,EAAG,EAAK,CAAS,EAEjE,EAAU,aACV,EAAU,EAAK,EAAS,EAAK,EAAU,WAAW,EAAG,EAAK,CAAS,CAE3E,CAEA,SAAS,EACL,EACA,EACA,EACA,EACI,CACJ,IAAM,EAAW,EAAI,IAAI,CAAI,EACzB,EACK,EAAS,OAAO,SAAS,CAAS,GACnC,EAAS,OAAO,KAAK,CAAS,EAGlC,EAAI,IAAI,EAAM,CAAE,OAAM,gBAAe,OAAQ,CAAC,CAAS,CAAE,CAAC,CAElE,CAEA,SAAS,EAAS,EAAW,EAAmB,CAG5C,OAFI,IAAM,KAAO,IAAM,GAAW,EAC9B,EAAE,WAAW,GAAG,EAAU,GAAG,IAAI,IAC9B,GAAG,EAAE,GAAG,GACnB,CAMA,SAAgB,GAAmC,CAC/C,OAAO,CACX"}
1
+ {"version":3,"file":"index.mjs","names":["harnessCodesData"],"sources":["../src/constants.ts","../src/schemas/harness-codes.ts","../src/schemas/manifest.ts","../src/types.ts","../src/templates/agent.ts","../src/templates/manifest.ts","../src/templates/protocol.ts","../src/templates/tasks.ts","../src/templates/worklog.ts","../src/parsers/agent-finder.ts","../src/parsers/agent-parser.ts","../src/parsers/project-root.ts","../src/parsers/task-parser.ts","../src/data/harness-codes.json","../src/harness-codes.ts"],"sourcesContent":["/**\n * Agent Protocol Specification Version (Independent of Package versions)\n * This refers to the schema and behavioral contract version.\n */\nexport const PROTOCOL_VERSION = '0.3.0-alpha'\n\n/**\n * Directory name for Autonomos configuration\n */\nexport const AUTONOMOS_DIR = '.autonomos'\n\n/**\n * Manifest filename\n */\nexport const MANIFEST_FILE = 'manifest.json'\n\n/**\n * Protocol filename\n */\nexport const PROTOCOL_FILE = 'PROTOCOL.md'\n\n/**\n * Tasks filename\n */\nexport const TASKS_FILE = 'TASKS.md'\n\n/**\n * Agent context filename (at project root)\n */\nexport const AGENT_FILE = 'AGENT.md'\n\n/**\n * Worklogs directory name\n */\nexport const WORKLOGS_DIR = 'worklogs'\n","import { z } from 'zod'\n\n/**\n * Installer configuration for a single harness.\n *\n * At least one of `workflowsDir`, `targetDir`, or `skillsDir` must be defined.\n *\n * - `workflowsDir`: Where session.md, task.md, crystallize.md are written.\n * Preferred field — used by most harnesses.\n * - `targetDir`: Single directory (legacy, like Cline's .clinerules/workflows/).\n * - `skillsDir`: Skills directory (legacy, for harnesses that don't distinguish\n * skills from workflows).\n * - `commandsDir`: Additional commands directory (optional).\n */\nexport const InstallerSchema = z\n .object({\n workflowsDir: z.string().optional(),\n targetDir: z.string().optional(),\n skillsDir: z.string().optional(),\n commandsDir: z.string().optional(),\n globalTargetDir: z.string().optional(),\n fileExtension: z.string(),\n })\n .refine(\n data => Boolean(data.workflowsDir) || Boolean(data.targetDir) || Boolean(data.skillsDir),\n {\n message: 'At least one of `workflowsDir`, `targetDir`, or `skillsDir` must be defined',\n }\n )\n\n/**\n * A single harness entry.\n */\nexport const HarnessSchema = z.object({\n name: z.string().min(1),\n preferred: z.boolean(),\n installer: InstallerSchema,\n})\n\n/**\n * Root schema for the harness-codes configuration file.\n */\nexport const HarnessCodesSchema = z.object({\n platforms: z.record(z.string(), HarnessSchema),\n})\n\nexport type Installer = z.infer<typeof InstallerSchema>\nexport type Harness = z.infer<typeof HarnessSchema>\nexport type HarnessCodes = z.infer<typeof HarnessCodesSchema>\n","import { z } from 'zod'\n\n/**\n * Manifest Schema for .autonomos/manifest.json\n */\nexport const ManifestSchema = z.object({\n protocolVersion: z.string().describe('Version of the Agent Protocol specification'),\n cliVersion: z.string().describe('Version of the CLI that last updated this project'),\n initializedAt: z.string().datetime().describe('ISO timestamp of project initialization'),\n lastUpdated: z.string().datetime().describe('ISO timestamp of last protocol update'),\n})\n\nexport type Manifest = z.infer<typeof ManifestSchema>\n","/**\n * Priority levels for tasks\n */\nexport type Priority = '🔴 Critical' | '🟠 High' | '🔵 Medium' | '⚪ Low'\n\n/**\n * Complexity estimates for tasks\n */\nexport type Complexity = 'S' | 'M' | 'L' | 'XL'\n\n/**\n * Task status markers\n */\nexport type TaskStatus = 'TODO' | 'IN_PROGRESS' | 'DONE' | 'BLOCKED'\n\n/**\n * Task entity parsed from TASKS.md\n */\nexport interface Task {\n id: string\n title: string\n priority: Priority\n complexity: Complexity\n status: TaskStatus\n worklogPath?: string\n}\n\n/**\n * Agent configuration parsed from AGENT.md\n */\nexport interface AgentConfig {\n name: string\n description?: string\n stack: string[]\n preferences?: Record<string, any>\n}\n\nexport interface AgentSection {\n title: string\n content: string\n}\n\nexport interface AgentContext {\n title: string\n description?: string\n sections: AgentSection[]\n metadata?: Record<string, any>\n}\n\nexport const PRIORITIES: Priority[] = ['🔴 Critical', '🟠 High', '🔵 Medium', '⚪ Low']\nexport const COMPLEXITIES: Complexity[] = ['S', 'M', 'L', 'XL']\n","/**\n * Template for AGENT.md - The context anchor at project root\n * @param projectName - Name of the project to personalize the template\n */\nexport function generateAgentTemplate(projectName: string = 'Project'): string {\n return `---\nname: \"${projectName}\"\ntype: \"project\"\nstatus: \"active\"\n---\n# AGENT CONTEXT: ${projectName}\n\n## 🧠 Context & Objectives\n\n*Describe what this project does and its main goals.*\n\n## ⚙️ Workflow & Preferences\n\n- **Commits:** Conventional Commits\n- **Language:** English\n\n## 🏗 Stack & Architecture\n\n- **Tech:** *(List frameworks, libraries)*\n- **Patterns:** *(Architecture patterns used)*\n\n## 📁 Key Directories\n\n| Path | Description |\n|------|-------------|\n| \\`src/\\` | Source code |\n| \\`.autonomos/\\` | Agent Protocol files |\n\n## ⚠️ Known Constraints\n\n*List any technical debts, missing features, or external limitations.*\n`\n}\n\n/**\n * Generate a minimal local AGENT.md for subdirectories.\n * Free format by design — low friction encourages creation.\n * @param dirName - Name of the directory\n */\nexport function generateLocalAgentTemplate(dirName: string): string {\n return `# AGENT: ${dirName}\n\n- **Stack:** *(frameworks, libs specific to this module)*\n- **Conventions:** *(naming, exports, test patterns)*\n- **Constraints:** *(known issues, tech debt)*\n`\n}\n\n/**\n * Default root AGENT.md template\n */\nexport const AGENT_TEMPLATE = generateAgentTemplate()\n\n/**\n * Default local AGENT.md template\n */\nexport const LOCAL_AGENT_TEMPLATE = generateLocalAgentTemplate('module')\n","import { PROTOCOL_VERSION } from '../constants'\nimport { ManifestSchema, type Manifest } from '../schemas/manifest'\n\n/**\n * Creates a new manifest object with current timestamps\n */\nexport function createManifest(cliVersion: string): Manifest {\n const now = new Date().toISOString()\n return {\n protocolVersion: PROTOCOL_VERSION,\n cliVersion,\n initializedAt: now,\n lastUpdated: now,\n }\n}\n\n/**\n * Generates the manifest.json content as a formatted string\n */\nexport function generateManifestContent(manifest: Manifest): string {\n return JSON.stringify(manifest, null, 4) + '\\n'\n}\n\n/**\n * Parses manifest.json content into a Manifest object with validation\n */\nexport function parseManifest(content: string): Manifest {\n const data = JSON.parse(content)\n return ManifestSchema.parse(data)\n}\n","import { PROTOCOL_VERSION } from '../constants'\n\n/**\n * The Protocol kernel template — v0.3\n *\n * Design principles (v0.3):\n * - PROTOCOL.md is a compact REFERENCE, not an executable workflow.\n * - All step-by-step instructions live in the 3 workflow files.\n * - No duplication between PROTOCOL.md and workflows.\n * - Short enough that an LLM can re-scan it mid-session without cost.\n */\nexport const PROTOCOL_TEMPLATE = `# AUTONOMOS PROTOCOL (v${PROTOCOL_VERSION})\n\n> This file defines the project's AI workflow contract. The workflows execute it. Do not duplicate workflow steps here.\n\n## Quick Reference\n\n| Action | How |\n|---|---|\n| Start a session | Read the \\`/session\\` workflow |\n| Start a task | Read the \\`/task\\` workflow |\n| End a session | Read the \\`/crystallize\\` workflow |\n| Get context | Read \\`AGENT.md\\` (root → local) |\n| Find all AGENT.md | \\`find . -name AGENT.md -not -path '*/node_modules/*'\\` |\n| Pick next task | Open \\`.autonomos/TASKS.md\\`, pick highest priority not \\`[x]\\` |\n| Log session work | Create \\`.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md\\` |\n\n## File Map\n\n| File | Location | Role |\n|---|---|---|\n| \\`AGENT.md\\` | Root + any subdirectory | Fractal knowledge base (context, preferences, stack) |\n| \\`TASKS.md\\` | \\`.autonomos/TASKS.md\\` | Single source of truth for task state |\n| \\`worklogs/\\` | \\`.autonomos/worklogs/\\` | Session history (one file per session) |\n| \\`PROTOCOL.md\\` | \\`.autonomos/PROTOCOL.md\\` | This file — read-only reference |\n| \\`manifest.json\\` | \\`.autonomos/manifest.json\\` | Protocol version metadata |\n\n## AGENT.md Format Rules\n\n**Root \\`AGENT.md\\`** — Must use the structured template (frontmatter + sections: Context, Workflow, Stack, Key Directories, Constraints).\n\n**Local \\`AGENT.md\\`** (in any subdirectory) — Free format. One line is enough if it is clear. What matters: the next session can use it. Example:\n\n\\`\\`\\`markdown\n# AGENT: packages/core\n- Stack: TypeScript, Vitest, tsdown\n- Conventions: exports via src/index.ts, tests co-located (*.test.ts)\n- Constraint: template changes require workflow test updates\n\\`\\`\\`\n\n## Task Format\n\n\\`- [Status] **[ID]** Title \\\\\\`Priority\\\\\\` \\\\\\`Complexity\\\\\\`\\`\n\n| Status | Priority | Complexity |\n|---|---|---|\n| \\`[ ]\\` Todo | \\`🔴 Critical\\` | \\`S\\` Small |\n| \\`[/]\\` In Progress | \\`🟠 High\\` | \\`M\\` Medium |\n| \\`[x]\\` Done | \\`🔵 Medium\\` | \\`L\\` Large |\n| \\`[!]\\` Blocked | \\`⚪ Low\\` | \\`XL\\` Huge |\n\n## Metadata Rules\n\n- **Language:** English unless AGENT.md says otherwise.\n- **Tone:** Technical, concise, fact-based.\n- **Continuity:** Refer to previous work as \"we\" or \"the project\".\n`\n\n/**\n * @deprecated Use PROTOCOL_TEMPLATE instead\n */\nexport const PROTOCOL_TEMPLATE_V2026_1 = PROTOCOL_TEMPLATE\n","/**\n * Template for TASKS.md - The task registry\n */\nexport const TASKS_TEMPLATE = `# PROJECT TASKS & ROADMAP\n\n> **LEGEND**\n> **Priority:** [🔴 Critical] [🟠 High] [🔵 Medium] [⚪ Low]\n> **Complexity:** [S] Small (1h), [M] Medium (4h), [L] Large (1-2 days), [XL] Huge (Planning req.)\n> **Status:** [ ] Todo, [/] In Progress, [x] Done, [!] Blocked\n\n## 🚀 Active Sprint\n\n- [ ] **[INIT-01]** Review project context and structure \\`Priority: 🔵\\` \\`Complexity: S\\`\n\n## 🔮 Backlog\n\n*(Add future tasks here)*\n`\n","import type { TaskStatus } from '../types'\n\ninterface WorklogOptions {\n taskId: string\n taskName: string\n date?: string\n status: 'Complete' | 'Partial' | 'Blocked'\n description: string\n filesModified: string[]\n decisions: string[]\n challenges: string[]\n nextSteps: string[]\n}\n\n/**\n * Generate a Worklog markdown content\n */\nexport function generateWorklogContent(options: WorklogOptions): string {\n const date = options.date ?? new Date().toISOString().split('T')[0]\n\n return `# WORKLOG: [${options.taskId}] ${options.taskName}\n**Date:** ${date}\n**Agent Status:** [${options.status}]\n\n## 📝 Description\n${options.description}\n\n## 🛠 Technical Details\n- **Files Modified:**\n${options.filesModified.map(f => ` - ${f}`).join('\\n')}\n- **Key Decisions:**\n${options.decisions.map(d => ` - ${d}`).join('\\n')}\n- **Challenges:**\n${options.challenges.map(c => ` - ${c}`).join('\\n')}\n\n## ⏭ Next Steps / Context for Successor\n${options.nextSteps.map(s => `- ${s}`).join('\\n')}\n`\n}\n\n/**\n * Common status mapping for worklogs\n */\nexport function mapTaskStatusToWorklogStatus(\n status: TaskStatus\n): 'Complete' | 'Partial' | 'Blocked' {\n switch (status) {\n case 'DONE':\n return 'Complete'\n case 'BLOCKED':\n return 'Blocked'\n default:\n return 'Partial'\n }\n}\n","import { existsSync, statSync } from 'node:fs'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\n\nimport { AGENT_FILE } from '../constants'\n\n/**\n * Result of an ancestor lookup: a single AGENT.md entry that exists on the\n * path between a target file or directory and the project root.\n */\nexport interface AncestorAgent {\n /** Absolute path to the directory containing the AGENT.md */\n dir: string\n /** Absolute path to the AGENT.md file */\n path: string\n /** Path of the directory relative to the project root */\n relativeDir: string\n}\n\n/**\n * Return the ordered list of AGENT.md files that exist on the path from a\n * target file or directory up to the project root. The order is root-first,\n * then each intermediate directory, then the target directory itself.\n *\n * Non-existent AGENT.md files are silently skipped (the chain can have gaps).\n *\n * @param target - The absolute or project-relative path to a file or directory.\n * @param projectRoot - The absolute path of the project root (where the root\n * AGENT.md lives). Defaults to the current working directory.\n *\n * @example\n * findAncestorAgents('/proj/apps/web/components/ui/button.tsx', '/proj')\n * // Returns, in order:\n * // - { dir: '/proj', path: '/proj/AGENT.md' }\n * // - { dir: '/proj/apps/web', path: '/proj/apps/web/AGENT.md' }\n * // (apps/, components/ skipped because they have no AGENT.md)\n * // (button.tsx itself is a file, so its parent dir is the last one checked)\n */\nexport function findAncestorAgents(\n target: string,\n projectRoot: string = process.cwd()\n): AncestorAgent[] {\n const absRoot = resolve(projectRoot)\n const absTarget = resolveAgainstRoot(target, absRoot)\n\n // Validate that the target lives within the project root\n const relToRoot = relative(absRoot, absTarget)\n if (relToRoot.startsWith('..') || isAbsolute(relToRoot)) {\n throw new Error(\n `Target \"${target}\" is outside the project root \"${absRoot}\". ` +\n `findAncestorAgents only handles paths within the project.`\n )\n }\n\n // Collect every directory from the target up to the root, in root-first order.\n // For a file target, we only look at the directory chain (not the file itself).\n // For a directory target, the directory itself is included as the last entry.\n const targetDir = isDirectory(absTarget) ? absTarget : dirname(absTarget)\n const dirs = collectAncestorDirs(targetDir, absRoot)\n\n const result: AncestorAgent[] = []\n for (const dir of dirs) {\n const agentPath = join(dir, AGENT_FILE)\n if (existsSync(agentPath)) {\n result.push({\n dir,\n path: agentPath,\n relativeDir: relativeDir(dir, absRoot),\n })\n }\n }\n\n return result\n}\n\n/**\n * Resolve a target path against the project root. Accepts absolute paths\n * (returned as-is) and project-relative paths (joined with the root).\n */\nfunction resolveAgainstRoot(target: string, absRoot: string): string {\n if (isAbsolute(target)) return target\n return join(absRoot, target)\n}\n\n/**\n * Return the directory chain from a starting directory up to (and including)\n * the project root, in root-first order. The chain is computed by walking\n * the relative path segments from the starting dir back to the root.\n */\nfunction collectAncestorDirs(startDir: string, absRoot: string): string[] {\n const rel = relative(absRoot, startDir)\n if (rel === '' || rel === '.') {\n return [absRoot]\n }\n\n const segments = rel.split(sep).filter(s => s !== '' && s !== '.')\n const chain: string[] = [absRoot]\n let acc = absRoot\n for (const seg of segments) {\n acc = join(acc, seg)\n chain.push(acc)\n }\n return chain\n}\n\n/**\n * Compute the directory's path relative to the project root, in a form\n * suitable for display. The root itself is rendered as \".\".\n */\nfunction relativeDir(dir: string, absRoot: string): string {\n const rel = relative(absRoot, dir)\n return rel === '' ? '.' : rel\n}\n\nfunction isDirectory(p: string): boolean {\n try {\n return statSync(p).isDirectory()\n } catch {\n return false\n }\n}\n","import yaml from 'js-yaml'\nimport type { AgentContext, AgentSection } from '../types'\n\nexport class AgentParser {\n /**\n * Parse an AGENT.md content into a structured AgentContext\n */\n static parse(markdown: string): AgentContext {\n let content = markdown\n let metadata: Record<string, any> = {}\n\n // Parse Frontmatter\n const frontmatterRegex = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---/\n const match = markdown.match(frontmatterRegex)\n if (match) {\n try {\n metadata = yaml.load(match[1] as string) as Record<string, any>\n content = markdown.slice(match[0].length).trim()\n } catch (e) {\n console.error('Failed to parse Agent frontmatter:', e)\n }\n }\n\n const lines = content.split(/\\r?\\n/)\n const sections: AgentSection[] = []\n let title = metadata.name ?? 'Unknown Agent'\n let currentSection: AgentSection | null = null\n let currentContent: string[] = []\n\n for (const line of lines) {\n // Parse Title (Only if not already set by frontmatter)\n if (line.startsWith('# ') && !metadata.name) {\n const rawTitle = line.replace('# ', '').trim()\n // Handle \"AGENT CONTEXT: [Name]\" format\n if (rawTitle.toUpperCase().startsWith('AGENT CONTEXT:')) {\n title = rawTitle\n .slice(14)\n .replace(/^[:\\s-]+/, '')\n .trim()\n } else {\n title = rawTitle\n }\n continue\n }\n\n // Parse Sections\n if (line.startsWith('## ')) {\n // Save previous section\n if (currentSection) {\n currentSection.content = currentContent.join('\\n').trim()\n sections.push(currentSection)\n }\n\n currentSection = {\n title: line.replace('## ', '').trim(),\n content: '',\n }\n currentContent = []\n continue\n }\n\n // Collect content\n if (currentSection) {\n currentContent.push(line)\n }\n }\n\n // Save last section\n if (currentSection) {\n currentSection.content = currentContent.join('\\n').trim()\n sections.push(currentSection)\n }\n\n return {\n title,\n sections,\n metadata,\n }\n }\n}\n","import { existsSync } from 'node:fs'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\n\nimport { AUTONOMOS_DIR } from '../constants'\n\n/**\n * Markers that identify the root of an Autonomos / git project.\n *\n * `.autonomos/` is a strong signal: if it exists, the project has already\n * been initialized with the protocol and the directory containing it is,\n * by definition, the project root.\n *\n * `.git/` is a weaker signal: it only tells us the directory is inside a\n * git working tree. We still stop at the first `.git/` we see, which is\n * good enough for the common monorepo case (the monorepo root contains\n * the `.git/`, package subdirectories do not).\n */\nconst PROJECT_MARKERS = [AUTONOMOS_DIR, '.git'] as const\n\n/**\n * Find the directory that owns this project by walking up from `startDir`\n * until we find a directory containing `.autonomos/` or `.git/`.\n *\n * Returns `null` if no such directory exists before we reach the\n * filesystem root.\n *\n * Notes on behavior:\n * - The search stops at the first directory that contains any of the\n * markers. For monorepos this is the monorepo root, not the package\n * directory the caller is sitting in.\n * - A directory containing `.git/` is preferred over walking further up:\n * this prevents leaking into a parent repository in nested-worktree\n * setups. Callers that need the absolute git toplevel can run\n * `git rev-parse --show-toplevel` themselves after this returns.\n *\n * @param startDir - Absolute path to start the search from.\n */\nexport function findProjectRoot(startDir: string): string | null {\n if (!startDir) return null\n const start = resolve(startDir)\n let current = start\n\n while (true) {\n if (PROJECT_MARKERS.some(marker => existsSync(join(current, marker)))) {\n return current\n }\n const parent = dirname(current)\n if (parent === current) return null\n current = parent\n }\n}\n\n/**\n * Check whether two absolute paths refer to the same directory.\n *\n * Resolves `.` / `..` segments before comparing, so `/a/b` and\n * `/a/b/./` are considered the same.\n */\nexport function isSamePath(a: string, b: string): boolean {\n if (!a || !b) return false\n return resolve(a) === resolve(b)\n}\n\n/**\n * Render a path relative to another path, with one guarantee that the\n * default `path.relative` doesn't give us: we never return a value that\n * starts with `..`. If `target` is not under `base`, we return the\n * absolute resolved path of `target` so the caller can still show a\n * useful location.\n */\nexport function displayRelative(target: string, base: string): string {\n const rel = relative(base, target)\n if (rel === '' || rel === '.') return '.'\n if (rel.startsWith(`..${sep}`) || rel === '..' || isAbsolute(rel)) {\n return resolve(target)\n }\n return rel\n}\n","import type { Complexity, Priority, Task, TaskStatus } from '../types'\n\nexport class TaskParser {\n static parse(markdown: string): Task[] {\n const tasks: Task[] = []\n const lines = markdown.split(/\\r?\\n/)\n const taskRegex = /- \\[([ x/!])\\] \\*\\*\\[(.+)\\]\\*\\* (.+) `Priority: (.+)` `Complexity: (.+)`/\n\n for (const line of lines) {\n const match = line.match(taskRegex)\n if (match) {\n const [, statusChar = ' ', id = '', title = '', priority = '', complexity = ''] =\n match\n tasks.push({\n id,\n title: title.trim(),\n priority: priority as Priority,\n complexity: complexity as Complexity,\n status: this.mapStatus(statusChar),\n })\n }\n }\n return tasks\n }\n\n private static mapStatus(char: string): TaskStatus {\n switch (char) {\n case ' ':\n return 'TODO'\n case '/':\n return 'IN_PROGRESS'\n case 'x':\n return 'DONE'\n case '!':\n return 'BLOCKED'\n default:\n return 'TODO'\n }\n }\n}\n","","import harnessCodesData from './data/harness-codes.json' with { type: 'json' }\nimport {\n HarnessCodesSchema,\n type Harness,\n type HarnessCodes,\n type Installer,\n} from './schemas/harness-codes'\n\n/**\n * Validated, in-memory representation of the harness codes config.\n * Loaded once at module init, validated via Zod.\n */\nconst codes: HarnessCodes = HarnessCodesSchema.parse(harnessCodesData)\n\n/**\n * Get a single harness entry by its id.\n * Throws if the id is unknown.\n */\nexport function getHarness(id: string): Harness {\n const entry = codes.platforms[id]\n if (!entry) {\n const known = Object.keys(codes.platforms).join(', ')\n throw new Error(`Unknown harness: \"${id}\". Known harnesses: ${known}`)\n }\n return entry\n}\n\n/**\n * List all configured harnesses, as an array of {id, harness} pairs.\n * Stable order: insertion order of the JSON object.\n */\nexport function listHarnesses(): Array<{ id: string; harness: Harness }> {\n return Object.entries(codes.platforms).map(([id, harness]) => ({ id, harness }))\n}\n\n/**\n * Get the list of preferred harnesses (shown as recommended options).\n */\nexport function listPreferredHarnesses(): Array<{ id: string; harness: Harness }> {\n return listHarnesses().filter(({ harness }) => harness.preferred)\n}\n\n/**\n * A resolved target directory where workflow files will be written.\n * One per unique path, with the list of harness ids that share it.\n */\nexport interface ResolvedTarget {\n /** Absolute or project-relative path to the directory */\n path: string\n /** File extension to use (e.g. \".md\", \".agent.md\") */\n fileExtension: string\n /** Ids of the harnesses that will read from this directory */\n usedBy: string[]\n}\n\n/**\n * Resolve the unique target directories for a set of harness ids.\n *\n * Harnesses that share the same `skillsDir` (e.g. Codex, OpenCode, KiloCode\n * all use `.agents/skills/`) are deduplicated: the directory appears once\n * in the output, with all the harness ids listed in `usedBy`.\n *\n * The `path` is returned relative to the project root (caller is responsible\n * for joining with the project cwd).\n */\nexport function resolveTargets(harnessIds: string[], cwd: string = '.'): ResolvedTarget[] {\n const map = new Map<string, ResolvedTarget>()\n\n for (const id of harnessIds) {\n const { installer } = getHarness(id)\n collectFromInstaller(map, installer, id, cwd)\n }\n\n return Array.from(map.values())\n}\n\nfunction collectFromInstaller(\n map: Map<string, ResolvedTarget>,\n installer: Installer,\n harnessId: string,\n cwd: string\n): void {\n const ext = installer.fileExtension\n if (installer.workflowsDir) {\n addTarget(map, joinPath(cwd, installer.workflowsDir), ext, harnessId)\n } else if (installer.targetDir) {\n addTarget(map, joinPath(cwd, installer.targetDir), ext, harnessId)\n } else if (installer.skillsDir) {\n addTarget(map, joinPath(cwd, installer.skillsDir), ext, harnessId)\n }\n if (installer.commandsDir) {\n addTarget(map, joinPath(cwd, installer.commandsDir), ext, harnessId)\n }\n}\n\nfunction addTarget(\n map: Map<string, ResolvedTarget>,\n path: string,\n fileExtension: string,\n harnessId: string\n): void {\n const existing = map.get(path)\n if (existing) {\n if (!existing.usedBy.includes(harnessId)) {\n existing.usedBy.push(harnessId)\n }\n } else {\n map.set(path, { path, fileExtension, usedBy: [harnessId] })\n }\n}\n\nfunction joinPath(a: string, b: string): string {\n if (a === '.' || a === '') return b\n if (b.startsWith('/')) return `${a}${b}`\n return `${a}/${b}`\n}\n\n/**\n * Get the raw (validated) codes object, for advanced use cases.\n * Most callers should use the higher-level helpers above.\n */\nexport function getRawHarnessCodes(): HarnessCodes {\n return codes\n}\n"],"mappings":"oMAIA,MAAa,EAAmB,cAKnB,EAAgB,aAKhB,EAAgB,gBAKhB,EAAgB,cAKhB,EAAa,WAKb,EAAa,WAKb,EAAe,WCpBf,EAAkB,EAC1B,OAAO,CACJ,aAAc,EAAE,OAAO,CAAC,CAAC,SAAS,EAClC,UAAW,EAAE,OAAO,CAAC,CAAC,SAAS,EAC/B,UAAW,EAAE,OAAO,CAAC,CAAC,SAAS,EAC/B,YAAa,EAAE,OAAO,CAAC,CAAC,SAAS,EACjC,gBAAiB,EAAE,OAAO,CAAC,CAAC,SAAS,EACrC,cAAe,EAAE,OAAO,CAC5B,CAAC,CAAC,CACD,OACG,GAAQ,EAAQ,EAAK,cAAiB,EAAQ,EAAK,WAAc,EAA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AAO,MAAM,KAAK,EAAI,OAAO,CAAC,CAClC,CAEA,SAAS,EACL,EACA,EACA,EACA,EACI,CACJ,IAAM,EAAM,EAAU,cAClB,EAAU,aACV,EAAU,EAAK,EAAS,EAAK,EAAU,YAAY,EAAG,EAAK,CAAS,EAC7D,EAAU,UACjB,EAAU,EAAK,EAAS,EAAK,EAAU,SAAS,EAAG,EAAK,CAAS,EAC1D,EAAU,WACjB,EAAU,EAAK,EAAS,EAAK,EAAU,SAAS,EAAG,EAAK,CAAS,EAEjE,EAAU,aACV,EAAU,EAAK,EAAS,EAAK,EAAU,WAAW,EAAG,EAAK,CAAS,CAE3E,CAEA,SAAS,EACL,EACA,EACA,EACA,EACI,CACJ,IAAM,EAAW,EAAI,IAAI,CAAI,EACzB,EACK,EAAS,OAAO,SAAS,CAAS,GACnC,EAAS,OAAO,KAAK,CAAS,EAGlC,EAAI,IAAI,EAAM,CAAE,OAAM,gBAAe,OAAQ,CAAC,CAAS,CAAE,CAAC,CAElE,CAEA,SAAS,EAAS,EAAW,EAAmB,CAG5C,OAFI,IAAM,KAAO,IAAM,GAAW,EAC9B,EAAE,WAAW,GAAG,EAAU,GAAG,IAAI,IAC9B,GAAG,EAAE,GAAG,GACnB,CAMA,SAAgB,IAAmC,CAC/C,OAAO,CACX"}
@@ -1,48 +1,39 @@
1
1
  ---
2
2
  name: protocol-crystallize
3
- description: 'Mandatory close-out procedure for any session. Invoked before declaring the session done. Forces the agent to crystallize learnings into AGENT.md files.'
3
+ description: 'Mandatory close-out before ending a session. Forces durable knowledge capture.'
4
4
  ---
5
5
 
6
- # Protocol Crystallize
6
+ # /crystallize — End session
7
7
 
8
- **Goal:** Convert session activity into durable project knowledge.
9
- **Your Role:** Reflective agent that improves the project for the next session.
10
-
11
- ## STEP 0 — STOP
12
-
13
- DO NOT close the session before every step below is complete.
8
+ > **CRITICAL:** You MUST NOT ask the user what to crystallize. This is YOUR job. Reflect, decide, write. Then inform the user what you saved.
14
9
 
15
10
  ## STEP 1 — Worklog
16
11
 
17
- Create or complete `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md`. Free format, but MUST contain:
18
-
19
- - A summary of what was done
20
- - The technical decisions made and why
21
- - The files modified
22
- - Clear next steps (for the next session)
23
-
24
- ## STEP 2 — Crystallize into AGENT.md files
25
-
26
- Ask yourself these three questions. For each, you MUST answer honestly. Do NOT say "nothing new".
12
+ Create `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md` containing:
27
13
 
28
- **Question 1:** `What did I learn of significance about this project during this session?` (preferences, constraints, discovered conventions, user corrections, etc.)
14
+ - What was done
15
+ - Key decisions and why
16
+ - Files modified
17
+ - Next steps for the next session
29
18
 
30
- If the answer is not `nothing`, write it to the relevant AGENT.md (root or subfolder). No format is imposed. One line is enough if it is clear.
19
+ ## STEP 2 — Crystallize into AGENT.md
31
20
 
32
- **Question 2:** `Has any AGENT.md entry been contradicted or superseded?` If yes, update the relevant AGENT.md entry **in place** — the file is a current-state document, not a changelog. Then record the change in the worklog of this session (e.g. `PREF-007: GSAP → Motion, superseded by PREF-009`). Do NOT append superseded entries to AGENT.md; do NOT keep both.
21
+ Ask yourself silently — do NOT ask the user:
33
22
 
34
- **Question 3:** `Is there something in the worklog that should have been in an AGENT.md and is not yet?` If yes, lift it out of the worklog and put it in the AGENT.md.
23
+ 1. **What did I learn?** (preferences, constraints, conventions, corrections) → Write to the relevant AGENT.md.
24
+ 2. **Is any AGENT.md entry now wrong?** → Replace in place, log the change in the worklog.
25
+ 3. **Should a new local AGENT.md exist?** (worked in a folder with >5 files and no AGENT.md) → Create one, free format.
35
26
 
36
27
  ## STEP 3 — Task status
37
28
 
38
- Mark the task as `[x]` (or `[!]` if blocked) in `.autonomos/TASKS.md`.
29
+ Mark the task `[x]` (or `[!]` if blocked) in `.autonomos/TASKS.md`.
39
30
 
40
- ## STEP 4 — Final verification
31
+ ## STEP 4 — Report
41
32
 
42
- RESPOND to the user with:
33
+ RESPOND with exactly:
43
34
 
44
35
  - `Task: [x] / [!] — [ID]`
45
- - `Worklog created: .autonomos/worklogs/...`
46
- - `AGENT.md updated: [yes / no, and why]`
36
+ - `Worklog: .autonomos/worklogs/...`
37
+ - `AGENT.md updated: [yes / no — reason]`
47
38
 
48
- If you cannot produce these three lines, the session is not complete. Resume from Step 1.
39
+ If you cannot produce these 3 lines, resume from Step 1.
@@ -1,50 +1,32 @@
1
1
  ---
2
2
  name: protocol-session
3
- description: 'Mandatory bootstrap for any new session on a project following the Autonomos protocol. Invoked at the start of every session, before any work begins.'
3
+ description: 'Mandatory bootstrap for any new session. Invoke before any work begins.'
4
4
  ---
5
5
 
6
- # Protocol Session
6
+ # /session — Start
7
7
 
8
- **Goal:** Load all project context, identify the next task, and establish a clean working state.
9
- **Your Role:** Disciplined agent that respects the project's accumulated knowledge.
8
+ **You MUST complete Steps 1–3 before writing any code.**
10
9
 
11
- ## STEP 0 — STOP
10
+ ## STEP 1 — Load context
12
11
 
13
- You are starting a new session. You MUST complete Steps 1, 2, and 3 before any other action.
12
+ 1. Run `find . -name AGENT.md -not -path '*/node_modules/*'` and read every file found, root-first.
13
+ 2. Read the most recent file in `.autonomos/worklogs/` (if any).
14
+ 3. Read `.autonomos/TASKS.md`.
14
15
 
15
- DO NOT skip steps. DO NOT begin work before Step 3 is complete.
16
+ RESPOND with a **3-line max** summary of what you retained. Do not continue without this response.
16
17
 
17
- ## STEP 1 — Load context (three mandatory reads)
18
+ ## STEP 2 — Select task
18
19
 
19
- 1. Read the root `AGENT.md`. This is your project identity.
20
- 2. Run `autonomos agents` (no argument) to get the **full tree of all AGENT.md files in the project**. Read each one. This is your full fractal context — it lets you discover shared packages, cross-cutting conventions, and traps before starting any work.
21
- 3. Read the most recent file in `.autonomos/worklogs/`. This is the memory of the previous session — read it to avoid repeating the same mistakes.
20
+ Pick the highest-priority task not marked `[x]` or `[!]`. If none, ask the user.
22
21
 
23
- RESPOND to the user with a 5-line maximum summary of what you have retained. You are FORBIDDEN to continue without this response.
22
+ RESPOND: `Task: [ID] — [title]. Starting.`
24
23
 
25
- ## STEP 2 — Identify the next task
24
+ ## STEP 3 — Mark and begin
26
25
 
27
- Open `.autonomos/TASKS.md`. Identify the highest-priority task that is not yet `[x]`. If none qualify, ask the user what to work on.
26
+ Set the task to `[/]` in `.autonomos/TASKS.md`. Now you may work.
28
27
 
29
- RESPOND with: `Task selected: [ID] — [title]. Starting.`
28
+ ## Session rules (apply until session ends)
30
29
 
31
- ## STEP 3 — Mark the task and begin
32
-
33
- - Edit `.autonomos/TASKS.md` to change this task's status from `[ ]` to `[/]`.
34
- - NOW you may begin working.
35
-
36
- ## REMINDER — applies to the entire session
37
-
38
- - **RAPPEL 1:** For every non-trivial decision (library choice, naming, structure, framework), STOP and ask: "Does an AGENT.md say something about this?" If yes, apply it. If no, propose the decision to the user.
39
- - **RAPPEL 2:** Every time you learn something important (the user corrects you, you discover a convention, you make a technical choice), STOP. Write it immediately to an AGENT.md (root or subfolder, depending on scope). Do NOT say "I'll note it later". It is NOW.
40
- - **RAPPEL 3:** No format is imposed on AGENT.md content. One line is enough if it's clear. What matters is that the next session can use it.
41
-
42
- ## FINAL STEP (MANDATORY before saying "session done")
43
-
44
- You CANNOT end a session without all three of the following. DO NOT say "done" until each box is checked.
45
-
46
- - [ ] Task status in TASKS.md is `[x]` (or `[!]` if blocked)
47
- - [ ] A worklog exists at `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md` containing: what was done, decisions made, files modified, and clear next steps
48
- - [ ] You have asked the user the following question and recorded the answer in the worklog: `What did this session learn about this project that deserves to live in an AGENT.md?`
49
-
50
- When all three boxes are checked, you may say `session complete`.
30
+ 1. **Before every non-trivial decision:** check if an AGENT.md says something about it.
31
+ 2. **Every time you learn something new** (user correction, discovered convention, technical choice): write it to the relevant AGENT.md **now**, not later.
32
+ 3. **When the session ends:** invoke the `/crystallize` workflow. You cannot close without it.
@@ -1,37 +1,31 @@
1
1
  ---
2
2
  name: protocol-task
3
- description: 'Mandatory procedure for starting a new task within an active session. Invoked at task start, before any code is touched.'
3
+ description: 'Mandatory procedure before starting a new task. Invoke before touching code.'
4
4
  ---
5
5
 
6
- # Protocol Task
6
+ # /task — Begin a task
7
7
 
8
- **Goal:** Confirm context, declare intent, and avoid scope drift.
9
- **Your Role:** Disciplined agent that respects local conventions.
8
+ **Do NOT touch code before Step 2 is done.**
10
9
 
11
- ## STEP 0 — STOP
10
+ ## STEP 1 — Build fractal context
12
11
 
13
- You are about to begin a new task. DO NOT touch code before the end of Step 2.
12
+ 1. From the target file/folder, walk up to the project root. Read every `AGENT.md` you find on that path (root → target).
13
+ 2. If no local `AGENT.md` exists at the target and you have worked in that folder before, propose creating one.
14
14
 
15
- ## STEP 1 — Build the precise fractal context for this task
15
+ ## STEP 2 — Declare plan
16
16
 
17
- 1. Run `autonomos agents <path-to-target-file-or-folder>` to get the **ordered list of ancestor AGENT.md files** for the file or folder you'll be working in. The output is root-first; non-existent ancestors are silently skipped.
18
- 2. Read each returned AGENT.md **in order** (root → target). This is your precise fractal context for this task.
19
- 3. If no local `AGENT.md` exists at the target AND you have worked in that folder multiple times before, propose to the user: `This folder has no AGENT.md yet. Should we create one to crystallize the conventions we have established here?`
20
-
21
- ## STEP 2 — Declare the plan
22
-
23
- State in 3 to 5 steps what you intend to do for this task. No more. The user must be able to say `OK` or adjust before you begin.
17
+ State in 3–5 steps what you will do. The user must be able to say OK or adjust.
24
18
 
25
19
  ## STEP 3 — Execute
26
20
 
27
- Mark the task `[/]` in TASKS.md, then execute your plan.
21
+ Mark the task `[/]` in `.autonomos/TASKS.md`, then work.
28
22
 
29
- ## DURING EXECUTION — three reminders
23
+ ## During execution
30
24
 
31
- - **REMINDER 1:** For every non-trivial decision, consult the relevant AGENT.md.
32
- - **REMINDER 2:** For every new learning, append a new line to an AGENT.md. If the new learning contradicts an existing one, replace the old entry in place and log the change in the worklog. AGENT.md stays a sharp current-state document, not a log.
33
- - **REMINDER 3:** You may edit any AGENT.md at any time. No format is imposed. What matters is that the next session can use it.
25
+ 1. **Before every non-trivial decision:** consult the relevant AGENT.md.
26
+ 2. **Every new learning:** append to an AGENT.md immediately. If it contradicts an existing entry, replace in place and note the change in the worklog.
27
+ 3. **Root AGENT.md** uses the structured template. **Local AGENT.md** files are free format — one line is enough.
34
28
 
35
- ## END OF TASK
29
+ ## End of task
36
30
 
37
- When the task is complete, mark it `[x]` in TASKS.md and invoke the `protocol-crystallize` workflow.
31
+ Mark `[x]` in TASKS.md. Invoke `/crystallize`.
@@ -0,0 +1,157 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { describe, expect, it } from 'vitest'
4
+ import { PROTOCOL_TEMPLATE } from '../templates/protocol'
5
+
6
+ /**
7
+ * Validates the content of all workflow files and the PROTOCOL_TEMPLATE.
8
+ * These tests guard against regressions on the v0.3 design:
9
+ * - No crystallization questions directed at the user
10
+ * - No duplicated close-out procedures in session.md
11
+ * - find-based AGENT.md discovery (no CLI dependency in workflows)
12
+ * - Consistent AGENT.md format rules
13
+ * - Workflows are short enough to fit in LLM working memory
14
+ */
15
+
16
+ function loadWorkflow(name: string): string {
17
+ return readFileSync(join(import.meta.dirname, name), 'utf-8')
18
+ }
19
+
20
+ const session = loadWorkflow('protocol-session.md')
21
+ const crystallize = loadWorkflow('protocol-crystallize.md')
22
+ const task = loadWorkflow('protocol-task.md')
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // 1. Crystallization — agent-directed, never asks the user
26
+ // ---------------------------------------------------------------------------
27
+ describe('crystallize.md — self-directed crystallization', () => {
28
+ it('contains the MUST NOT ask the user rule', () => {
29
+ expect(crystallize).toContain('MUST NOT ask the user what to crystallize')
30
+ })
31
+
32
+ it('directs the agent to ask itself', () => {
33
+ expect(crystallize).toContain('Ask yourself silently')
34
+ })
35
+
36
+ it('does not contain a user-questioning pattern', () => {
37
+ const lower = crystallize.toLowerCase()
38
+ expect(lower).not.toMatch(/ask\s+the\s+user.*what.*learn/i)
39
+ })
40
+ })
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // 2. Session.md — no duplicated close-out, defers to crystallize
44
+ // ---------------------------------------------------------------------------
45
+ describe('session.md — clean separation of concerns', () => {
46
+ it('does not contain "FINAL STEP"', () => {
47
+ expect(session).not.toContain('FINAL STEP')
48
+ })
49
+
50
+ it('does not ask the user what to crystallize', () => {
51
+ const lower = session.toLowerCase()
52
+ expect(lower).not.toMatch(/ask(?:ed)?\s+the\s+user.*learn/i)
53
+ expect(lower).not.toMatch(/what did this session learn/i)
54
+ })
55
+
56
+ it('points to /crystallize for session close-out', () => {
57
+ expect(session).toContain('/crystallize')
58
+ })
59
+
60
+ it('does not duplicate worklog creation logic', () => {
61
+ expect(session).not.toMatch(/- \[ \] A worklog exists/)
62
+ })
63
+ })
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // 3. AGENT.md discovery — find-based, no CLI dependency
67
+ // ---------------------------------------------------------------------------
68
+ describe('AGENT.md discovery — universal method', () => {
69
+ it('session.md uses find as primary method', () => {
70
+ expect(session).toContain('find . -name AGENT.md')
71
+ })
72
+
73
+ it('task.md uses directory walk, not CLI', () => {
74
+ // task.md should instruct walking up the directory tree
75
+ expect(task).toContain('walk up')
76
+ // Should NOT require autonomos CLI as a mandatory step
77
+ expect(task).not.toContain('npx --yes @autonomos/cli')
78
+ })
79
+ })
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // 4. AGENT.md format rules — root vs local distinction
83
+ // ---------------------------------------------------------------------------
84
+ describe('AGENT.md format rules — consistent across files', () => {
85
+ it('session.md does not impose format on local AGENT.md', () => {
86
+ // Session rules should mention AGENT.md but not impose root template everywhere
87
+ expect(session).toContain('AGENT.md')
88
+ })
89
+
90
+ it('task.md clarifies root vs local format', () => {
91
+ expect(task).toContain('Root AGENT.md')
92
+ expect(task).toContain('free format')
93
+ })
94
+
95
+ it('crystallize.md allows free format for local files', () => {
96
+ expect(crystallize).toContain('free format')
97
+ })
98
+
99
+ it('PROTOCOL_TEMPLATE has explicit format rules section', () => {
100
+ expect(PROTOCOL_TEMPLATE).toContain('Format Rules')
101
+ })
102
+ })
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // 5. PROTOCOL_TEMPLATE — compact reference, no workflow duplication
106
+ // ---------------------------------------------------------------------------
107
+ describe('PROTOCOL_TEMPLATE — v0.3 design', () => {
108
+ it('does not contain Phase 1/2/3 workflow steps', () => {
109
+ expect(PROTOCOL_TEMPLATE).not.toContain('Phase 1:')
110
+ expect(PROTOCOL_TEMPLATE).not.toContain('Phase 2:')
111
+ expect(PROTOCOL_TEMPLATE).not.toContain('Phase 3:')
112
+ })
113
+
114
+ it('points to workflows as the executable contract', () => {
115
+ expect(PROTOCOL_TEMPLATE).toContain('/session')
116
+ expect(PROTOCOL_TEMPLATE).toContain('/task')
117
+ expect(PROTOCOL_TEMPLATE).toContain('/crystallize')
118
+ })
119
+
120
+ it('contains the quick reference table', () => {
121
+ expect(PROTOCOL_TEMPLATE).toContain('Quick Reference')
122
+ })
123
+
124
+ it('does not contain deprecated .ai/ paths', () => {
125
+ expect(PROTOCOL_TEMPLATE).not.toContain('.ai/')
126
+ })
127
+
128
+ it('uses .autonomos/ consistently', () => {
129
+ expect(PROTOCOL_TEMPLATE).toContain('.autonomos/TASKS.md')
130
+ expect(PROTOCOL_TEMPLATE).toContain('.autonomos/worklogs/')
131
+ })
132
+ })
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // 6. Workflow brevity — each must be concise enough for LLM working memory
136
+ // ---------------------------------------------------------------------------
137
+ describe('Workflow brevity', () => {
138
+ const maxLines = 35 // allowing some margin over the 30-line target
139
+
140
+ it(`session.md is ≤${maxLines} lines (excluding frontmatter)`, () => {
141
+ const body = session.replace(/^---[\s\S]*?---\n/, '')
142
+ const lines = body.trim().split('\n').length
143
+ expect(lines).toBeLessThanOrEqual(maxLines)
144
+ })
145
+
146
+ it(`task.md is ≤${maxLines} lines (excluding frontmatter)`, () => {
147
+ const body = task.replace(/^---[\s\S]*?---\n/, '')
148
+ const lines = body.trim().split('\n').length
149
+ expect(lines).toBeLessThanOrEqual(maxLines)
150
+ })
151
+
152
+ it(`crystallize.md is ≤${maxLines} lines (excluding frontmatter)`, () => {
153
+ const body = crystallize.replace(/^---[\s\S]*?---\n/, '')
154
+ const lines = body.trim().split('\n').length
155
+ expect(lines).toBeLessThanOrEqual(maxLines)
156
+ })
157
+ })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autonomos/core",
3
- "version": "0.1.0",
3
+ "version": "0.3.1",
4
4
  "description": "SDK and core definitions for the Agent Protocol",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.mts",