Skip to content

Commit fe4e80b

Browse files
authored
feat(ai): socratic inquiry & knowledge gap formulator (devops ai research socratic) (#1568)
- Add metacognitive knowledge gap and ambiguity analysis for task self-assessment (#276). - Implement structured models KnowledgeGap, ClarifyingQuestion, and CodeLookupInstruction. - Implement SocraticFormulator with task prompt and bounded diagnostic probes via --max-probes. - Register devops ai research socratic subcommand supporting table, JSON, YAML, and Markdown formats. - Add unit and integration tests in tests/test_ai_research_socratic.py. - Synchronize CLI documentation and add changelog fragment.
1 parent 33bc45c commit fe4e80b

13 files changed

Lines changed: 914 additions & 8 deletions

File tree

‎changelog.d/276.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
### Added
2+
- **Socratic inquiry & knowledge gap formulator (`devops ai research socratic`)**:
3+
- Added metacognitive knowledge gap and ambiguity analysis for task self-assessment.
4+
- Implemented structured output models for `GAP`, `AMBIGUITY`, and `UNDERSPECIFIED_CONTRACT` with associated rationales.
5+
- Added minimal diagnostic probes emitting concise clarifying questions and concrete code lookup instructions bounded by `--max-probes`.
6+
- Added `devops ai research socratic` subcommand supporting table, JSON, YAML, and Markdown formats.

‎docs/CLI_REFERENCE.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5120,6 +5120,30 @@ devops ai research annotate [OPTIONS] <path>
51205120
| `--format`, `-f` | `string` | `text` | Output format type (table, json, yaml, markdown). |
51215121
| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. |
51225122

5123+
#### `devops ai research socratic`
5124+
5125+
**Metacognitive Socratic inquiry identifying knowledge gaps, ambiguities, and probes.**
5126+
5127+
```bash
5128+
devops ai research socratic [OPTIONS] <task>
5129+
```
5130+
5131+
**Arguments:**
5132+
5133+
| Argument | Type | Required | Description |
5134+
|---|---|---|---|
5135+
| `<task>` | `string` | No | Task description or objective to analyze for knowledge gaps. |
5136+
5137+
**Options:**
5138+
5139+
| Option / Flag | Type | Default | Description |
5140+
|---|---|---|---|
5141+
| `--task`, `-t` | `string` | - | Task description or objective to analyze for knowledge gaps. |
5142+
| `--context`, `-c` | `string` | - | Optional additional context, instructions, or code snippets. |
5143+
| `--max-probes`, `-n` | `integer` | `5` | Maximum number of clarifying questions and code lookups to emit. |
5144+
| `--format`, `-f` | `string` | `text` | Output format type (table, json, yaml, markdown). |
5145+
| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. |
5146+
51235147
---
51245148

51255149
## devops review
Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
# Task 276: Socratic Inquiry & Knowledge Gap Formulator (`devops ai research socratic`)
22

33
**Issue**: [#276](https://github.com/dan-petty/devops-cli/issues/276)
4-
**Status**: Backlog
5-
**Milestone**: `v0.2.21`
4+
**Status**: Done
5+
**Milestone**: `v0.2.35`
66
**Priority**: `priority/p1-high`
77
**Scope**: `type/feature`, `scope/ai`, `priority/p1-high`
8+
**Feasibility**: Verified against `devops_cli.ai.research` module, model gateway seam, and Typer CLI runtime.
89

910
---
1011

@@ -13,8 +14,10 @@
1314
Emulates metacognitive awareness ("knowing what you don't know"). Proactively analyzes the agent's current state of knowledge for a task to identify gaps, ambiguities, and underspecified contracts.
1415

1516
#### Key Deliverables:
16-
- Context & Rationale*: Emulates metacognitive awareness ("knowing what you don't know"). Proactively analyzes the agent's current state of knowledge for a task to identify gaps, ambiguities, and underspecified contracts.
17-
- Minimal Diagnostic Probing*: Formulates concise, highly targeted clarifying questions or targeted code lookup instructions that eliminate maximum uncertainty with minimal token expenditure.
18-
- Unit and integration test coverage with structural tuple equality assertions.
19-
- Maintain cyclomatic complexity $M \le 10$ and nesting depth $\le 5$.
20-
- 100% passing across all 10 CI quality gates (`uv run devops ci`).
17+
- [x] Structured epistemic models: `KnowledgeGap` (`GAP`, `AMBIGUITY`, `UNDERSPECIFIED_CONTRACT`), `ClarifyingQuestion`, and `CodeLookupInstruction` with associated rationales.
18+
- [x] Socratic inquiry engine `SocraticFormulator` interfacing with LLM client structured output and markdown task prompt `socratic_inquiry.md`.
19+
- [x] Minimal diagnostic probes with bounded questions and code lookups constrained by `--max-probes`.
20+
- [x] Command `devops ai research socratic` supporting table, JSON, YAML, and Markdown output formats.
21+
- [x] Unit and integration test coverage with structural tuple equality assertions in `tests/test_ai_research_socratic.py`.
22+
- [x] Complexity $M \le 10$ and nesting depth $\le 5$ enforced.
23+
- [x] 100% passing across Gated CI validation suite (`uv run devops ci`).

‎docs/commands/ai.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2139,4 +2139,28 @@ devops ai research annotate [OPTIONS] <path>
21392139
| `--format`, `-f` | `string` | `text` | Output format type (table, json, yaml, markdown). |
21402140
| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. |
21412141

2142+
### `devops ai research socratic`
2143+
2144+
**Metacognitive Socratic inquiry identifying knowledge gaps, ambiguities, and probes.**
2145+
2146+
```bash
2147+
devops ai research socratic [OPTIONS] <task>
2148+
```
2149+
2150+
**Arguments:**
2151+
2152+
| Argument | Type | Required | Description |
2153+
|---|---|---|---|
2154+
| `<task>` | `string` | No | Task description or objective to analyze for knowledge gaps. |
2155+
2156+
**Options:**
2157+
2158+
| Option / Flag | Type | Default | Description |
2159+
|---|---|---|---|
2160+
| `--task`, `-t` | `string` | - | Task description or objective to analyze for knowledge gaps. |
2161+
| `--context`, `-c` | `string` | - | Optional additional context, instructions, or code snippets. |
2162+
| `--max-probes`, `-n` | `integer` | `5` | Maximum number of clarifying questions and code lookups to emit. |
2163+
| `--format`, `-f` | `string` | `text` | Output format type (table, json, yaml, markdown). |
2164+
| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. |
2165+
21422166
---

‎src/devops_cli/ai/research/__init__.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,42 @@
1616
)
1717
from devops_cli.ai.research.models import (
1818
BacktrackEvent,
19+
ClarifyingQuestion,
20+
CodeLookupInstruction,
1921
ForageEdge,
2022
ForageNode,
2123
ForageTrail,
24+
KnowledgeGap,
25+
KnowledgeGapType,
2226
MarginaliaRecord,
2327
MarginaliaType,
28+
SocraticInquiryResult,
29+
)
30+
from devops_cli.ai.research.socratic import (
31+
SocraticFormulator,
32+
render_socratic_markdown,
2433
)
2534

2635
__all__ = [
2736
"BacktrackEvent",
37+
"ClarifyingQuestion",
38+
"CodeLookupInstruction",
2839
"ForageCrawler",
2940
"ForageEdge",
3041
"ForageNode",
3142
"ForageTrail",
43+
"KnowledgeGap",
44+
"KnowledgeGapType",
3245
"MarginaliaRecord",
3346
"MarginaliaType",
47+
"SocraticFormulator",
48+
"SocraticInquiryResult",
3449
"annotate_file",
3550
"extract_git_co_changes",
3651
"extract_markdown_links",
3752
"extract_python_imports",
3853
"get_marginalia_path",
3954
"read_marginalia",
55+
"render_socratic_markdown",
4056
"write_marginalia",
4157
]

‎src/devops_cli/ai/research/models.py‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,77 @@ class ForageTrail(BaseModel):
111111
default_factory=list,
112112
description="Nodes ranked by relevance scent score.",
113113
)
114+
115+
116+
class KnowledgeGapType(StrEnum):
117+
"""Classification of epistemic uncertainty."""
118+
119+
GAP = "GAP"
120+
AMBIGUITY = "AMBIGUITY"
121+
UNDERSPECIFIED_CONTRACT = "UNDERSPECIFIED_CONTRACT"
122+
123+
124+
class KnowledgeGap(BaseModel):
125+
"""An identified gap, ambiguity, or underspecified contract in task requirements."""
126+
127+
model_config = ConfigDict(frozen=True, extra="forbid")
128+
129+
type: Literal["GAP", "AMBIGUITY", "UNDERSPECIFIED_CONTRACT"] = Field(
130+
description="Classification of uncertainty: GAP, AMBIGUITY, or UNDERSPECIFIED_CONTRACT."
131+
)
132+
description: str = Field(
133+
description="Description of what is missing, uncertain, or underspecified."
134+
)
135+
rationale: str = Field(
136+
description="Short rationale explaining why this uncertainty impedes execution."
137+
)
138+
139+
140+
class ClarifyingQuestion(BaseModel):
141+
"""A concise, targeted diagnostic question to eliminate uncertainty."""
142+
143+
model_config = ConfigDict(frozen=True, extra="forbid")
144+
145+
question: str = Field(
146+
description="Concise, targeted clarifying question addressing a specific gap."
147+
)
148+
target_gap: str = Field(description="The gap, ambiguity, or contract this question clarifies.")
149+
rationale: str = Field(
150+
description="Rationale explaining why answering this question eliminates uncertainty."
151+
)
152+
153+
154+
class CodeLookupInstruction(BaseModel):
155+
"""A concrete instruction to inspect code or symbols to resolve a gap."""
156+
157+
model_config = ConfigDict(frozen=True, extra="forbid")
158+
159+
target: str = Field(description="Concrete file path, symbol name, or search term to inspect.")
160+
lookup_type: Literal["file", "symbol", "search"] = Field(
161+
description="Type of lookup: file, symbol, or search."
162+
)
163+
rationale: str = Field(description="Information to extract from this code inspection.")
164+
target_gap: str = Field(description="The gap or contract this lookup resolves.")
165+
166+
167+
class SocraticInquiryResult(BaseModel):
168+
"""Structured output of metacognitive Socratic inquiry."""
169+
170+
model_config = ConfigDict(extra="forbid")
171+
172+
task: str = Field(description="Task description analyzed.")
173+
summary: str = Field(
174+
default="", description="Metacognitive summary of epistemic knowledge state."
175+
)
176+
gaps: list[KnowledgeGap] = Field(
177+
default_factory=list,
178+
description="Identified knowledge gaps, ambiguities, and underspecified contracts.",
179+
)
180+
questions: list[ClarifyingQuestion] = Field(
181+
default_factory=list,
182+
description="Targeted clarifying questions bounded by max_probes.",
183+
)
184+
lookups: list[CodeLookupInstruction] = Field(
185+
default_factory=list,
186+
description="Targeted code lookup instructions bounded by max_probes.",
187+
)
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
"""Socratic inquiry and knowledge gap formulator for metacognitive task self-assessment."""
2+
3+
from __future__ import annotations
4+
5+
from pathlib import Path
6+
from typing import Any
7+
8+
from devops_cli.ai.research.models import (
9+
SocraticInquiryResult,
10+
)
11+
from devops_cli.ai.task_loader import load_task_prompt
12+
from devops_cli.config.defaults import DEFAULT_AI_SOCRATIC_MAX_PROBES
13+
from devops_cli.config.settings import get_llm_client
14+
15+
_DEFAULT_SOCRATIC_SYSTEM = (
16+
"You are a metacognitive Socratic inquiry engine for software engineering tasks. "
17+
"Analyze the task to identify gaps, ambiguities, and underspecified contracts, "
18+
"and formulate concise, targeted clarifying questions and concrete code lookup instructions."
19+
)
20+
21+
22+
def _build_user_prompt(
23+
task: str,
24+
context: str | None = None,
25+
repo_root: Path | None = None,
26+
max_probes: int = DEFAULT_AI_SOCRATIC_MAX_PROBES,
27+
) -> str:
28+
"""Compose user prompt containing task, optional context, and probe constraints."""
29+
sections = [
30+
f"Task Description:\n{task}",
31+
f"Max Probes Constraint: Limit clarifying questions to at most {max_probes} "
32+
f"and code lookups to at most {max_probes}.",
33+
]
34+
if context:
35+
sections.append(f"Context / Instructions:\n{context}")
36+
if repo_root:
37+
sections.append(f"Repository Root:\n{repo_root}")
38+
return "\n\n".join(sections)
39+
40+
41+
def _bound_inquiry_result(
42+
result: SocraticInquiryResult,
43+
original_task: str,
44+
max_probes: int,
45+
) -> SocraticInquiryResult:
46+
"""Enforce bounded probe ceiling on questions and code lookup instructions."""
47+
bounded_questions = result.questions[:max_probes]
48+
bounded_lookups = result.lookups[:max_probes]
49+
return SocraticInquiryResult(
50+
task=original_task,
51+
summary=result.summary,
52+
gaps=result.gaps,
53+
questions=bounded_questions,
54+
lookups=bounded_lookups,
55+
)
56+
57+
58+
def render_socratic_markdown(result: SocraticInquiryResult) -> str:
59+
"""Render Socratic inquiry results as clean GitHub-flavored markdown."""
60+
lines: list[str] = [
61+
"# Socratic Inquiry & Knowledge Gap Analysis",
62+
"",
63+
f"**Task**: {result.task}",
64+
"",
65+
]
66+
if result.summary:
67+
lines.extend(["## Metacognitive Summary", "", result.summary, ""])
68+
69+
lines.extend(["## Knowledge Gaps & Ambiguities", ""])
70+
if not result.gaps:
71+
lines.extend(["*No knowledge gaps identified.*", ""])
72+
else:
73+
lines.extend(
74+
[
75+
"| Type | Description | Rationale |",
76+
"| :--- | :--- | :--- |",
77+
]
78+
)
79+
for gap in result.gaps:
80+
desc = gap.description.replace("|", "\\|")
81+
rat = gap.rationale.replace("|", "\\|")
82+
lines.append(f"| `{gap.type}` | {desc} | {rat} |")
83+
lines.append("")
84+
85+
lines.extend(["## Targeted Clarifying Questions", ""])
86+
if not result.questions:
87+
lines.extend(["*No clarifying questions required.*", ""])
88+
else:
89+
for idx, q in enumerate(result.questions, start=1):
90+
lines.extend(
91+
[
92+
f"{idx}. **{q.question}**",
93+
f" - *Target Gap*: {q.target_gap}",
94+
f" - *Rationale*: {q.rationale}",
95+
]
96+
)
97+
lines.append("")
98+
99+
lines.extend(["## Concrete Code Lookup Instructions", ""])
100+
if not result.lookups:
101+
lines.extend(["*No code lookup instructions required.*", ""])
102+
else:
103+
for idx, lk in enumerate(result.lookups, start=1):
104+
lines.extend(
105+
[
106+
f"{idx}. `{lk.target}` ({lk.lookup_type})",
107+
f" - *Target Gap*: {lk.target_gap}",
108+
f" - *Rationale*: {lk.rationale}",
109+
]
110+
)
111+
lines.append("")
112+
113+
return "\n".join(lines).strip() + "\n"
114+
115+
116+
class SocraticFormulator:
117+
"""Metacognitive analyzer formulating knowledge gaps, questions, and lookups."""
118+
119+
def __init__(
120+
self,
121+
client: Any | None = None,
122+
max_probes: int = DEFAULT_AI_SOCRATIC_MAX_PROBES,
123+
) -> None:
124+
self.client = client
125+
self.max_probes = max_probes
126+
127+
def formulate(
128+
self,
129+
task: str,
130+
context: str | None = None,
131+
repo_root: Path | None = None,
132+
) -> SocraticInquiryResult:
133+
"""Analyze task and context to formulate knowledge gaps and minimal probes."""
134+
stripped_task = task.strip()
135+
if not stripped_task:
136+
raise ValueError("Task description must not be empty.")
137+
138+
client = self.client or get_llm_client(task="research")
139+
system_prompt = load_task_prompt("socratic_inquiry.md") or _DEFAULT_SOCRATIC_SYSTEM
140+
user_prompt = _build_user_prompt(
141+
stripped_task,
142+
context=context,
143+
repo_root=repo_root,
144+
max_probes=self.max_probes,
145+
)
146+
147+
res = client.chat_structured(
148+
system=system_prompt,
149+
prompt=user_prompt,
150+
schema=SocraticInquiryResult,
151+
)
152+
return _bound_inquiry_result(res, stripped_task, self.max_probes)
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
You are a metacognitive Socratic inquiry and knowledge gap formulation engine for an autonomous software engineering assistant.
2+
Your goal is to practice epistemic humility and metacognitive awareness ("knowing what you don't know") before code execution begins.
3+
4+
Analyze the given task description and optional context to:
5+
1. Identify knowledge gaps, ambiguities, and underspecified contracts:
6+
- "GAP": Missing critical domain knowledge, architectural context, or unspecified prerequisites.
7+
- "AMBIGUITY": Multiple contradictory or divergent interpretations of requirements or semantics.
8+
- "UNDERSPECIFIED_CONTRACT": Missing schemas, boundary conditions, error handling behaviors, or performance bounds.
9+
For each item, provide a clear description and an explicit rationale explaining why this uncertainty impedes execution.
10+
11+
2. Formulate minimal diagnostic probes to eliminate maximum uncertainty with minimal token expenditure:
12+
- Clarifying questions: Formulate concise, highly targeted clarifying questions directly addressing the identified gaps. Never ask vague or generic prompts like "what do you mean" or "can you elaborate". Every question must cite or resolve a specific gap.
13+
- Targeted code-lookup instructions: Provide concrete instructions to inspect existing code or symbols where checking the codebase can answer the question without guessing. Name specific file paths, symbol names, or search terms (e.g. "src/devops_cli/config/settings.py", "class Settings"). Never provide generic instructions like "check the codebase".
14+
15+
Constraint: Keep the number of clarifying questions and code lookups strictly within the configured probe limit.

0 commit comments

Comments
 (0)