@codeledger/cli 0.9.2 → 0.9.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.
Files changed (40) hide show
  1. package/dist/commands/activate.d.ts.map +1 -1
  2. package/dist/commands/activate.js +276 -134
  3. package/dist/commands/activate.js.map +1 -1
  4. package/dist/commands/capsule-change.d.ts +7 -0
  5. package/dist/commands/capsule-change.d.ts.map +1 -0
  6. package/dist/commands/capsule-change.js +177 -0
  7. package/dist/commands/capsule-change.js.map +1 -0
  8. package/dist/commands/graph.d.ts +7 -3
  9. package/dist/commands/graph.d.ts.map +1 -1
  10. package/dist/commands/graph.js +272 -4
  11. package/dist/commands/graph.js.map +1 -1
  12. package/dist/commands/merge-check.d.ts +15 -0
  13. package/dist/commands/merge-check.d.ts.map +1 -0
  14. package/dist/commands/merge-check.js +137 -0
  15. package/dist/commands/merge-check.js.map +1 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +56 -8
  18. package/dist/index.js.map +1 -1
  19. package/dist/memory/context-injection.d.ts.map +1 -1
  20. package/dist/memory/context-injection.js +10 -8
  21. package/dist/memory/context-injection.js.map +1 -1
  22. package/dist/memory/policy-artifacts.d.ts.map +1 -1
  23. package/dist/memory/policy-artifacts.js +5 -1
  24. package/dist/memory/policy-artifacts.js.map +1 -1
  25. package/dist/merge-check/hallucination-guard.d.ts +49 -0
  26. package/dist/merge-check/hallucination-guard.d.ts.map +1 -0
  27. package/dist/merge-check/hallucination-guard.js +228 -0
  28. package/dist/merge-check/hallucination-guard.js.map +1 -0
  29. package/dist/merge-check/intent-registry.d.ts +42 -0
  30. package/dist/merge-check/intent-registry.d.ts.map +1 -0
  31. package/dist/merge-check/intent-registry.js +154 -0
  32. package/dist/merge-check/intent-registry.js.map +1 -0
  33. package/dist/merge-check/sentinel.d.ts +60 -0
  34. package/dist/merge-check/sentinel.d.ts.map +1 -0
  35. package/dist/merge-check/sentinel.js +399 -0
  36. package/dist/merge-check/sentinel.js.map +1 -0
  37. package/dist/templates/config.d.ts.map +1 -1
  38. package/dist/templates/config.js +14 -49
  39. package/dist/templates/config.js.map +1 -1
  40. package/package.json +17 -17
@@ -1 +1 @@
1
- {"version":3,"file":"activate.d.ts","sourceRoot":"","sources":["../../src/commands/activate.ts"],"names":[],"mappings":"AAsCA;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,WAAW,CAC/B,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC5B,OAAO,CAAC,IAAI,CAAC,CAgmBf"}
1
+ {"version":3,"file":"activate.d.ts","sourceRoot":"","sources":["../../src/commands/activate.ts"],"names":[],"mappings":"AAoCA;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,WAAW,CAC/B,GAAG,EAAE,MAAM,EACX,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC5B,OAAO,CAAC,IAAI,CAAC,CAquBf"}
@@ -15,10 +15,11 @@ import { runDiscovery } from '../discovery/index.js';
15
15
  import { memoryExists, loadMemory } from '../memory/storage.js';
16
16
  import { generateContextPreamble } from '../memory/preamble.js';
17
17
  import { appendDecisionEvent, newTimelineCommandId } from '../session-timeline.js';
18
- import { loadPromotedPatterns, scorePatternRelevance, migrateActiveBundle } from '../ecl/persistence.js';
19
- import { evaluateInteractionPolicy, buildCoachEvent, formatCoachOutput, formatPostSummary, isInteractive, handleInteraction, DEFAULT_PROMPT_COACH_CONFIG, } from '../prompt-coach/index.js';
20
- import { detectRiskZones } from '../risk-detection/index.js';
18
+ import { migrateActiveBundle } from '../ecl/persistence.js';
21
19
  import { maybeShowUpgradeNudge } from '../utils/upgrade-nudge.js';
