Skip to content

Commit 6eaa7aa

Browse files
feat(code-intel): dev task enhancement with IDS G4 automation [Story NOG-3]
Integrate code intelligence into @dev development tasks for automatic duplicate detection (IDS Gate G4), conventions checking, and blast radius assessment. All integrations use graceful fallback when no provider available. - Create dev-helper.js with 4 public functions (checkBeforeWriting, suggestReuse, getConventionsForPath, assessRefactoringImpact) - Modify dev-develop-story.md: add Code Intelligence Check step - Modify create-service.md: add pre-scaffold duplicate check - Modify dev-suggest-refactoring.md: add blast radius in analysis - Modify build-autonomous.md: add IDS G4 check in build loop - Add 24 unit tests (all passing) covering T1-T9 scenarios - Register dev-helper entity in entity-registry.yaml - QA gate: PASS (quality score 100/100) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 03c5255 commit 6eaa7aa

10 files changed

Lines changed: 1263 additions & 119 deletions

File tree

Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
'use strict';
2+
3+
const { getEnricher, getClient, isCodeIntelAvailable } = require('../index');
4+
5+
// Risk level thresholds based on blast radius (reference count)
6+
const RISK_THRESHOLDS = {
7+
LOW_MAX: 4, // 0-4 refs = LOW
8+
MEDIUM_MAX: 15, // 5-15 refs = MEDIUM
9+
// >15 refs = HIGH
10+
};
11+
12+
// Minimum references to suggest REUSE (>threshold = REUSE, <=threshold = ADAPT)
13+
const REUSE_MIN_REFS = 2;
14+
15+
/**
16+
* DevHelper — Code intelligence helper for @dev agent tasks.
17+
*
18+
* All functions return null gracefully when no provider is available.
19+
* Never throws — safe to call unconditionally in task workflows.
20+
*/
21+
22+
/**
23+
* Check for duplicates and similar code before writing a new file or function.
24+
* Used by IDS Gate G4 in dev-develop-story and build-autonomous tasks.
25+
*
26+
* @param {string} fileName - Name of the file/function to be created
27+
* @param {string} description - Description of what it does
28+
* @returns {Promise<{duplicates: Object, references: Array, suggestion: string}|null>}
29+
*/
30+
async function checkBeforeWriting(fileName, description) {
31+
if (!isCodeIntelAvailable()) {
32+
return null;
33+
}
34+
35+
try {
36+
const enricher = getEnricher();
37+
const dupes = await enricher.detectDuplicates(description, { path: '.' });
38+
39+
// Also search for the fileName as a symbol reference
40+
const client = getClient();
41+
const nameRefs = await client.findReferences(fileName);
42+
43+
const hasMatches = (dupes && dupes.matches && dupes.matches.length > 0) ||
44+
(nameRefs && nameRefs.length > 0);
45+
46+
if (!hasMatches) {
47+
return null;
48+
}
49+
50+
return {
51+
duplicates: dupes,
52+
references: nameRefs || [],
53+
suggestion: _formatSuggestion(dupes, nameRefs),
54+
};
55+
} catch {
56+
return null;
57+
}
58+
}
59+
60+
/**
61+
* Suggest reuse of an existing symbol instead of creating a new one.
62+
* Searches for definitions and references to determine REUSE vs ADAPT.
63+
*
64+
* @param {string} symbol - Symbol name to search for
65+
* @returns {Promise<{file: string, line: number, references: number, suggestion: string}|null>}
66+
*/
67+
async function suggestReuse(symbol) {
68+
if (!isCodeIntelAvailable()) {
69+
return null;
70+
}
71+
72+
try {
73+
const client = getClient();
74+
const [definition, refs] = await Promise.all([
75+
client.findDefinition(symbol),
76+
client.findReferences(symbol),
77+
]);
78+
79+
if (!definition && (!refs || refs.length === 0)) {
80+
return null;
81+
}
82+
83+
const refCount = refs ? refs.length : 0;
84+
// REUSE if widely used, ADAPT if exists but lightly used
85+
const suggestion = refCount > REUSE_MIN_REFS ? 'REUSE' : 'ADAPT';
86+
87+
return {
88+
file: definition ? definition.file : (refs[0] ? refs[0].file : null),
89+
line: definition ? definition.line : (refs[0] ? refs[0].line : null),
90+
references: refCount,
91+
suggestion,
92+
};
93+
} catch {
94+
return null;
95+
}
96+
}
97+
98+
/**
99+
* Get naming conventions and patterns for a given path.
100+
* Used to ensure new code follows existing project conventions.
101+
*
102+
* @param {string} targetPath - Path to analyze conventions for
103+
* @returns {Promise<{patterns: Array, stats: Object}|null>}
104+
*/
105+
async function getConventionsForPath(targetPath) {
106+
if (!isCodeIntelAvailable()) {
107+
return null;
108+
}
109+
110+
try {
111+
const enricher = getEnricher();
112+
return await enricher.getConventions(targetPath);
113+
} catch {
114+
return null;
115+
}
116+
}
117+
118+
/**
119+
* Assess refactoring impact with blast radius and risk level.
120+
* Used by dev-suggest-refactoring to show impact before changes.
121+
*
122+
* @param {string[]} files - Files to assess impact for
123+
* @returns {Promise<{blastRadius: number, riskLevel: string, references: Array, complexity: Object}|null>}
124+
*/
125+
async function assessRefactoringImpact(files) {
126+
if (!isCodeIntelAvailable()) {
127+
return null;
128+
}
129+
130+
try {
131+
const enricher = getEnricher();
132+
const impact = await enricher.assessImpact(files);
133+
134+
if (!impact) {
135+
return null;
136+
}
137+
138+
return {
139+
blastRadius: impact.blastRadius,
140+
riskLevel: _calculateRiskLevel(impact.blastRadius),
141+
references: impact.references,
142+
complexity: impact.complexity,
143+
};
144+
} catch {
145+
return null;
146+
}
147+
}
148+
149+
/**
150+
* Format a Code Intelligence Suggestion message from duplicate detection results.
151+
* @param {Object|null} dupes - Result from detectDuplicates
152+
* @param {Array|null} nameRefs - Result from findReferences
153+
* @returns {string} Formatted suggestion message
154+
* @private
155+
*/
156+
function _formatSuggestion(dupes, nameRefs) {
157+
const parts = [];
158+
159+
if (dupes && dupes.matches && dupes.matches.length > 0) {
160+
parts.push(`Found ${dupes.matches.length} similar match(es) in codebase`);
161+
const firstMatch = dupes.matches[0];
162+
if (firstMatch.file) {
163+
parts.push(`Closest: ${firstMatch.file}${firstMatch.line ? ':' + firstMatch.line : ''}`);
164+
}
165+
}
166+
167+
if (nameRefs && nameRefs.length > 0) {
168+
parts.push(`Symbol already referenced in ${nameRefs.length} location(s)`);
169+
const firstRef = nameRefs[0];
170+
if (firstRef.file) {
171+
parts.push(`First ref: ${firstRef.file}${firstRef.line ? ':' + firstRef.line : ''}`);
172+
}
173+
}
174+
175+
parts.push('Consider REUSE or ADAPT before creating new code (IDS Article IV-A)');
176+
177+
return parts.join('. ') + '.';
178+
}
179+
180+
/**
181+
* Calculate risk level from blast radius count.
182+
* @param {number} blastRadius - Number of references affected
183+
* @returns {string} 'LOW' | 'MEDIUM' | 'HIGH'
184+
* @private
185+
*/
186+
function _calculateRiskLevel(blastRadius) {
187+
if (blastRadius <= RISK_THRESHOLDS.LOW_MAX) {
188+
return 'LOW';
189+
}
190+
if (blastRadius <= RISK_THRESHOLDS.MEDIUM_MAX) {
191+
return 'MEDIUM';
192+
}
193+
return 'HIGH';
194+
}
195+
196+
module.exports = {
197+
checkBeforeWriting,
198+
suggestReuse,
199+
getConventionsForPath,
200+
assessRefactoringImpact,
201+
// Exposed for testing
202+
_formatSuggestion,
203+
_calculateRiskLevel,
204+
RISK_THRESHOLDS,
205+
REUSE_MIN_REFS,
206+
};

