abelworkflow 1.2.2 → 1.2.4

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.
@@ -10,7 +10,9 @@ import {
10
10
  writeText
11
11
  } from "../config/store.mjs";
12
12
  import {
13
+ extractTopLevelTomlEntries,
13
14
  formatTomlKeySegment,
15
+ mergeMissingTopLevelTomlEntries,
14
16
  parseToml,
15
17
  removeTomlSectionField,
16
18
  removeTopLevelTomlField,
@@ -23,6 +25,21 @@ import { normalizeOpenAiBaseUrl } from "./url.mjs";
23
25
 
24
26
  const CODEX_ENV_KEY = "OPENAI_API_KEY";
25
27
  const CODEX_PROVIDER_ID = "abelworkflow";
28
+ const publishedCodexDeveloperInstructionHashes = new Set([
29
+ "9a70e45a6f4a201f617b657207f32b61901ecc70071dfb4f9d905cc23a6f35a7",
30
+ "81aa8aaf309ed374dbc2d8ae55ca793ad39a4befc75aba6cac32736da368e2fd"
31
+ ]);
32
+ const obsoleteCodexTopLevelFields = [
33
+ "disable_response_storage",
34
+ "network_access",
35
+ "supports_websockets",
36
+ "requires_openai_auth"
37
+ ];
38
+ const obsoleteCodexFeatureFields = [
39
+ "js_repl",
40
+ "responses_websockets",
41
+ "responses_websockets_v2"
42
+ ];
26
43
 
27
44
  function assertTomlTable(value, name) {
28
45
  if (value === undefined) return {};
@@ -36,6 +53,59 @@ function assertTomlTable(value, name) {
36
53
  return value;
37
54
  }
38
55
 
56
+ function mergeCodexTemplateDefaults(content, templateContent) {
57
+ const template = parseToml(templateContent);
58
+ const current = parseToml(content);
59
+ const templateEntries = extractTopLevelTomlEntries(templateContent);
60
+ let nextContent = mergeMissingTopLevelTomlEntries(content, templateEntries);
61
+ const currentInstructions = typeof current.developer_instructions === "string"
62
+ ? current.developer_instructions
63
+ : "";
64
+
65
+ if (publishedCodexDeveloperInstructionHashes.has(hashBytes(currentInstructions))) {
66
+ const legacyDefaults = {
67
+ approvals_reviewer: "guardian_subagent",
68
+ approval_policy: "on-request",
69
+ sandbox_mode: "workspace-write",
70
+ model: "gpt-5.5"
71
+ };
72
+ const replacementFields = new Set(["developer_instructions"]);
73
+ for (const [field, value] of Object.entries(legacyDefaults)) {
74
+ if (current[field] === value) replacementFields.add(field);
75
+ }
76
+ for (const field of replacementFields) {
77
+ nextContent = removeTopLevelTomlField(nextContent, field);
78
+ }
79
+ nextContent = mergeMissingTopLevelTomlEntries(
80
+ nextContent,
81
+ templateEntries.filter(({ field }) => replacementFields.has(field))
82
+ );
83
+ }
84
+
85
+ for (const field of obsoleteCodexTopLevelFields) {
86
+ nextContent = removeTopLevelTomlField(nextContent, field);
87
+ }
88
+ for (const field of obsoleteCodexFeatureFields) {
89
+ nextContent = removeTomlSectionField(nextContent, "features", field);
90
+ }
91
+
92
+ for (const sectionName of ["agents", "features"]) {
93
+ const templateSection = assertTomlTable(template[sectionName], `template ${sectionName}`);
94
+ const currentSection = assertTomlTable(current[sectionName], sectionName);
95
+ const missingValues = Object.fromEntries(
96
+ Object.entries(templateSection).filter(([field]) => !Object.hasOwn(currentSection, field))
97
+ );
98
+ if (Object.keys(missingValues).length) {
99
+ nextContent = updateTomlSectionFields(nextContent, sectionName, missingValues);
100
+ }
101
+ }
102
+ return nextContent;
103
+ }
104
+
105
+ async function loadBundledCodexConfigTemplate(paths) {
106
+ return readFile(paths.codexTemplateConfigPath, "utf8");
107
+ }
108
+
39
109
  async function readCodexAgentTarget(path) {
40
110
  try {
41
111
  const targetStat = await lstat(path);
@@ -189,6 +259,7 @@ async function getExistingCodexApiConfig(paths) {
189
259
  }
190
260
 
191
261
  async function persistCodexConfiguration(paths, intent, operations = {}) {
262
+ const templateContent = await loadBundledCodexConfigTemplate(paths);
192
263
  return withFileTransaction([
193
264
  { path: paths.codexConfigPath, safeRoot: paths.homeDir },
194
265
  { path: paths.codexAuthPath, safeRoot: paths.homeDir, sensitive: true }
@@ -198,6 +269,7 @@ async function persistCodexConfiguration(paths, intent, operations = {}) {
198
269
  assertPlainObject(currentAuth, "Codex auth");
199
270
  const current = resolveExistingCodexApiConfig(currentContent, currentAuth);
200
271
  const content = buildCodexConfigContent(currentContent, {
272
+ templateContent,
201
273
  providerName: current.providerName,
202
274
  baseUrl: intent.baseUrl
203
275
  });
@@ -270,6 +342,7 @@ async function configureCodexApi(paths, promptApi, ownership = {}, runtime = {})
270
342
  }
271
343
 
272
344
  function buildCodexConfigContent(currentContent, {
345
+ templateContent = "",
273
346
  providerName,
274
347
  baseUrl
275
348
  }) {
@@ -280,17 +353,21 @@ function buildCodexConfigContent(currentContent, {
280
353
  `model_providers.${CODEX_PROVIDER_ID}`
281
354
  );
282
355
  const providerSection = `model_providers.${formatTomlKeySegment(CODEX_PROVIDER_ID)}`;
283
- let content = updateTopLevelTomlField(currentContent, "model_provider", CODEX_PROVIDER_ID);
356
+ let content = currentContent.trim()
357
+ ? mergeCodexTemplateDefaults(currentContent, templateContent)
358
+ : templateContent;
359
+ content = updateTopLevelTomlField(content, "model_provider", CODEX_PROVIDER_ID);
284
360
  content = removeTopLevelTomlField(content, "preferred_auth_method");
285
361
  content = removeTopLevelTomlField(content, "temp_env_key");
286
- for (const field of ["env_key", "temp_env_key", "supports_websockets"]) {
362
+ for (const field of ["env_key", "temp_env_key"]) {
287
363
  content = removeTomlSectionField(content, providerSection, field);
288
364
  }
289
365
  content = updateTomlSectionFields(content, providerSection, {
290
366
  name: providerName || CODEX_PROVIDER_ID,
291
367
  base_url: normalizeOpenAiBaseUrl(baseUrl),
292
368
  wire_api: "responses",
293
- requires_openai_auth: true
369
+ requires_openai_auth: true,
370
+ supports_websockets: true
294
371
  });
295
372
  parseToml(content);
296
373
  return content;
@@ -315,6 +392,7 @@ export {
315
392
  configureCodexApi,
316
393
  deployBundledCodexAgents,
317
394
  mergeCodexAuthData,
395
+ mergeCodexTemplateDefaults,
318
396
  persistCodexConfiguration,
319
397
  resolveExistingCodexApiConfig
320
398
  };
@@ -84,17 +84,18 @@ function buildPiModelsConfig(modelsConfig = {}, { baseUrl, api, apiKey, modelIds
84
84
  const provider = {
85
85
  baseUrl: normalizeOpenAiBaseUrl(baseUrl),
86
86
  api,
87
- ...(responses ? {
88
- apiKey,
89
- compat: { supportsDeveloperRole: false }
90
- } : {}),
87
+ ...(responses ? { apiKey } : {}),
88
+ compat: { supportsDeveloperRole: false },
91
89
  models: modelIds.map((modelId) => {
92
90
  const name = existingModels.get(modelId)?.name;
93
- const model = { id: modelId, name: typeof name === "string" && name ? name : modelId };
91
+ const model = {
92
+ id: modelId,
93
+ name: typeof name === "string" && name ? name : modelId,
94
+ reasoning: true,
95
+ input: ["text", "image"]
96
+ };
94
97
  return responses ? {
95
98
  ...model,
96
- reasoning: true,
97
- input: ["text", "image"],
98
99
  thinkingLevelMap: {
99
100
  off: null,
100
101
  minimal: "low",
@@ -106,7 +107,11 @@ function buildPiModelsConfig(modelsConfig = {}, { baseUrl, api, apiKey, modelIds
106
107
  },
107
108
  contextWindow: 262144,
108
109
  maxTokens: 131072
109
- } : model;
110
+ } : {
111
+ ...model,
112
+ contextWindow: 262144,
113
+ maxTokens: 64000
114
+ };
110
115
  })
111
116
  };
112
117
 
@@ -11,7 +11,7 @@ Do NOT dispatch for review after implementation — use reviewer instead.
11
11
  Do NOT dispatch if the affected files are already known and confirmed.
12
12
  """
13
13
  nickname_candidates = ["Atlas", "Trace", "Scout"]
14
- model = "gpt-5.6-sol"
14
+ model = "gpt-5.6-luna"
15
15
  model_reasoning_effort = "high"
16
16
  sandbox_mode = "read-only"
17
17
 
@@ -10,7 +10,7 @@ Do NOT dispatch when the task touches global configs, shared utilities,
10
10
  public interfaces used across modules, or project scaffolding.
11
11
  """
12
12
  nickname_candidates = ["Forge", "Patch", "Builder"]
13
- model = "gpt-5.6-sol"
13
+ model = "gpt-5.6-luna"
14
14
  model_reasoning_effort = "high"
15
15
  sandbox_mode = "workspace-write"
16
16
 
@@ -0,0 +1,77 @@
1
+ personality = "pragmatic"
2
+ approval_policy = "never"
3
+ sandbox_mode = "danger-full-access"
4
+ model = "gpt-5.6-sol"
5
+ model_reasoning_effort = "high"
6
+ developer_instructions = """
7
+ Act as the parent agent and orchestrator. Prefer direct execution for simple,
8
+ well-scoped tasks; delegate only when specialization or parallelism adds clear
9
+ value.
10
+
11
+ ## Instruction Precedence
12
+
13
+ - An active workflow command takes precedence over this default orchestration
14
+ policy. Follow its phase rules, write boundaries, required tools,
15
+ verification order, and stop/go gates exactly.
16
+ - `/abel-design` is design-only: investigate and produce validated OpenSpec
17
+ artifacts without implementing product code.
18
+ - `/abel-implement` requires OpenSpec readiness and test-first Red, Green,
19
+ Refactor cycles before completion is recorded.
20
+ - `/abel-diagnose` requires reproduction and evidence for the root cause before
21
+ a regression test and minimal fix.
22
+ - Subagents assist inside the active phase. They never own workflow transitions
23
+ or bypass required user confirmation.
24
+
25
+ ## Direct Work and Delegation
26
+
27
+ - For simple, local, low-risk tasks, the parent agent completes the work
28
+ directly when delegation overhead would exceed its value.
29
+ - Do not dispatch Planner or Reviewer by default. Use them only when planning
30
+ uncertainty or review risk justifies the extra step.
31
+ - Delegate with an explicit goal, bounded scope, relevant evidence, and a
32
+ disjoint write set. Parallelize only independent work.
33
+ - Keep working on non-overlapping integration or verification while delegated
34
+ tasks run; avoid duplicate exploration or implementation.
35
+
36
+ ## Agent Roles
37
+
38
+ - `explorer`: read-only codebase mapping, symbol lookup, execution tracing, and
39
+ impact discovery.
40
+ - `planner`: pre-implementation scope, sequencing, risks, and verification when
41
+ the next steps are genuinely unclear.
42
+ - `worker`: bounded implementation, tests, and module-local fixes after the
43
+ active phase permits writes.
44
+ - `reviewer`: post-implementation correctness, regression, security, and test
45
+ coverage review when change risk warrants it.
46
+ - `default`: concise synthesis, fallback triage, and mixed-scope support that
47
+ does not fit a specialist.
48
+
49
+ ## Phase Boundaries
50
+
51
+ - Do not dispatch implementation work during design or other read-only phases.
52
+ - Do not ask a Reviewer to substitute for missing reproduction, readiness, or
53
+ tests.
54
+ - Do not let a subagent broaden scope, make unresolved product decisions, or
55
+ cross an active command's write boundary.
56
+ - If a critical unknown blocks the active phase, stop and ask rather than
57
+ delegating around it.
58
+
59
+ ## Parent Responsibility
60
+
61
+ - The parent agent owns decisions, synthesis, conflict resolution, integration,
62
+ final verification, and the user-facing result.
63
+ - Validate delegated output against the active workflow and repository
64
+ instructions before using it.
65
+ - Resolve handoffs and conflicts explicitly; never treat a subagent report as
66
+ automatic permission to advance phases or declare completion.
67
+ """
68
+
69
+ [agents]
70
+ max_threads = 10
71
+ max_depth = 1
72
+ job_max_runtime_seconds = 2400
73
+
74
+ [features]
75
+ multi_agent = true
76
+ guardian_approval = true
77
+ shell_snapshot = true
@@ -1,37 +1,175 @@
1
1
  ---
2
2
  name: abel-design
3
- description: Transform requirements into implementation-ready OpenSpec artifacts.
3
+ description: Transform requirements into implementation-ready, traceable specs via gated clarification.
4
4
  category: abel
5
- tags: [abel, design, openspec]
5
+ tags: [abel, design, constraints, PBT, subagents]
6
6
  argument-hint: [requirement | --change <change_name>]
7
7
  ---
8
8
 
9
9
  <!-- ABEL:START -->
10
- # abel-design
11
10
 
12
- Turn a requirement into a validated, traceable OpenSpec change. This command is design only; do not implement product code.
11
+ # abel-design Gated Design Mode (Specs Only, No Implementation)
13
12
 
14
- ## Rules
13
+ ## Non-Negotiable Rules (Highest Priority)
14
+ 1. DESIGN MODE ONLY — you MUST NOT generate implementation code.
15
+ 2. WRITE SCOPE:
16
+ - Before Gate A: strictly read-only; persist nothing.
17
+ - After Gate A: write ONLY inside the resolved `changeRoot`. Create only ready artifacts; edit a done artifact only when an approved loop-back/consistency repair explicitly targets it.
18
+ 3. NEVER assume or guess — every blocking decision goes to the user (see Decision Model).
19
+ 4. Final output: a schema-valid, fully traceable OpenSpec change with BLOCKING_DECISIONS = 0, READY_TO_IMPLEMENT.
15
20
 
16
- - Follow the repository instructions and the Design column of its Stage Skill Matrix.
17
- - Before any write, state assumptions and unknowns explicitly. If a critical unknown could change scope, behavior, architecture, data handling, security, or an irreversible action, stop and ask the user.
18
- - Retrieve project context with `rg`, `rg --files`, `git grep`, and direct file reads. Use only project evidence and research sources allowed by the repository instructions.
19
- - Use unified diff patches for proposed and applied changes. Write only inside the resolved OpenSpec `changeRoot`.
20
- - Do not create runtime approval or resume state.
21
+ **Skill Integration**: See `Stage Skill Matrix` (Design column)
21
22
 
22
- ## Process
23
+ ---
24
+
25
+ ## Decision Model
26
+ - Maintain an in-session Decision Ledger with: `id`, `class`, `question`, `evidence`, `options`, `recommendation`, `resolution`, `status`, `affected_artifacts`.
27
+ - `BLOCKING_DECISIONS` is the count of unresolved, non-mechanical decisions in that ledger.
28
+ - Behavior decisions answer WHAT: observable outcomes, scope/non-goals, scenarios, failure behavior, data/security/privacy/compatibility policies and success criteria.
29
+ - Technical decisions answer HOW: interfaces, data flow, dependencies, storage/algorithms, implementation error mechanisms and key technical parameters.
30
+ - MUST be approved by the user: goal, scope, non-goals and observable success behavior; data, security, privacy, compatibility and migration rules; new dependencies, cross-module architecture, irreversible changes; any technical choice with substantive trade-offs, including key parameters.
31
+ - MAY be decided mechanically by the agent: naming, file locations and local structure uniquely determined by existing repo conventions; easily reversible details with no external behavior change; test placement and execution order derived directly from the approved design.
32
+ - Record mechanical decisions and never re-ask them. Two or more viable options with substantive differences → escalate to a blocking decision.
33
+ - Do NOT create a runtime ledger or approval-state file. Materialize approved decisions only in schema artifacts.
34
+
35
+ ## Phase 0 — Entry, Mode & Readiness (read-only)
36
+ - Verify an initialized OpenSpec root and the required CLI capabilities: `new change`, `list --json`, `schemas --json`, `schema which --json`, `schema validate --json`, `templates --json`, `status --json`, `instructions --json`, and `validate --strict`. If unavailable, STOP with actionable `/abel-init` remediation; do not initialize or update from this command.
37
+ - Resolve mode:
38
+ - Explicit `--change <name>` → Resume. If that change does not exist, STOP and ask the user to correct the name or choose New mode.
39
+ - Otherwise, an exact existing-change match → Resume.
40
+ - Otherwise → New mode; do not silently interpret an explicit/resume-like typo as a requirement.
41
+ - Resolve the effective schema by precedence: explicit schema choice, existing change metadata, project config, then `spec-driven`; verify it appears in `openspec schemas --json`.
42
+ - Before creating a change, run `openspec schema which <schema> --json` and `openspec schema validate <schema> --json`, inspect its definition and `openspec templates --schema <schema> --json`, and perform a preliminary behavior/technical/mixed dependency check. Implementation compatibility also requires a non-empty concrete `apply.tracks` that matches exactly one artifact's `generates`. An incompatible schema must fail closed before creation.
43
+ - New mode minimum intake before ANY exploration:
44
+ - Problem/goal statement, AND
45
+ - Scope anchor (which module/directory is involved).
46
+ - If either intake item is missing, ask the user concisely before proceeding.
47
+ - Generate a provisional kebab-case change name and check `openspec list --changes --json`. Recompute and confirm it from the final Gate A scope before creation. Persist nothing yet.
48
+
49
+ ## Phase 1 — Evidence Exploration (read-only)
50
+ - Use local codebase retrieval with `rg`, `rg --files`, `git grep`, and direct file reads.
51
+ - Single context boundary → main agent explores directly.
52
+ - Multiple independent context boundaries, when the platform permits → dispatch parallel Explore subagents:
53
+ - Divide by context boundary (NOT functional role); each boundary self-contained.
54
+ - Each subagent receives: mandatory use of the codebase retrieval policy, a clear scope, and the mandatory JSON output schema:
55
+ {
56
+ "module_name": "所探索的上下文边界",
57
+ "existing_structures": ["关键结构/模式"],
58
+ "existing_conventions": ["约定/标准"],
59
+ "constraints_discovered": ["硬约束"],
60
+ "open_questions": ["需用户输入的歧义"],
61
+ "dependencies": ["跨模块依赖"],
62
+ "risks": ["风险/阻碍"],
63
+ "success_criteria_hints": ["可观察的成功行为"]
64
+ }
65
+ - Validate every subagent JSON before aggregation; aggregate constraints, dependencies, risks, conflicts and questions into the Decision Ledger.
66
+ - Audit existing codebase patterns:
67
+ Use `rg`, `rg --files`, `git grep`, and direct file reads to validate against existing codebase patterns.
68
+ - On-demand /context7-auto-research: verify candidate libraries/APIs against official contracts.
69
+ - On-demand /grok-search: architectural patterns and best practices for candidate directions.
70
+ - PBT boundary screening: probe empty input, idempotency, ordering, size/value bounds, state-transition legality → feed the question list for Phase 2.
71
+ - Reference: Inspect codebase structure with `rg --files`, `git grep`, and direct file reads.
72
+
73
+ ## Phase 2 — Behavior Clarification Loop (multiple rounds allowed)
74
+ - Cover WHAT only: goal, scope, non-goals, observable scenarios/success criteria, failure behavior, and data/security/privacy/compatibility policies.
75
+ - Do not choose libraries, protocols, algorithms, storage, topology or implementation parameters in this phase; route them to Phase 4.
76
+ - Each round asks ONLY the current highest-impact blocking questions, grouped concisely, each with evidence, impact and a recommended default.
77
+ - Anti-patterns (flag and reject):
78
+ - Observable behavior deferred to implementation ("error behavior decided while coding")
79
+ - Technical mechanisms smuggled in as product requirements
80
+ - Target behavior patterns:
81
+ - "Lock the account for 30 minutes after 5 consecutive failed logins."
82
+ - "Retain audit records for 30 days and never expose secrets in responses."
83
+ - "For an empty query, return an empty result within the approved latency bound."
84
+ - An answer that widens modules, scenarios or data boundaries → return to Phase 1 for INCREMENTAL exploration only.
85
+ - Loop until unresolved behavior decisions = 0.
86
+
87
+ ## ⛔ Gate A — Approve Behavior Contract
88
+ - Present the behavior contract and affected Decision Ledger entries; the user explicitly approves goal, scope/non-goals, scenarios/success criteria and policies.
89
+ - Recompute the change name from the approved scope and recheck duplicates.
90
+ - New mode: ONLY NOW create the change with `openspec new change <change-name>` (add `--schema <schema>` only for an explicit non-default choice).
91
+ - Build the Artifact Plan, then materialize only behavior-class artifacts that are safe and ready.
92
+
93
+ ## Artifact Plan & Write Protocol
94
+ - Before New-mode creation, build a preliminary compatibility map from the resolved schema definition/templates. After creation or in Resume mode, build the final Artifact Plan from `status --json` and available `instructions --json`. Record the schema's `apply.tracks`; for every artifact record capture id/output paths, dependencies/status, substantive decision class (`behavior|technical|mixed`), write Gate, and affected decisions. Mechanical impact information alone does not make an artifact mixed.
95
+ - Classify by the decisions the artifact carries, never by a hardcoded artifact name:
96
+ - behavior → Gate A
97
+ - technical or mixed → Gate B
98
+ - behavior depending on a Gate B artifact → defer until after Gate B and then follow the DAG
99
+ - If the schema requires a write before Gate A, a write outside `changeRoot`, or an unapproved technical decision to unlock behavior, STOP before New-mode creation and ask the user to select a compatible schema/mapping. Schema order never overrides decision approval.
100
+ - Mandatory loop for EVERY artifact write:
101
+ 1. Run `openspec status --change <change-name> --json`; verify `schemaName`, `changeRoot`, `artifactPaths`, status/dependencies and `applyRequires`. `existingOutputPaths` may be empty and is not a new-file target.
102
+ 2. Run `openspec instructions <artifact-id> --change <change-name> --json`; follow its template/rules/dependencies.
103
+ 3. Read dependencies and existing outputs; check consistency in both directions.
104
+ 4. Prepare content in memory and show the decision summary or unified diff before the corresponding Gate. If materialization reveals a new substantive decision, return to the relevant loop and re-approve it.
105
+ 5. After Gate approval, create exactly one ready artifact, or edit one done artifact explicitly targeted by an approved loop-back/consistency repair. Rerun status after every write and process newly unlocked artifacts topologically.
106
+
107
+ ## Phase 3 — Technical Derivation
108
+ - Derive the technical design from the Gate A contract, existing codebase patterns and official API contracts.
109
+ - Mechanical decisions → record directly in the design. Substantive trade-offs → Phase 4.
110
+
111
+ ## Phase 4 — Technical Decision & Verification Loop
112
+ - Cover HOW: interfaces, data flow, implementation error mechanisms, dependencies/algorithms and key parameters. Examples include JWT vs session design and an approved bcrypt cost factor.
113
+ - Apply the same evidence/options/recommendation format to every substantive technical decision; update the Decision Ledger.
114
+ - PBT applicability rule (screen with the six categories: commutativity/associativity, idempotency, round-trip, invariant preservation, monotonicity, bounds):
115
+ - Behavior with invariants, round-trips, idempotency, ordering, bounds or state transitions → MUST extract a property + falsification strategy.
116
+ - Behavior unsuited to PBT → use example/E2E/static verification and record why PBT does not apply. Do NOT force every requirement through every category.
117
+ - Give every scenario a stable reference: `<spec-path>#<requirement-heading>/<scenario-heading>` and require those headings to be unique within the spec; maintain Requirement → Scenario → Verification → Task.
118
+ - Every task has exactly one schema checkbox and a verification contract using ordinary indented bullets, NEVER nested `- [ ]`/`- [x]` lines:
119
+ - Task ID / dependencies
120
+ - Requirement + stable Scenario reference
121
+ - Verification type: property | example | E2E | static
122
+ - Red command + expected failure reason
123
+ - Green expected behavior
124
+ - Affected-suite verification command
125
+ - Target scope/files
126
+ - For a non-behavior-change task, the Red command is a pre-change executable static verification. Manual-only verification is not implementation-ready and MUST NOT pass Gate B or Exit; reshape the task until it has executable property/example/E2E/static verification.
127
+ - Loop until unresolved technical decisions = 0; prepare proposed remaining artifact contents/unified diffs in memory.
128
+
129
+ ## ⛔ Gate B — Approve Implementation Contract
130
+ - Verify Phase 3/4 faithfully expand the Gate A contract; no unapproved new decisions introduced.
131
+ - Present substantive technical decisions, task/verification mapping and artifact materialization preview.
132
+ - The user explicitly approves that implementation contract.
133
+ - Write the remaining ready artifacts one at a time per the Artifact Plan & Write Protocol.
134
+
135
+ ## Loop-Back Rules
136
+ - A user answer widens modules, scenarios or data boundaries → return to Phase 1.
137
+ - Technical analysis overturns the behavior contract → return to Phase 2; re-approve ONLY the affected decisions and synchronize all affected artifacts.
138
+ - Gate B finds the materialization unfaithful → return to Phase 3/4; unaffected Gate A decisions remain approved.
139
+ - Strict validation, verification-contract or traceability failure → return to the earliest phase that introduced the inconsistency.
140
+ - Never hide a late-discovered blocking question.
141
+
142
+ ## Resume Rules
143
+ - Never infer user approval from artifact existence: `status` reporting `done` proves file completion only, not Gate approval.
144
+ - Never resume by fixed file names or file existence alone; the active schema decides.
145
+ - Algorithm:
146
+ 1. Run `openspec status --change <change-name> --json`.
147
+ 2. Use its `schemaName`, `changeRoot`, `artifactPaths` and statuses; read all `existingOutputPaths` and dependencies.
148
+ 3. Check `openspec validate <change-name> --strict --type change`, template completeness, cross-artifact consistency, traceability and verification contracts.
149
+ 4. Rebuild Gate A/B summaries and the Artifact Plan. Re-confirm every Gate approval that cannot be proven in the current conversation.
150
+ 5. Choose the next step:
151
+ - Explicit Resume change not found (`change_error`) → STOP for spelling/New-mode confirmation; never create silently.
152
+ - Artifacts incomplete → repair/confirm the nearest safe Gate, then handle the artifacts the schema reports ready.
153
+ - Artifacts complete but validation/traceability fails → earliest inconsistent phase.
154
+ - Every artifact id listed in `applyRequires` is `done` → re-confirm any unproven Gate, then run the Exit audit.
155
+ - Only in-session, un-persisted analysis exists → no mid-loop resume; re-run the read-only analysis.
156
+ - Do NOT create runtime approval-state files; re-confirming the Gate summary IS the resume mechanism.
23
157
 
24
- 1. Resolve the input as a new requirement or an explicit `--change <change-name>`. Never silently create a mistyped explicit change.
25
- 2. Verify the OpenSpec project and CLI. Use `openspec context --json`, `openspec list --changes --json`, and `openspec schemas --json`; direct missing setup to `/abel-init`.
26
- 3. Resolve the schema from the existing change, explicit choice, project configuration, or the OpenSpec default. Inspect it with `openspec schema which <schema> --json`, `openspec schema validate <schema> --json`, and `openspec templates --schema <schema> --json`.
27
- 4. Confirm the schema exposes a concrete `apply.tracks` path generated by one artifact. For an existing change, read `schemaName`, `changeRoot`, `artifactPaths`, `applyRequires`, and artifact states from `openspec status --change <change-name> --json`.
28
- 5. Explore the affected code and nearby tests. Summarize current behavior, constraints, dependencies, risks, assumptions, and unknowns with file evidence.
29
- 6. Clarify the smallest set of unresolved behavior and technical decisions. Ask only questions whose answers materially affect the design, and include evidence, impact, options, and a recommended default.
30
- 7. Define scope, non-goals, observable scenarios, failure behavior, data/security/privacy effects, interfaces, dependencies, and verification. Keep the Requirement → Scenario → Verification → Task chain explicit.
31
- 8. For a new change, choose a kebab-case name, check for conflicts, show the planned artifact changes as a unified diff, then run `openspec new change <change-name>`; add `--schema <schema>` only for an explicit non-default choice.
32
- 9. Materialize artifacts in schema dependency order. Before each artifact, run `openspec status --change <change-name> --json` and `openspec instructions <artifact-id> --change <change-name> --json`, read its dependencies and existing output, then apply the smallest consistent patch.
33
- 10. Give each implementation task its target files, dependencies, requirement/scenario reference, Red command and expected failure, minimal Green behavior, and affected/final verification commands.
34
- 11. Run `openspec validate <change-name> --strict --type change`. Finish only when validation passes, every `applyRequires` artifact is done, `apply.tracks` resolves inside `changeRoot`, artifacts agree, and no critical unknown remains.
158
+ ## Exit Criteria
159
+ - [ ] `openspec validate <change-name> --strict --type change` returns zero issues
160
+ - [ ] Every artifact id in `applyRequires` has status `done`
161
+ - [ ] Schema `apply.tracks` resolves to the generated task artifact inside `changeRoot`
162
+ - [ ] Artifacts are consistent and traceable; every task has a valid verification contract
163
+ - [ ] Every task has executable property/example/E2E/static verification; no task is manual-only
164
+ - [ ] BLOCKING_DECISIONS = 0
165
+ - [ ] User has explicitly approved the reconstructed/current Gate A and Gate B summaries in this conversation
166
+ - [ ] Status: READY_TO_IMPLEMENT
35
167
 
36
- Report the change name, decisions made, artifacts changed, validation evidence, and any non-blocking residual risks.
168
+ ## Reference
169
+ - `openspec context --json` / `openspec schemas --json`
170
+ - `openspec view` / `openspec list --changes --json` / `openspec list --specs` (conflicts with existing specs)
171
+ - `openspec status --change <change-name> --json` / `openspec instructions <artifact-id> --change <change-name> --json`
172
+ - `openspec new change <change-name>` (Gate A only)
173
+ - `openspec show <change-name> --json --deltas-only` when validation fails
174
+ - `rg -n "Constraint:|MUST|MUST NOT|INVARIANT:|PROPERTY:" openspec/` before defining new ones
37
175
  <!-- ABEL:END -->
@@ -1,37 +1,63 @@
1
1
  ---
2
2
  name: abel-diagnose
3
- description: Diagnose bugs from evidence and apply minimal regression-tested fixes.
3
+ description: Parallel diagnosis with batch fix reporting via systematic root cause analysis.
4
4
  category: abel
5
- tags: [abel, diagnosis, bugfix, TDD]
5
+ tags: [abel, diagnosis, bugfix]
6
6
  argument-hint: <problem-description>
7
7
  ---
8
-
9
8
  <!-- ABEL:START -->
10
- # abel-diagnose
11
-
12
- Find the verified root cause of the reported problem, then fix it with a regression test and minimal patch.
13
-
14
- ## Rules
15
-
16
- - Follow the repository instructions and the Diagnose column of its Stage Skill Matrix.
17
- - State assumptions and unknowns before any write. If a critical unknown prevents reliable reproduction, changes fix scope, or affects safety, stop and ask the user.
18
- - Retrieve project context with `rg`, `rg --files`, `git grep`, and direct file reads. Use logs, traces, tests, and project evidence before forming conclusions.
19
- - Do not apply a fix until evidence supports the root cause. Do not broaden scope to speculative cleanup.
20
- - Use unified diff patches for every change.
21
-
22
- ## Process
23
-
24
- 1. Restate the observed failure and expected behavior. Identify the smallest affected boundary and relevant verification command.
25
- 2. Reproduce the problem when safe. Record the command, environment facts, output, and failure identity. If it cannot be reproduced, distinguish missing evidence from disproven hypotheses.
26
- 3. Trace the failing path through callers, state transitions, data boundaries, and nearby tests. Compare working and failing cases.
27
- 4. Form the smallest falsifiable root-cause hypothesis and test it against the evidence. For multiple issues, identify dependencies or file conflicts before editing.
28
- 5. Red: add or update a focused regression test and run it before the fix; require failure for the verified root cause. If no meaningful executable regression is possible, state why and stop for direction.
29
- 6. Green: apply the smallest fix and rerun the regression test. Preserve unrelated behavior and user-owned state.
30
- 7. Refactor only if needed for clarity, keeping the regression and affected tests green.
31
-
32
- ## Final Verification
33
-
34
- - Run the regression test, affected suite, and any proportionate broader suite.
35
- - Review the complete diff for scope, side effects, security, secrets, and runtime state accidentally added to the repository.
36
- - Report the verified root cause with evidence, modified files, Red/Green results, final verification commands, and residual risks or unresolved issues.
9
+ **Arguments**
10
+ - Required: `<problem-description>` (one or more bug descriptions; comma-separated supported)
11
+
12
+ **Guardrails**
13
+ - Root cause first; never fix symptoms only
14
+ - Verify root cause hypothesis with evidence before fix
15
+ - Only fixes with evidence-verified root cause may be applied
16
+ - Every fix must include a regression test
17
+ - Keep changes minimal and scoped
18
+ - If verification fails, rollback and iterate
19
+
20
+ **Execution Model**
21
+ - Run detection and root-cause analysis for all issues in parallel
22
+ - Infer scope automatically from problem text, traces, and retrieved code context
23
+ - Build dependency/conflict order before any fix application
24
+ - Same file: force sequential fix order; same symbol: merge when compatible, otherwise sequential
25
+ - Independent scopes: parallel-safe
26
+ - Fix generation for READY issues runs fully in parallel via subagents with forked/minimal context; main agent only aggregates and resolves conflicts
27
+ - Patch application and final verification must run strictly sequential by dependency order
28
+ - Always output one consolidated batch report
29
+
30
+ **Skill Integration**: See `Stage Skill Matrix` (Diagnose column)
31
+
32
+ **Steps**
33
+ 1. Parse input, infer scope, and split into issue list (single or multiple).
34
+ 2. For each issue in parallel: collect logs/traces and locate code via the configured codebase retrieval policy.
35
+ 3. For each issue in parallel: perform root cause analysis; for multi-component chains, decompose the failure chain step by step with evidence.
36
+ 4. Build dependency/conflict graph across issues and compute safe fix order.
37
+ 5. Verify each issue's root cause against collected evidence; only issues with a verified root cause can move to fix generation.
38
+ 6. Spawn one subagent per READY issue to generate `unified diff patch` and regression test with minimal scoped context.
39
+ 7. Main agent reviews/merges subagent outputs by dependency order and outputs one batch report with all issue statuses and patches.
40
+ 8. Apply merged patches strictly sequentially by dependency order.
41
+ 9. Run final verification strictly sequentially by the same dependency order and output verification matrix.
42
+
43
+ **Batch Output**
44
+ ```text
45
+ ## /abel-diagnose Batch Report
46
+
47
+ ### Batch Summary
48
+ Total: {n} | ReadyToFix: {n_ready} | Blocked: {n_blocked}
49
+
50
+ ### Issue Results
51
+ - [{id}] Classification: {category}/{severity} | Root Cause: {summary} | Verified: {yes|no} | Subagent: {agent_id|none} | Status: {READY|BLOCKED}
52
+
53
+ ### Patch Queue (dependency order)
54
+ 1. [{id}] [subagent:{agent_id}] {file_list}
55
+ {unified_diff_patch}
56
+
57
+ ### Verification Matrix
58
+ - [{id}] Regression: {passed|failed} | Affected Suite: {passed|failed}
59
+
60
+ ### Final Status
61
+ {FIXED|PARTIAL|NEEDS_REVIEW|BLOCKED}
62
+ ```
37
63
  <!-- ABEL:END -->