20
+ import { formatPostSummary, DEFAULT_PROMPT_COACH_CONFIG, } from '../prompt-coach/index.js';
21
+ import { refineTask, completeRefinement, DEFAULT_REFINEMENT_SETTINGS, buildSnapshot, deriveLogicalEdges, buildChangeCapsule } from '@codeledger/engine';
22
+ import { loadEntries, buildFailureHotspots, recordExecution, buildEntry, deriveIntentSignature } from '@codeledger/engine';
22
23
  /**
23
24
  * `codeledger activate [--task "..."] [--session <id>]`
24
25
  *
@@ -158,6 +159,172 @@ export async function runActivate(cwd, flags) {
158
159
  if (branchAware || continueMode) {
159
160
  branchChangedFiles = detectBranchChangedFiles(cwd);
160
161
  }
162
+ // -- Step 2.2: Prompt Coach — repo-aware task refinement ─────────────────
163
+ const refinementSettings = {
164
+ ...DEFAULT_REFINEMENT_SETTINGS,
165
+ ...config['refinement'],
166
+ };
167
+ // CLI flag overrides: --refine forces interactive, --no-refine disables
168
+ if (flags['refine'] === 'true') {
169
+ refinementSettings.enabled = true;
170
+ refinementSettings.mode = 'interactive';
171
+ }
172
+ if (flags['no-refine'] === 'true') {
173
+ refinementSettings.enabled = false;
174
+ }
175
+ let coachResult;
176
+ if (refinementSettings.enabled && refinementSettings.mode !== 'off') {
177
+ try {
178
+ coachResult = refineTask(task, repoIndex, refinementSettings);
179
+ if (!coachResult.bypassed && coachResult.candidates.length > 0) {
180
+ if (!quiet) {
181
+ console.log('');
182
+ console.log(' Prompt Coach — repo-aware refinement');
183
+ console.log(' ────────────────────────────────────');
184
+ console.log(` Raw task: ${truncate(task, 70)}`);
185
+ console.log('');
186
+ for (let i = 0; i < coachResult.candidates.length; i++) {
187
+ const c = coachResult.candidates[i];
188
+ console.log(` [${i + 1}] ${c.label} (confidence: ${(c.confidence * 100).toFixed(0)}%)`);
189
+ console.log(` ${truncate(c.text, 90)}`);
190
+ // Context scope summary (entity-based)
191
+ if (c.context_intent) {
192
+ const ci = c.context_intent;
193
+ const requiredEntities = ci.entities.filter((e) => e.disposition === 'required');
194
+ const supportingEntities = ci.entities.filter((e) => e.disposition === 'supporting');
195
+ const relCount = ci.relationships.length;
196
+ console.log(` entities: ${requiredEntities.length} required, ${supportingEntities.length} supporting (${relCount} relationships)`);
197
+ if (ci.scope_packages.length > 0) {
198
+ console.log(` packages: ${ci.scope_packages.join(', ')}`);
199
+ }
200
+ // Show top required entity labels
201
+ for (const ent of requiredEntities.slice(0, 3)) {
202
+ console.log(` ├ ${ent.kind}: ${ent.label}`);
203
+ }
204
+ }
205
+ if (c.evidence.length > 0) {
206
+ const topEvidence = c.evidence.slice(0, 2);
207
+ for (const e of topEvidence) {
208
+ console.log(` ↳ ${e.description}`);
209
+ }
210
+ }
211
+ console.log('');
212
+ }
213
+ // Context reduction summary
214
+ if (coachResult.context_reduction) {
215
+ const cr = coachResult.context_reduction;
216
+ if (cr.reduction_ratio > 0) {
217
+ console.log(` context: ${cr.refined_file_count} files (~${cr.refined_tokens} tokens) vs ${cr.naive_file_count} naive (${(cr.reduction_ratio * 100).toFixed(0)}% smaller)`);
218
+ console.log('');
219
+ }
220
+ }
221
+ }
222
+ // Auto mode: accept top candidate silently
223
+ if (refinementSettings.mode === 'auto') {
224
+ const top = coachResult.candidates[0];
225
+ const decision = {
226
+ action: 'accept',
227
+ selected_index: 0,
228
+ final_task: top.text,
229
+ decision_time_ms: 0,
230
+ };
231
+ task = completeRefinement(cwd, coachResult, decision);
232
+ if (!quiet) {
233
+ console.log(` → Using refined task: "${truncate(task, 70)}"`);
234
+ console.log('');
235
+ }
236
+ }
237
+ // Interactive mode: readline-based user selection (TTY only)
238
+ else if (refinementSettings.mode === 'interactive') {
239
+ const isTTY = process.stdin.isTTY && process.stdout.isTTY;
240
+ if (isTTY) {
241
+ const selectedIndex = await promptUserSelection(coachResult.candidates.length);
242
+ const startTime = Date.now();
243
+ if (selectedIndex === -1) {
244
+ // User chose to keep original
245
+ const decision = {
246
+ action: 'keep_original',
247
+ final_task: task,
248
+ decision_time_ms: Date.now() - startTime,
249
+ };
250
+ completeRefinement(cwd, coachResult, decision);
251
+ console.log(' → Keeping original task');
252
+ console.log('');
253
+ }
254
+ else {
255
+ const selected = coachResult.candidates[selectedIndex];
256
+ const decision = {
257
+ action: 'accept',
258
+ selected_index: selectedIndex,
259
+ final_task: selected.text,
260
+ decision_time_ms: Date.now() - startTime,
261
+ };
262
+ task = completeRefinement(cwd, coachResult, decision);
263
+ console.log(` → Using option [${selectedIndex + 1}]: "${truncate(task, 70)}"`);
264
+ console.log('');
265
+ }
266
+ }
267
+ else {
268
+ // Non-TTY (agent context): auto-accept top candidate
269
+ const top = coachResult.candidates[0];
270
+ const decision = {
271
+ action: 'accept',
272
+ selected_index: 0,
273
+ final_task: top.text,
274
+ decision_time_ms: 0,
275
+ };
276
+ task = completeRefinement(cwd, coachResult, decision);
277
+ if (!quiet) {
278
+ console.log(` → Using refined task: "${truncate(task, 70)}"`);
279
+ console.log('');
280
+ }
281
+ }
282
+ }
283
+ }
284
+ else if (!coachResult.bypassed && coachResult.candidates.length === 0) {
285
+ // No suggestions generated — proceed with raw task
286
+ }
287
+ else if (coachResult.bypassed && !quiet) {
288
+ // Bypassed — task is already well-specified, no output needed
289
+ }
290
+ }
291
+ catch {
292
+ // Prompt Coach must never break activation — fail silently
293
+ }
294
+ }
295
+ // -- Step 2.3: Apply context pack as scope constraint ──────────────────
296
+ // If context minimization produced a pack, use its file paths as a hard
297
+ // scope constraint for the downstream selector. This is the critical
298
+ // compound optimization: the pack's curated files become the ONLY files
299
+ // the selector considers, not just a budget hint.
300
+ let effectiveBudgetTokens = budgetTokens;
301
+ let effectiveMaxFiles = maxFiles;
302
+ let effectiveScope = scope;
303
+ if (coachResult?.context_pack && coachResult.context_reduction) {
304
+ const pack = coachResult.context_pack;
305
+ const packPaths = pack.candidates.map((c) => c.path);
306
+ // Hard scope constraint: selector only considers pack files
307
+ // Merge with any user-provided --scope (intersection if both set)
308
+ if (packPaths.length > 0) {
309
+ if (effectiveScope && effectiveScope.length > 0) {
310
+ // User scope takes precedence — only include pack files within user scope
311
+ const intersected = packPaths.filter((p) => effectiveScope.some((s) => p.startsWith(s)));
312
+ effectiveScope = intersected.length > 0 ? intersected : effectiveScope;
313
+ }
314
+ else {
315
+ effectiveScope = packPaths;
316
+ }
317
+ }
318
+ // Budget: tighten to pack token estimate (with headroom for stubs/excerpts)
319
+ if (pack.total_tokens > 0 && budgetTokens && pack.total_tokens < budgetTokens) {
320
+ effectiveBudgetTokens = Math.ceil(pack.total_tokens * 1.3);
321
+ }
322
+ // File count: pack size + allowance for test pairs and stubs
323
+ const packFileCount = pack.candidates.length;
324
+ if (packFileCount > 0 && maxFiles && packFileCount + 4 < maxFiles) {
325
+ effectiveMaxFiles = packFileCount + 4;
326
+ }
327
+ }
161
328
  log(`Generating context bundle for: "${truncate(task, 80)}"`);
162
329
  const includeNearMisses = flags['near-misses'] === 'true';
163
330
  const includeBlastRadius = flags['blast-radius'] === 'true';
@@ -167,114 +334,60 @@ export async function runActivate(cwd, flags) {
167
334
  taskText: task,
168
335
  repoIndex,
169
336
  selectorConfig: config.selector,
170
- budget: { tokens: budgetTokens, max_files: maxFiles },
337
+ budget: { tokens: effectiveBudgetTokens, max_files: effectiveMaxFiles },
171
338
  explain,
172
339
  indexPath: indexPath,
173
- scope,
340
+ scope: effectiveScope,
174
341
  branchChangedFiles,
175
342
  includeNearMisses,
176
343
  includeBlastRadius,
177
344
  layerOrder,
178
345
  });
179
- // -- Step 2.0b: Consult promoted patterns (💎 memory → ⚡ activation) ----------
180
- let patternMatches = [];
181
- try {
182
- const promotedPatterns = loadPromotedPatterns(cwd);
183
- if (promotedPatterns.length > 0) {
184
- const bundleFiles = bundle.files.map((f) => f.path);
185
- patternMatches = scorePatternRelevance(task, promotedPatterns, bundleFiles, cwd);
186
- // Record which patterns influenced this activation (for session-summary outcome linking)
187
- if (patternMatches.length > 0) {
188
- try {
189
- const markerPath = join(sessionId
190
- ? join(cwd, '.codeledger', 'sessions', sessionId)
191
- : join(cwd, '.codeledger'), '.active-patterns.json');
192
- ensureDir(markerPath);
193
- writeFileSync(markerPath, JSON.stringify(patternMatches.map((m) => ({ id: m.pattern.id, name: m.pattern.name, relevance: m.relevance }))) + '\n');
194
- }
195
- catch { /* non-fatal */ }
346
+ // -- Step 2.2b: Pre-change intelligence (Graph+ECL capsule) ─────────────
347
+ // If the bundle has a clear primary target, generate a change capsule
348
+ // and surface risk + validation guidance alongside the bundle.
349
+ if (bundle.files.length > 0 && !quiet) {
350
+ try {
351
+ const topFile = bundle.files[0].path;
352
+ let commitSha = 'unknown';
353
+ try {
354
+ commitSha = execSync('git rev-parse HEAD 2>/dev/null', { cwd, encoding: 'utf-8' }).trim();
196
355
  }
197
- }
198
- }
199
- catch { /* non-fatal: pattern lookup is best-effort */ }
200
- // -- Step 2.1: Prompt Coach — interaction level decision -----------------------
201
- const coachDisabled = flags['no-coach'] === 'true';
202
- const coachConfig = config.prompt_coach
203
- ? { ...DEFAULT_PROMPT_COACH_CONFIG, ...config.prompt_coach }
204
- : { ...DEFAULT_PROMPT_COACH_CONFIG };
205
- if (coachDisabled || quiet) {
206
- coachConfig.enabled = false;
207
- }
208
- // Detect risk zones for the bundle
209
- let riskZones = detectRiskZones(repoIndex, cwd);
210
- // Get discovery verdict if available (cached from previous run or below)
211
- let discoveryVerdict;
212
- try {
213
- const discoveryTtl = config.selector.discovery_ttl_seconds ?? 3600;
214
- const cached = getCachedDiscovery(cwd, task, discoveryTtl);
215
- if (cached)
216
- discoveryVerdict = cached.verdict;
217
- }
218
- catch { /* non-fatal */ }
219
- const coachResult = evaluateInteractionPolicy({
220
- task,
221
- bundle,
222
- riskZones,
223
- discoveryVerdict,
224
- config: coachConfig,
225
- cwd,
226
- sessionId,
227
- repoIndex,
228
- });
229
- // Handle interactive prompting if needed
230
- const interactive = isInteractive() && coachConfig.enabled && !quiet;
231
- if (coachResult.level > 0 && interactive) {
232
- const output = formatCoachOutput(coachResult, task, true);
233
- console.error(output);
234
- const { choice, task: refinedTask } = await handleInteraction(coachResult, task);
235
- if (choice === 'cancel') {
236
- log('Cancelled.');
237
- // Emit telemetry event
238
- const event = buildCoachEvent(coachResult, 'cancel', false);
239
- appendCoachEvent(cwd, sessionId, event);
240
- return;
241
- }
242
- if (choice === 'review_areas') {
243
- // Show affected files and let the user decide
244
- log('\n Affected areas:');
245
- for (const f of bundle.files.slice(0, 10)) {
246
- log(` ${f.score.toFixed(3)} ${f.path}`);
356
+ catch { /* ok */ }
357
+ const snapshot = buildSnapshot(repoIndex, commitSha);
358
+ const eclEntries = loadEntries(cwd);
359
+ const eclEvents = eclEntries.map((e) => ({
360
+ timestamp: e.timestamp,
361
+ files: e.files,
362
+ outcome: e.outcome,
363
+ failureVector: e.failureVector,
364
+ }));
365
+ const logicalEdges = deriveLogicalEdges(eclEvents);
366
+ const hotspots = buildFailureHotspots(eclEntries);
367
+ const hotspotMap = new Map(hotspots.map((h) => [h.file, h.failureCount]));
368
+ const capsule = buildChangeCapsule({
369
+ target: topFile,
370
+ task,
371
+ snapshot,
372
+ repoIndex,
373
+ logicalEdges,
374
+ eclEventCount: eclEvents.length,
375
+ failureHotspots: hotspotMap,
376
+ });
377
+ // Surface risk summary if non-trivial
378
+ if (capsule.change_risk.classification !== 'low' || capsule.failure_hotspots.length > 0) {
379
+ console.log(` Risk: ${capsule.change_risk.classification} (${(capsule.change_risk.overall * 100).toFixed(0)}%) | confidence: ${(capsule.overall_confidence * 100).toFixed(0)}% | action: ${capsule.recommended_action}`);
380
+ }
381
+ if (capsule.likely_tests.length > 0) {
382
+ console.log(` Validate: ${capsule.likely_tests.slice(0, 3).join(', ')}`);
383
+ }
384
+ if (capsule.failure_hotspots.length > 0) {
385
+ console.log(` Hotspots: ${capsule.failure_hotspots.slice(0, 2).map((h) => h.path).join(', ')}`);
247
386
  }
248
- log('');
249
- // After review, proceed with original task
250
- }
251
- // If the user chose a refined task, update it
252
- if ((choice === 'use_suggested' || choice === 'edit_suggested') && refinedTask !== task) {
253
- task = refinedTask;
254
- log(` Using refined task: "${truncate(task, 80)}"`);
255
- }
256
- // Emit telemetry event
257
- const event = buildCoachEvent(coachResult, choice, false);
258
- appendCoachEvent(cwd, sessionId, event);
259
- }
260
- else if (coachResult.level > 0 && !interactive) {
261
- // Non-interactive: show warnings but proceed
262
- const output = formatCoachOutput(coachResult, task, false);
263
- if (coachResult.level >= 2) {
264
- console.error(output);
265
387
  }
266
- else {
267
- log(output);
388
+ catch {
389
+ // Capsule generation must never break activation
268
390
  }
269
- const event = buildCoachEvent(coachResult, 'non_interactive_fallback', false);
270
- appendCoachEvent(cwd, sessionId, event);
271
- }
272
- else if (coachResult.level === 0 && coachConfig.enabled && !quiet) {
273
- // Auto-pass: minimal output
274
- const output = formatCoachOutput(coachResult, task, true);
275
- log(output);
276
- const event = buildCoachEvent(coachResult, 'auto_pass', false);
277
- appendCoachEvent(cwd, sessionId, event);
278
391
  }
279
392
  // -- Step 2.3: Review mode — attach review metadata + write review config -----
280
393
  const bundleMode = (flags['mode'] === 'review') ? 'review' : 'edit';
@@ -405,6 +518,34 @@ export async function runActivate(cwd, flags) {
405
518
  }
406
519
  // -- Step 3.5: Record activation in task history (JSONL) -------------------
407
520
  recordTaskActivation(cwd, sessionId, task, bundle);
521
+ // -- Step 3.5b: Record ECL event with graph linkage ────────────────────────
522
+ // Write an ECL entry tied to the current graph snapshot so that future
523
+ // logical dependency derivation can trace events to structural context.
524
+ try {
525
+ let snapshotId;
526
+ try {
527
+ const snapPath = join(cwd, '.codeledger', 'cache', 'graph-snapshot.json');
528
+ if (existsSync(snapPath)) {
529
+ const snapData = JSON.parse(readFileSync(snapPath, 'utf-8'));
530
+ snapshotId = snapData['snapshot_id'];
531
+ }
532
+ }
533
+ catch { /* no snapshot yet — ok */ }
534
+ const bundleFiles = bundle.files.map((f) => f.path);
535
+ const graphLinkage = snapshotId
536
+ ? { snapshot_id: snapshotId, node_ids: bundleFiles.map((f) => `file:${f}`) }
537
+ : undefined;
538
+ const eclEntry = buildEntry(deriveIntentSignature(task).hash, bundleFiles, [], // symbols — populated by downstream execution
539
+ 0, // expansionLevel — initial activation
540
+ 'success', // outcome — activation itself succeeded
541
+ bundle.confidence?.score ?? 0.5, undefined, // failureVector
542
+ undefined, // intentCategory
543
+ graphLinkage);
544
+ recordExecution(cwd, eclEntry);
545
+ }
546
+ catch {
547
+ // ECL recording must never break activation
548
+ }
408
549
  // -- Step 3.6: Reset drift tracking on fresh activation --------------------
409
550
  // Remove out-of-bundle edit counter and hook-reminded marker so the agent
410
551
  // gets a fresh nudge cycle on the new bundle
@@ -551,6 +692,7 @@ export async function runActivate(cwd, flags) {
551
692
  catch { /* non-fatal: never block activation */ }
552
693
  }
553
694
  // -- Post-execution summary: confidence-building, short ----------------------
695
+ const coachConfig = DEFAULT_PROMPT_COACH_CONFIG;
554
696
  if (!quiet && coachConfig.enabled && coachConfig.show_post_summary) {
555
697
  log(formatPostSummary(bundle));
556
698
  }
@@ -560,9 +702,10 @@ export async function runActivate(cwd, flags) {
560
702
  log(' Selected minimal working context for this task');
561
703
  log(' Reduced search space before execution');
562
704
  // ISC advisory warning (F9: consistent enforcement)
563
- if (coachConfig.enabled && coachResult.isc.decision === 'INSUFFICIENT') {
705
+ if (coachResult && typeof coachResult === 'object' && 'isc' in coachResult && coachResult.isc?.decision === 'INSUFFICIENT') {
706
+ const isc = coachResult.isc;
564
707
  log('');
565
- log(` \u26A0\uFE0F Intent sufficiency: ${coachResult.isc.decision} (score: ${coachResult.isc.score.toFixed(3)})`);
708
+ log(` \u26A0\uFE0F Intent sufficiency: ${isc.decision} (score: ${isc.score.toFixed(3)})`);
566
709
  log(' Context selection may be unreliable for vague tasks.');
567
710
  log(' Tip: add specifics — file paths, function names, domain keywords.');
568
711
  }
@@ -571,24 +714,9 @@ export async function runActivate(cwd, flags) {
571
714
  log(' Session will generate evidence about what works');
572
715
  log(' Successful flows may become reusable patterns');
573
716
  log('');
574
- // 🧠 Repo memory influence — lifecycle-aware
575
- if (patternMatches.length > 0) {
576
- log(' \uD83E\uDDE0 Repo memory influence');
577
- log(` ${patternMatches.length} promoted pattern${patternMatches.length > 1 ? 's' : ''} matched this task`);
578
- for (const m of patternMatches.slice(0, 3)) {
579
- const status = m.pattern.score?.status ?? 'emerging';
580
- const verb = status === 'validated' ? 'boosted'
581
- : status === 'emerging' ? 'softly boosted'
582
- : status === 'mixed' ? 'cautiously applied'
583
- : 'ignored (stale/retired)';
584
- log(` ${m.pattern.name} — ${status}, ${verb}`);
585
- }
586
- }
587
- else {
588
- log(' \uD83E\uDDE0 Repo memory influence');
589
- log(' No relevant promoted patterns found');
590
- log(' Activation used current repo signals only');
591
- }
717
+ // 🧠 Repo memory influence
718
+ log(' \uD83E\uDDE0 Repo memory influence');
719
+ log(' Activation used current repo signals + prompt refinement');
592
720
  log('');
593
721
  log(' \uD83D\uDCC2 Working context');
594
722
  log(` ${displayPath}`);
@@ -875,20 +1003,7 @@ function emitDiscoveryGuidance(result, log) {
875
1003
  }
876
1004
  // GO_GENUINELY_NEW — no guidance needed, proceed normally
877
1005
  }
878
- // ── Prompt Coach Telemetry ────────────────────────────────────────────────
879
- function appendCoachEvent(cwd, sessionId, event) {
880
- try {
881
- const eventsDir = sessionId
882
- ? join(cwd, '.codeledger', 'sessions', sessionId)
883
- : join(cwd, '.codeledger');
884
- const eventsPath = join(eventsDir, '.coach-events.jsonl');
885
- ensureDir(eventsPath);
886
- appendFileSync(eventsPath, JSON.stringify(event) + '\n');
887
- }
888
- catch {
889
- // Non-fatal: telemetry is best-effort
890
- }
891
- }
1006
+ // Coach telemetry is now handled by the engine-level prompt coach (completeRefinement).
892
1007
  // ── Task History ──────────────────────────────────────────────────────────
893
1008
  function recordTaskActivation(cwd, sessionId, task, bundle) {
894
1009
  try {
@@ -914,4 +1029,31 @@ function recordTaskActivation(cwd, sessionId, task, bundle) {
914
1029
  // Non-fatal: task history is best-effort
915
1030
  }
916
1031
  }
1032
+ // ── Readline-based interactive selection ──────────────────────────────────
1033
+ /**
1034
+ * Prompt the user to select a refined task candidate via readline.
1035
+ * Returns the 0-based index, or -1 to keep the original task.
1036
+ */
1037
+ function promptUserSelection(candidateCount) {
1038
+ const { createInterface } = require('node:readline');
1039
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1040
+ return new Promise((resolve) => {
1041
+ const prompt = ` Select [1-${candidateCount}] or [k]eep original: `;
1042
+ rl.question(prompt, (answer) => {
1043
+ rl.close();
1044
+ const trimmed = answer.trim().toLowerCase();
1045
+ if (trimmed === 'k' || trimmed === 'keep') {
1046
+ resolve(-1);
1047
+ return;
1048
+ }
1049
+ const num = parseInt(trimmed, 10);
1050
+ if (!isNaN(num) && num >= 1 && num <= candidateCount) {
1051
+ resolve(num - 1);
1052
+ return;
1053
+ }
1054
+ // Invalid input → default to option 1
1055
+ resolve(0);
1056
+ });
1057
+ });
1058
+ }
917
1059
  //# sourceMappingURL=activate.js.map