.aios-core/data/entity-registry.yaml

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5997,6 +5997,33 @@ entities:
59975997
checksum: sha256:310884d94b81be976a346987822306a16a73ba812c08c3b805f4a03216ffef38
59985998
lastVerified: '2026-02-15T19:28:17.743Z'
59995999
modules:
6000+
dev-helper:
6001+
path: .aios-core/core/code-intel/helpers/dev-helper.js
6002+
type: module
6003+
purpose: Code intelligence helper for @dev agent tasks - IDS G4 automation, duplicate detection, conventions, blast radius
6004+
keywords:
6005+
- code-intel
6006+
- dev-helper
6007+
- ids-g4
6008+
- duplicate-detection
6009+
- blast-radius
6010+
- conventions
6011+
- reuse
6012+
usedBy:
6013+
- dev-develop-story
6014+
- create-service
6015+
- dev-suggest-refactoring
6016+
- build-autonomous
6017+
dependencies:
6018+
- code-intel
6019+
adaptability:
6020+
score: 0.7
6021+
constraints:
6022+
- Requires code-intel module (NOG-1)
6023+
extensionPoints:
6024+
- Additional helper functions for other agents
6025+
checksum: ''
6026+
lastVerified: '2026-02-16T00:00:00.000Z'
60006027
registry-syncer:
60016028
path: .aios-core/core/code-intel/registry-syncer.js
60026029
type: module

