@autonomos/core 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +139 -15
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +73 -78
- package/dist/index.mjs.map +1 -1
- package/dist/workflows/protocol-crystallize.md +15 -11
- package/dist/workflows/protocol-issue.md +3 -3
- package/dist/workflows/protocol-reconcile.md +4 -2
- package/dist/workflows/protocol-session.md +3 -2
- package/dist/workflows/protocol-task.md +1 -1
- package/dist/workflows/protocol-workflows.test.ts +42 -3
- package/package.json +1 -1
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.
|
|
8
|
+
declare const PROTOCOL_VERSION = "0.8.0-alpha";
|
|
9
9
|
/**
|
|
10
10
|
* Directory name for Autonomos configuration
|
|
11
11
|
*/
|
|
@@ -40,6 +40,32 @@ declare const SPECS_DIR = "specs";
|
|
|
40
40
|
declare const DECISIONS_DIR = "decisions";
|
|
41
41
|
/** Optional project-owned history, never loaded by default. */
|
|
42
42
|
declare const ARCHIVE_DIR = "archive";
|
|
43
|
+
/**
|
|
44
|
+
* Layout version of project-owned records. Absent in a manifest means 1.
|
|
45
|
+
* Format 2: current registries hold open work only, closed records live in
|
|
46
|
+
* `archive/closed/`, and worklogs follow the proportionate shape.
|
|
47
|
+
*/
|
|
48
|
+
declare const ARTIFACT_FORMAT = 2;
|
|
49
|
+
/** Issues registry filename. */
|
|
50
|
+
declare const ISSUES_FILE = "ISSUES.md";
|
|
51
|
+
/** Append-only registries of closed tasks and issues, under the archive. */
|
|
52
|
+
declare const CLOSED_DIR = "closed";
|
|
53
|
+
/** Archive batch that receives worklogs written before artifact format 2. */
|
|
54
|
+
declare const LEGACY_WORKLOGS_DIR = "worklogs-format-1";
|
|
55
|
+
/** Archive index filename. */
|
|
56
|
+
declare const ARCHIVE_INDEX_FILE = "README.md";
|
|
57
|
+
/**
|
|
58
|
+
* Advisory size budgets (bytes or characters) reported by `autonomos status`.
|
|
59
|
+
* They keep startup and close-out context proportionate; they are not parsers.
|
|
60
|
+
*/
|
|
61
|
+
declare const CONTEXT_BUDGETS: {
|
|
62
|
+
readonly rootAgentBytes: 8000;
|
|
63
|
+
readonly localAgentBytes: 4000;
|
|
64
|
+
readonly tasksBytes: 16000;
|
|
65
|
+
readonly issuesBytes: 24000;
|
|
66
|
+
readonly taskEntryChars: 300;
|
|
67
|
+
readonly worklogBytes: 2500;
|
|
68
|
+
};
|
|
43
69
|
//#endregion
|
|
44
70
|
//#region src/schemas/harness-codes.d.ts
|
|
45
71
|
/**
|
|
@@ -303,16 +329,19 @@ declare const ManifestSchema: z.ZodObject<{
|
|
|
303
329
|
cliVersion: z.ZodString;
|
|
304
330
|
initializedAt: z.ZodString;
|
|
305
331
|
lastUpdated: z.ZodString;
|
|
332
|
+
artifactFormat: z.ZodOptional<z.ZodNumber>;
|
|
306
333
|
}, "strip", z.ZodTypeAny, {
|
|
307
334
|
protocolVersion: string;
|
|
308
335
|
cliVersion: string;
|
|
309
336
|
initializedAt: string;
|
|
310
337
|
lastUpdated: string;
|
|
338
|
+
artifactFormat?: number | undefined;
|
|
311
339
|
}, {
|
|
312
340
|
protocolVersion: string;
|
|
313
341
|
cliVersion: string;
|
|
314
342
|
initializedAt: string;
|
|
315
343
|
lastUpdated: string;
|
|
344
|
+
artifactFormat?: number | undefined;
|
|
316
345
|
}>;
|
|
317
346
|
type Manifest = z.infer<typeof ManifestSchema>;
|
|
318
347
|
//#endregion
|
|
@@ -396,22 +425,24 @@ declare function generateManifestContent(manifest: Manifest): string;
|
|
|
396
425
|
* Parses manifest.json content into a Manifest object with validation
|
|
397
426
|
*/
|
|
398
427
|
declare function parseManifest(content: string): Manifest;
|
|
428
|
+
/** Artifact format recorded by a manifest (format 1 when absent). */
|
|
429
|
+
declare function manifestArtifactFormat(manifest: Manifest): number;
|
|
399
430
|
//#endregion
|
|
400
431
|
//#region src/templates/protocol.d.ts
|
|
401
432
|
/**
|
|
402
|
-
* The Protocol kernel template — v0.
|
|
433
|
+
* The Protocol kernel template — v0.8
|
|
403
434
|
*
|
|
404
|
-
* Design principles (v0.
|
|
435
|
+
* Design principles (v0.8):
|
|
405
436
|
* - PROTOCOL.md is a compact REFERENCE, not an executable workflow.
|
|
406
437
|
* - All step-by-step instructions live in the workflow files.
|
|
407
438
|
* - No duplication between PROTOCOL.md and workflows.
|
|
408
439
|
* - Short enough that an LLM can re-scan it mid-session without cost.
|
|
409
440
|
*/
|
|
410
|
-
declare const PROTOCOL_TEMPLATE = "# AUTONOMOS PROTOCOL (v0.7.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| Triage a problem or proposal | Read the optional `/issue` workflow |\n| Adopt existing project knowledge | Read the optional `/adopt` workflow |\n| Reconcile drift and archive history | Read the `/reconcile` workflow |\n| Design or critique a surface | Read the optional `/design` workflow |\n| End a session | Read the `/crystallize` workflow |\n| Get context | Read root `AGENT.md`, then only the selected scope's ancestor chain |\n| Resolve objective | Explicit user request first; otherwise resume `[/]` or pick highest-priority `[ ]` |\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 | Durable guidance for its directory scope |\n| `TASKS.md` | `.autonomos/TASKS.md` | Current task state and optional Current direction |\n| `ISSUES.md` | `.autonomos/ISSUES.md` | Optional problem, proposal, and question intake |\n| `worklogs/` | `.autonomos/worklogs/` | Historical session evidence, not current guidance |\n| `archive/` | `.autonomos/archive/` | Optional history, searched only when justified |\n| `specs/` | `.autonomos/specs/` | Optional project-owned normative target state |\n| `decisions/` | `.autonomos/decisions/` | Optional project-owned decision records (ADRs) |\n| `DESIGN.md` | Root or target scope | Optional project-owned visual/interaction direction |\n| `PROTOCOL.md` | `.autonomos/PROTOCOL.md` | This file \u2014 read-only reference |\n| `manifest.json` | `.autonomos/manifest.json` | Protocol version metadata |\n\n## Design Direction Boundary\n\n`DESIGN.md` is optional project-owned direction, not a managed protocol\nartifact. Use `/design` when a surface needs direction, critique, or\ndesign-knowledge extraction; keep the project's identity and examples local.\nThe workflow supplies routing and evidence rules, not a universal visual style.\n\n## AGENT.md Format Rules\n\nStore only stable guidance that will affect different future tasks. Keep transient evidence in worklogs and operational explanations in component documentation. Use the narrowest applicable `AGENT.md`; consolidate or replace obsolete entries instead of appending history. Preserve valid subclaims in mixed paragraphs. Check the resulting text for completed-action narratives, task progress and unsupported prohibitions; these do not belong in operating guidance.\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\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## Issue, Specification, Decision, and Task Rules\n\nIssues describe evidence, impact, and a desired outcome without choosing implementation; proposed directions remain hypotheses until an approach is accepted. Specifications describe accepted target behavior or requirements that may guide multiple tasks. A decision record (commonly ADR, Architecture Decision Record) captures one technical choice and its rationale. Tasks describe an accepted intervention and completion criteria. Use optional `ISSUES.md`, `specs/`, and `decisions/` only when they provide value; direct, clear changes may become tasks immediately. Link related issues, specs, decisions, and tasks in both directions.\n\n## Specification and Decision Rules\n\n- `.autonomos/specs/` and `.autonomos/decisions/` are optional, project-owned, first-use directories; `init`, `update`, and artifact-integrity checks do not create or overwrite them.\n- Keep one Markdown file per bounded specification or decision. Include status, scope, provenance, acceptance criteria or consequences, and replacement links where relevant; no parser or independent version is required initially.\n- Specification status is `draft`, `accepted`, or `superseded`. Only `accepted` is normative; `superseded` points to its successor. Acceptance does not mean implementation is complete.\n- Decision records use `proposed`, `accepted`, or `superseded`; they preserve rationale and alternatives rather than duplicating the full specification.\n- Keep stable agent operating rules in `AGENT.md`, user/developer reference in `docs/`, execution state in `TASKS.md`, and historical evidence in `worklogs/`.\n- Read only relevant accepted records at task start. Use `/adopt` to extract legacy knowledge; never rewrite historical worklogs, issues, or tasks to create current artifacts.\n\nThe protocol-facing name is **decision record**. **ADR** (Architecture Decision Record) is a common convention for the same kind of document, not a required external standard. Use these lightweight Markdown shapes as a starting point; they are conventions, not parser-enforced schemas:\n\n```markdown\n# SPEC-001 \u2014 Concise target-state title\n\n- Status: draft | accepted | superseded\n- Scope: component, capability, or boundary\n- Provenance: issue, discussion, or source links\n- Related decisions: ADR-001, ...\n- Superseded by: SPEC-002 (when applicable)\n\n## Intent\n\n## Requirements\n\n## Acceptance criteria\n\n## Out of scope\n```\n\n```markdown\n# ADR-001 \u2014 Concise decision title\n\n- Status: proposed | accepted | superseded\n- Scope: component or technical boundary\n- Provenance: issue, task, or investigation links\n- Related specs: SPEC-001, ...\n- Superseded by: ADR-002 (when applicable)\n\n## Context\n\n## Decision\n\n## Alternatives considered\n\n## Consequences\n```\n\nOnly user/project governance accepts a specification or decision as normative. Agents may draft and link records, but must not silently promote them; acceptance is separate from implementation completion.\n\n## Current Context and Archival Lifecycle\n\n- Current context must support ordinary work without archives. Keep applicable guidance, accepted requirements/decisions, unresolved work, dependencies and necessary next actions discoverable. Acceptance is independent of implementation; dated temporary directives remain active until lifted or their stated end condition is met.\n- A completed task or resolved/declined issue is an archival candidate only when its own scope is settled and still-needed outcomes/constraints/references are retained in current context. Explicitly abandoned work may be archived with its reason, without claiming it was completed. A completed child does not satisfy unmet parent acceptance criteria.\n- Record new task completion dates as `Completed: YYYY-MM-DD`; do not infer missing old dates from worklog filenames. Age, a checkbox, absent code or a newer statement alone is not proof of obsolescence.\n- Group archival at coherent completed-work boundaries, not per task or calendar interval. No Sprint object or scheduled maintenance is required. Correct certain in-scope drift proactively during normal work; use `/reconcile` for investigation, consolidation and archival.\n- Before moving history, consolidate current knowledge in its existing narrowest home. Optional `Current direction` in `TASKS.md` explains present aims, recent consequential outcomes and next work; rewrite it rather than append chronology. Keep progress out of `AGENT.md`.\n- Create project-owned `.autonomos/archive/README.md` and meaningful batch directories on first use only. A batch can contain `TASKS.md`, `ISSUES.md`, `worklogs/` and provenance for retired guidance. Group/split batches by useful scope; there is no fixed age, size or mandatory per-record schema.\n- Archive means move, not delete or rewrite conclusions. Preserve historical record content, identifiers and provenance; repair relative paths when necessary. Preserve original mixed-source text when retiring only some claims. Applicable specs/decisions stay current independently of execution records. Extraction into new normative artifacts still uses `/adopt`.\n- The archive index maps batch topics to records, not a second task journal. Search by ID or subject only when a specific question requires history; neither archives nor their entire index are routine startup context. Keep only necessary dependency/outcome pointers in current records, not a permanent stub for every completed task.\n- Archived task and issue IDs remain reserved. Before assigning an ID, search current and archived registries. With a CLI, `readTaskRegistry(root, { history: true })` exposes task references and duplicates; plain Markdown search works without it.\n- Verify exact source text before edits, retained current knowledge, IDs and resolvable references after moves. Do not confuse tool annotations with file content or historical validation with a current observation. Re-read shared files before writing and preserve unrelated concurrent changes. Stop when a second pass yields no deterministic correction.\n- `autonomos status` summarizes the current task registry; `--history` adds separate archived counts and read/collision diagnostics. Archived means historical, not necessarily completed. History uses batch `TASKS.md` files, not arbitrary worklog checklists.\n- Archives are project-owned, like specs and decisions. Initialization, updates and integrity checks neither create empty archives nor overwrite, relocate or judge their contents. Installing a new protocol performs no automatic cleanup. Version-control policy stays project-owned; Git is not required for archival or retrieval.\n\nExample (only files needed by a batch are created):\n\n```text\n.autonomos/\n TASKS.md\n ISSUES.md\n archive/\n README.md\n realtime-experiment-retirement/\n TASKS.md\n ISSUES.md\n worklogs/\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";
|
|
441
|
+
declare const PROTOCOL_TEMPLATE = "# AUTONOMOS PROTOCOL (v0.8.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| Triage a problem or proposal | Read the optional `/issue` workflow |\n| Adopt existing project knowledge | Read the optional `/adopt` workflow |\n| Reconcile drift and archive history | Read the `/reconcile` workflow |\n| Design or critique a surface | Read the optional `/design` workflow |\n| End a session | Read the `/crystallize` workflow |\n| Get context | Read root `AGENT.md`, then only the selected scope's ancestor chain |\n| Resolve objective | Explicit user request first; otherwise resume `[/]` or pick highest-priority `[ ]` |\n| Log session work | Create `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md` (shape in `/crystallize`) |\n| Close finished work | `autonomos close <ID>` \u2192 `.autonomos/archive/closed/` |\n| Check context budgets | `autonomos status`; upgrade old records with `autonomos migrate` |\n\n## File Map\n\n| File | Location | Role |\n| --------------- | -------------------------- | --------------------------------------------------------------------- |\n| `AGENT.md` | Root + any subdirectory | Durable guidance for its directory scope |\n| `TASKS.md` | `.autonomos/TASKS.md` | Open tasks and optional Current direction |\n| `ISSUES.md` | `.autonomos/ISSUES.md` | Optional intake: open and accepted issues only |\n| `worklogs/` | `.autonomos/worklogs/` | Historical session evidence, not current guidance |\n| `archive/` | `.autonomos/archive/` | History (`closed/` registries, batches), searched only when justified |\n| `specs/` | `.autonomos/specs/` | Optional project-owned normative target state |\n| `decisions/` | `.autonomos/decisions/` | Optional project-owned decision records (ADRs) |\n| `DESIGN.md` | Root or target scope | Optional project-owned visual/interaction direction |\n| `PROTOCOL.md` | `.autonomos/PROTOCOL.md` | This file \u2014 read-only reference |\n| `manifest.json` | `.autonomos/manifest.json` | Protocol version and artifact format |\n\n## Design Direction Boundary\n\n`DESIGN.md` is optional project-owned direction, not a managed protocol\nartifact. Use `/design` when a surface needs direction, critique, or\ndesign-knowledge extraction; keep the project's identity and examples local.\nThe workflow supplies routing and evidence rules, not a universal visual style.\n\n## AGENT.md Format Rules\n\nStore only stable guidance that will affect different future tasks. Keep transient evidence in worklogs and operational explanations in component documentation. Use the narrowest applicable `AGENT.md`; consolidate or replace obsolete entries instead of appending history. Preserve valid subclaims in mixed paragraphs. Check the resulting text for completed-action narratives, task progress and unsupported prohibitions; these do not belong in operating guidance.\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\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## Issue, Specification, Decision, and Task Rules\n\nIssues describe evidence, impact, and a desired outcome without choosing implementation; proposed directions remain hypotheses until an approach is accepted. Specifications describe accepted target behavior or requirements that may guide multiple tasks. A decision record (commonly ADR, Architecture Decision Record) captures one technical choice and its rationale. Tasks describe an accepted intervention and completion criteria. Use optional `ISSUES.md`, `specs/`, and `decisions/` only when they provide value; direct, clear changes may become tasks immediately. Link related issues, specs, decisions, and tasks in both directions.\n\n## Specification and Decision Rules\n\n- `.autonomos/specs/` and `.autonomos/decisions/` are optional, project-owned, first-use directories; `init`, `update`, and artifact-integrity checks do not create or overwrite them.\n- Keep one Markdown file per bounded specification or decision. Include status, scope, provenance, acceptance criteria or consequences, and replacement links where relevant; no parser or independent version is required initially.\n- Specification status is `draft`, `accepted`, or `superseded`. Only `accepted` is normative; `superseded` points to its successor. Acceptance does not mean implementation is complete.\n- Decision records use `proposed`, `accepted`, or `superseded`; they preserve rationale and alternatives rather than duplicating the full specification.\n- Keep stable agent operating rules in `AGENT.md`, user/developer reference in `docs/`, execution state in `TASKS.md`, and historical evidence in `worklogs/`.\n- Read only relevant accepted records at task start. Use `/adopt` to extract legacy knowledge; never rewrite historical worklogs, issues, or tasks to create current artifacts.\n\nThe protocol-facing name is **decision record**. **ADR** (Architecture Decision Record) is a common convention for the same kind of document, not a required external standard. Use these lightweight Markdown shapes as a starting point; they are conventions, not parser-enforced schemas:\n\n```markdown\n# SPEC-001 \u2014 Concise target-state title\n\n- Status: draft | accepted | superseded\n- Scope: component, capability, or boundary\n- Provenance: issue, discussion, or source links\n- Related decisions: ADR-001, ...\n- Superseded by: SPEC-002 (when applicable)\n\n## Intent\n\n## Requirements\n\n## Acceptance criteria\n\n## Out of scope\n```\n\n```markdown\n# ADR-001 \u2014 Concise decision title\n\n- Status: proposed | accepted | superseded\n- Scope: component or technical boundary\n- Provenance: issue, task, or investigation links\n- Related specs: SPEC-001, ...\n- Superseded by: ADR-002 (when applicable)\n\n## Context\n\n## Decision\n\n## Alternatives considered\n\n## Consequences\n```\n\nOnly user/project governance accepts a specification or decision as normative. Agents may draft and link records, but must not silently promote them; acceptance is separate from implementation completion.\n\n## Current Context and Archival Lifecycle\n\n- Current context must support ordinary work without archives, and its size follows open work, not project age. Keep applicable guidance, accepted requirements/decisions, unresolved work, dependencies and necessary next actions discoverable. Acceptance is independent of implementation; dated temporary directives remain active until lifted or their stated end condition is met.\n- `TASKS.md` holds `[ ]`, `[/]` and `[!]` tasks; `ISSUES.md` holds open and accepted issues. When work closes, move its record in the same session to the append-only `.autonomos/archive/closed/TASKS.md` or `ISSUES.md` (`autonomos close <ID>`, or by hand). Unfinished work may be closed only as abandoned, with its reason. A completed child does not satisfy unmet parent acceptance criteria; a parent with open children stays current.\n- Record new task completion dates as `Completed: YYYY-MM-DD`; do not infer missing old dates. Age, a checkbox, absent code or a newer statement alone is not proof of obsolescence.\n- Before moving history, consolidate still-needed knowledge in its existing narrowest home. Optional `Current direction` in `TASKS.md` explains present aims, recent consequential outcomes and next work; rewrite it rather than append chronology. Keep progress out of `AGENT.md`.\n- Other history may form named batches under `.autonomos/archive/<batch>/` via `/reconcile`; create `archive/README.md` and batch directories on first use only. The index maps topics to records; it is not a second journal.\n- Archive means move, not delete or rewrite conclusions. Preserve historical record content, identifiers and provenance; repair relative paths when necessary. Applicable specs/decisions stay current independently of execution records. Extraction into new normative artifacts still uses `/adopt`.\n- Archived task and issue IDs remain reserved. Before assigning an ID, search current and archived registries (`autonomos status --history` reports duplicates).\n- Verify exact source text before edits and resolvable references after moves. Re-read shared files before writing and preserve unrelated concurrent changes.\n\n## Context Budgets\n\nAdvisory limits reported by `autonomos status` (`--strict` makes them fail): root `AGENT.md` 8,000 bytes, local `AGENT.md` 4,000 bytes, `TASKS.md` 16 KB, `ISSUES.md` 24 KB, one task entry 300 characters, one worklog 2,500 bytes, and no closed record in current registries. Over budget, consolidate or move knowledge to its narrowest home before adding more. Root `AGENT.md` admits only guidance that applies to most tasks in the project.\n\n## Artifact Format and Migration\n\n`manifest.json` records `artifactFormat` (absent means 1); this protocol defines format 2. Installing a new protocol performs no automatic cleanup: `autonomos update` only replaces managed artifacts. `autonomos migrate` is the explicit, content-preserving upgrade: it closes finished records, moves pre-format-2 worklogs to `.autonomos/archive/worklogs-format-1/` so they stop serving as examples, repairs references and records the format. Run it with `--dry-run` first on a clean working tree, then resolve the remaining `status` findings with `/reconcile`.\n\n## Task Format\n\nOne line per task: `` - [Status] **[ID]** Title `Priority` `Complexity` `` plus, when useful, `Completed: YYYY-MM-DD`, a short note and links to its issue or worklog. Evidence, measurements and progress belong in the worklog, not the task entry.\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";
|
|
411
442
|
/**
|
|
412
443
|
* @deprecated Use PROTOCOL_TEMPLATE instead
|
|
413
444
|
*/
|
|
414
|
-
declare const PROTOCOL_TEMPLATE_V2026_1 = "# AUTONOMOS PROTOCOL (v0.7.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| Triage a problem or proposal | Read the optional `/issue` workflow |\n| Adopt existing project knowledge | Read the optional `/adopt` workflow |\n| Reconcile drift and archive history | Read the `/reconcile` workflow |\n| Design or critique a surface | Read the optional `/design` workflow |\n| End a session | Read the `/crystallize` workflow |\n| Get context | Read root `AGENT.md`, then only the selected scope's ancestor chain |\n| Resolve objective | Explicit user request first; otherwise resume `[/]` or pick highest-priority `[ ]` |\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 | Durable guidance for its directory scope |\n| `TASKS.md` | `.autonomos/TASKS.md` | Current task state and optional Current direction |\n| `ISSUES.md` | `.autonomos/ISSUES.md` | Optional problem, proposal, and question intake |\n| `worklogs/` | `.autonomos/worklogs/` | Historical session evidence, not current guidance |\n| `archive/` | `.autonomos/archive/` | Optional history, searched only when justified |\n| `specs/` | `.autonomos/specs/` | Optional project-owned normative target state |\n| `decisions/` | `.autonomos/decisions/` | Optional project-owned decision records (ADRs) |\n| `DESIGN.md` | Root or target scope | Optional project-owned visual/interaction direction |\n| `PROTOCOL.md` | `.autonomos/PROTOCOL.md` | This file \u2014 read-only reference |\n| `manifest.json` | `.autonomos/manifest.json` | Protocol version metadata |\n\n## Design Direction Boundary\n\n`DESIGN.md` is optional project-owned direction, not a managed protocol\nartifact. Use `/design` when a surface needs direction, critique, or\ndesign-knowledge extraction; keep the project's identity and examples local.\nThe workflow supplies routing and evidence rules, not a universal visual style.\n\n## AGENT.md Format Rules\n\nStore only stable guidance that will affect different future tasks. Keep transient evidence in worklogs and operational explanations in component documentation. Use the narrowest applicable `AGENT.md`; consolidate or replace obsolete entries instead of appending history. Preserve valid subclaims in mixed paragraphs. Check the resulting text for completed-action narratives, task progress and unsupported prohibitions; these do not belong in operating guidance.\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\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## Issue, Specification, Decision, and Task Rules\n\nIssues describe evidence, impact, and a desired outcome without choosing implementation; proposed directions remain hypotheses until an approach is accepted. Specifications describe accepted target behavior or requirements that may guide multiple tasks. A decision record (commonly ADR, Architecture Decision Record) captures one technical choice and its rationale. Tasks describe an accepted intervention and completion criteria. Use optional `ISSUES.md`, `specs/`, and `decisions/` only when they provide value; direct, clear changes may become tasks immediately. Link related issues, specs, decisions, and tasks in both directions.\n\n## Specification and Decision Rules\n\n- `.autonomos/specs/` and `.autonomos/decisions/` are optional, project-owned, first-use directories; `init`, `update`, and artifact-integrity checks do not create or overwrite them.\n- Keep one Markdown file per bounded specification or decision. Include status, scope, provenance, acceptance criteria or consequences, and replacement links where relevant; no parser or independent version is required initially.\n- Specification status is `draft`, `accepted`, or `superseded`. Only `accepted` is normative; `superseded` points to its successor. Acceptance does not mean implementation is complete.\n- Decision records use `proposed`, `accepted`, or `superseded`; they preserve rationale and alternatives rather than duplicating the full specification.\n- Keep stable agent operating rules in `AGENT.md`, user/developer reference in `docs/`, execution state in `TASKS.md`, and historical evidence in `worklogs/`.\n- Read only relevant accepted records at task start. Use `/adopt` to extract legacy knowledge; never rewrite historical worklogs, issues, or tasks to create current artifacts.\n\nThe protocol-facing name is **decision record**. **ADR** (Architecture Decision Record) is a common convention for the same kind of document, not a required external standard. Use these lightweight Markdown shapes as a starting point; they are conventions, not parser-enforced schemas:\n\n```markdown\n# SPEC-001 \u2014 Concise target-state title\n\n- Status: draft | accepted | superseded\n- Scope: component, capability, or boundary\n- Provenance: issue, discussion, or source links\n- Related decisions: ADR-001, ...\n- Superseded by: SPEC-002 (when applicable)\n\n## Intent\n\n## Requirements\n\n## Acceptance criteria\n\n## Out of scope\n```\n\n```markdown\n# ADR-001 \u2014 Concise decision title\n\n- Status: proposed | accepted | superseded\n- Scope: component or technical boundary\n- Provenance: issue, task, or investigation links\n- Related specs: SPEC-001, ...\n- Superseded by: ADR-002 (when applicable)\n\n## Context\n\n## Decision\n\n## Alternatives considered\n\n## Consequences\n```\n\nOnly user/project governance accepts a specification or decision as normative. Agents may draft and link records, but must not silently promote them; acceptance is separate from implementation completion.\n\n## Current Context and Archival Lifecycle\n\n- Current context must support ordinary work without archives. Keep applicable guidance, accepted requirements/decisions, unresolved work, dependencies and necessary next actions discoverable. Acceptance is independent of implementation; dated temporary directives remain active until lifted or their stated end condition is met.\n- A completed task or resolved/declined issue is an archival candidate only when its own scope is settled and still-needed outcomes/constraints/references are retained in current context. Explicitly abandoned work may be archived with its reason, without claiming it was completed. A completed child does not satisfy unmet parent acceptance criteria.\n- Record new task completion dates as `Completed: YYYY-MM-DD`; do not infer missing old dates from worklog filenames. Age, a checkbox, absent code or a newer statement alone is not proof of obsolescence.\n- Group archival at coherent completed-work boundaries, not per task or calendar interval. No Sprint object or scheduled maintenance is required. Correct certain in-scope drift proactively during normal work; use `/reconcile` for investigation, consolidation and archival.\n- Before moving history, consolidate current knowledge in its existing narrowest home. Optional `Current direction` in `TASKS.md` explains present aims, recent consequential outcomes and next work; rewrite it rather than append chronology. Keep progress out of `AGENT.md`.\n- Create project-owned `.autonomos/archive/README.md` and meaningful batch directories on first use only. A batch can contain `TASKS.md`, `ISSUES.md`, `worklogs/` and provenance for retired guidance. Group/split batches by useful scope; there is no fixed age, size or mandatory per-record schema.\n- Archive means move, not delete or rewrite conclusions. Preserve historical record content, identifiers and provenance; repair relative paths when necessary. Preserve original mixed-source text when retiring only some claims. Applicable specs/decisions stay current independently of execution records. Extraction into new normative artifacts still uses `/adopt`.\n- The archive index maps batch topics to records, not a second task journal. Search by ID or subject only when a specific question requires history; neither archives nor their entire index are routine startup context. Keep only necessary dependency/outcome pointers in current records, not a permanent stub for every completed task.\n- Archived task and issue IDs remain reserved. Before assigning an ID, search current and archived registries. With a CLI, `readTaskRegistry(root, { history: true })` exposes task references and duplicates; plain Markdown search works without it.\n- Verify exact source text before edits, retained current knowledge, IDs and resolvable references after moves. Do not confuse tool annotations with file content or historical validation with a current observation. Re-read shared files before writing and preserve unrelated concurrent changes. Stop when a second pass yields no deterministic correction.\n- `autonomos status` summarizes the current task registry; `--history` adds separate archived counts and read/collision diagnostics. Archived means historical, not necessarily completed. History uses batch `TASKS.md` files, not arbitrary worklog checklists.\n- Archives are project-owned, like specs and decisions. Initialization, updates and integrity checks neither create empty archives nor overwrite, relocate or judge their contents. Installing a new protocol performs no automatic cleanup. Version-control policy stays project-owned; Git is not required for archival or retrieval.\n\nExample (only files needed by a batch are created):\n\n```text\n.autonomos/\n TASKS.md\n ISSUES.md\n archive/\n README.md\n realtime-experiment-retirement/\n TASKS.md\n ISSUES.md\n worklogs/\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";
|
|
445
|
+
declare const PROTOCOL_TEMPLATE_V2026_1 = "# AUTONOMOS PROTOCOL (v0.8.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| Triage a problem or proposal | Read the optional `/issue` workflow |\n| Adopt existing project knowledge | Read the optional `/adopt` workflow |\n| Reconcile drift and archive history | Read the `/reconcile` workflow |\n| Design or critique a surface | Read the optional `/design` workflow |\n| End a session | Read the `/crystallize` workflow |\n| Get context | Read root `AGENT.md`, then only the selected scope's ancestor chain |\n| Resolve objective | Explicit user request first; otherwise resume `[/]` or pick highest-priority `[ ]` |\n| Log session work | Create `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md` (shape in `/crystallize`) |\n| Close finished work | `autonomos close <ID>` \u2192 `.autonomos/archive/closed/` |\n| Check context budgets | `autonomos status`; upgrade old records with `autonomos migrate` |\n\n## File Map\n\n| File | Location | Role |\n| --------------- | -------------------------- | --------------------------------------------------------------------- |\n| `AGENT.md` | Root + any subdirectory | Durable guidance for its directory scope |\n| `TASKS.md` | `.autonomos/TASKS.md` | Open tasks and optional Current direction |\n| `ISSUES.md` | `.autonomos/ISSUES.md` | Optional intake: open and accepted issues only |\n| `worklogs/` | `.autonomos/worklogs/` | Historical session evidence, not current guidance |\n| `archive/` | `.autonomos/archive/` | History (`closed/` registries, batches), searched only when justified |\n| `specs/` | `.autonomos/specs/` | Optional project-owned normative target state |\n| `decisions/` | `.autonomos/decisions/` | Optional project-owned decision records (ADRs) |\n| `DESIGN.md` | Root or target scope | Optional project-owned visual/interaction direction |\n| `PROTOCOL.md` | `.autonomos/PROTOCOL.md` | This file \u2014 read-only reference |\n| `manifest.json` | `.autonomos/manifest.json` | Protocol version and artifact format |\n\n## Design Direction Boundary\n\n`DESIGN.md` is optional project-owned direction, not a managed protocol\nartifact. Use `/design` when a surface needs direction, critique, or\ndesign-knowledge extraction; keep the project's identity and examples local.\nThe workflow supplies routing and evidence rules, not a universal visual style.\n\n## AGENT.md Format Rules\n\nStore only stable guidance that will affect different future tasks. Keep transient evidence in worklogs and operational explanations in component documentation. Use the narrowest applicable `AGENT.md`; consolidate or replace obsolete entries instead of appending history. Preserve valid subclaims in mixed paragraphs. Check the resulting text for completed-action narratives, task progress and unsupported prohibitions; these do not belong in operating guidance.\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\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## Issue, Specification, Decision, and Task Rules\n\nIssues describe evidence, impact, and a desired outcome without choosing implementation; proposed directions remain hypotheses until an approach is accepted. Specifications describe accepted target behavior or requirements that may guide multiple tasks. A decision record (commonly ADR, Architecture Decision Record) captures one technical choice and its rationale. Tasks describe an accepted intervention and completion criteria. Use optional `ISSUES.md`, `specs/`, and `decisions/` only when they provide value; direct, clear changes may become tasks immediately. Link related issues, specs, decisions, and tasks in both directions.\n\n## Specification and Decision Rules\n\n- `.autonomos/specs/` and `.autonomos/decisions/` are optional, project-owned, first-use directories; `init`, `update`, and artifact-integrity checks do not create or overwrite them.\n- Keep one Markdown file per bounded specification or decision. Include status, scope, provenance, acceptance criteria or consequences, and replacement links where relevant; no parser or independent version is required initially.\n- Specification status is `draft`, `accepted`, or `superseded`. Only `accepted` is normative; `superseded` points to its successor. Acceptance does not mean implementation is complete.\n- Decision records use `proposed`, `accepted`, or `superseded`; they preserve rationale and alternatives rather than duplicating the full specification.\n- Keep stable agent operating rules in `AGENT.md`, user/developer reference in `docs/`, execution state in `TASKS.md`, and historical evidence in `worklogs/`.\n- Read only relevant accepted records at task start. Use `/adopt` to extract legacy knowledge; never rewrite historical worklogs, issues, or tasks to create current artifacts.\n\nThe protocol-facing name is **decision record**. **ADR** (Architecture Decision Record) is a common convention for the same kind of document, not a required external standard. Use these lightweight Markdown shapes as a starting point; they are conventions, not parser-enforced schemas:\n\n```markdown\n# SPEC-001 \u2014 Concise target-state title\n\n- Status: draft | accepted | superseded\n- Scope: component, capability, or boundary\n- Provenance: issue, discussion, or source links\n- Related decisions: ADR-001, ...\n- Superseded by: SPEC-002 (when applicable)\n\n## Intent\n\n## Requirements\n\n## Acceptance criteria\n\n## Out of scope\n```\n\n```markdown\n# ADR-001 \u2014 Concise decision title\n\n- Status: proposed | accepted | superseded\n- Scope: component or technical boundary\n- Provenance: issue, task, or investigation links\n- Related specs: SPEC-001, ...\n- Superseded by: ADR-002 (when applicable)\n\n## Context\n\n## Decision\n\n## Alternatives considered\n\n## Consequences\n```\n\nOnly user/project governance accepts a specification or decision as normative. Agents may draft and link records, but must not silently promote them; acceptance is separate from implementation completion.\n\n## Current Context and Archival Lifecycle\n\n- Current context must support ordinary work without archives, and its size follows open work, not project age. Keep applicable guidance, accepted requirements/decisions, unresolved work, dependencies and necessary next actions discoverable. Acceptance is independent of implementation; dated temporary directives remain active until lifted or their stated end condition is met.\n- `TASKS.md` holds `[ ]`, `[/]` and `[!]` tasks; `ISSUES.md` holds open and accepted issues. When work closes, move its record in the same session to the append-only `.autonomos/archive/closed/TASKS.md` or `ISSUES.md` (`autonomos close <ID>`, or by hand). Unfinished work may be closed only as abandoned, with its reason. A completed child does not satisfy unmet parent acceptance criteria; a parent with open children stays current.\n- Record new task completion dates as `Completed: YYYY-MM-DD`; do not infer missing old dates. Age, a checkbox, absent code or a newer statement alone is not proof of obsolescence.\n- Before moving history, consolidate still-needed knowledge in its existing narrowest home. Optional `Current direction` in `TASKS.md` explains present aims, recent consequential outcomes and next work; rewrite it rather than append chronology. Keep progress out of `AGENT.md`.\n- Other history may form named batches under `.autonomos/archive/<batch>/` via `/reconcile`; create `archive/README.md` and batch directories on first use only. The index maps topics to records; it is not a second journal.\n- Archive means move, not delete or rewrite conclusions. Preserve historical record content, identifiers and provenance; repair relative paths when necessary. Applicable specs/decisions stay current independently of execution records. Extraction into new normative artifacts still uses `/adopt`.\n- Archived task and issue IDs remain reserved. Before assigning an ID, search current and archived registries (`autonomos status --history` reports duplicates).\n- Verify exact source text before edits and resolvable references after moves. Re-read shared files before writing and preserve unrelated concurrent changes.\n\n## Context Budgets\n\nAdvisory limits reported by `autonomos status` (`--strict` makes them fail): root `AGENT.md` 8,000 bytes, local `AGENT.md` 4,000 bytes, `TASKS.md` 16 KB, `ISSUES.md` 24 KB, one task entry 300 characters, one worklog 2,500 bytes, and no closed record in current registries. Over budget, consolidate or move knowledge to its narrowest home before adding more. Root `AGENT.md` admits only guidance that applies to most tasks in the project.\n\n## Artifact Format and Migration\n\n`manifest.json` records `artifactFormat` (absent means 1); this protocol defines format 2. Installing a new protocol performs no automatic cleanup: `autonomos update` only replaces managed artifacts. `autonomos migrate` is the explicit, content-preserving upgrade: it closes finished records, moves pre-format-2 worklogs to `.autonomos/archive/worklogs-format-1/` so they stop serving as examples, repairs references and records the format. Run it with `--dry-run` first on a clean working tree, then resolve the remaining `status` findings with `/reconcile`.\n\n## Task Format\n\nOne line per task: `` - [Status] **[ID]** Title `Priority` `Complexity` `` plus, when useful, `Completed: YYYY-MM-DD`, a short note and links to its issue or worklog. Evidence, measurements and progress belong in the worklog, not the task entry.\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";
|
|
415
446
|
//#endregion
|
|
416
447
|
//#region src/templates/tasks.d.ts
|
|
417
448
|
/**
|
|
@@ -422,17 +453,19 @@ declare const TASKS_TEMPLATE = "# PROJECT TASKS & ROADMAP\n\n> **LEGEND**\n> **P
|
|
|
422
453
|
//#region src/templates/worklog.d.ts
|
|
423
454
|
interface WorklogOptions {
|
|
424
455
|
taskId: string;
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
456
|
+
title: string;
|
|
457
|
+
/** 1–3 lines: what is now true. */
|
|
458
|
+
outcome: string;
|
|
459
|
+
/** Non-obvious choices with their reason. */
|
|
460
|
+
decisions?: string[];
|
|
461
|
+
/** Checks actually run, `command → result`. */
|
|
462
|
+
validation?: string[];
|
|
463
|
+
/** Limits and follow-ups. */
|
|
464
|
+
open?: string[];
|
|
433
465
|
}
|
|
434
466
|
/**
|
|
435
|
-
* Generate a
|
|
467
|
+
* Generate a proportionate worklog (artifact format 2): only what a future
|
|
468
|
+
* agent cannot recover from code, git, tests or other records.
|
|
436
469
|
*/
|
|
437
470
|
declare function generateWorklogContent(options: WorklogOptions): string;
|
|
438
471
|
/**
|
|
@@ -604,5 +637,96 @@ declare function resolveTargets(harnessIds: string[], cwd?: string): ResolvedTar
|
|
|
604
637
|
*/
|
|
605
638
|
declare function getRawHarnessCodes(): HarnessCodes;
|
|
606
639
|
//#endregion
|
|
607
|
-
|
|
640
|
+
//#region src/records/budgets.d.ts
|
|
641
|
+
type BudgetFindingCode = 'format-outdated' | 'closed-tasks-in-current' | 'closed-issues-in-current' | 'tasks-size' | 'issues-size' | 'task-entry-length' | 'root-agent-size' | 'local-agent-size' | 'worklog-size';
|
|
642
|
+
interface BudgetFinding {
|
|
643
|
+
code: BudgetFindingCode;
|
|
644
|
+
/** Project-relative path the finding concerns. */
|
|
645
|
+
path: string;
|
|
646
|
+
message: string;
|
|
647
|
+
/** Offending IDs or files, largest first, when relevant. */
|
|
648
|
+
items?: string[];
|
|
649
|
+
}
|
|
650
|
+
type ContextBudgets = { [K in keyof typeof CONTEXT_BUDGETS]: number };
|
|
651
|
+
/** Find AGENT.md files below root, skipping hidden, dependency and build directories. */
|
|
652
|
+
declare function findAgentFilePaths(root: string): string[];
|
|
653
|
+
/**
|
|
654
|
+
* Report where current context exceeds the protocol's proportionate budgets.
|
|
655
|
+
* Findings are advisory; agents resolve them through `/reconcile` or `migrate`.
|
|
656
|
+
*/
|
|
657
|
+
declare function checkContextBudgets(root: string, options?: {
|
|
658
|
+
artifactFormat?: number;
|
|
659
|
+
budgets?: Partial<ContextBudgets>;
|
|
660
|
+
}): BudgetFinding[];
|
|
661
|
+
//#endregion
|
|
662
|
+
//#region src/records/links.d.ts
|
|
663
|
+
/** Map an absolute path to its new location, or return it unchanged. */
|
|
664
|
+
type PathMapper = (absolutePath: string) => string;
|
|
665
|
+
declare function prefixMapper(from: string, to: string): PathMapper;
|
|
666
|
+
declare function composeMappers(...mappers: PathMapper[]): PathMapper;
|
|
667
|
+
/**
|
|
668
|
+
* Rewrite relative Markdown link targets of a document that moves from
|
|
669
|
+
* `oldDir` to `newDir`, also following targets that moved (`mapPath`).
|
|
670
|
+
* Targets that resolve to the same file are left byte-identical.
|
|
671
|
+
*/
|
|
672
|
+
declare function relocateLinks(markdown: string, oldDir: string, newDir: string, mapPath?: PathMapper): string;
|
|
673
|
+
/**
|
|
674
|
+
* Rewrite plain project-root-relative mentions of moved files, such as
|
|
675
|
+
* `_See: .autonomos/worklogs/2026-01-01-X.md_`, outside of link targets.
|
|
676
|
+
*/
|
|
677
|
+
declare function relocateRootMentions(markdown: string, fromPrefix: string, toPrefix: string, names: ReadonlySet<string>): string;
|
|
678
|
+
//#endregion
|
|
679
|
+
//#region src/records/registry-edit.d.ts
|
|
680
|
+
/**
|
|
681
|
+
* Pure text operations on TASKS.md / ISSUES.md used by `close`, `migrate`
|
|
682
|
+
* and budget checks. They never rewrite the content of a moved record.
|
|
683
|
+
*/
|
|
684
|
+
/** Issue statuses that mean the issue no longer needs current attention. */
|
|
685
|
+
declare const CLOSED_ISSUE_STATUSES: string[];
|
|
686
|
+
interface TaskEntry {
|
|
687
|
+
id: string;
|
|
688
|
+
status: ' ' | 'x' | '/' | '!';
|
|
689
|
+
/** 0-based index of the first line of the entry. */
|
|
690
|
+
start: number;
|
|
691
|
+
/** 0-based exclusive end line index. */
|
|
692
|
+
end: number;
|
|
693
|
+
/** Heading path enclosing the entry, outermost first (title excluded). */
|
|
694
|
+
headings: string[];
|
|
695
|
+
text: string;
|
|
696
|
+
}
|
|
697
|
+
interface IssueEntry {
|
|
698
|
+
id: string;
|
|
699
|
+
status: string;
|
|
700
|
+
start: number;
|
|
701
|
+
end: number;
|
|
702
|
+
text: string;
|
|
703
|
+
}
|
|
704
|
+
/**
|
|
705
|
+
* Parse task entries: a task line plus following lines indented deeper than it
|
|
706
|
+
* (continuations and sub-bullets). Nested tasks are returned as their own entries
|
|
707
|
+
* and are also part of their parent's text.
|
|
708
|
+
*/
|
|
709
|
+
declare function parseTaskEntries(markdown: string): TaskEntry[];
|
|
710
|
+
declare function parseIssueEntries(markdown: string): IssueEntry[];
|
|
711
|
+
declare function isClosedIssueStatus(status: string): boolean;
|
|
712
|
+
interface Extraction<T> {
|
|
713
|
+
remaining: string;
|
|
714
|
+
moved: T[];
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Extract task entries matching `select` from a TASKS.md document.
|
|
718
|
+
* Entries with open nested tasks are never extracted.
|
|
719
|
+
*/
|
|
720
|
+
declare function extractTasks(markdown: string, select: (entry: TaskEntry) => boolean): Extraction<TaskEntry>;
|
|
721
|
+
declare function extractIssues(markdown: string, select: (entry: IssueEntry) => boolean): Extraction<IssueEntry>;
|
|
722
|
+
/** Remove the common leading indentation of an entry so it stands alone. */
|
|
723
|
+
declare function dedentEntry(text: string): string;
|
|
724
|
+
/** Add `Completed: <date>` to a task line that has no completion date. */
|
|
725
|
+
declare function stampCompleted(text: string, date: string): string;
|
|
726
|
+
/** Mark an unfinished task as abandoned (it keeps its status marker). */
|
|
727
|
+
declare function stampAbandoned(text: string, date: string, reason: string): string;
|
|
728
|
+
/** Append entries to a closed registry, creating its header when empty. */
|
|
729
|
+
declare function appendToClosedRegistry(existing: string | undefined, kind: 'tasks' | 'issues', entries: string[], groupHeading?: string): string;
|
|
730
|
+
//#endregion
|
|
731
|
+
export { AGENT_FILE, AGENT_TEMPLATE, ARCHIVE_DIR, ARCHIVE_INDEX_FILE, ARTIFACT_FORMAT, AUTONOMOS_DIR, AgentConfig, AgentContext, AgentParser, AgentSection, AncestorAgent, BudgetFinding, BudgetFindingCode, CLOSED_DIR, CLOSED_ISSUE_STATUSES, COMPLEXITIES, CONTEXT_BUDGETS, Complexity, ContextBudgets, DECISIONS_DIR, Extraction, Harness, HarnessCodes, HarnessCodesSchema, HarnessSchema, ISSUES_FILE, Installer, InstallerSchema, IssueEntry, LEGACY_WORKLOGS_DIR, LOCAL_AGENT_TEMPLATE, MANIFEST_FILE, Manifest, ManifestSchema, PRIORITIES, PROTOCOL_FILE, PROTOCOL_TEMPLATE, PROTOCOL_TEMPLATE_V2026_1, PROTOCOL_VERSION, PathMapper, Priority, ResolvedTarget, SPECS_DIR, TASKS_FILE, TASKS_TEMPLATE, TargetKind, Task, TaskEntry, TaskParser, TaskReference, TaskRegistry, TaskStatus, WORKLOGS_DIR, appendToClosedRegistry, checkContextBudgets, composeMappers, createManifest, dedentEntry, displayRelative, extractIssues, extractTasks, findAgentFilePaths, findAncestorAgents, findProjectRoot, generateAgentTemplate, generateLocalAgentTemplate, generateManifestContent, generateWorklogContent, getHarness, getRawHarnessCodes, isClosedIssueStatus, isSamePath, listHarnesses, listPreferredHarnesses, manifestArtifactFormat, mapTaskStatusToWorklogStatus, parseIssueEntries, parseManifest, parseTaskEntries, prefixMapper, readTaskRegistry, relocateLinks, relocateRootMentions, resolveTargets, stampAbandoned, stampCompleted };
|
|
608
732
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -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/project-root.ts","../src/parsers/task-parser.ts","../src/parsers/task-registry.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;;;;cAKA,SAAA;AALb;;;AAAA,cAUa,aAAA;AAVY;AAAA,cAaZ,WAAA
|
|
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/parsers/task-registry.ts","../src/harness-codes.ts","../src/records/budgets.ts","../src/records/links.ts","../src/records/registry-edit.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;;;;cAKA,SAAA;AALb;;;AAAA,cAUa,aAAA;AAVY;AAAA,cAaZ,WAAA;;;;AARS;AAKtB;cAUa,eAAA;;cAGA,WAAA;AAba;AAAA,cAgBb,UAAA;;cAGA,mBAAA;;cAGA,kBAAA;AAZb;;;;AAAA,cAkBa,eAAA;EAAA;;;;;;;;;;;AApEb;;;;AAA6B;AAK7B;;;;AAA0B;cCKb,eAAA,EAAe,CAAA,CAAA,UAAA,CAAA,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA2Bf,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,YAAA,GAAe,CAAA,CAAE,KAAK,QAAQ,kBAAA;;;;;ADpD1C;cECa,cAAA,EAAc,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;KAaf,QAAA,GAAW,CAAA,CAA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AAoB,MAAc;AAAA,UAWjC,UAAA;EACb,SAAA;EACA,KAAA,EAAO,CAAC;AAAA;;AjB9Ha;AAKzB;;iBiB8LgB,YAAA,CACZ,QAAA,UACA,MAAA,GAAS,KAAA,EAAO,SAAA,eACjB,UAAA,CAAW,SAAA;AAAA,iBAYE,aAAA,CACZ,QAAA,UACA,MAAA,GAAS,KAAA,EAAO,UAAA,eACjB,UAAA,CAAW,UAAA;AjBhNQ;AAAA,iBiBuNN,WAAA,CAAY,IAAY;;iBAQxB,cAAA,CAAe,IAAA,UAAc,IAAY;;iBAWzC,cAAA,CAAe,IAAA,UAAc,IAAA,UAAc,MAAA;AjBlO3D;AAAA,iBiBwOgB,sBAAA,CACZ,QAAA,sBACA,IAAA,sBACA,OAAA,YACA,YAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{z as e}from"zod";import{existsSync as t,lstatSync as n,readFileSync as r,readdirSync as i,statSync as a}from"node:fs";import{dirname as o,isAbsolute as s,join as c,
|
|
1
|
+
import{z as e}from"zod";import{existsSync as t,lstatSync as n,readFileSync as r,readdirSync as i,statSync as a}from"node:fs";import{dirname as o,isAbsolute as s,join as c,posix as l,relative as u,resolve as d,sep as f}from"node:path";import p from"js-yaml";const m=`0.8.0-alpha`,h=`.autonomos`,g=`manifest.json`,ee=`PROTOCOL.md`,_=`TASKS.md`,v=`AGENT.md`,y=`worklogs`,te=`specs`,ne=`decisions`,b=`archive`,re=2,x=`ISSUES.md`,ie=`closed`,ae=`worklogs-format-1`,oe=`README.md`,S={rootAgentBytes:8e3,localAgentBytes:4e3,tasksBytes:16e3,issuesBytes:24e3,taskEntryChars:300,worklogBytes:2500},C=e.object({workflowsDir:e.string().optional(),targetDir:e.string().optional(),skillsDir:e.string().optional(),commandsDir:e.string().optional(),promptsDir:e.string().optional(),globalTargetDir:e.string().optional(),fileExtension:e.string(),_note:e.string().optional()}).refine(e=>!!e.workflowsDir||!!e.targetDir||!!e.skillsDir||!!e.commandsDir||!!e.promptsDir,{message:"At least one of `workflowsDir`, `targetDir`, `skillsDir`, `commandsDir`, or `promptsDir` must be defined"}),w=e.object({name:e.string().min(1),preferred:e.boolean(),installer:C}),T=e.object({platforms:e.record(e.string(),w)}),E=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`),artifactFormat:e.number().int().positive().optional().describe(`Layout version of project-owned records; absent means 1`)}),se=[`🔴 Critical`,`🟠 High`,`🔵 Medium`,`⚪ Low`],ce=[`S`,`M`,`L`,`XL`];function D(e=`Project`){return`---
|
|
2
2
|
name: "${e}"
|
|
3
3
|
type: "project"
|
|
4
4
|
status: "active"
|
|
@@ -35,40 +35,42 @@ status: "active"
|
|
|
35
35
|
- **Stack:** *(frameworks, libs specific to this module)*
|
|
36
36
|
- **Conventions:** *(naming, exports, test patterns)*
|
|
37
37
|
- **Constraints:** *(known issues, tech debt)*
|
|
38
|
-
`}const
|
|
39
|
-
`}function
|
|
38
|
+
`}const le=D(),ue=O(`module`);function de(e){let t=new Date().toISOString();return{protocolVersion:m,cliVersion:e,initializedAt:t,lastUpdated:t,artifactFormat:2}}function fe(e){return JSON.stringify(e,null,4)+`
|
|
39
|
+
`}function pe(e){let t=JSON.parse(e);return E.parse(t)}function me(e){return e.artifactFormat??1}const k=`# AUTONOMOS PROTOCOL (v${m})
|
|
40
40
|
|
|
41
41
|
> This file defines the project's AI workflow contract. The workflows execute it. Do not duplicate workflow steps here.
|
|
42
42
|
|
|
43
43
|
## Quick Reference
|
|
44
44
|
|
|
45
|
-
| Action
|
|
46
|
-
|
|
|
47
|
-
| Start a session
|
|
48
|
-
| Start a task
|
|
49
|
-
| Triage a problem or proposal
|
|
50
|
-
| Adopt existing project knowledge
|
|
51
|
-
| Reconcile drift and archive history
|
|
52
|
-
| Design or critique a surface
|
|
53
|
-
| End a session
|
|
54
|
-
| Get context
|
|
55
|
-
| Resolve objective
|
|
56
|
-
| Log session work
|
|
45
|
+
| Action | How |
|
|
46
|
+
| ----------------------------------- | ---------------------------------------------------------------------------------- |
|
|
47
|
+
| Start a session | Read the \`/session\` workflow |
|
|
48
|
+
| Start a task | Read the \`/task\` workflow |
|
|
49
|
+
| Triage a problem or proposal | Read the optional \`/issue\` workflow |
|
|
50
|
+
| Adopt existing project knowledge | Read the optional \`/adopt\` workflow |
|
|
51
|
+
| Reconcile drift and archive history | Read the \`/reconcile\` workflow |
|
|
52
|
+
| Design or critique a surface | Read the optional \`/design\` workflow |
|
|
53
|
+
| End a session | Read the \`/crystallize\` workflow |
|
|
54
|
+
| Get context | Read root \`AGENT.md\`, then only the selected scope's ancestor chain |
|
|
55
|
+
| Resolve objective | Explicit user request first; otherwise resume \`[/]\` or pick highest-priority \`[ ]\` |
|
|
56
|
+
| Log session work | Create \`.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md\` (shape in \`/crystallize\`) |
|
|
57
|
+
| Close finished work | \`autonomos close <ID>\` → \`.autonomos/archive/closed/\` |
|
|
58
|
+
| Check context budgets | \`autonomos status\`; upgrade old records with \`autonomos migrate\` |
|
|
57
59
|
|
|
58
60
|
## File Map
|
|
59
61
|
|
|
60
|
-
| File | Location | Role
|
|
61
|
-
| --------------- | -------------------------- |
|
|
62
|
-
| \`AGENT.md\` | Root + any subdirectory | Durable guidance for its directory scope
|
|
63
|
-
| \`TASKS.md\` | \`.autonomos/TASKS.md\` |
|
|
64
|
-
| \`ISSUES.md\` | \`.autonomos/ISSUES.md\` | Optional
|
|
65
|
-
| \`worklogs/\` | \`.autonomos/worklogs/\` | Historical session evidence, not current guidance
|
|
66
|
-
| \`archive/\`
|
|
67
|
-
| \`specs/\` | \`.autonomos/specs/\` | Optional project-owned normative target state
|
|
68
|
-
| \`decisions/\` | \`.autonomos/decisions/\` | Optional project-owned decision records (ADRs)
|
|
69
|
-
| \`DESIGN.md\` | Root or target scope
|
|
70
|
-
| \`PROTOCOL.md\` | \`.autonomos/PROTOCOL.md\` | This file — read-only reference
|
|
71
|
-
| \`manifest.json\` | \`.autonomos/manifest.json\` | Protocol version
|
|
62
|
+
| File | Location | Role |
|
|
63
|
+
| --------------- | -------------------------- | --------------------------------------------------------------------- |
|
|
64
|
+
| \`AGENT.md\` | Root + any subdirectory | Durable guidance for its directory scope |
|
|
65
|
+
| \`TASKS.md\` | \`.autonomos/TASKS.md\` | Open tasks and optional Current direction |
|
|
66
|
+
| \`ISSUES.md\` | \`.autonomos/ISSUES.md\` | Optional intake: open and accepted issues only |
|
|
67
|
+
| \`worklogs/\` | \`.autonomos/worklogs/\` | Historical session evidence, not current guidance |
|
|
68
|
+
| \`archive/\` | \`.autonomos/archive/\` | History (\`closed/\` registries, batches), searched only when justified |
|
|
69
|
+
| \`specs/\` | \`.autonomos/specs/\` | Optional project-owned normative target state |
|
|
70
|
+
| \`decisions/\` | \`.autonomos/decisions/\` | Optional project-owned decision records (ADRs) |
|
|
71
|
+
| \`DESIGN.md\` | Root or target scope | Optional project-owned visual/interaction direction |
|
|
72
|
+
| \`PROTOCOL.md\` | \`.autonomos/PROTOCOL.md\` | This file — read-only reference |
|
|
73
|
+
| \`manifest.json\` | \`.autonomos/manifest.json\` | Protocol version and artifact format |
|
|
72
74
|
|
|
73
75
|
## Design Direction Boundary
|
|
74
76
|
|
|
@@ -148,36 +150,26 @@ Only user/project governance accepts a specification or decision as normative. A
|
|
|
148
150
|
|
|
149
151
|
## Current Context and Archival Lifecycle
|
|
150
152
|
|
|
151
|
-
- Current context must support ordinary work without archives. Keep applicable guidance, accepted requirements/decisions, unresolved work, dependencies and necessary next actions discoverable. Acceptance is independent of implementation; dated temporary directives remain active until lifted or their stated end condition is met.
|
|
152
|
-
-
|
|
153
|
-
- Record new task completion dates as \`Completed: YYYY-MM-DD\`; do not infer missing old dates
|
|
154
|
-
-
|
|
155
|
-
-
|
|
156
|
-
-
|
|
157
|
-
-
|
|
158
|
-
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
.autonomos/
|
|
168
|
-
TASKS.md
|
|
169
|
-
ISSUES.md
|
|
170
|
-
archive/
|
|
171
|
-
README.md
|
|
172
|
-
realtime-experiment-retirement/
|
|
173
|
-
TASKS.md
|
|
174
|
-
ISSUES.md
|
|
175
|
-
worklogs/
|
|
176
|
-
\`\`\`
|
|
153
|
+
- Current context must support ordinary work without archives, and its size follows open work, not project age. Keep applicable guidance, accepted requirements/decisions, unresolved work, dependencies and necessary next actions discoverable. Acceptance is independent of implementation; dated temporary directives remain active until lifted or their stated end condition is met.
|
|
154
|
+
- \`TASKS.md\` holds \`[ ]\`, \`[/]\` and \`[!]\` tasks; \`ISSUES.md\` holds open and accepted issues. When work closes, move its record in the same session to the append-only \`.autonomos/archive/closed/TASKS.md\` or \`ISSUES.md\` (\`autonomos close <ID>\`, or by hand). Unfinished work may be closed only as abandoned, with its reason. A completed child does not satisfy unmet parent acceptance criteria; a parent with open children stays current.
|
|
155
|
+
- Record new task completion dates as \`Completed: YYYY-MM-DD\`; do not infer missing old dates. Age, a checkbox, absent code or a newer statement alone is not proof of obsolescence.
|
|
156
|
+
- Before moving history, consolidate still-needed knowledge in its existing narrowest home. Optional \`Current direction\` in \`TASKS.md\` explains present aims, recent consequential outcomes and next work; rewrite it rather than append chronology. Keep progress out of \`AGENT.md\`.
|
|
157
|
+
- Other history may form named batches under \`.autonomos/archive/<batch>/\` via \`/reconcile\`; create \`archive/README.md\` and batch directories on first use only. The index maps topics to records; it is not a second journal.
|
|
158
|
+
- Archive means move, not delete or rewrite conclusions. Preserve historical record content, identifiers and provenance; repair relative paths when necessary. Applicable specs/decisions stay current independently of execution records. Extraction into new normative artifacts still uses \`/adopt\`.
|
|
159
|
+
- Archived task and issue IDs remain reserved. Before assigning an ID, search current and archived registries (\`autonomos status --history\` reports duplicates).
|
|
160
|
+
- Verify exact source text before edits and resolvable references after moves. Re-read shared files before writing and preserve unrelated concurrent changes.
|
|
161
|
+
|
|
162
|
+
## Context Budgets
|
|
163
|
+
|
|
164
|
+
Advisory limits reported by \`autonomos status\` (\`--strict\` makes them fail): root \`AGENT.md\` 8,000 bytes, local \`AGENT.md\` 4,000 bytes, \`TASKS.md\` 16 KB, \`ISSUES.md\` 24 KB, one task entry 300 characters, one worklog 2,500 bytes, and no closed record in current registries. Over budget, consolidate or move knowledge to its narrowest home before adding more. Root \`AGENT.md\` admits only guidance that applies to most tasks in the project.
|
|
165
|
+
|
|
166
|
+
## Artifact Format and Migration
|
|
167
|
+
|
|
168
|
+
\`manifest.json\` records \`artifactFormat\` (absent means 1); this protocol defines format 2. Installing a new protocol performs no automatic cleanup: \`autonomos update\` only replaces managed artifacts. \`autonomos migrate\` is the explicit, content-preserving upgrade: it closes finished records, moves pre-format-2 worklogs to \`.autonomos/archive/worklogs-format-1/\` so they stop serving as examples, repairs references and records the format. Run it with \`--dry-run\` first on a clean working tree, then resolve the remaining \`status\` findings with \`/reconcile\`.
|
|
177
169
|
|
|
178
170
|
## Task Format
|
|
179
171
|
|
|
180
|
-
|
|
172
|
+
One line per task: \`\` - [Status] **[ID]** Title \`Priority\` \`Complexity\` \`\` plus, when useful, \`Completed: YYYY-MM-DD\`, a short note and links to its issue or worklog. Evidence, measurements and progress belong in the worklog, not the task entry.
|
|
181
173
|
|
|
182
174
|
| Status | Priority | Complexity |
|
|
183
175
|
| ----------------- | ------------- | ---------- |
|
|
@@ -191,7 +183,7 @@ Example (only files needed by a batch are created):
|
|
|
191
183
|
- **Language:** English unless AGENT.md says otherwise.
|
|
192
184
|
- **Tone:** Technical, concise, fact-based.
|
|
193
185
|
- **Continuity:** Refer to previous work as "we" or "the project".
|
|
194
|
-
`,
|
|
186
|
+
`,he=k,ge=`# PROJECT TASKS & ROADMAP
|
|
195
187
|
|
|
196
188
|
> **LEGEND**
|
|
197
189
|
> **Priority:** [🔴 Critical] [🟠 High] [🔵 Medium] [⚪ Low]
|
|
@@ -205,28 +197,31 @@ Example (only files needed by a batch are created):
|
|
|
205
197
|
## 🔮 Backlog
|
|
206
198
|
|
|
207
199
|
*(Add future tasks here)*
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
-
|
|
217
|
-
${e.filesModified.map(e=>` - ${e}`).join(`
|
|
218
|
-
`)}
|
|
219
|
-
- **Key Decisions:**
|
|
220
|
-
${e.decisions.map(e=>` - ${e}`).join(`
|
|
221
|
-
`)}
|
|
222
|
-
- **Challenges:**
|
|
223
|
-
${e.challenges.map(e=>` - ${e}`).join(`
|
|
224
|
-
`)}
|
|
225
|
-
|
|
226
|
-
## ⏭ Next Steps / Context for Successor
|
|
227
|
-
${e.nextSteps.map(e=>`- ${e}`).join(`
|
|
228
|
-
`)}
|
|
229
|
-
`}function I(e){switch(e){case`DONE`:return`Complete`;case`BLOCKED`:return`Blocked`;default:return`Partial`}}function L(e,n=process.cwd()){let r=u(n),i=R(e,r),a=l(r,i);if(a.startsWith(`..`)||s(a))throw Error(`Target "${e}" is outside the project root "${r}". findAncestorAgents only handles paths within the project.`);let d=z(V(i)?i:o(i),r),f=[];for(let e of d){let n=c(e,v);t(n)&&f.push({dir:e,path:n,relativeDir:B(e,r)})}return f}function R(e,t){return s(e)?e:c(t,e)}function z(e,t){let n=l(t,e);if(n===``||n===`.`)return[t];let r=n.split(d).filter(e=>e!==``&&e!==`.`),i=[t],a=t;for(let e of r)a=c(a,e),i.push(a);return i}function B(e,t){let n=l(t,e);return n===``?`.`:n}function V(e){try{return a(e).isDirectory()}catch{return!1}}var H=class{static parse(e){let t=e,n={},r=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(r)try{n=f.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(`
|
|
200
|
+
`,A=e=>e?.length?`
|
|
201
|
+
`+e.map(e=>`- ${e}`).join(`
|
|
202
|
+
`):` none`;function _e(e){return`# [${e.taskId}] ${e.title}
|
|
203
|
+
|
|
204
|
+
Outcome: ${e.outcome}
|
|
205
|
+
Decisions:${A(e.decisions)}
|
|
206
|
+
Validation:${A(e.validation)}
|
|
207
|
+
Open:${A(e.open)}
|
|
208
|
+
`}function ve(e){switch(e){case`DONE`:return`Complete`;case`BLOCKED`:return`Blocked`;default:return`Partial`}}function ye(e,n=process.cwd()){let r=d(n),i=be(e,r),a=u(r,i);if(a.startsWith(`..`)||s(a))throw Error(`Target "${e}" is outside the project root "${r}". findAncestorAgents only handles paths within the project.`);let l=xe(M(i)?i:o(i),r),f=[];for(let e of l){let n=c(e,v);t(n)&&f.push({dir:e,path:n,relativeDir:j(e,r)})}return f}function be(e,t){return s(e)?e:c(t,e)}function xe(e,t){let n=u(t,e);if(n===``||n===`.`)return[t];let r=n.split(f).filter(e=>e!==``&&e!==`.`),i=[t],a=t;for(let e of r)a=c(a,e),i.push(a);return i}function j(e,t){let n=u(t,e);return n===``?`.`:n}function M(e){try{return a(e).isDirectory()}catch{return!1}}var Se=class{static parse(e){let t=e,n={},r=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(r)try{n=p.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(`
|
|
230
209
|
`).trim(),a.push(s)),s={title:e.replace(`## `,``).trim(),content:``},c=[];continue}s&&c.push(e)}return s&&(s.content=c.join(`
|
|
231
|
-
`).trim(),a.push(s)),{title:o,sections:a,metadata:n}}};const
|
|
210
|
+
`).trim(),a.push(s)),{title:o,sections:a,metadata:n}}};const Ce=[h,`.git`];function we(e){if(!e)return null;let n=d(e);for(;;){if(Ce.some(e=>t(c(n,e))))return n;let e=o(n);if(e===n)return null;n=e}}function Te(e,t){return!e||!t?!1:d(e)===d(t)}function Ee(e,t){let n=u(t,e);return n===``||n===`.`?`.`:n.startsWith(`..${f}`)||n===`..`||s(n)?d(e):n}var N=class{static references(e){let t=[],n;for(let[r,i]of e.split(/\r?\n/).entries()){let e=i.match(/^\s{0,3}(`{3,}|~{3,})/);if(e?.[1]){n?e[1][0]===n[0]&&e[1].length>=n.length&&!i.slice(e[0].length).trim()&&(n=void 0):n=e[1];continue}if(n)continue;let a=i.match(/^\s*- \[([ x/!])\] \*\*\[([^\]]+)\]\*\*/);a?.[1]&&a[2]?.trim()&&t.push({id:a[2].trim(),status:this.mapStatus(a[1]),line:r+1})}return t}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`}}};function De(e,t={}){let a={current:[],archived:[],duplicateIds:[],warnings:[],complete:!0};function o(t,n){a.complete=!1,a.warnings.push(`${u(e,t)}: ${n}`)}function s(t,i){try{if(!n(t).isFile()){o(t,`Expected a regular task registry; symbolic links are not followed`);return}i.push(...N.references(r(t,`utf8`)).map(n=>({...n,path:u(e,t)})))}catch(e){o(t,e instanceof Error?e.message:String(e))}}function l(e,t=!1){try{if(!n(e).isDirectory()){o(e,`Expected an archive directory; symbolic links are not followed`);return}for(let t of i(e,{withFileTypes:!0}).sort((e,t)=>e.name.localeCompare(t.name))){let n=c(e,t.name);t.isSymbolicLink()?o(n,`Skipped symbolic link in archive`):t.isDirectory()?l(n):t.name===`TASKS.md`&&s(n,a.archived)}}catch(n){if(t&&n.code===`ENOENT`)return;o(e,n instanceof Error?n.message:String(n))}}let d=c(e,h);try{if(!n(d).isDirectory())return o(d,`Expected a regular project directory; symbolic links are not followed`),a}catch(e){return e.code!==`ENOENT`&&o(d,e instanceof Error?e.message:String(e)),a}let f=c(d,_);try{n(f),s(f,a.current)}catch(e){e.code!==`ENOENT`&&o(f,e instanceof Error?e.message:String(e))}t.history&&l(c(e,h,b),!0);let p=new Set,m=new Set;for(let e of[...a.current,...a.archived])p.has(e.id)&&m.add(e.id),p.add(e.id);return a.duplicateIds=[...m].sort(),a}const P=T.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:{commandsDir:`.claude/commands`,skillsDir:`.agents/skills`,fileExtension:`.md`}},codex:{name:`Codex`,preferred:!0,installer:{promptsDir:`.codex/prompts`,skillsDir:`.agents/skills`,fileExtension:`.md`,globalTargetDir:`~/.codex/prompts`,_note:`OpenAI Codex CLI. Slash commands live in .codex/prompts/, skills live in the cross-tool .agents/skills/ standard.`}},antigravity:{name:`Antigravity`,preferred:!0,installer:{workflowsDir:`.agents/workflows`,skillsDir:`.agents/skills`,fileExtension:`.md`,globalTargetDir:`~/.gemini/config/workflows`,_note:`Google Antigravity. Workflows live in .agents/workflows/, skills live in the cross-tool .agents/skills/ standard.`}},opencode:{name:`OpenCode`,preferred:!0,installer:{commandsDir:`.opencode/commands`,skillsDir:`.agents/skills`,fileExtension:`.md`}},kilocode:{name:`KiloCode`,preferred:!0,installer:{workflowsDir:`.agents/workflows`,skillsDir:`.agents/skills`,fileExtension:`.md`,globalTargetDir:`~/.kilocode/skills`}}}});function F(e){let t=P.platforms[e];if(!t){let t=Object.keys(P.platforms).join(`, `);throw Error(`Unknown harness: "${e}". Known harnesses: ${t}`)}return t}function I(){return Object.entries(P.platforms).map(([e,t])=>({id:e,harness:t}))}function Oe(){return I().filter(({harness:e})=>e.preferred)}function ke(e,t=`.`){let n=new Map;for(let r of e){let{installer:e}=F(r);Ae(n,e,r,t)}return Array.from(n.values())}function Ae(e,t,n,r){let i=t.fileExtension;t.workflowsDir&&L(e,R(r,t.workflowsDir),i,`flat`,n),t.commandsDir&&L(e,R(r,t.commandsDir),i,`flat`,n),t.promptsDir&&L(e,R(r,t.promptsDir),i,`flat`,n),t.targetDir&&L(e,R(r,t.targetDir),i,`flat`,n),t.skillsDir&&L(e,R(r,t.skillsDir),i,`skill`,n)}function L(e,t,n,r,i){let a=e.get(t);a?a.usedBy.includes(i)||a.usedBy.push(i):e.set(t,{path:t,fileExtension:n,kind:r,usedBy:[i]})}function R(e,t){return e===`.`||e===``?t:t.startsWith(`/`)?`${e}${t}`:`${e}/${t}`}function je(){return P}const Me=/^\s*- \[([ x/!])\] \*\*\[([^\]]+)\]\*\*/,z=/^(#{1,6})[ \t]+(\S.*)?$/,Ne=/^\s{0,3}(`{3,}|~{3,})/,Pe=/^##\s+\[([^\]]+)\]/,Fe=/^\s*[-*]\s*(?:\*\*)?status:?(?:\*\*)?:?[ \t]*(?:\*\*)?([a-z-]+)/i,B=[`resolved`,`declined`,`closed`,`superseded`,`rejected`];function V(e){return e.split(/\r?\n/)}function H(e){let t=[],n;for(let r of e){let e=r.match(Ne);if(e?.[1]){if(!n){n=e[1],t.push(!0);continue}if(e[1][0]===n[0]&&e[1].length>=n.length&&!r.slice(e[0].length).trim()){n=void 0,t.push(!0);continue}}t.push(n!==void 0)}return t}function U(e){return(e.match(/^\s*/)?.[0]??``).replace(/\t/g,` `).length}function W(e){let t=V(e),n=H(t),r=[],i=[];for(let e=0;e<t.length;e++){let a=t[e]??``;if(n[e])continue;let o=a.match(z);if(o?.[1]){let e=o[1].length;for(;i.length&&(i.at(-1)?.level??0)>=e;)i.pop();i.push({level:e,text:(o[2]??``).trim()});continue}let s=a.match(Me);if(!s)continue;let c=U(a),l=e+1,u=e+1;for(;l<t.length;){let e=t[l]??``;if(!n[l]&&e.trim()===``){l++;continue}if(n[l]&&!n[l-1]&&U(e)<=c||!n[l]&&U(e)<=c||!n[l]&&z.test(e))break;l++,u=l}r.push({id:(s[2]??``).trim(),status:s[1]??` `,start:e,end:u,headings:i.filter(e=>e.level>1).map(e=>e.text),text:t.slice(e,u).join(`
|
|
211
|
+
`)})}return r}function G(e){let t=V(e),n=H(t),r=[];for(let e=0;e<t.length;e++)!n[e]&&/^#{1,2}\s/.test(t[e]??``)&&r.push(e);let i=[];for(let[e,n]of r.entries()){let a=(t[n]??``).match(Pe)?.[1]?.trim();if(!a)continue;let o=r[e+1]??t.length;for(;o>n+1&&(t[o-1]??``).trim()===``;)o--;let s=t.slice(n,o),c=``;for(let e of s){let t=e.match(Fe);if(t?.[1]){c=t[1].toLowerCase();break}}i.push({id:a,status:c,start:n,end:o,text:s.join(`
|
|
212
|
+
`)})}return i}function K(e){return B.includes(e.toLowerCase())}function Ie(e,t){return t.some(t=>t.start>e.start&&t.start<e.end&&t.status!==`x`)}function q(e,t){let n=V(e),r=H(n),i=new Set;for(let e of t)for(let t=e.start;t<e.end;t++)i.add(t);let a=(e,t)=>t?0:e.match(z)?.[1]?.length??0,o=new Set;for(let e=0;e<n.length;e++){let t=a(n[e]??``,r[e]);if(!(t<2))for(let s=e+1;s<n.length;s++){let c=a(n[s]??``,r[s]);if(c&&c<=t)break;if(i.has(s)){o.add(e);break}}}let s=n.map((e,t)=>({text:e,index:t})).filter(e=>!i.has(e.index));for(let e=!0;e;){e=!1;let t=H(s.map(e=>e.text));for(let n=s.length-1;n>=0;n--){let r=s[n];if(!r||!o.has(r.index))continue;let i=a(r.text,t[n]);if(i<2)continue;let c=n+1,l=!0;for(;c<s.length;c++){let e=s[c]?.text??``,n=a(e,t[c]);if(n&&n<=i)break;if(n||e.trim()!==``){l=!1;break}}if(l){s=[...s.slice(0,n),...s.slice(c)],e=!0;break}}}let c=[];for(let{text:e}of s)e.trim()===``&&(c.at(-1)??`x`).trim()===``||c.push(e);for(;c.length&&(c.at(-1)??``).trim()===``;)c.pop();return c.join(`
|
|
213
|
+
`)+`
|
|
214
|
+
`}function Le(e,t){let n=W(e),r=[];for(let e of n)r.some(t=>e.start>=t.start&&e.start<t.end)||!t(e)||Ie(e,n)||r.push(e);return r.length?{remaining:q(e,r),moved:r}:{remaining:e,moved:r}}function Re(e,t){let n=G(e).filter(t);return n.length?{remaining:q(e,n),moved:n}:{remaining:e,moved:n}}function ze(e){let t=e.split(`
|
|
215
|
+
`),n=U(t[0]??``);return n?t.map(e=>U(e)>=n?e.slice(n):e).join(`
|
|
216
|
+
`):e}function Be(e,t){if(/Completed:\s*\d{4}-\d{2}-\d{2}/.test(e))return e;let[n=``,...r]=e.split(`
|
|
217
|
+
`),i=n.match(/`Complexity: [^`]+`/);return[i?n.replace(i[0],`${i[0]} \`Completed: ${t}\``):`${n} \`Completed: ${t}\``,...r].join(`
|
|
218
|
+
`)}function Ve(e,t,n){let[r=``,...i]=e.split(`
|
|
219
|
+
`);return[`${r} \`Abandoned: ${t}\` — ${n}`,...i].join(`
|
|
220
|
+
`)}function He(e,t,n,r){let i=`# ${t===`tasks`?`Closed tasks`:`Closed issues`}\n\n> Append-only history moved out of \`.autonomos/${t===`tasks`?`TASKS.md`:`ISSUES.md`}\`. Not startup context; search by ID.\n`,a=[e&&e.trim()?e.replace(/\s*$/,`
|
|
221
|
+
`):i];r&&a.push(`## ${r}\n`);let o=t===`issues`?`
|
|
222
|
+
|
|
223
|
+
`:`
|
|
224
|
+
`;return a.push(n.map(e=>e.replace(/\s*$/,``)).join(o)+`
|
|
225
|
+
`),a.join(`
|
|
226
|
+
`)}const Ue=new Set([`node_modules`,`dist`,`build`,`coverage`]);function J(e){return Buffer.byteLength(r(e,`utf8`))}function Y(e){return`${e.toLocaleString(`en-US`)} bytes`}function X(e){try{return n(e).isFile()?r(e,`utf8`):void 0}catch{return}}function Z(e){let t=[],n=e=>{let r;try{r=i(e,{withFileTypes:!0})}catch{return}for(let i of r)i.isFile()&&i.name===`AGENT.md`?t.push(c(e,i.name)):i.isDirectory()&&!i.name.startsWith(`.`)&&!Ue.has(i.name)&&n(c(e,i.name))};return n(e),t.sort()}function We(e,n={}){let r={...S,...n.budgets},a=[],o=c(e,h),s=t=>u(e,t),l=n.artifactFormat??1;l<2&&a.push({code:`format-outdated`,path:s(c(o,`manifest.json`)),message:`Records use artifact format ${l}; run \`autonomos migrate\` to reach format 2.`});let d=c(o,_),f=X(d);if(f!==void 0){let e=W(f),t=e.filter(e=>e.status===`x`).map(e=>e.id);t.length&&a.push({code:`closed-tasks-in-current`,path:s(d),message:`${t.length} completed task(s) still in the current registry; run \`autonomos close <ID>\`.`,items:t});let n=Buffer.byteLength(f);n>r.tasksBytes&&a.push({code:`tasks-size`,path:s(d),message:`${Y(n)} exceeds the ${Y(r.tasksBytes)} budget.`});let i=e.filter(e=>e.status!==`x`&&e.text.length>r.taskEntryChars).sort((e,t)=>t.text.length-e.text.length);i.length&&a.push({code:`task-entry-length`,path:s(d),message:`${i.length} open task entr${i.length===1?`y exceeds`:`ies exceed`} ${r.taskEntryChars} characters; keep evidence in worklogs.`,items:i.map(e=>`${e.id} (${e.text.length})`)})}let p=c(o,x),m=X(p);if(m!==void 0){let e=G(m).filter(e=>K(e.status)).map(e=>e.id);e.length&&a.push({code:`closed-issues-in-current`,path:s(p),message:`${e.length} closed issue(s) still in the current registry; run \`autonomos close <ID>\`.`,items:e});let t=Buffer.byteLength(m);t>r.issuesBytes&&a.push({code:`issues-size`,path:s(p),message:`${Y(t)} exceeds the ${Y(r.issuesBytes)} budget.`})}for(let t of Z(e)){let n=t===c(e,v),i=n?r.rootAgentBytes:r.localAgentBytes,o=J(t);o>i&&a.push({code:n?`root-agent-size`:`local-agent-size`,path:s(t),message:`${Y(o)} exceeds the ${Y(i)} budget; move scoped or incidental knowledge to a narrower AGENT.md or project documentation.`})}let g=c(o,y);if(t(g)){let e=[];for(let t of i(g,{withFileTypes:!0})){if(!t.isFile()||!t.name.endsWith(`.md`))continue;let n=J(c(g,t.name));n>r.worklogBytes&&e.push({name:t.name,bytes:n})}e.length&&(e.sort((e,t)=>t.bytes-e.bytes),a.push({code:`worklog-size`,path:s(g),message:`${e.length} worklog(s) exceed ${Y(r.worklogBytes)}; keep only outcome, decisions, validation and open items.`,items:e.map(e=>`${e.name} (${Y(e.bytes)})`)}))}return a}function Ge(e,t){return n=>n===e?t:n.startsWith(e+f)?t+n.slice(e.length):n}function Q(...e){return t=>e.reduce((e,t)=>t(e),t)}const Ke=/\]\((<[^>\n]+>|[^)\s]+)((?:\s+"[^"\n]*")?)\)/g,qe=/^(\s{0,3}\[[^\]\n]+\]:\s*)(<[^>\n]+>|\S+)/gm;function Je(e){return!!e&&!e.startsWith(`#`)&&!s(e)&&!/^[a-z][\w+.-]*:/i.test(e)}function $(e){return e.split(f).join(l.sep)}function Ye(e,t,n,r=e=>e){let i=e=>{let i=e.startsWith(`<`)&&e.endsWith(`>`),a=i?e.slice(1,-1):e;if(!Je(a))return e;let o=a.search(/[#?]/),s=o===-1?a:a.slice(0,o),c=o===-1?``:a.slice(o);if(!s)return e;let l=s;try{l=decodeURI(s)}catch{}let f=d(t,l),p=r(f);if(p===f&&t===n)return e;let m=$(u(n,p))||`.`;if(s.startsWith(`./`)&&!m.startsWith(`.`)&&(m=`./${m}`),m===$(l))return e;let h=i?m:m.replace(/ /g,`%20`);return i?`<${h}${c}>`:`${h}${c}`};return e.replace(Ke,(e,t,n)=>`](${i(t)}${n})`).replace(qe,(e,t,n)=>`${t}${i(n)}`)}function Xe(e,t,n,r){if(!e.includes(t+`/`))return e;let i=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),a=RegExp(`(?<![\\w./-])${i}/([^\\s)\\]>'"\`,;|]+)`,`g`);return e.replace(a,(e,t)=>{let i=t;for(;i&&!r.has(i)&&/[._*~]$/.test(i);)i=i.slice(0,-1);return r.has(i)?`${n}/${i}${t.slice(i.length)}`:e})}export{v as AGENT_FILE,le as AGENT_TEMPLATE,b as ARCHIVE_DIR,oe as ARCHIVE_INDEX_FILE,re as ARTIFACT_FORMAT,h as AUTONOMOS_DIR,Se as AgentParser,ie as CLOSED_DIR,B as CLOSED_ISSUE_STATUSES,ce as COMPLEXITIES,S as CONTEXT_BUDGETS,ne as DECISIONS_DIR,T as HarnessCodesSchema,w as HarnessSchema,x as ISSUES_FILE,C as InstallerSchema,ae as LEGACY_WORKLOGS_DIR,ue as LOCAL_AGENT_TEMPLATE,g as MANIFEST_FILE,E as ManifestSchema,se as PRIORITIES,ee as PROTOCOL_FILE,k as PROTOCOL_TEMPLATE,he as PROTOCOL_TEMPLATE_V2026_1,m as PROTOCOL_VERSION,te as SPECS_DIR,_ as TASKS_FILE,ge as TASKS_TEMPLATE,N as TaskParser,y as WORKLOGS_DIR,He as appendToClosedRegistry,We as checkContextBudgets,Q as composeMappers,de as createManifest,ze as dedentEntry,Ee as displayRelative,Re as extractIssues,Le as extractTasks,Z as findAgentFilePaths,ye as findAncestorAgents,we as findProjectRoot,D as generateAgentTemplate,O as generateLocalAgentTemplate,fe as generateManifestContent,_e as generateWorklogContent,F as getHarness,je as getRawHarnessCodes,K as isClosedIssueStatus,Te as isSamePath,I as listHarnesses,Oe as listPreferredHarnesses,me as manifestArtifactFormat,ve as mapTaskStatusToWorklogStatus,G as parseIssueEntries,pe as parseManifest,W as parseTaskEntries,Ge as prefixMapper,De as readTaskRegistry,Ye as relocateLinks,Xe as relocateRootMentions,ke as resolveTargets,Ve as stampAbandoned,Be as stampCompleted};
|
|
232
227
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -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/project-root.ts","../src/parsers/task-parser.ts","../src/parsers/task-registry.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.7.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\n/**\n * Optional project-owned directory for durable target-state specifications\n */\nexport const SPECS_DIR = 'specs'\n\n/**\n * Optional project-owned directory for technical decision records (ADRs)\n */\nexport const DECISIONS_DIR = 'decisions'\n\n/** Optional project-owned history, never loaded by default. */\nexport const ARCHIVE_DIR = 'archive'\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 the protocol workflow files 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 promptsDir: z.string().optional(),\n globalTargetDir: z.string().optional(),\n fileExtension: z.string(),\n _note: z.string().optional(),\n })\n .refine(\n data =>\n Boolean(data.workflowsDir) ||\n Boolean(data.targetDir) ||\n Boolean(data.skillsDir) ||\n Boolean(data.commandsDir) ||\n Boolean(data.promptsDir),\n {\n message:\n 'At least one of `workflowsDir`, `targetDir`, `skillsDir`, `commandsDir`, or `promptsDir` 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- **Design:** If present, read root \\`DESIGN.md\\` before changing a user-facing surface; use \\`/design\\` for new direction, critique, or design-knowledge extraction.\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.7\n *\n * Design principles (v0.7):\n * - PROTOCOL.md is a compact REFERENCE, not an executable workflow.\n * - All step-by-step instructions live in the 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| Triage a problem or proposal | Read the optional \\`/issue\\` workflow |\n| Adopt existing project knowledge | Read the optional \\`/adopt\\` workflow |\n| Reconcile drift and archive history | Read the \\`/reconcile\\` workflow |\n| Design or critique a surface | Read the optional \\`/design\\` workflow |\n| End a session | Read the \\`/crystallize\\` workflow |\n| Get context | Read root \\`AGENT.md\\`, then only the selected scope's ancestor chain |\n| Resolve objective | Explicit user request first; otherwise resume \\`[/]\\` or pick highest-priority \\`[ ]\\` |\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 | Durable guidance for its directory scope |\n| \\`TASKS.md\\` | \\`.autonomos/TASKS.md\\` | Current task state and optional Current direction |\n| \\`ISSUES.md\\` | \\`.autonomos/ISSUES.md\\` | Optional problem, proposal, and question intake |\n| \\`worklogs/\\` | \\`.autonomos/worklogs/\\` | Historical session evidence, not current guidance |\n| \\`archive/\\` | \\`.autonomos/archive/\\` | Optional history, searched only when justified |\n| \\`specs/\\` | \\`.autonomos/specs/\\` | Optional project-owned normative target state |\n| \\`decisions/\\` | \\`.autonomos/decisions/\\` | Optional project-owned decision records (ADRs) |\n| \\`DESIGN.md\\` | Root or target scope | Optional project-owned visual/interaction direction |\n| \\`PROTOCOL.md\\` | \\`.autonomos/PROTOCOL.md\\` | This file — read-only reference |\n| \\`manifest.json\\` | \\`.autonomos/manifest.json\\` | Protocol version metadata |\n\n## Design Direction Boundary\n\n\\`DESIGN.md\\` is optional project-owned direction, not a managed protocol\nartifact. Use \\`/design\\` when a surface needs direction, critique, or\ndesign-knowledge extraction; keep the project's identity and examples local.\nThe workflow supplies routing and evidence rules, not a universal visual style.\n\n## AGENT.md Format Rules\n\nStore only stable guidance that will affect different future tasks. Keep transient evidence in worklogs and operational explanations in component documentation. Use the narrowest applicable \\`AGENT.md\\`; consolidate or replace obsolete entries instead of appending history. Preserve valid subclaims in mixed paragraphs. Check the resulting text for completed-action narratives, task progress and unsupported prohibitions; these do not belong in operating guidance.\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\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## Issue, Specification, Decision, and Task Rules\n\nIssues describe evidence, impact, and a desired outcome without choosing implementation; proposed directions remain hypotheses until an approach is accepted. Specifications describe accepted target behavior or requirements that may guide multiple tasks. A decision record (commonly ADR, Architecture Decision Record) captures one technical choice and its rationale. Tasks describe an accepted intervention and completion criteria. Use optional \\`ISSUES.md\\`, \\`specs/\\`, and \\`decisions/\\` only when they provide value; direct, clear changes may become tasks immediately. Link related issues, specs, decisions, and tasks in both directions.\n\n## Specification and Decision Rules\n\n- \\`.autonomos/specs/\\` and \\`.autonomos/decisions/\\` are optional, project-owned, first-use directories; \\`init\\`, \\`update\\`, and artifact-integrity checks do not create or overwrite them.\n- Keep one Markdown file per bounded specification or decision. Include status, scope, provenance, acceptance criteria or consequences, and replacement links where relevant; no parser or independent version is required initially.\n- Specification status is \\`draft\\`, \\`accepted\\`, or \\`superseded\\`. Only \\`accepted\\` is normative; \\`superseded\\` points to its successor. Acceptance does not mean implementation is complete.\n- Decision records use \\`proposed\\`, \\`accepted\\`, or \\`superseded\\`; they preserve rationale and alternatives rather than duplicating the full specification.\n- Keep stable agent operating rules in \\`AGENT.md\\`, user/developer reference in \\`docs/\\`, execution state in \\`TASKS.md\\`, and historical evidence in \\`worklogs/\\`.\n- Read only relevant accepted records at task start. Use \\`/adopt\\` to extract legacy knowledge; never rewrite historical worklogs, issues, or tasks to create current artifacts.\n\nThe protocol-facing name is **decision record**. **ADR** (Architecture Decision Record) is a common convention for the same kind of document, not a required external standard. Use these lightweight Markdown shapes as a starting point; they are conventions, not parser-enforced schemas:\n\n\\`\\`\\`markdown\n# SPEC-001 — Concise target-state title\n\n- Status: draft | accepted | superseded\n- Scope: component, capability, or boundary\n- Provenance: issue, discussion, or source links\n- Related decisions: ADR-001, ...\n- Superseded by: SPEC-002 (when applicable)\n\n## Intent\n\n## Requirements\n\n## Acceptance criteria\n\n## Out of scope\n\\`\\`\\`\n\n\\`\\`\\`markdown\n# ADR-001 — Concise decision title\n\n- Status: proposed | accepted | superseded\n- Scope: component or technical boundary\n- Provenance: issue, task, or investigation links\n- Related specs: SPEC-001, ...\n- Superseded by: ADR-002 (when applicable)\n\n## Context\n\n## Decision\n\n## Alternatives considered\n\n## Consequences\n\\`\\`\\`\n\nOnly user/project governance accepts a specification or decision as normative. Agents may draft and link records, but must not silently promote them; acceptance is separate from implementation completion.\n\n## Current Context and Archival Lifecycle\n\n- Current context must support ordinary work without archives. Keep applicable guidance, accepted requirements/decisions, unresolved work, dependencies and necessary next actions discoverable. Acceptance is independent of implementation; dated temporary directives remain active until lifted or their stated end condition is met.\n- A completed task or resolved/declined issue is an archival candidate only when its own scope is settled and still-needed outcomes/constraints/references are retained in current context. Explicitly abandoned work may be archived with its reason, without claiming it was completed. A completed child does not satisfy unmet parent acceptance criteria.\n- Record new task completion dates as \\`Completed: YYYY-MM-DD\\`; do not infer missing old dates from worklog filenames. Age, a checkbox, absent code or a newer statement alone is not proof of obsolescence.\n- Group archival at coherent completed-work boundaries, not per task or calendar interval. No Sprint object or scheduled maintenance is required. Correct certain in-scope drift proactively during normal work; use \\`/reconcile\\` for investigation, consolidation and archival.\n- Before moving history, consolidate current knowledge in its existing narrowest home. Optional \\`Current direction\\` in \\`TASKS.md\\` explains present aims, recent consequential outcomes and next work; rewrite it rather than append chronology. Keep progress out of \\`AGENT.md\\`.\n- Create project-owned \\`.autonomos/archive/README.md\\` and meaningful batch directories on first use only. A batch can contain \\`TASKS.md\\`, \\`ISSUES.md\\`, \\`worklogs/\\` and provenance for retired guidance. Group/split batches by useful scope; there is no fixed age, size or mandatory per-record schema.\n- Archive means move, not delete or rewrite conclusions. Preserve historical record content, identifiers and provenance; repair relative paths when necessary. Preserve original mixed-source text when retiring only some claims. Applicable specs/decisions stay current independently of execution records. Extraction into new normative artifacts still uses \\`/adopt\\`.\n- The archive index maps batch topics to records, not a second task journal. Search by ID or subject only when a specific question requires history; neither archives nor their entire index are routine startup context. Keep only necessary dependency/outcome pointers in current records, not a permanent stub for every completed task.\n- Archived task and issue IDs remain reserved. Before assigning an ID, search current and archived registries. With a CLI, \\`readTaskRegistry(root, { history: true })\\` exposes task references and duplicates; plain Markdown search works without it.\n- Verify exact source text before edits, retained current knowledge, IDs and resolvable references after moves. Do not confuse tool annotations with file content or historical validation with a current observation. Re-read shared files before writing and preserve unrelated concurrent changes. Stop when a second pass yields no deterministic correction.\n- \\`autonomos status\\` summarizes the current task registry; \\`--history\\` adds separate archived counts and read/collision diagnostics. Archived means historical, not necessarily completed. History uses batch \\`TASKS.md\\` files, not arbitrary worklog checklists.\n- Archives are project-owned, like specs and decisions. Initialization, updates and integrity checks neither create empty archives nor overwrite, relocate or judge their contents. Installing a new protocol performs no automatic cleanup. Version-control policy stays project-owned; Git is not required for archival or retrieval.\n\nExample (only files needed by a batch are created):\n\n\\`\\`\\`text\n.autonomos/\n TASKS.md\n ISSUES.md\n archive/\n README.md\n realtime-experiment-retirement/\n TASKS.md\n ISSUES.md\n worklogs/\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, [M] Medium, [L] Large, [XL] Huge (Planning required)\n> **Status:** [ ] Todo, [/] In Progress, [x] Done, [!] Blocked\n\n## 🚀 Current work\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 /** Discover IDs/status without requiring optional priority or complexity metadata. */\n static references(markdown: string): { id: string; status: TaskStatus; line: number }[] {\n const references: { id: string; status: TaskStatus; line: number }[] = []\n let fence: string | undefined\n for (const [index, line] of markdown.split(/\\r?\\n/).entries()) {\n const marker = line.match(/^\\s{0,3}(`{3,}|~{3,})/)\n if (marker?.[1]) {\n if (!fence) fence = marker[1]\n else if (\n marker[1][0] === fence[0] &&\n marker[1].length >= fence.length &&\n !line.slice(marker[0].length).trim()\n )\n fence = undefined\n continue\n }\n if (fence) continue\n const match = line.match(/^\\s*- \\[([ x/!])\\] \\*\\*\\[([^\\]]+)\\]\\*\\*/)\n if (match?.[1] && match[2]?.trim()) {\n references.push({\n id: match[2].trim(),\n status: this.mapStatus(match[1]),\n line: index + 1,\n })\n }\n }\n return references\n }\n\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 { lstatSync, readFileSync, readdirSync } from 'node:fs'\nimport { join, relative } from 'node:path'\n\nimport { ARCHIVE_DIR, AUTONOMOS_DIR, TASKS_FILE } from '../constants'\nimport { TaskParser } from './task-parser'\n\nexport interface TaskReference {\n id: string\n status: ReturnType<typeof TaskParser.references>[number]['status']\n line: number\n /** Source path relative to the supplied project root. */\n path: string\n}\n\nexport interface TaskRegistry {\n current: TaskReference[]\n archived: TaskReference[]\n duplicateIds: string[]\n warnings: string[]\n /** False if a requested registry could not be inspected completely. */\n complete: boolean\n}\n\n/** Read current task IDs; opt into history for reporting or reserving a new ID. */\nexport function readTaskRegistry(root: string, options: { history?: boolean } = {}): TaskRegistry {\n const registry: TaskRegistry = {\n current: [],\n archived: [],\n duplicateIds: [],\n warnings: [],\n complete: true,\n }\n function warn(path: string, message: string): void {\n registry.complete = false\n registry.warnings.push(`${relative(root, path)}: ${message}`)\n }\n function read(path: string, target: TaskReference[]): void {\n try {\n const stat = lstatSync(path)\n if (!stat.isFile()) {\n warn(path, 'Expected a regular task registry; symbolic links are not followed')\n return\n }\n target.push(\n ...TaskParser.references(readFileSync(path, 'utf8')).map(task => ({\n ...task,\n path: relative(root, path),\n }))\n )\n } catch (error) {\n warn(path, error instanceof Error ? error.message : String(error))\n }\n }\n function scan(path: string, optional = false): void {\n try {\n const stat = lstatSync(path)\n if (!stat.isDirectory()) {\n warn(path, 'Expected an archive directory; symbolic links are not followed')\n return\n }\n for (const entry of readdirSync(path, { withFileTypes: true }).sort((a, b) =>\n a.name.localeCompare(b.name)\n )) {\n const child = join(path, entry.name)\n if (entry.isSymbolicLink()) warn(child, 'Skipped symbolic link in archive')\n else if (entry.isDirectory()) scan(child)\n else if (entry.name === TASKS_FILE) read(child, registry.archived)\n }\n } catch (error) {\n if (optional && (error as NodeJS.ErrnoException).code === 'ENOENT') return\n warn(path, error instanceof Error ? error.message : String(error))\n }\n }\n const autonomosPath = join(root, AUTONOMOS_DIR)\n try {\n if (!lstatSync(autonomosPath).isDirectory()) {\n warn(\n autonomosPath,\n 'Expected a regular project directory; symbolic links are not followed'\n )\n return registry\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n warn(autonomosPath, error instanceof Error ? error.message : String(error))\n }\n return registry\n }\n const currentPath = join(autonomosPath, TASKS_FILE)\n try {\n lstatSync(currentPath)\n read(currentPath, registry.current)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n warn(currentPath, error instanceof Error ? error.message : String(error))\n }\n }\n if (options.history) scan(join(root, AUTONOMOS_DIR, ARCHIVE_DIR), true)\n const seen = new Set<string>()\n const duplicates = new Set<string>()\n for (const task of [...registry.current, ...registry.archived]) {\n if (seen.has(task.id)) duplicates.add(task.id)\n seen.add(task.id)\n }\n registry.duplicateIds = [...duplicates].sort()\n return registry\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\nexport type TargetKind = 'flat' | 'skill'\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 /** Whether target receives flat files (e.g. session.md) or skill bundles (e.g. protocol-session/SKILL.md) */\n kind: TargetKind\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 * Antigravity, Claude Code all use `.agents/skills/`) are deduplicated:\n * the directory appears once 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, 'flat', harnessId)\n }\n if (installer.commandsDir) {\n addTarget(map, joinPath(cwd, installer.commandsDir), ext, 'flat', harnessId)\n }\n if (installer.promptsDir) {\n addTarget(map, joinPath(cwd, installer.promptsDir), ext, 'flat', harnessId)\n }\n if (installer.targetDir) {\n addTarget(map, joinPath(cwd, installer.targetDir), ext, 'flat', harnessId)\n }\n if (installer.skillsDir) {\n addTarget(map, joinPath(cwd, installer.skillsDir), ext, 'skill', harnessId)\n }\n}\n\nfunction addTarget(\n map: Map<string, ResolvedTarget>,\n path: string,\n fileExtension: string,\n kind: TargetKind,\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, kind, 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":"sPAIA,MAAa,EAAmB,cAKnB,EAAgB,aAKhB,EAAgB,gBAKhB,EAAgB,cAKhB,EAAa,WAKb,EAAa,WAKb,GAAe,WAKf,GAAY,QAKZ,EAAgB,YAGhB,EAAc,UCjCd,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,WAAY,EAAE,OAAO,CAAC,CAAC,SAAS,EAChC,gBAAiB,EAAE,OAAO,CAAC,CAAC,SAAS,EACrC,cAAe,EAAE,OAAO,EACxB,MAAO,EAAE,OAAO,CAAC,CAAC,SAAS,CAC/B,CAAC,CAAC,CACD,OACG,GACI,EAAQ,EAAK,cACb,EAAQ,EAAK,WACb,EAAQ,EAAK,WACb,EAAQ,EAAK,aACb,EA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
+
{"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/parsers/task-registry.ts","../src/data/harness-codes.json","../src/harness-codes.ts","../src/records/registry-edit.ts","../src/records/budgets.ts","../src/records/links.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.8.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\n/**\n * Optional project-owned directory for durable target-state specifications\n */\nexport const SPECS_DIR = 'specs'\n\n/**\n * Optional project-owned directory for technical decision records (ADRs)\n */\nexport const DECISIONS_DIR = 'decisions'\n\n/** Optional project-owned history, never loaded by default. */\nexport const ARCHIVE_DIR = 'archive'\n\n/**\n * Layout version of project-owned records. Absent in a manifest means 1.\n * Format 2: current registries hold open work only, closed records live in\n * `archive/closed/`, and worklogs follow the proportionate shape.\n */\nexport const ARTIFACT_FORMAT = 2\n\n/** Issues registry filename. */\nexport const ISSUES_FILE = 'ISSUES.md'\n\n/** Append-only registries of closed tasks and issues, under the archive. */\nexport const CLOSED_DIR = 'closed'\n\n/** Archive batch that receives worklogs written before artifact format 2. */\nexport const LEGACY_WORKLOGS_DIR = 'worklogs-format-1'\n\n/** Archive index filename. */\nexport const ARCHIVE_INDEX_FILE = 'README.md'\n\n/**\n * Advisory size budgets (bytes or characters) reported by `autonomos status`.\n * They keep startup and close-out context proportionate; they are not parsers.\n */\nexport const CONTEXT_BUDGETS = {\n rootAgentBytes: 8_000,\n localAgentBytes: 4_000,\n tasksBytes: 16_000,\n issuesBytes: 24_000,\n taskEntryChars: 300,\n worklogBytes: 2_500,\n} as const\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 the protocol workflow files 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 promptsDir: z.string().optional(),\n globalTargetDir: z.string().optional(),\n fileExtension: z.string(),\n _note: z.string().optional(),\n })\n .refine(\n data =>\n Boolean(data.workflowsDir) ||\n Boolean(data.targetDir) ||\n Boolean(data.skillsDir) ||\n Boolean(data.commandsDir) ||\n Boolean(data.promptsDir),\n {\n message:\n 'At least one of `workflowsDir`, `targetDir`, `skillsDir`, `commandsDir`, or `promptsDir` 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 artifactFormat: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('Layout version of project-owned records; absent means 1'),\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- **Design:** If present, read root \\`DESIGN.md\\` before changing a user-facing surface; use \\`/design\\` for new direction, critique, or design-knowledge extraction.\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 { ARTIFACT_FORMAT, 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 artifactFormat: ARTIFACT_FORMAT,\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\n/** Artifact format recorded by a manifest (format 1 when absent). */\nexport function manifestArtifactFormat(manifest: Manifest): number {\n return manifest.artifactFormat ?? 1\n}\n","import { PROTOCOL_VERSION } from '../constants'\n\n/**\n * The Protocol kernel template — v0.8\n *\n * Design principles (v0.8):\n * - PROTOCOL.md is a compact REFERENCE, not an executable workflow.\n * - All step-by-step instructions live in the 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| Triage a problem or proposal | Read the optional \\`/issue\\` workflow |\n| Adopt existing project knowledge | Read the optional \\`/adopt\\` workflow |\n| Reconcile drift and archive history | Read the \\`/reconcile\\` workflow |\n| Design or critique a surface | Read the optional \\`/design\\` workflow |\n| End a session | Read the \\`/crystallize\\` workflow |\n| Get context | Read root \\`AGENT.md\\`, then only the selected scope's ancestor chain |\n| Resolve objective | Explicit user request first; otherwise resume \\`[/]\\` or pick highest-priority \\`[ ]\\` |\n| Log session work | Create \\`.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md\\` (shape in \\`/crystallize\\`) |\n| Close finished work | \\`autonomos close <ID>\\` → \\`.autonomos/archive/closed/\\` |\n| Check context budgets | \\`autonomos status\\`; upgrade old records with \\`autonomos migrate\\` |\n\n## File Map\n\n| File | Location | Role |\n| --------------- | -------------------------- | --------------------------------------------------------------------- |\n| \\`AGENT.md\\` | Root + any subdirectory | Durable guidance for its directory scope |\n| \\`TASKS.md\\` | \\`.autonomos/TASKS.md\\` | Open tasks and optional Current direction |\n| \\`ISSUES.md\\` | \\`.autonomos/ISSUES.md\\` | Optional intake: open and accepted issues only |\n| \\`worklogs/\\` | \\`.autonomos/worklogs/\\` | Historical session evidence, not current guidance |\n| \\`archive/\\` | \\`.autonomos/archive/\\` | History (\\`closed/\\` registries, batches), searched only when justified |\n| \\`specs/\\` | \\`.autonomos/specs/\\` | Optional project-owned normative target state |\n| \\`decisions/\\` | \\`.autonomos/decisions/\\` | Optional project-owned decision records (ADRs) |\n| \\`DESIGN.md\\` | Root or target scope | Optional project-owned visual/interaction direction |\n| \\`PROTOCOL.md\\` | \\`.autonomos/PROTOCOL.md\\` | This file — read-only reference |\n| \\`manifest.json\\` | \\`.autonomos/manifest.json\\` | Protocol version and artifact format |\n\n## Design Direction Boundary\n\n\\`DESIGN.md\\` is optional project-owned direction, not a managed protocol\nartifact. Use \\`/design\\` when a surface needs direction, critique, or\ndesign-knowledge extraction; keep the project's identity and examples local.\nThe workflow supplies routing and evidence rules, not a universal visual style.\n\n## AGENT.md Format Rules\n\nStore only stable guidance that will affect different future tasks. Keep transient evidence in worklogs and operational explanations in component documentation. Use the narrowest applicable \\`AGENT.md\\`; consolidate or replace obsolete entries instead of appending history. Preserve valid subclaims in mixed paragraphs. Check the resulting text for completed-action narratives, task progress and unsupported prohibitions; these do not belong in operating guidance.\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\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## Issue, Specification, Decision, and Task Rules\n\nIssues describe evidence, impact, and a desired outcome without choosing implementation; proposed directions remain hypotheses until an approach is accepted. Specifications describe accepted target behavior or requirements that may guide multiple tasks. A decision record (commonly ADR, Architecture Decision Record) captures one technical choice and its rationale. Tasks describe an accepted intervention and completion criteria. Use optional \\`ISSUES.md\\`, \\`specs/\\`, and \\`decisions/\\` only when they provide value; direct, clear changes may become tasks immediately. Link related issues, specs, decisions, and tasks in both directions.\n\n## Specification and Decision Rules\n\n- \\`.autonomos/specs/\\` and \\`.autonomos/decisions/\\` are optional, project-owned, first-use directories; \\`init\\`, \\`update\\`, and artifact-integrity checks do not create or overwrite them.\n- Keep one Markdown file per bounded specification or decision. Include status, scope, provenance, acceptance criteria or consequences, and replacement links where relevant; no parser or independent version is required initially.\n- Specification status is \\`draft\\`, \\`accepted\\`, or \\`superseded\\`. Only \\`accepted\\` is normative; \\`superseded\\` points to its successor. Acceptance does not mean implementation is complete.\n- Decision records use \\`proposed\\`, \\`accepted\\`, or \\`superseded\\`; they preserve rationale and alternatives rather than duplicating the full specification.\n- Keep stable agent operating rules in \\`AGENT.md\\`, user/developer reference in \\`docs/\\`, execution state in \\`TASKS.md\\`, and historical evidence in \\`worklogs/\\`.\n- Read only relevant accepted records at task start. Use \\`/adopt\\` to extract legacy knowledge; never rewrite historical worklogs, issues, or tasks to create current artifacts.\n\nThe protocol-facing name is **decision record**. **ADR** (Architecture Decision Record) is a common convention for the same kind of document, not a required external standard. Use these lightweight Markdown shapes as a starting point; they are conventions, not parser-enforced schemas:\n\n\\`\\`\\`markdown\n# SPEC-001 — Concise target-state title\n\n- Status: draft | accepted | superseded\n- Scope: component, capability, or boundary\n- Provenance: issue, discussion, or source links\n- Related decisions: ADR-001, ...\n- Superseded by: SPEC-002 (when applicable)\n\n## Intent\n\n## Requirements\n\n## Acceptance criteria\n\n## Out of scope\n\\`\\`\\`\n\n\\`\\`\\`markdown\n# ADR-001 — Concise decision title\n\n- Status: proposed | accepted | superseded\n- Scope: component or technical boundary\n- Provenance: issue, task, or investigation links\n- Related specs: SPEC-001, ...\n- Superseded by: ADR-002 (when applicable)\n\n## Context\n\n## Decision\n\n## Alternatives considered\n\n## Consequences\n\\`\\`\\`\n\nOnly user/project governance accepts a specification or decision as normative. Agents may draft and link records, but must not silently promote them; acceptance is separate from implementation completion.\n\n## Current Context and Archival Lifecycle\n\n- Current context must support ordinary work without archives, and its size follows open work, not project age. Keep applicable guidance, accepted requirements/decisions, unresolved work, dependencies and necessary next actions discoverable. Acceptance is independent of implementation; dated temporary directives remain active until lifted or their stated end condition is met.\n- \\`TASKS.md\\` holds \\`[ ]\\`, \\`[/]\\` and \\`[!]\\` tasks; \\`ISSUES.md\\` holds open and accepted issues. When work closes, move its record in the same session to the append-only \\`.autonomos/archive/closed/TASKS.md\\` or \\`ISSUES.md\\` (\\`autonomos close <ID>\\`, or by hand). Unfinished work may be closed only as abandoned, with its reason. A completed child does not satisfy unmet parent acceptance criteria; a parent with open children stays current.\n- Record new task completion dates as \\`Completed: YYYY-MM-DD\\`; do not infer missing old dates. Age, a checkbox, absent code or a newer statement alone is not proof of obsolescence.\n- Before moving history, consolidate still-needed knowledge in its existing narrowest home. Optional \\`Current direction\\` in \\`TASKS.md\\` explains present aims, recent consequential outcomes and next work; rewrite it rather than append chronology. Keep progress out of \\`AGENT.md\\`.\n- Other history may form named batches under \\`.autonomos/archive/<batch>/\\` via \\`/reconcile\\`; create \\`archive/README.md\\` and batch directories on first use only. The index maps topics to records; it is not a second journal.\n- Archive means move, not delete or rewrite conclusions. Preserve historical record content, identifiers and provenance; repair relative paths when necessary. Applicable specs/decisions stay current independently of execution records. Extraction into new normative artifacts still uses \\`/adopt\\`.\n- Archived task and issue IDs remain reserved. Before assigning an ID, search current and archived registries (\\`autonomos status --history\\` reports duplicates).\n- Verify exact source text before edits and resolvable references after moves. Re-read shared files before writing and preserve unrelated concurrent changes.\n\n## Context Budgets\n\nAdvisory limits reported by \\`autonomos status\\` (\\`--strict\\` makes them fail): root \\`AGENT.md\\` 8,000 bytes, local \\`AGENT.md\\` 4,000 bytes, \\`TASKS.md\\` 16 KB, \\`ISSUES.md\\` 24 KB, one task entry 300 characters, one worklog 2,500 bytes, and no closed record in current registries. Over budget, consolidate or move knowledge to its narrowest home before adding more. Root \\`AGENT.md\\` admits only guidance that applies to most tasks in the project.\n\n## Artifact Format and Migration\n\n\\`manifest.json\\` records \\`artifactFormat\\` (absent means 1); this protocol defines format 2. Installing a new protocol performs no automatic cleanup: \\`autonomos update\\` only replaces managed artifacts. \\`autonomos migrate\\` is the explicit, content-preserving upgrade: it closes finished records, moves pre-format-2 worklogs to \\`.autonomos/archive/worklogs-format-1/\\` so they stop serving as examples, repairs references and records the format. Run it with \\`--dry-run\\` first on a clean working tree, then resolve the remaining \\`status\\` findings with \\`/reconcile\\`.\n\n## Task Format\n\nOne line per task: \\`\\` - [Status] **[ID]** Title \\`Priority\\` \\`Complexity\\` \\`\\` plus, when useful, \\`Completed: YYYY-MM-DD\\`, a short note and links to its issue or worklog. Evidence, measurements and progress belong in the worklog, not the task entry.\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, [M] Medium, [L] Large, [XL] Huge (Planning required)\n> **Status:** [ ] Todo, [/] In Progress, [x] Done, [!] Blocked\n\n## 🚀 Current work\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 title: string\n /** 1–3 lines: what is now true. */\n outcome: string\n /** Non-obvious choices with their reason. */\n decisions?: string[]\n /** Checks actually run, `command → result`. */\n validation?: string[]\n /** Limits and follow-ups. */\n open?: string[]\n}\n\nconst list = (items: string[] | undefined): string =>\n items?.length ? '\\n' + items.map(item => `- ${item}`).join('\\n') : ' none'\n\n/**\n * Generate a proportionate worklog (artifact format 2): only what a future\n * agent cannot recover from code, git, tests or other records.\n */\nexport function generateWorklogContent(options: WorklogOptions): string {\n return `# [${options.taskId}] ${options.title}\n\nOutcome: ${options.outcome}\nDecisions:${list(options.decisions)}\nValidation:${list(options.validation)}\nOpen:${list(options.open)}\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 /** Discover IDs/status without requiring optional priority or complexity metadata. */\n static references(markdown: string): { id: string; status: TaskStatus; line: number }[] {\n const references: { id: string; status: TaskStatus; line: number }[] = []\n let fence: string | undefined\n for (const [index, line] of markdown.split(/\\r?\\n/).entries()) {\n const marker = line.match(/^\\s{0,3}(`{3,}|~{3,})/)\n if (marker?.[1]) {\n if (!fence) fence = marker[1]\n else if (\n marker[1][0] === fence[0] &&\n marker[1].length >= fence.length &&\n !line.slice(marker[0].length).trim()\n )\n fence = undefined\n continue\n }\n if (fence) continue\n const match = line.match(/^\\s*- \\[([ x/!])\\] \\*\\*\\[([^\\]]+)\\]\\*\\*/)\n if (match?.[1] && match[2]?.trim()) {\n references.push({\n id: match[2].trim(),\n status: this.mapStatus(match[1]),\n line: index + 1,\n })\n }\n }\n return references\n }\n\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 { lstatSync, readFileSync, readdirSync } from 'node:fs'\nimport { join, relative } from 'node:path'\n\nimport { ARCHIVE_DIR, AUTONOMOS_DIR, TASKS_FILE } from '../constants'\nimport { TaskParser } from './task-parser'\n\nexport interface TaskReference {\n id: string\n status: ReturnType<typeof TaskParser.references>[number]['status']\n line: number\n /** Source path relative to the supplied project root. */\n path: string\n}\n\nexport interface TaskRegistry {\n current: TaskReference[]\n archived: TaskReference[]\n duplicateIds: string[]\n warnings: string[]\n /** False if a requested registry could not be inspected completely. */\n complete: boolean\n}\n\n/** Read current task IDs; opt into history for reporting or reserving a new ID. */\nexport function readTaskRegistry(root: string, options: { history?: boolean } = {}): TaskRegistry {\n const registry: TaskRegistry = {\n current: [],\n archived: [],\n duplicateIds: [],\n warnings: [],\n complete: true,\n }\n function warn(path: string, message: string): void {\n registry.complete = false\n registry.warnings.push(`${relative(root, path)}: ${message}`)\n }\n function read(path: string, target: TaskReference[]): void {\n try {\n const stat = lstatSync(path)\n if (!stat.isFile()) {\n warn(path, 'Expected a regular task registry; symbolic links are not followed')\n return\n }\n target.push(\n ...TaskParser.references(readFileSync(path, 'utf8')).map(task => ({\n ...task,\n path: relative(root, path),\n }))\n )\n } catch (error) {\n warn(path, error instanceof Error ? error.message : String(error))\n }\n }\n function scan(path: string, optional = false): void {\n try {\n const stat = lstatSync(path)\n if (!stat.isDirectory()) {\n warn(path, 'Expected an archive directory; symbolic links are not followed')\n return\n }\n for (const entry of readdirSync(path, { withFileTypes: true }).sort((a, b) =>\n a.name.localeCompare(b.name)\n )) {\n const child = join(path, entry.name)\n if (entry.isSymbolicLink()) warn(child, 'Skipped symbolic link in archive')\n else if (entry.isDirectory()) scan(child)\n else if (entry.name === TASKS_FILE) read(child, registry.archived)\n }\n } catch (error) {\n if (optional && (error as NodeJS.ErrnoException).code === 'ENOENT') return\n warn(path, error instanceof Error ? error.message : String(error))\n }\n }\n const autonomosPath = join(root, AUTONOMOS_DIR)\n try {\n if (!lstatSync(autonomosPath).isDirectory()) {\n warn(\n autonomosPath,\n 'Expected a regular project directory; symbolic links are not followed'\n )\n return registry\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n warn(autonomosPath, error instanceof Error ? error.message : String(error))\n }\n return registry\n }\n const currentPath = join(autonomosPath, TASKS_FILE)\n try {\n lstatSync(currentPath)\n read(currentPath, registry.current)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n warn(currentPath, error instanceof Error ? error.message : String(error))\n }\n }\n if (options.history) scan(join(root, AUTONOMOS_DIR, ARCHIVE_DIR), true)\n const seen = new Set<string>()\n const duplicates = new Set<string>()\n for (const task of [...registry.current, ...registry.archived]) {\n if (seen.has(task.id)) duplicates.add(task.id)\n seen.add(task.id)\n }\n registry.duplicateIds = [...duplicates].sort()\n return registry\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\nexport type TargetKind = 'flat' | 'skill'\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 /** Whether target receives flat files (e.g. session.md) or skill bundles (e.g. protocol-session/SKILL.md) */\n kind: TargetKind\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 * Antigravity, Claude Code all use `.agents/skills/`) are deduplicated:\n * the directory appears once 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, 'flat', harnessId)\n }\n if (installer.commandsDir) {\n addTarget(map, joinPath(cwd, installer.commandsDir), ext, 'flat', harnessId)\n }\n if (installer.promptsDir) {\n addTarget(map, joinPath(cwd, installer.promptsDir), ext, 'flat', harnessId)\n }\n if (installer.targetDir) {\n addTarget(map, joinPath(cwd, installer.targetDir), ext, 'flat', harnessId)\n }\n if (installer.skillsDir) {\n addTarget(map, joinPath(cwd, installer.skillsDir), ext, 'skill', harnessId)\n }\n}\n\nfunction addTarget(\n map: Map<string, ResolvedTarget>,\n path: string,\n fileExtension: string,\n kind: TargetKind,\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, kind, 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","/**\n * Pure text operations on TASKS.md / ISSUES.md used by `close`, `migrate`\n * and budget checks. They never rewrite the content of a moved record.\n */\n\nconst TASK_LINE = /^\\s*- \\[([ x/!])\\] \\*\\*\\[([^\\]]+)\\]\\*\\*/\nconst HEADING = /^(#{1,6})[ \\t]+(\\S.*)?$/\nconst FENCE = /^\\s{0,3}(`{3,}|~{3,})/\nconst ISSUE_HEADING = /^##\\s+\\[([^\\]]+)\\]/\nconst ISSUE_STATUS = /^\\s*[-*]\\s*(?:\\*\\*)?status:?(?:\\*\\*)?:?[ \\t]*(?:\\*\\*)?([a-z-]+)/i\n\n/** Issue statuses that mean the issue no longer needs current attention. */\nexport const CLOSED_ISSUE_STATUSES = ['resolved', 'declined', 'closed', 'superseded', 'rejected']\n\nexport interface TaskEntry {\n id: string\n status: ' ' | 'x' | '/' | '!'\n /** 0-based index of the first line of the entry. */\n start: number\n /** 0-based exclusive end line index. */\n end: number\n /** Heading path enclosing the entry, outermost first (title excluded). */\n headings: string[]\n text: string\n}\n\nexport interface IssueEntry {\n id: string\n status: string\n start: number\n end: number\n text: string\n}\n\nfunction splitLines(markdown: string): string[] {\n return markdown.split(/\\r?\\n/)\n}\n\n/** Mark lines that are inside fenced code blocks (fence lines included). */\nfunction fencedLines(lines: string[]): boolean[] {\n const result: boolean[] = []\n let fence: string | undefined\n for (const line of lines) {\n const marker = line.match(FENCE)\n if (marker?.[1]) {\n if (!fence) {\n fence = marker[1]\n result.push(true)\n continue\n }\n if (\n marker[1][0] === fence[0] &&\n marker[1].length >= fence.length &&\n !line.slice(marker[0].length).trim()\n ) {\n fence = undefined\n result.push(true)\n continue\n }\n }\n result.push(fence !== undefined)\n }\n return result\n}\n\nfunction indentOf(line: string): number {\n return (line.match(/^\\s*/)?.[0] ?? '').replace(/\\t/g, ' ').length\n}\n\n/**\n * Parse task entries: a task line plus following lines indented deeper than it\n * (continuations and sub-bullets). Nested tasks are returned as their own entries\n * and are also part of their parent's text.\n */\nexport function parseTaskEntries(markdown: string): TaskEntry[] {\n const lines = splitLines(markdown)\n const fenced = fencedLines(lines)\n const entries: TaskEntry[] = []\n const headingStack: { level: number; text: string }[] = []\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? ''\n if (fenced[i]) continue\n const heading = line.match(HEADING)\n if (heading?.[1]) {\n const level = heading[1].length\n while (headingStack.length && (headingStack.at(-1)?.level ?? 0) >= level)\n headingStack.pop()\n headingStack.push({ level, text: (heading[2] ?? '').trim() })\n continue\n }\n const match = line.match(TASK_LINE)\n if (!match) continue\n const indent = indentOf(line)\n let end = i + 1\n let lastContent = i + 1\n while (end < lines.length) {\n const next = lines[end] ?? ''\n if (!fenced[end] && next.trim() === '') {\n end++\n continue\n }\n const opensFence = fenced[end] && !fenced[end - 1]\n if (opensFence && indentOf(next) <= indent) break\n if (!fenced[end] && indentOf(next) <= indent) break\n if (!fenced[end] && HEADING.test(next)) break\n end++\n lastContent = end\n }\n entries.push({\n id: (match[2] ?? '').trim(),\n status: (match[1] ?? ' ') as TaskEntry['status'],\n start: i,\n end: lastContent,\n headings: headingStack.filter(h => h.level > 1).map(h => h.text),\n text: lines.slice(i, lastContent).join('\\n'),\n })\n }\n return entries\n}\n\nexport function parseIssueEntries(markdown: string): IssueEntry[] {\n const lines = splitLines(markdown)\n const fenced = fencedLines(lines)\n const starts: number[] = []\n for (let i = 0; i < lines.length; i++) {\n if (!fenced[i] && /^#{1,2}\\s/.test(lines[i] ?? '')) starts.push(i)\n }\n const entries: IssueEntry[] = []\n for (const [index, start] of starts.entries()) {\n const id = (lines[start] ?? '').match(ISSUE_HEADING)?.[1]?.trim()\n if (!id) continue\n let end = starts[index + 1] ?? lines.length\n while (end > start + 1 && (lines[end - 1] ?? '').trim() === '') end--\n const body = lines.slice(start, end)\n let status = ''\n for (const line of body) {\n const m = line.match(ISSUE_STATUS)\n if (m?.[1]) {\n status = m[1].toLowerCase()\n break\n }\n }\n entries.push({ id, status, start, end, text: body.join('\\n') })\n }\n return entries\n}\n\nexport function isClosedIssueStatus(status: string): boolean {\n return CLOSED_ISSUE_STATUSES.includes(status.toLowerCase())\n}\n\n/** True when an entry contains an open nested task (it must stay current). */\nfunction hasOpenDescendant(entry: TaskEntry, all: TaskEntry[]): boolean {\n return all.some(\n other => other.start > entry.start && other.start < entry.end && other.status !== 'x'\n )\n}\n\nexport interface Extraction<T> {\n remaining: string\n moved: T[]\n}\n\n/**\n * Remove whole-line ranges from a document, then drop headings that lost all\n * their content because of the removal (never the level-1 title or a heading\n * that was already empty), and collapse blank-line runs.\n */\nfunction removeRanges(markdown: string, ranges: { start: number; end: number }[]): string {\n const lines = splitLines(markdown)\n const originalFenced = fencedLines(lines)\n const drop = new Set<number>()\n for (const range of ranges) for (let i = range.start; i < range.end; i++) drop.add(i)\n const level = (line: string, fenced: boolean | undefined): number =>\n fenced ? 0 : (line.match(HEADING)?.[1]?.length ?? 0)\n // Headings whose section (up to the next heading of the same or higher level) lost lines.\n const eligible = new Set<number>()\n for (let i = 0; i < lines.length; i++) {\n const own = level(lines[i] ?? '', originalFenced[i])\n if (own < 2) continue\n for (let j = i + 1; j < lines.length; j++) {\n const other = level(lines[j] ?? '', originalFenced[j])\n if (other && other <= own) break\n if (drop.has(j)) {\n eligible.add(i)\n break\n }\n }\n }\n let kept = lines.map((text, index) => ({ text, index })).filter(l => !drop.has(l.index))\n for (let changed = true; changed; ) {\n changed = false\n const fenced = fencedLines(kept.map(l => l.text))\n for (let i = kept.length - 1; i >= 0; i--) {\n const current = kept[i]\n if (!current || !eligible.has(current.index)) continue\n const own = level(current.text, fenced[i])\n if (own < 2) continue\n let j = i + 1\n let empty = true\n for (; j < kept.length; j++) {\n const next = kept[j]?.text ?? ''\n const other = level(next, fenced[j])\n if (other && other <= own) break\n if (other || next.trim() !== '') {\n empty = false\n break\n }\n }\n if (empty) {\n kept = [...kept.slice(0, i), ...kept.slice(j)]\n changed = true\n break\n }\n }\n }\n const collapsed: string[] = []\n for (const { text } of kept) {\n if (text.trim() === '' && (collapsed.at(-1) ?? 'x').trim() === '') continue\n collapsed.push(text)\n }\n while (collapsed.length && (collapsed.at(-1) ?? '').trim() === '') collapsed.pop()\n return collapsed.join('\\n') + '\\n'\n}\n\n/**\n * Extract task entries matching `select` from a TASKS.md document.\n * Entries with open nested tasks are never extracted.\n */\nexport function extractTasks(\n markdown: string,\n select: (entry: TaskEntry) => boolean\n): Extraction<TaskEntry> {\n const all = parseTaskEntries(markdown)\n const moved: TaskEntry[] = []\n for (const entry of all) {\n if (moved.some(m => entry.start >= m.start && entry.start < m.end)) continue\n if (!select(entry) || hasOpenDescendant(entry, all)) continue\n moved.push(entry)\n }\n if (!moved.length) return { remaining: markdown, moved }\n return { remaining: removeRanges(markdown, moved), moved }\n}\n\nexport function extractIssues(\n markdown: string,\n select: (entry: IssueEntry) => boolean\n): Extraction<IssueEntry> {\n const moved = parseIssueEntries(markdown).filter(select)\n if (!moved.length) return { remaining: markdown, moved }\n return { remaining: removeRanges(markdown, moved), moved }\n}\n\n/** Remove the common leading indentation of an entry so it stands alone. */\nexport function dedentEntry(text: string): string {\n const lines = text.split('\\n')\n const indent = indentOf(lines[0] ?? '')\n if (!indent) return text\n return lines.map(line => (indentOf(line) >= indent ? line.slice(indent) : line)).join('\\n')\n}\n\n/** Add `Completed: <date>` to a task line that has no completion date. */\nexport function stampCompleted(text: string, date: string): string {\n if (/Completed:\\s*\\d{4}-\\d{2}-\\d{2}/.test(text)) return text\n const [first = '', ...rest] = text.split('\\n')\n const complexity = first.match(/`Complexity: [^`]+`/)\n const stamped = complexity\n ? first.replace(complexity[0], `${complexity[0]} \\`Completed: ${date}\\``)\n : `${first} \\`Completed: ${date}\\``\n return [stamped, ...rest].join('\\n')\n}\n\n/** Mark an unfinished task as abandoned (it keeps its status marker). */\nexport function stampAbandoned(text: string, date: string, reason: string): string {\n const [first = '', ...rest] = text.split('\\n')\n return [`${first} \\`Abandoned: ${date}\\` — ${reason}`, ...rest].join('\\n')\n}\n\n/** Append entries to a closed registry, creating its header when empty. */\nexport function appendToClosedRegistry(\n existing: string | undefined,\n kind: 'tasks' | 'issues',\n entries: string[],\n groupHeading?: string\n): string {\n const source = kind === 'tasks' ? 'TASKS.md' : 'ISSUES.md'\n const title = kind === 'tasks' ? 'Closed tasks' : 'Closed issues'\n const header = `# ${title}\\n\\n> Append-only history moved out of \\`.autonomos/${source}\\`. Not startup context; search by ID.\\n`\n const base = existing && existing.trim() ? existing.replace(/\\s*$/, '\\n') : header\n const parts = [base]\n if (groupHeading) parts.push(`## ${groupHeading}\\n`)\n const joiner = kind === 'issues' ? '\\n\\n' : '\\n'\n parts.push(entries.map(e => e.replace(/\\s*$/, '')).join(joiner) + '\\n')\n return parts.join('\\n')\n}\n","import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs'\nimport { join, relative } from 'node:path'\n\nimport {\n AGENT_FILE,\n ARTIFACT_FORMAT,\n AUTONOMOS_DIR,\n CONTEXT_BUDGETS,\n ISSUES_FILE,\n TASKS_FILE,\n WORKLOGS_DIR,\n} from '../constants'\nimport { isClosedIssueStatus, parseIssueEntries, parseTaskEntries } from './registry-edit'\n\nexport type BudgetFindingCode =\n | 'format-outdated'\n | 'closed-tasks-in-current'\n | 'closed-issues-in-current'\n | 'tasks-size'\n | 'issues-size'\n | 'task-entry-length'\n | 'root-agent-size'\n | 'local-agent-size'\n | 'worklog-size'\n\nexport interface BudgetFinding {\n code: BudgetFindingCode\n /** Project-relative path the finding concerns. */\n path: string\n message: string\n /** Offending IDs or files, largest first, when relevant. */\n items?: string[]\n}\n\nexport type ContextBudgets = { [K in keyof typeof CONTEXT_BUDGETS]: number }\n\nconst SKIPPED_DIRS = new Set(['node_modules', 'dist', 'build', 'coverage'])\n\nfunction size(path: string): number {\n return Buffer.byteLength(readFileSync(path, 'utf8'))\n}\n\nfunction kb(bytes: number): string {\n return `${bytes.toLocaleString('en-US')} bytes`\n}\n\nfunction readIfFile(path: string): string | undefined {\n try {\n return lstatSync(path).isFile() ? readFileSync(path, 'utf8') : undefined\n } catch {\n return undefined\n }\n}\n\n/** Find AGENT.md files below root, skipping hidden, dependency and build directories. */\nexport function findAgentFilePaths(root: string): string[] {\n const found: string[] = []\n const walk = (dir: string): void => {\n let entries\n try {\n entries = readdirSync(dir, { withFileTypes: true })\n } catch {\n return\n }\n for (const entry of entries) {\n if (entry.isFile() && entry.name === AGENT_FILE) found.push(join(dir, entry.name))\n else if (\n entry.isDirectory() &&\n !entry.name.startsWith('.') &&\n !SKIPPED_DIRS.has(entry.name)\n )\n walk(join(dir, entry.name))\n }\n }\n walk(root)\n return found.sort()\n}\n\n/**\n * Report where current context exceeds the protocol's proportionate budgets.\n * Findings are advisory; agents resolve them through `/reconcile` or `migrate`.\n */\nexport function checkContextBudgets(\n root: string,\n options: { artifactFormat?: number; budgets?: Partial<ContextBudgets> } = {}\n): BudgetFinding[] {\n const budgets: ContextBudgets = { ...CONTEXT_BUDGETS, ...options.budgets }\n const findings: BudgetFinding[] = []\n const autonomos = join(root, AUTONOMOS_DIR)\n const rel = (path: string): string => relative(root, path)\n\n const format = options.artifactFormat ?? 1\n if (format < ARTIFACT_FORMAT) {\n findings.push({\n code: 'format-outdated',\n path: rel(join(autonomos, 'manifest.json')),\n message: `Records use artifact format ${format}; run \\`autonomos migrate\\` to reach format ${ARTIFACT_FORMAT}.`,\n })\n }\n\n const tasksPath = join(autonomos, TASKS_FILE)\n const tasks = readIfFile(tasksPath)\n if (tasks !== undefined) {\n const entries = parseTaskEntries(tasks)\n const closed = entries.filter(e => e.status === 'x').map(e => e.id)\n if (closed.length) {\n findings.push({\n code: 'closed-tasks-in-current',\n path: rel(tasksPath),\n message: `${closed.length} completed task(s) still in the current registry; run \\`autonomos close <ID>\\`.`,\n items: closed,\n })\n }\n const bytes = Buffer.byteLength(tasks)\n if (bytes > budgets.tasksBytes) {\n findings.push({\n code: 'tasks-size',\n path: rel(tasksPath),\n message: `${kb(bytes)} exceeds the ${kb(budgets.tasksBytes)} budget.`,\n })\n }\n const long = entries\n .filter(e => e.status !== 'x' && e.text.length > budgets.taskEntryChars)\n .sort((a, b) => b.text.length - a.text.length)\n if (long.length) {\n findings.push({\n code: 'task-entry-length',\n path: rel(tasksPath),\n message: `${long.length} open task entr${long.length === 1 ? 'y exceeds' : 'ies exceed'} ${budgets.taskEntryChars} characters; keep evidence in worklogs.`,\n items: long.map(e => `${e.id} (${e.text.length})`),\n })\n }\n }\n\n const issuesPath = join(autonomos, ISSUES_FILE)\n const issues = readIfFile(issuesPath)\n if (issues !== undefined) {\n const closed = parseIssueEntries(issues)\n .filter(e => isClosedIssueStatus(e.status))\n .map(e => e.id)\n if (closed.length) {\n findings.push({\n code: 'closed-issues-in-current',\n path: rel(issuesPath),\n message: `${closed.length} closed issue(s) still in the current registry; run \\`autonomos close <ID>\\`.`,\n items: closed,\n })\n }\n const bytes = Buffer.byteLength(issues)\n if (bytes > budgets.issuesBytes) {\n findings.push({\n code: 'issues-size',\n path: rel(issuesPath),\n message: `${kb(bytes)} exceeds the ${kb(budgets.issuesBytes)} budget.`,\n })\n }\n }\n\n for (const agentPath of findAgentFilePaths(root)) {\n const isRoot = agentPath === join(root, AGENT_FILE)\n const limit = isRoot ? budgets.rootAgentBytes : budgets.localAgentBytes\n const bytes = size(agentPath)\n if (bytes > limit) {\n findings.push({\n code: isRoot ? 'root-agent-size' : 'local-agent-size',\n path: rel(agentPath),\n message: `${kb(bytes)} exceeds the ${kb(limit)} budget; move scoped or incidental knowledge to a narrower AGENT.md or project documentation.`,\n })\n }\n }\n\n const worklogs = join(autonomos, WORKLOGS_DIR)\n if (existsSync(worklogs)) {\n const over: { name: string; bytes: number }[] = []\n for (const entry of readdirSync(worklogs, { withFileTypes: true })) {\n if (!entry.isFile() || !entry.name.endsWith('.md')) continue\n const bytes = size(join(worklogs, entry.name))\n if (bytes > budgets.worklogBytes) over.push({ name: entry.name, bytes })\n }\n if (over.length) {\n over.sort((a, b) => b.bytes - a.bytes)\n findings.push({\n code: 'worklog-size',\n path: rel(worklogs),\n message: `${over.length} worklog(s) exceed ${kb(budgets.worklogBytes)}; keep only outcome, decisions, validation and open items.`,\n items: over.map(w => `${w.name} (${kb(w.bytes)})`),\n })\n }\n }\n\n return findings\n}\n","import { isAbsolute, posix, relative, resolve, sep } from 'node:path'\n\n/** Map an absolute path to its new location, or return it unchanged. */\nexport type PathMapper = (absolutePath: string) => string\n\nexport function prefixMapper(from: string, to: string): PathMapper {\n return path => {\n if (path === from) return to\n if (path.startsWith(from + sep)) return to + path.slice(from.length)\n return path\n }\n}\n\nexport function composeMappers(...mappers: PathMapper[]): PathMapper {\n return path => mappers.reduce((current, mapper) => mapper(current), path)\n}\n\nconst INLINE_LINK = /\\]\\((<[^>\\n]+>|[^)\\s]+)((?:\\s+\"[^\"\\n]*\")?)\\)/g\nconst REFERENCE_DEFINITION = /^(\\s{0,3}\\[[^\\]\\n]+\\]:\\s*)(<[^>\\n]+>|\\S+)/gm\n\nfunction isRelativeTarget(target: string): boolean {\n return (\n !!target &&\n !target.startsWith('#') &&\n !isAbsolute(target) &&\n !/^[a-z][\\w+.-]*:/i.test(target)\n )\n}\n\nfunction toPosix(path: string): string {\n return path.split(sep).join(posix.sep)\n}\n\n/**\n * Rewrite relative Markdown link targets of a document that moves from\n * `oldDir` to `newDir`, also following targets that moved (`mapPath`).\n * Targets that resolve to the same file are left byte-identical.\n */\nexport function relocateLinks(\n markdown: string,\n oldDir: string,\n newDir: string,\n mapPath: PathMapper = p => p\n): string {\n const rewrite = (raw: string): string => {\n const angled = raw.startsWith('<') && raw.endsWith('>')\n const target = angled ? raw.slice(1, -1) : raw\n if (!isRelativeTarget(target)) return raw\n const hashIndex = target.search(/[#?]/)\n const pathPart = hashIndex === -1 ? target : target.slice(0, hashIndex)\n const suffix = hashIndex === -1 ? '' : target.slice(hashIndex)\n if (!pathPart) return raw\n let decoded = pathPart\n try {\n decoded = decodeURI(pathPart)\n } catch {\n // keep raw path\n }\n const absolute = resolve(oldDir, decoded)\n const mapped = mapPath(absolute)\n if (mapped === absolute && oldDir === newDir) return raw\n let next = toPosix(relative(newDir, mapped)) || '.'\n if (pathPart.startsWith('./') && !next.startsWith('.')) next = `./${next}`\n if (next === toPosix(decoded)) return raw\n const encoded = angled ? next : next.replace(/ /g, '%20')\n return angled ? `<${encoded}${suffix}>` : `${encoded}${suffix}`\n }\n return markdown\n .replace(\n INLINE_LINK,\n (_m, target: string, title: string) => `](${rewrite(target)}${title})`\n )\n .replace(\n REFERENCE_DEFINITION,\n (_m, lead: string, target: string) => `${lead}${rewrite(target)}`\n )\n}\n\n/**\n * Rewrite plain project-root-relative mentions of moved files, such as\n * `_See: .autonomos/worklogs/2026-01-01-X.md_`, outside of link targets.\n */\nexport function relocateRootMentions(\n markdown: string,\n fromPrefix: string,\n toPrefix: string,\n names: ReadonlySet<string>\n): string {\n if (!markdown.includes(fromPrefix + '/')) return markdown\n const escaped = fromPrefix.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const pattern = new RegExp(`(?<![\\\\w./-])${escaped}/([^\\\\s)\\\\]>'\"\\`,;|]+)`, 'g')\n return markdown.replace(pattern, (match, candidate: string) => {\n let name = candidate\n while (name && !names.has(name) && /[._*~]$/.test(name)) name = name.slice(0, -1)\n if (!names.has(name)) return match\n return `${toPrefix}/${name}${candidate.slice(name.length)}`\n })\n}\n"],"mappings":"iQAIA,MAAa,EAAmB,cAKnB,EAAgB,aAKhB,EAAgB,gBAKhB,GAAgB,cAKhB,EAAa,WAKb,EAAa,WAKb,EAAe,WAKf,GAAY,QAKZ,GAAgB,YAGhB,EAAc,UAOd,GAAkB,EAGlB,EAAc,YAGd,GAAa,SAGb,GAAsB,oBAGtB,GAAqB,YAMrB,EAAkB,CAC3B,eAAgB,IAChB,gBAAiB,IACjB,WAAY,KACZ,YAAa,KACb,eAAgB,IAChB,aAAc,IAClB,ECjEa,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,C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KAAK,CAAI,GAAG,EAAO,EAAK,MAAM,EAAG,EAAE,EAEhF,OADK,EAAM,IAAI,CAAI,EACZ,GAAG,EAAS,GAAG,IAAO,EAAU,MAAM,EAAK,MAAM,IAD3B,CAEjC,CAAC,CACL"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: protocol-crystallize
|
|
3
|
-
description: 'Close work with
|
|
3
|
+
description: 'Close work with a proportionate record, durable knowledge and bounded current context.'
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# /crystallize — End session
|
|
@@ -8,29 +8,33 @@ description: 'Close work with durable knowledge, truthful state and bounded curr
|
|
|
8
8
|
> **CRITICAL:** You MUST NOT ask the user what to crystallize. Reflect, decide, write, then report.
|
|
9
9
|
> **Authority:** If the user limited the work to read-only or no changes, do not modify any artifact; deliver the substantive answer and report that crystallization was skipped.
|
|
10
10
|
|
|
11
|
-
## STEP 1 — Worklog
|
|
11
|
+
## STEP 1 — Worklog: only what outlives the session
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
Write `.autonomos/worklogs/YYYY-MM-DD-[TASK_ID].md` with only what a future agent cannot recover from code, git, tests or other records. Use exactly this shape; do not model it on existing worklogs:
|
|
14
|
+
|
|
15
|
+
`# [ID] Title` · `Outcome:` 1–3 lines · `Decisions:` non-obvious choices and why · `Validation:` check → result, one line each · `Open:` limits and follow-ups (write `none` when empty).
|
|
16
|
+
|
|
17
|
+
Leave out chronology, plans, file lists, restated task/issue/commit text, explanations of what was unnecessary, and raw data (save it beside the worklog and link it). Stay under 2,500 bytes. An S task whose commit and task line say everything needs no worklog.
|
|
14
18
|
|
|
15
19
|
## STEP 2 — Consolidate knowledge
|
|
16
20
|
|
|
17
|
-
For each candidate ask: **Would this still guide a different future task?**
|
|
21
|
+
For each candidate ask: **Would this still guide a different future task?** Then: does it apply to most tasks in this scope, already exist, replace a claim, or belong in a narrower scope?
|
|
18
22
|
|
|
19
23
|
- Keep observations, measurements, chronology and completed actions in the worklog; update existing component documentation for operational explanation.
|
|
20
|
-
- Route stable operating guidance to the narrowest `AGENT.md
|
|
24
|
+
- Route stable operating guidance to the narrowest `AGENT.md`; tool-, component- or incident-specific knowledge goes to a local `AGENT.md` or project documentation. Root `AGENT.md` stays under 8,000 bytes, local ones under 4,000: consolidate before adding.
|
|
25
|
+
- Route target requirements to `specs/` and decision rationale to `decisions/`; update existing knowledge instead of duplicating it.
|
|
21
26
|
- Consolidate or replace superseded and disproven guidance claim by claim, preserving valid restrictions in mixed paragraphs. Do not turn a current choice into a broader prohibition.
|
|
22
|
-
- Do not turn historical worklogs, issues, or tasks into current specs/decisions without `/adopt`. Never create an `AGENT.md` based on file count alone.
|
|
23
|
-
- Keep progress in `TASKS.md`; rewrite optional Current direction only when it helps the next session. Do not append a completed-task journal there or in `AGENT.md`.
|
|
27
|
+
- Do not turn historical worklogs, issues, or tasks into current specs/decisions without `/adopt`. Never create an `AGENT.md` based on file count alone. Keep progress out of `AGENT.md`; rewrite Current direction only when it helps the next session.
|
|
24
28
|
|
|
25
29
|
## STEP 3 — Close the work boundary
|
|
26
30
|
|
|
27
|
-
Mark `[x]` only if complete, `[!]` only if an unresolved dependency prevents progress, or keep `[/]` for partial work.
|
|
28
|
-
|
|
29
|
-
Verify the actual resulting text and links
|
|
31
|
+
Mark `[x]` only if complete, `[!]` only if an unresolved dependency prevents progress, or keep `[/]` for partial work. Check linked issue acceptance separately.
|
|
32
|
+
Move finished records out of current context now: `autonomos close <ID>` moves a `[x]` task (adding `Completed:`) or a resolved/declined issue to `.autonomos/archive/closed/`; without the CLI, move the entry by hand. A closed issue gets a one-line resolution, never a progress journal.
|
|
33
|
+
Verify the actual resulting text and links; preserve unrelated concurrent edits.
|
|
30
34
|
|
|
31
35
|
## STEP 4 — User response
|
|
32
36
|
|
|
33
37
|
First deliver a self-contained answer to the original request: outcome, evidence, limitations, and relevant next step.
|
|
34
38
|
Then append this supplementary handoff:
|
|
35
39
|
|
|
36
|
-
`Crystallization — Task: [x] / [/] / [!] — [ID] | Worklog: .autonomos/worklogs/... | AGENT.md updated: [yes / no — reason]`
|
|
40
|
+
`Crystallization — Task: [x] / [/] / [!] — [ID] | Worklog: .autonomos/worklogs/... or none (S) | AGENT.md updated: [yes / no — reason]`
|
|
@@ -11,7 +11,7 @@ description: 'Optional intake for problems, proposals, and questions before choo
|
|
|
11
11
|
## STEP 1 — Build context
|
|
12
12
|
|
|
13
13
|
1. Read root and applicable root → target `AGENT.md` files.
|
|
14
|
-
2. Read `.autonomos/ISSUES.md` if it exists and search for duplicates; targeted
|
|
14
|
+
2. Read `.autonomos/ISSUES.md` (open and accepted issues) if it exists and search for duplicates; targeted lookup in `.autonomos/archive/` prevents duplicate intake and identifier reuse.
|
|
15
15
|
3. Read related tasks or worklogs only when they provide evidence.
|
|
16
16
|
|
|
17
17
|
## STEP 2 — Record the signal
|
|
@@ -29,11 +29,11 @@ Create `.autonomos/ISSUES.md` on first use. Record without prescribing implement
|
|
|
29
29
|
- Tasks: none | TASK-ID, ...
|
|
30
30
|
```
|
|
31
31
|
|
|
32
|
-
Merge duplicate evidence into the existing issue instead of creating another.
|
|
32
|
+
Keep each field to a few factual lines. Merge duplicate evidence into the existing issue instead of creating another.
|
|
33
33
|
|
|
34
34
|
## STEP 3 — Triage
|
|
35
35
|
|
|
36
36
|
- **Open:** preserve the signal; do not create a task before an approach is accepted.
|
|
37
37
|
- **Accepted:** create one or more scoped tasks through `/task` and link both directions.
|
|
38
38
|
If the outcome spans tasks, create or link a specification; record each consequential technical choice separately.
|
|
39
|
-
- **Resolved/declined:**
|
|
39
|
+
- **Resolved/declined:** add a one-line resolution linking the task or worklog, then close it (`autonomos close <ID>`, or move it by hand to `.autonomos/archive/closed/ISSUES.md`). Progress belongs in task worklogs, never appended to the issue.
|
|
@@ -11,7 +11,8 @@ description: 'Investigate drift, consolidate current knowledge and archive settl
|
|
|
11
11
|
|
|
12
12
|
1. Read root and applicable scoped `AGENT.md`, current tasks/issues and relevant accepted records. Follow the protocol's archival criteria; search history only for a specific question.
|
|
13
13
|
2. Classify individual claims as current guidance, current state, historical evidence, or version-pinned protocol content; a paragraph may mix them.
|
|
14
|
-
3. Check managed integrity with `autonomos status` when available; repair managed artifacts only through authorized `autonomos update`.
|
|
14
|
+
3. Check managed integrity and context budgets with `autonomos status` when available; repair managed artifacts only through authorized `autonomos update`.
|
|
15
|
+
4. If the artifact format is outdated, run an authorized `autonomos migrate --dry-run`, then `autonomos migrate`, before semantic work; its remaining findings become this pass's work items.
|
|
15
16
|
|
|
16
17
|
## STEP 2 — Investigate
|
|
17
18
|
|
|
@@ -26,7 +27,8 @@ Classify findings as **certain**, **uncertain**, or **historical-only**.
|
|
|
26
27
|
- **Historical-only:** preserve it outside default context when eligible; do not rewrite conclusions to match today.
|
|
27
28
|
- Apply the protocol's archival eligibility to coherent work batches. Completing a child task does not resolve unmet parent criteria. Consolidate still-needed knowledge in its existing narrowest home first.
|
|
28
29
|
- Use `/adopt` for history-to-artifact extraction into new specs/decisions; routine reconciliation may update existing guidance within authority.
|
|
29
|
-
- Move eligible
|
|
30
|
+
- Closed tasks/issues go to `.autonomos/archive/closed/` (`autonomos close <ID>`). Move other eligible history to `.autonomos/archive/<batch>/`, preserve content/provenance/IDs and repair references. Update the topic index; retain only necessary current dependencies/outcomes, not permanent per-completion stubs.
|
|
31
|
+
- Over-budget `AGENT.md`: keep guidance that applies to most tasks of its scope; move the rest to a narrower `AGENT.md` or project documentation and link it. Over-long open task entries: shorten to one line and move evidence to the worklog.
|
|
30
32
|
|
|
31
33
|
## STEP 4 — Verify and report
|
|
32
34
|
|
|
@@ -10,9 +10,10 @@ description: 'Mandatory bootstrap for any new session. Invoke before any work be
|
|
|
10
10
|
## STEP 1 — Orient
|
|
11
11
|
|
|
12
12
|
1. Read the root `AGENT.md`.
|
|
13
|
-
2. Read `.autonomos/TASKS.md
|
|
13
|
+
2. Read `.autonomos/TASKS.md`: open work and Current direction. Archives are not bootstrap context; search them only for a specific question.
|
|
14
|
+
3. When the CLI is available, run `autonomos status`. Note version, format or budget findings; do not fix them unasked.
|
|
14
15
|
|
|
15
|
-
RESPOND with a **3-line max** summary of relevant project context. Do not continue without this response.
|
|
16
|
+
RESPOND with a **3-line max** summary of relevant project context, including status findings. Do not continue without this response.
|
|
16
17
|
|
|
17
18
|
## STEP 2 — Resolve the objective
|
|
18
19
|
|
|
@@ -22,7 +22,7 @@ State in 3–5 steps what you will do. The user must be able to say OK or adjust
|
|
|
22
22
|
|
|
23
23
|
## STEP 3 — Execute
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
Register a new task as one line (format in `PROTOCOL.md`), mark it `[/]` in `.autonomos/TASKS.md`, then work. Evidence never goes into the task entry.
|
|
26
26
|
|
|
27
27
|
## During execution
|
|
28
28
|
|
|
@@ -387,9 +387,6 @@ describe('Archival and current-context continuity', () => {
|
|
|
387
387
|
)
|
|
388
388
|
expect(reconcile).toContain('not permanent per-completion stubs')
|
|
389
389
|
expect(crystallize).toContain('Do not turn a current choice into a broader prohibition')
|
|
390
|
-
expect(crystallize).toContain(
|
|
391
|
-
'Do not reorganize archives mechanically after every task or by calendar age'
|
|
392
|
-
)
|
|
393
390
|
})
|
|
394
391
|
it('checks actual output and preserves valid parts of mixed claims', () => {
|
|
395
392
|
expect(reconcile).toContain('Re-read exact source text before edits')
|
|
@@ -400,3 +397,45 @@ describe('Archival and current-context continuity', () => {
|
|
|
400
397
|
expect(issue).toContain('identifier reuse')
|
|
401
398
|
})
|
|
402
399
|
})
|
|
400
|
+
|
|
401
|
+
// ---------------------------------------------------------------------------
|
|
402
|
+
// 13. Artifact format 2 — bounded context, proportionate records, migration
|
|
403
|
+
// ---------------------------------------------------------------------------
|
|
404
|
+
describe('Bounded context and proportionate records (format 2)', () => {
|
|
405
|
+
it('closes finished records mechanically in the same session', () => {
|
|
406
|
+
expect(crystallize).toContain('`autonomos close <ID>`')
|
|
407
|
+
expect(crystallize).toContain('.autonomos/archive/closed/')
|
|
408
|
+
expect(crystallize).toContain('never a progress journal')
|
|
409
|
+
expect(issue).toContain('never appended to the issue')
|
|
410
|
+
expect(PROTOCOL_TEMPLATE).toContain('`ISSUES.md` holds open and accepted issues')
|
|
411
|
+
expect(PROTOCOL_TEMPLATE).toContain('Unfinished work may be closed only as abandoned')
|
|
412
|
+
})
|
|
413
|
+
|
|
414
|
+
it('prescribes a fixed, bounded worklog shape and forbids imitation', () => {
|
|
415
|
+
for (const field of ['`Outcome:`', '`Decisions:`', '`Validation:`', '`Open:`'])
|
|
416
|
+
expect(crystallize).toContain(field)
|
|
417
|
+
expect(crystallize).toContain('do not model it on existing worklogs')
|
|
418
|
+
expect(crystallize).toContain('Leave out chronology, plans, file lists')
|
|
419
|
+
expect(crystallize).toContain('2,500 bytes')
|
|
420
|
+
expect(crystallize).toContain('needs no worklog')
|
|
421
|
+
})
|
|
422
|
+
|
|
423
|
+
it('admits AGENT.md knowledge by cost, with budgets', () => {
|
|
424
|
+
expect(crystallize).toContain('does it apply to most tasks in this scope')
|
|
425
|
+
expect(crystallize).toContain('Root `AGENT.md` stays under 8,000 bytes')
|
|
426
|
+
expect(PROTOCOL_TEMPLATE).toContain('## Context Budgets')
|
|
427
|
+
expect(reconcile).toContain('Over-budget `AGENT.md`')
|
|
428
|
+
})
|
|
429
|
+
|
|
430
|
+
it('keeps evidence out of task entries', () => {
|
|
431
|
+
expect(task).toContain('Evidence never goes into the task entry')
|
|
432
|
+
expect(PROTOCOL_TEMPLATE).toContain('One line per task')
|
|
433
|
+
})
|
|
434
|
+
|
|
435
|
+
it('surfaces status findings and routes format upgrades through migrate', () => {
|
|
436
|
+
expect(session).toContain('run `autonomos status`')
|
|
437
|
+
expect(reconcile).toContain('autonomos migrate --dry-run')
|
|
438
|
+
expect(PROTOCOL_TEMPLATE).toContain('## Artifact Format and Migration')
|
|
439
|
+
expect(PROTOCOL_TEMPLATE).toContain('worklogs-format-1')
|
|
440
|
+
})
|
|
441
|
+
})
|