@christianmaf80/agentic-workflow 1.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/LICENSE +15 -0
  2. package/README.es.md +88 -0
  3. package/README.md +88 -0
  4. package/bin/cli.js +44 -0
  5. package/dist/artifacts/index.md +28 -0
  6. package/dist/cli/commands/create.js +178 -0
  7. package/dist/cli/commands/init.js +212 -0
  8. package/dist/cli/commands/mcp-register.js +33 -0
  9. package/dist/cli/commands/restore.js +67 -0
  10. package/dist/cli/index.js +2 -0
  11. package/dist/core/context/manager.js +136 -0
  12. package/dist/core/index.js +1 -0
  13. package/dist/core/mapping/resolver.js +72 -0
  14. package/dist/core/migration/backup.js +14 -0
  15. package/dist/core/migration/detector.js +32 -0
  16. package/dist/core/migration/transformer.js +11 -0
  17. package/dist/core/utils/backup.js +41 -0
  18. package/dist/mcp/server.js +160 -0
  19. package/dist/rules/constitution/GEMINI.location.md +29 -0
  20. package/dist/rules/constitution/agent-system.md +77 -0
  21. package/dist/rules/constitution/agents-behavior.md +188 -0
  22. package/dist/rules/constitution/clean-code.md +153 -0
  23. package/dist/rules/constitution/index.md +29 -0
  24. package/dist/rules/constitution/project-architecture.md +57 -0
  25. package/dist/rules/index.md +26 -0
  26. package/dist/rules/roles/architect.md +40 -0
  27. package/dist/rules/roles/index.md +45 -0
  28. package/dist/rules/roles/neo.md +32 -0
  29. package/dist/rules/roles/qa.md +22 -0
  30. package/dist/rules/roles/researcher.md +22 -0
  31. package/dist/rules/roles/tooling.md +22 -0
  32. package/dist/templates/acceptance.md +64 -0
  33. package/dist/templates/agent-scores.md +25 -0
  34. package/dist/templates/agent-task.md +106 -0
  35. package/dist/templates/analysis.md +161 -0
  36. package/dist/templates/brief.md +96 -0
  37. package/dist/templates/changelog.md +30 -0
  38. package/dist/templates/closure.md +87 -0
  39. package/dist/templates/index.md +45 -0
  40. package/dist/templates/init.md +26 -0
  41. package/dist/templates/planning.md +157 -0
  42. package/dist/templates/research.md +89 -0
  43. package/dist/templates/results-acceptance.md +177 -0
  44. package/dist/templates/review.md +110 -0
  45. package/dist/templates/subtask-implementation.md +67 -0
  46. package/dist/templates/supplemental-report.md +30 -0
  47. package/dist/templates/task-metrics.md +39 -0
  48. package/dist/templates/task.md +151 -0
  49. package/dist/templates/todo-item.md +49 -0
  50. package/dist/templates/verification.md +77 -0
  51. package/dist/workflows/index.md +44 -0
  52. package/dist/workflows/init.md +61 -0
  53. package/dist/workflows/tasklifecycle-long/index.md +176 -0
  54. package/dist/workflows/tasklifecycle-long/phase-0-acceptance-criteria.md +161 -0
  55. package/dist/workflows/tasklifecycle-long/phase-1-research.md +151 -0
  56. package/dist/workflows/tasklifecycle-long/phase-2-analysis.md +136 -0
  57. package/dist/workflows/tasklifecycle-long/phase-3-planning.md +121 -0
  58. package/dist/workflows/tasklifecycle-long/phase-4-implementation.md +104 -0
  59. package/dist/workflows/tasklifecycle-long/phase-5-verification.md +82 -0
  60. package/dist/workflows/tasklifecycle-long/phase-6-results-acceptance.md +79 -0
  61. package/dist/workflows/tasklifecycle-long/phase-7-evaluation.md +85 -0
  62. package/dist/workflows/tasklifecycle-long/phase-8-commit-push.md +80 -0
  63. package/dist/workflows/tasklifecycle-short/index.md +67 -0
  64. package/dist/workflows/tasklifecycle-short/short-phase-1-brief.md +66 -0
  65. package/dist/workflows/tasklifecycle-short/short-phase-2-implementation.md +72 -0
  66. package/dist/workflows/tasklifecycle-short/short-phase-3-closure.md +67 -0
  67. package/package.json +53 -0
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 Christian Marino Alvarez
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.es.md ADDED
@@ -0,0 +1,88 @@
1
+ # @christian-marino-alvarez/agentic-workflow
2
+
3
+ [English](./README.md) | [Español]
4
+
5
+ > Sistema portátil de orquestación de flujos agénticos con estricta disciplina de identidad y puertas de control.
6
+
7
+ ## 🚀 Descripción General
8
+
9
+ **Agentic Workflow** es un framework de orquestación ligero e agnóstico al lenguaje, diseñado para imponer disciplina y seguridad en el desarrollo asistido por agentes de IA. Proporciona un ciclo de vida estructurado para las tareas, puertas de control obligatorias con intervención humana (human-in-the-loop) y un robusto modelo de arquitectura por referencia.
10
+
11
+ ## ✨ Características Principales
12
+
13
+ - **Protocolo AHRP (Agentic Handover & Reasoning Protocol)**: Impone un flujo estricto de Triple-Puerta para cada tarea (Activación, Aprobación de Razonamiento y Aceptación de Resultados).
14
+ - **Arquitectura por Referencia**: Mantiene tu proyecto limpio referenciando las reglas y workflows del núcleo desde `node_modules`.
15
+ - **Gobernanza de Tolerancia Cero**: Penalizaciones automáticas de rendimiento por violaciones del protocolo.
16
+ - **Independiente y Portátil**: Funciona en cualquier proyecto, siempre que el agente del IDE pueda leer archivos Markdown.
17
+
18
+ ## 📦 Instalación
19
+
20
+ ```bash
21
+ npm install @christian-marino-alvarez/agentic-workflow
22
+ ```
23
+
24
+ ## 🛠️ Comandos del CLI
25
+
26
+ ### `init`
27
+ Inicializa el sistema agéntico en el directorio actual.
28
+ - Detecta sistemas heredados y ofrece migración con copias de seguridad automáticas.
29
+ - Crea la estructura `.agent/` (índices, directorios proxy).
30
+ - Genera `AGENTS.md`, el punto de entrada para los asistentes del IDE.
31
+ ```bash
32
+ npx agentic-workflow init
33
+ ```
34
+
35
+ ### `create <role|workflow> <name>`
36
+ Genera el andamiaje (scaffolding) para un nuevo componente personalizado.
37
+ - **role**: Crea un nuevo rol de agente con reglas de identificación obligatorias.
38
+ - **workflow**: Crea una plantilla de ciclo de trabajo personalizado.
39
+ ```bash
40
+ npx agentic-workflow create role neo
41
+ ```
42
+
43
+ ### `restore`
44
+ Recupera la configuración de `.agent/` desde una copia de seguridad previa.
45
+ - Los backups se almacenan en `.agent-backups/`.
46
+ - Permite seleccionar versiones antes de un cambio destructivo.
47
+ ```bash
48
+ npx agentic-workflow restore
49
+ ```
50
+
51
+ ## 🔌 Configuración del Servidor MCP
52
+
53
+ Para usar el framework con IDEs que soportan el Protocolo de Contexto de Modelo (ej: Cursor, Windsurf), debes añadir el servidor a tu configuración.
54
+
55
+ ### Recomendado (vía NPX)
56
+ Usa `npx` para asegurar que siempre usas la versión correcta de tu proyecto:
57
+ - **Comando**: `npx agentic-workflow mcp`
58
+
59
+ ### Manual (Global/Local)
60
+ Si tienes el paquete instalado localmente, puedes apuntar al binario local:
61
+ - **Comando**: `node ./node_modules/.bin/agentic-workflow mcp`
62
+
63
+ ## 🧠 Conceptos Core
64
+
65
+ ### Ciclos de Vida
66
+ El framework soporta dos flujos principales según la complejidad de la tarea:
67
+ 1. **Ciclo de Vida Largo (9 Fases)**: Para funcionalidades complejas que requieren Investigación, Análisis, Planificación y Revisión Arquitectónica formal.
68
+ 2. **Ciclo de Vida Corto (3 Fases)**: Para correcciones rápidas o actualizaciones simples, fusionando Aceptación, Implementación y Cierre.
69
+
70
+ ### Protocolo AHRP
71
+ Cada tarea de un agente sigue el **Protocolo de Traspaso y Razonamiento Agéntico**:
72
+ 1. **Puerta A (Activación)**: El agente es asignado pero está bloqueado. El desarrollador debe decir `SI`.
73
+ 2. **Puerta B (Razonamiento)**: El agente propone un plan. El desarrollador debe aprobar con `SI`.
74
+ 3. **Puerta C (Resultados)**: El agente completa el trabajo. El desarrollador valida con `SI`.
75
+
76
+ ### Arquitectura por Referencia
77
+ Para garantizar la estabilidad, la lógica central del framework (reglas y workflows) reside dentro de `node_modules`. El archivo `.agent/index.md` de tu proyecto utiliza rutas absolutas para referenciar estos activos inmutables, protegiendo al framework de modificaciones locales accidentales.
78
+
79
+ ## ⚖️ Gobernanza
80
+
81
+ Este framework se basa en el principio de **Máxima Disciplina**. Los agentes deben:
82
+ 1. Identificarse con un prefijo obligatorio.
83
+ 2. Enviar un plan de razonamiento antes de cualquier modificación.
84
+ 3. Obtener la aprobación explícita del desarrollador (`SI`) para cada transición.
85
+
86
+ ## 📄 Licencia
87
+
88
+ Licencia ISC. Consulta [LICENSE](./LICENSE) para más detalles.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # @christian-marino-alvarez/agentic-workflow
2
+
3
+ [English] | [Español](./README.es.md)
4
+
5
+ > Portable agentic workflow orchestration system with strict identity and gate discipline.
6
+
7
+ ## 🚀 Overview
8
+
9
+ **Agentic Workflow** is a lightweight, language-agnostic orchestration framework designed to enforce discipline and safety in AI-agent-assisted development. It provides a structured lifecycle for tasks, mandatory human-in-the-loop gates, and a robust architecture-by-reference model.
10
+
11
+ ## ✨ Key Features
12
+
13
+ - **AHRP (Agentic Handover & Reasoning Protocol)**: Enforces a strict Triple-Gate flow for every task (Activation, Reasoning Approval, and Results Acceptance).
14
+ - **Architecture by Reference**: Keeps your project clean by referencing core rules and workflows from `node_modules`.
15
+ - **Zero-Tolerance Governance**: Automatic performance penalties for protocol violations.
16
+ - **Standalone & Portable**: Works in any project provided the IDE agent can read Markdown files.
17
+
18
+ ## 📦 Installation
19
+
20
+ ```bash
21
+ npm install @christian-marino-alvarez/agentic-workflow
22
+ ```
23
+
24
+ ## 🛠️ CLI Commands
25
+
26
+ ### `init`
27
+ Initializes the agentic system in the current directory.
28
+ - Detects legacy systems and offers migration with automatic backups.
29
+ - Creates the `.agent/` structure (indexes, proxy directories).
30
+ - Generates `AGENTS.md`, the entry point for IDE assistants.
31
+ ```bash
32
+ npx agentic-workflow init
33
+ ```
34
+
35
+ ### `create <role|workflow> <name>`
36
+ Scaffolds a new custom component.
37
+ - **role**: Creates a new agent role with mandatory identification rules.
38
+ - **workflow**: Creates a custom work cycle template.
39
+ ```bash
40
+ npx agentic-workflow create role neo
41
+ ```
42
+
43
+ ### `restore`
44
+ Recovers the `.agent/` configuration from a previous backup.
45
+ - Backups are stored in `.agent-backups/`.
46
+ - Allows selecting versions before a destructive change.
47
+ ```bash
48
+ npx agentic-workflow restore
49
+ ```
50
+
51
+ ## 🔌 MCP Server Configuration
52
+
53
+ To use the framework with IDEs that support the Model Context Protocol (e.g., Cursor, Windsurf), you must add the server to your settings.
54
+
55
+ ### Recommended (via NPX)
56
+ Use `npx` to ensure you are always using the correct version from your project:
57
+ - **Command**: `npx agentic-workflow mcp`
58
+
59
+ ### Manual (Global/Local)
60
+ If you have the package installed locally, you can point to the local binary:
61
+ - **Command**: `node ./node_modules/.bin/agentic-workflow mcp`
62
+
63
+ ## 🧠 Core Concepts
64
+
65
+ ### Lifecycles
66
+ The framework supports two main workflows depending on task complexity:
67
+ 1. **Long Lifecycle (9 Phases)**: For complex features requiring Research, Analysis, Planning, and formal Architectural Review.
68
+ 2. **Short Lifecycle (3 Phases)**: For quick fixes or simple updates, merging Acceptance, Implementation, and Closure.
69
+
70
+ ### AHRP Protocol
71
+ Every agent task follows the **Agentic Handover & Reasoning Protocol**:
72
+ 1. **Gate A (Activation)**: The agent is assigned but blocked. Developer must say `YES`.
73
+ 2. **Gate B (Reasoning)**: The agent proposes a plan. Developer must approve with `YES`.
74
+ 3. **Gate C (Results)**: The agent completes the work. Developer validates with `YES`.
75
+
76
+ ### Architecture by Reference
77
+ To ensure stability, the framework's core logic (rules and workflows) resides inside `node_modules`. Your project's `.agent/index.md` uses absolute paths to reference these immutable assets, protecting the framework from accidental local modifications.
78
+
79
+ ## ⚖️ Governance
80
+
81
+ This framework is built on the principle of **Maximum Discipline**. Agents are required to:
82
+ 1. Identify themselves with a mandatory prefix.
83
+ 2. Submit a reasoning plan before any modification.
84
+ 3. Obtain explicit developer approval (`YES`) for every transition.
85
+
86
+ ## 📄 License
87
+
88
+ ISC License. See [LICENSE](./LICENSE) for details.
package/bin/cli.js ADDED
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { initCommand } from '../dist/cli/commands/init.js';
4
+ import { createCommand } from '../dist/cli/commands/create.js';
5
+ import { restoreCommand } from '../dist/cli/commands/restore.js';
6
+ import { runMcpServer } from '../dist/mcp/server.js';
7
+ import { registerMcpCommand } from '../dist/cli/commands/mcp-register.js';
8
+
9
+ const program = new Command();
10
+
11
+ program
12
+ .name('agentic-workflow')
13
+ .description('Portable agentic orchestration system')
14
+ .version('1.0.0');
15
+
16
+ program
17
+ .command('init')
18
+ .description('Initialize the agentic system in the current directory')
19
+ .action(initCommand);
20
+
21
+ program
22
+ .command('create')
23
+ .argument('<type>', 'The type of element to create (role, workflow)')
24
+ .argument('<name>', 'The name for the new element')
25
+ .description('Scaffold a new project-specific element')
26
+ .action(createCommand);
27
+
28
+ program
29
+ .command('mcp')
30
+ .description('Start the Model Context Protocol (MCP) server')
31
+ .action(runMcpServer);
32
+
33
+ program
34
+ .command('mcp:register')
35
+ .description('Register the MCP server in a config file')
36
+ .option('--path <path>', 'Write to a specific MCP config path (required)')
37
+ .action(registerMcpCommand);
38
+
39
+ program
40
+ .command('restore')
41
+ .description('Restore the agentic system from a backup')
42
+ .action(restoreCommand);
43
+
44
+ program.parse();
@@ -0,0 +1,28 @@
1
+ ---
2
+ id: artifacts.index
3
+ owner: architect-agent
4
+ version: 1.0.0
5
+ severity: PERMANENT
6
+ ---
7
+
8
+ # INDEX — Artifacts
9
+
10
+ ## Agent identification (MANDATORY)
11
+ First line of the document:
12
+ `<icon> **<agent-name>**: <message>`
13
+
14
+ ## Objective
15
+ List artifact aliases and their expected paths.
16
+
17
+ ## Aliases (YAML)
18
+ ```yaml
19
+ artifacts:
20
+ candidate:
21
+ dir: .agent/artifacts/candidate/
22
+ init: .agent/artifacts/candidate/init.md
23
+ bootstrap: .agent/artifacts/candidate/bootstrap.md
24
+ task: .agent/artifacts/candidate/task.md
25
+ ```
26
+
27
+ ## Rules
28
+ - Any new artifact alias MUST be added here.
@@ -0,0 +1,178 @@
1
+ import { intro, outro, spinner, note } from '@clack/prompts';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { resolveCorePath, resolveInstalledCorePath } from '../../core/mapping/resolver.js';
5
+ /**
6
+ * Lógica central para la creación de componentes sin dependencias de UI (Clack).
7
+ * Útil para ser llamada desde el CLI o desde un servidor MCP.
8
+ */
9
+ export async function performCreate(type, name, force = false) {
10
+ const cwd = process.cwd();
11
+ const agentDir = path.join(cwd, '.agent');
12
+ const typeFolder = type === 'role' ? 'rules/roles' : type === 'workflow' ? 'workflows' : 'tools';
13
+ const targetDir = path.join(agentDir, typeFolder);
14
+ const targetPath = path.join(targetDir, `${name}.md`);
15
+ try {
16
+ const corePath = (await resolveInstalledCorePath(cwd)) ?? await resolveCorePath();
17
+ const coreTypeFolder = type === 'role' ? 'rules/roles' : type === 'workflow' ? 'workflows' : 'templates';
18
+ const reservedPath = path.join(corePath, coreTypeFolder, `${name}.md`);
19
+ // 1. Reserved Namespace Check
20
+ try {
21
+ await fs.access(reservedPath);
22
+ return { success: false, message: `The name "${name}" is reserved by the core framework.` };
23
+ }
24
+ catch {
25
+ // Name is free in core
26
+ }
27
+ // 2. Local Existence Check
28
+ if (!force) {
29
+ try {
30
+ await fs.access(targetPath);
31
+ return { success: false, message: `A local file named "${name}" already exists in .agent/${typeFolder}/.`, path: targetPath };
32
+ }
33
+ catch {
34
+ // Name is free locally or we create it
35
+ }
36
+ }
37
+ // 3. Create Scaffolding
38
+ await fs.mkdir(targetDir, { recursive: true });
39
+ let content = '';
40
+ if (type === 'role') {
41
+ content = `---
42
+ id: role.${name}-agent
43
+ type: rule
44
+ owner: architect-agent
45
+ version: 1.0.0
46
+ severity: PERMANENT
47
+ scope: project
48
+ ---
49
+
50
+ # ROLE: ${name}-agent
51
+
52
+ ## Identity
53
+ You are the **${name}-agent**. Explain your purpose and specialty here.
54
+
55
+ ## Execution Rules (PERMANENT)
56
+ 1. **Mandatory Identification**: You MUST start ALL your responses with the prefix: \`🤖 **${name}-agent**:\`.
57
+ 2. (Add your specific rules here)
58
+
59
+ ## Agentic Discipline (PERMANENT)
60
+ 1. (Add your discipline principles here)
61
+ `;
62
+ }
63
+ else if (type === 'workflow') {
64
+ content = `---
65
+ id: workflow.custom.${name}
66
+ description: Description of this custom workflow.
67
+ owner: architect-agent
68
+ version: 1.0.0
69
+ severity: RECOMMENDED
70
+ ---
71
+
72
+ # WORKFLOW: ${name}
73
+
74
+ ## Input (REQUIRED)
75
+ - Pre-requisites
76
+
77
+ ## Mandatory Steps
78
+ 1. Step one
79
+ 2. Step two
80
+
81
+ ## Output (REQUIRED)
82
+ - Expected result
83
+ `;
84
+ }
85
+ await fs.writeFile(targetPath, content);
86
+ return { success: true, message: `${name} created successfully in .agent/${typeFolder}/`, path: targetPath };
87
+ }
88
+ catch (error) {
89
+ return { success: false, message: `Error during creation: ${error instanceof Error ? error.message : String(error)}` };
90
+ }
91
+ }
92
+ /**
93
+ * CLI Command with Clack visual interface.
94
+ */
95
+ import { select, text, isCancel, cancel } from '@clack/prompts';
96
+ export async function createCommand(type, name) {
97
+ intro(`Creating New ${type}: ${name}`);
98
+ const s = spinner();
99
+ s.start('Validating...');
100
+ // Try to create first
101
+ let result = await performCreate(type, name);
102
+ s.stop('Validation complete.');
103
+ // Handle conflicts interactively
104
+ if (!result.success && result.message.includes('reserved')) {
105
+ const action = await select({
106
+ message: `The name "${name}" is in use by the CORE. What do you want to do?`,
107
+ options: [
108
+ { value: 'rename', label: 'Rename (e.g., custom-neo)' },
109
+ { value: 'abort', label: 'Cancel operation' }
110
+ ],
111
+ });
112
+ if (isCancel(action) || action === 'abort') {
113
+ cancel('Operation cancelled.');
114
+ return process.exit(0);
115
+ }
116
+ if (action === 'rename') {
117
+ const newName = await text({
118
+ message: 'Enter the new name:',
119
+ placeholder: `custom-${name}`,
120
+ validate(value) {
121
+ if (value.trim().length === 0)
122
+ return 'Name cannot be empty';
123
+ return;
124
+ },
125
+ });
126
+ if (isCancel(newName)) {
127
+ cancel('Operation cancelled.');
128
+ return process.exit(0);
129
+ }
130
+ s.start('Creating with new name...');
131
+ result = await performCreate(type, newName);
132
+ s.stop('Done.');
133
+ }
134
+ }
135
+ else if (!result.success && result.message.includes('already exists')) {
136
+ const action = await select({
137
+ message: `The local file "${name}" already exists. What do you want to do?`,
138
+ options: [
139
+ { value: 'overwrite', label: 'Overwrite existing file' },
140
+ { value: 'rename', label: 'Rename new file' },
141
+ { value: 'abort', label: 'Cancel' }
142
+ ],
143
+ });
144
+ if (isCancel(action) || action === 'abort') {
145
+ cancel('Operation cancelled.');
146
+ return process.exit(0);
147
+ }
148
+ if (action === 'overwrite') {
149
+ s.start('Overwriting...');
150
+ result = await performCreate(type, name, true);
151
+ s.stop('Done.');
152
+ }
153
+ else if (action === 'rename') {
154
+ const newName = await text({
155
+ message: 'Enter the new name:',
156
+ validate(value) {
157
+ if (value.trim().length === 0)
158
+ return 'Required';
159
+ },
160
+ });
161
+ if (isCancel(newName)) {
162
+ cancel('Operation cancelled.');
163
+ return process.exit(0);
164
+ }
165
+ s.start('Creating...');
166
+ result = await performCreate(type, newName);
167
+ s.stop('Done.');
168
+ }
169
+ }
170
+ if (result.success) {
171
+ note('Remember to register it in the local index if you want to use an alias.', 'Next Step');
172
+ outro(result.message);
173
+ }
174
+ else {
175
+ note(result.message, 'Error');
176
+ outro('Process finished with errors.');
177
+ }
178
+ }
@@ -0,0 +1,212 @@
1
+ import { intro, outro, spinner, confirm, note } from '@clack/prompts';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { detectAgentSystem } from '../../core/migration/detector.js';
5
+ import { transformMarkdownContent } from '../../core/migration/transformer.js';
6
+ import { resolveCorePath, resolveInstalledCorePath } from '../../core/mapping/resolver.js';
7
+ import { performBackup } from '../../core/utils/backup.js';
8
+ export async function initCommand() {
9
+ intro('Agentic Workflow Initialization');
10
+ const cwd = process.cwd();
11
+ const agentDir = path.join(cwd, '.agent');
12
+ // 1. Existing System Detection
13
+ const systemType = await detectAgentSystem(cwd);
14
+ if (systemType === 'legacy') {
15
+ const shouldUpdate = await confirm({
16
+ message: 'A legacy .agent system has been detected. Do you want to migrate it to the latest portable version?',
17
+ });
18
+ if (!shouldUpdate || typeof shouldUpdate === 'symbol') {
19
+ outro('Initialization cancelled by user.');
20
+ return;
21
+ }
22
+ const sBackup = spinner();
23
+ sBackup.start('Creating backup...');
24
+ const resultBackup = await performBackup(cwd);
25
+ if (resultBackup) {
26
+ sBackup.stop(`Backup created at: ${path.relative(cwd, resultBackup)}`);
27
+ }
28
+ else {
29
+ sBackup.stop('No backup was required.');
30
+ }
31
+ }
32
+ else if (systemType === 'current') {
33
+ note('The system is already updated to the latest version.', 'Information');
34
+ const reinit = await confirm({
35
+ message: 'Do you want to force a re-initialization by reference? (A backup will be created)',
36
+ });
37
+ if (!reinit || typeof reinit === 'symbol') {
38
+ outro('Process finished.');
39
+ return;
40
+ }
41
+ const sBackup = spinner();
42
+ sBackup.start('Creating backup...');
43
+ const resultBackup = await performBackup(cwd);
44
+ sBackup.stop(`Backup created at: ${path.relative(cwd, resultBackup)}`);
45
+ }
46
+ // 2. Cleanup Legacy Files (Enforce Purity)
47
+ const sCleanup = spinner();
48
+ sCleanup.start('Cleaning up redundant legacy core files...');
49
+ await cleanupLegacyFiles(agentDir);
50
+ sCleanup.stop('Local environment cleaned (Core references only).');
51
+ const s = spinner();
52
+ s.start('Configuring Agentic Core Reference...');
53
+ try {
54
+ // Resolve absolute path to core package in node_modules
55
+ const corePath = (await resolveInstalledCorePath(cwd)) ?? await resolveCorePath();
56
+ // 1. Create .agent structure (Only project-specific directories)
57
+ await fs.mkdir(agentDir, { recursive: true });
58
+ // Create mirror directories (empty by default)
59
+ const mirrorDirs = ['rules/roles', 'rules/constitution', 'workflows', 'templates', 'artifacts', 'metrics'];
60
+ for (const dir of mirrorDirs) {
61
+ await fs.mkdir(path.join(agentDir, dir), { recursive: true });
62
+ }
63
+ // 2. Create Root Index with ABSOLUTE references to Core
64
+ const indexContent = transformMarkdownContent(`# INDEX — .agent (Root)
65
+
66
+ ## Objective
67
+ Global entry point for the agentic system. It uses absolute references to the core to ensure immutability and ease of update.
68
+
69
+ ## Aliases (YAML)
70
+ \`\`\`yaml
71
+ agent:
72
+ core:
73
+ root: "${corePath}"
74
+ artifacts: "${path.join(corePath, 'artifacts/index.md')}"
75
+ rules: "${path.join(corePath, 'rules/index.md')}"
76
+ workflows: "${path.join(corePath, 'workflows/index.md')}"
77
+ templates: "${path.join(corePath, 'templates/index.md')}"
78
+
79
+ domains:
80
+ workflows:
81
+ index: .agent/workflows/index.md
82
+ artifacts:
83
+ index: .agent/artifacts/index.md
84
+ rules:
85
+ index: .agent/rules/index.md
86
+ roles:
87
+ index: .agent/rules/roles/index.md
88
+ templates:
89
+ index: .agent/templates/index.md
90
+ \`\`\`
91
+ `, {
92
+ id: 'agent.index',
93
+ owner: 'architect-agent',
94
+ version: '1.3.0',
95
+ severity: 'PERMANENT',
96
+ description: 'Core Reference System'
97
+ });
98
+ await fs.writeFile(path.join(agentDir, 'index.md'), indexContent);
99
+ // 3. Create local domain indices (Proxy/Extension indices)
100
+ await fs.writeFile(path.join(agentDir, 'rules', 'index.md'), '# LOCAL RULES\n\nYou can add project-specific rules here.');
101
+ await fs.writeFile(path.join(agentDir, 'rules', 'constitution', 'index.md'), '# LOCAL CONSTITUTION\n\nYou can add project-specific constitutions here.');
102
+ await fs.writeFile(path.join(agentDir, 'rules', 'roles', 'index.md'), '# LOCAL ROLES\n\nYou can add custom roles here (e.g., neo-agent).');
103
+ await fs.writeFile(path.join(agentDir, 'workflows', 'index.md'), '# LOCAL WORKFLOWS\n\nYou can add your own custom workflows here.');
104
+ await fs.writeFile(path.join(agentDir, 'artifacts', 'index.md'), '# LOCAL ARTIFACTS\n\nYou can add custom artifact aliases here.');
105
+ // 4. Create AGENTS.md (The "Portal" for IDE Agents)
106
+ const agentsMdContent = `# AGENTS
107
+
108
+ This project uses the **Portable Agentic Workflow** framework.
109
+
110
+ ## Getting Started
111
+ To initialize the agentic session, the agent MUST first read the index files:
112
+ 1. Read the master index: \`.agent/index.md\`
113
+ 2. Follow the Core references in \`node_modules\` described in that index.
114
+
115
+ ## Main Workflow
116
+ Execute the core initialization workflow:
117
+ - \`${path.join(corePath, 'workflows/init.md')}\`
118
+
119
+ ## Rules and Discipline
120
+ The core rules reside at:
121
+ - \`${path.join(corePath, 'rules/index.md')}\`
122
+ `;
123
+ await fs.writeFile(path.join(cwd, 'AGENTS.md'), agentsMdContent);
124
+ // 5. Create MCP Configuration for Antigravity/IDE
125
+ const sMcp = spinner();
126
+ sMcp.start('Configuring MCP Server for IDE...');
127
+ const mcpConfigDir = path.join(cwd, '.antigravity');
128
+ await fs.mkdir(mcpConfigDir, { recursive: true });
129
+ const mcpConfig = {
130
+ mcpServers: {
131
+ "agentic-workflow": {
132
+ command: "node",
133
+ args: [path.join(corePath, '../bin/cli.js'), "mcp"],
134
+ env: {},
135
+ disabled: false
136
+ }
137
+ }
138
+ };
139
+ await fs.writeFile(path.join(mcpConfigDir, 'task_mcp_config.json'), JSON.stringify(mcpConfig, null, 2));
140
+ sMcp.stop('MCP Server configured (.antigravity/task_mcp_config.json)');
141
+ s.stop('Configuration complete.');
142
+ note(`Core located at: ${corePath}\nAbsolute references have been configured for the IDE.`, 'Architecture by Reference');
143
+ outro('Agentic System initialized successfully\nYour core is now protected in node_modules.');
144
+ }
145
+ catch (error) {
146
+ s.stop('Initialization failed.');
147
+ console.error(error);
148
+ process.exit(1);
149
+ }
150
+ }
151
+ /**
152
+ * Removes legacy core files that should now be consumed by reference.
153
+ */
154
+ async function cleanupLegacyFiles(agentDir) {
155
+ const coreFileNames = [
156
+ // Roles
157
+ 'architect.md', 'qa.md', 'driver.md', 'researcher.md',
158
+ 'module.md', 'surface.md', 'tooling.md', 'neo.md',
159
+ // Constitution
160
+ 'GEMINI.location.md', 'agent-system.md', 'agents-behavior.md',
161
+ 'clean-code.md', 'project-architecture.md', 'extensio-architecture.md',
162
+ 'drivers.md', 'modules.md', 'pages.md', 'shards.md',
163
+ // Lifecycle Long
164
+ 'phase-0-acceptance-criteria.md', 'phase-1-research.md', 'phase-2-analysis.md',
165
+ 'phase-3-planning.md', 'phase-4-implementation.md', 'phase-5-verification.md',
166
+ 'phase-6-results-acceptance.md', 'phase-7-evaluation.md', 'phase-8-commit-push.md',
167
+ // Lifecycle Short
168
+ 'short-phase-1-brief.md', 'short-phase-2-implementation.md', 'short-phase-3-closure.md',
169
+ // Command specific
170
+ 'init.md', 'analysis.md', 'planning.md', 'verification.md',
171
+ 'results-acceptance.md', 'review.md', 'changelog.md',
172
+ 'subtask-implementation.md', 'supplemental-report.md', 'todo-item.md',
173
+ // Templates
174
+ 'acceptance.md', 'agent-scores.md', 'agent-task.md', 'brief.md', 'closure.md',
175
+ 'driver-create.md', 'driver-delete.md', 'driver-refactor.md',
176
+ 'module-create.md', 'module-delete.md', 'module-refactor.md',
177
+ 'research.md', 'task-metrics.md', 'task.md',
178
+ // Driver & Module Workflows
179
+ 'create.md', 'delete.md', 'refactor.md', 'pages.create.md', 'shards.create.md'
180
+ ];
181
+ const targetDirs = [
182
+ 'rules/roles',
183
+ 'rules/constitution',
184
+ 'workflows',
185
+ 'templates',
186
+ 'workflows/drivers',
187
+ 'workflows/modules',
188
+ 'workflows/tasklifecycle-long',
189
+ 'workflows/tasklifecycle-short'
190
+ ];
191
+ for (const relDir of targetDirs) {
192
+ const dirPath = path.join(agentDir, relDir);
193
+ try {
194
+ const stats = await fs.stat(dirPath);
195
+ if (!stats.isDirectory())
196
+ continue;
197
+ const files = await fs.readdir(dirPath);
198
+ for (const file of files) {
199
+ // Never delete index files
200
+ if (file === 'index.md')
201
+ continue;
202
+ // Delete if it matches a known core filename
203
+ if (coreFileNames.includes(file)) {
204
+ await fs.unlink(path.join(dirPath, file));
205
+ }
206
+ }
207
+ }
208
+ catch {
209
+ // Directory doesn't exist, skip
210
+ }
211
+ }
212
+ }