.aios-core/development/tasks/build-autonomous.md

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,16 @@ steps:
7070
action: |
7171
FOR EACH subtask in implementation.yaml:
7272
1. Track attempt start (RecoveryTracker)
73-
2. Execute subtask (plan-execute-subtask.md workflow)
74-
3. Self-critique at steps 5.5 and 6.5
75-
4. Verify completion (verify-subtask.md workflow)
76-
5. Create checkpoint on success
73+
2. **Code Intelligence IDS G4 Check** (before creating new files):
74+
- If `isCodeIntelAvailable()` (from `.aios-core/core/code-intel`):
75+
- Call `checkBeforeWriting(fileName, description)` from `dev-helper`
76+
- If duplicates detected: log in decision-log and display as advisory
77+
- Does NOT block execution (autonomous mode continues)
78+
- If code intelligence not available: skip silently
79+
3. Execute subtask (plan-execute-subtask.md workflow)
80+
4. Self-critique at steps 5.5 and 6.5
81+
5. Verify completion (verify-subtask.md workflow)
82+
6. Create checkpoint on success
7783
7884
IF failure:
7985
- Increment attempt count

.aios-core/development/tasks/create-service.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,29 @@ Examples: API_KEY, BASE_URL, TIMEOUT_MS
151151
152152
## Implementation Steps
153153
154+
### Step 0: Code Intelligence Duplicate Check (Pre-Scaffold)
155+
156+
Before scaffolding the service, check if a similar service already exists using code intelligence:
157+
158+
```javascript
159+
// Code Intelligence pre-scaffold check (graceful — never blocks)
160+
const { isCodeIntelAvailable } = require('.aios-core/core/code-intel');
161+
const { checkBeforeWriting } = require('.aios-core/core/code-intel/helpers/dev-helper');
162+
163+
if (isCodeIntelAvailable()) {
164+
const result = await checkBeforeWriting(serviceName, description);
165+
if (result) {
166+
// Display as advisory — does NOT block scaffold
167+
console.log('⚠️ Code Intelligence Suggestion:');
168+
console.log(` ${result.suggestion}`);
169+
console.log(' Consider REUSE or ADAPT before creating a new service.');
170+
// In interactive mode: prompt user to confirm proceeding
171+
// In YOLO mode: log and continue
172+
}
173+
}
174+
// If code intelligence not available: proceed normally (no impact)
175+
```
176+
154177
### Step 1: Validate Inputs
155178
```javascript
156179
// Validate service_name

.aios-core/development/tasks/dev-develop-story.md

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -478,12 +478,18 @@ const {
478478
### Order of Execution
479479

480480
1. Read (first or next) task
481-
2. Implement task and its subtasks
482-
3. Write tests
483-
4. Execute validations
484-
5. **Only if ALL pass**: Mark task checkbox [x]
485-
6. Update story File List (ensure all created/modified/deleted files listed)
486-
7. Repeat until all tasks complete
481+
2. **Code Intelligence Check (IDS G4)** — Before creating new files or functions:
482+
- If code intelligence is available (`isCodeIntelAvailable()` from `.aios-core/core/code-intel`):
483+
- Call `checkBeforeWriting(fileName, description)` from `.aios-core/core/code-intel/helpers/dev-helper`
484+
- If result is not null, display as **"Code Intelligence Suggestion"** (non-blocking advisory)
485+
- Log suggestion in decision-log if in YOLO mode
486+
- If code intelligence is NOT available: skip silently (zero impact on workflow)
487+
3. Implement task and its subtasks
488+
4. Write tests
489+
5. Execute validations
490+
6. **Only if ALL pass**: Mark task checkbox [x]
491+
7. Update story File List (ensure all created/modified/deleted files listed)
492+
8. Repeat until all tasks complete
487493

488494
### Story File Updates (All Modes)
489495

.aios-core/development/tasks/dev-suggest-refactoring.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -825,11 +825,17 @@ module.exports = SuggestRefactoringTask;
825825
3. Run pattern detectors
826826
4. Generate suggestions
827827
5. Prioritize by impact
828+
6. **Code Intelligence Blast Radius** (if available):
829+
- Call `assessRefactoringImpact(candidateFiles)` from `.aios-core/core/code-intel/helpers/dev-helper`
830+
- If result is not null, enrich each suggestion with:
831+
- `blastRadius`: number of affected references
832+
- `riskLevel`: LOW (<5 refs) | MEDIUM (5-15) | HIGH (>15)
833+
- If code intelligence not available: suggestions work as before (no blast radius shown)
828834

829835
### Review Phase
830836
1. Display suggestions
831837
2. Group by file/type
832-
3. Show impact analysis
838+
3. Show impact analysis (including blast radius and risk level when available)
833839
4. Provide preview
834840
5. Export for review
835841

0 commit comments

Comments
 (0)