aiwcli 0.10.1 → 0.10.3

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 (110) hide show
  1. package/dist/commands/clean.js +1 -0
  2. package/dist/commands/clear.d.ts +19 -2
  3. package/dist/commands/clear.js +351 -160
  4. package/dist/commands/init/index.d.ts +1 -17
  5. package/dist/commands/init/index.js +19 -104
  6. package/dist/lib/gitignore-manager.d.ts +9 -0
  7. package/dist/lib/gitignore-manager.js +121 -0
  8. package/dist/lib/template-installer.d.ts +7 -12
  9. package/dist/lib/template-installer.js +69 -193
  10. package/dist/lib/template-settings-reconstructor.d.ts +35 -0
  11. package/dist/lib/template-settings-reconstructor.js +130 -0
  12. package/dist/templates/_shared/hooks/__pycache__/archive_plan.cpython-313.pyc +0 -0
  13. package/dist/templates/_shared/hooks/__pycache__/session_end.cpython-313.pyc +0 -0
  14. package/dist/templates/_shared/hooks/archive_plan.py +10 -2
  15. package/dist/templates/_shared/hooks/session_end.py +37 -29
  16. package/dist/templates/_shared/lib/base/__pycache__/hook_utils.cpython-313.pyc +0 -0
  17. package/dist/templates/_shared/lib/base/__pycache__/inference.cpython-313.pyc +0 -0
  18. package/dist/templates/_shared/lib/base/__pycache__/logger.cpython-313.pyc +0 -0
  19. package/dist/templates/_shared/lib/base/__pycache__/stop_words.cpython-313.pyc +0 -0
  20. package/dist/templates/_shared/lib/base/__pycache__/utils.cpython-313.pyc +0 -0
  21. package/dist/templates/_shared/lib/base/hook_utils.py +8 -10
  22. package/dist/templates/_shared/lib/base/inference.py +51 -62
  23. package/dist/templates/_shared/lib/base/logger.py +35 -21
  24. package/dist/templates/_shared/lib/base/stop_words.py +8 -0
  25. package/dist/templates/_shared/lib/base/utils.py +29 -8
  26. package/dist/templates/_shared/lib/context/__pycache__/plan_manager.cpython-313.pyc +0 -0
  27. package/dist/templates/_shared/lib/context/plan_manager.py +101 -2
  28. package/dist/templates/_shared/lib-ts/base/atomic-write.ts +138 -0
  29. package/dist/templates/_shared/lib-ts/base/constants.ts +299 -0
  30. package/dist/templates/_shared/lib-ts/base/git-state.ts +58 -0
  31. package/dist/templates/_shared/lib-ts/base/hook-utils.ts +360 -0
  32. package/dist/templates/_shared/lib-ts/base/inference.ts +245 -0
  33. package/dist/templates/_shared/lib-ts/base/logger.ts +234 -0
  34. package/dist/templates/_shared/lib-ts/base/state-io.ts +114 -0
  35. package/dist/templates/_shared/lib-ts/base/stop-words.ts +184 -0
  36. package/dist/templates/_shared/lib-ts/base/subprocess-utils.ts +23 -0
  37. package/dist/templates/_shared/lib-ts/base/utils.ts +184 -0
  38. package/dist/templates/_shared/lib-ts/context/context-formatter.ts +432 -0
  39. package/dist/templates/_shared/lib-ts/context/context-selector.ts +497 -0
  40. package/dist/templates/_shared/lib-ts/context/context-store.ts +679 -0
  41. package/dist/templates/_shared/lib-ts/context/plan-manager.ts +292 -0
  42. package/dist/templates/_shared/lib-ts/context/task-tracker.ts +181 -0
  43. package/dist/templates/_shared/lib-ts/handoff/document-generator.ts +215 -0
  44. package/dist/templates/_shared/lib-ts/package.json +21 -0
  45. package/dist/templates/_shared/lib-ts/templates/formatters.ts +102 -0
  46. package/dist/templates/_shared/lib-ts/templates/plan-context.ts +65 -0
  47. package/dist/templates/_shared/lib-ts/tsconfig.json +13 -0
  48. package/dist/templates/_shared/lib-ts/types.ts +151 -0
  49. package/dist/templates/_shared/scripts/__pycache__/status_line.cpython-313.pyc +0 -0
  50. package/dist/templates/_shared/scripts/save_handoff.ts +359 -0
  51. package/dist/templates/_shared/scripts/status_line.py +17 -2
  52. package/dist/templates/cc-native/_cc-native/agents/ARCH-EVOLUTION.md +63 -0
  53. package/dist/templates/cc-native/_cc-native/agents/ARCH-PATTERNS.md +62 -0
  54. package/dist/templates/cc-native/_cc-native/agents/ARCH-STRUCTURE.md +63 -0
  55. package/dist/templates/cc-native/_cc-native/agents/{ASSUMPTION-CHAIN-TRACER.md → ASSUMPTION-TRACER.md} +6 -10
  56. package/dist/templates/cc-native/_cc-native/agents/CLARITY-AUDITOR.md +6 -10
  57. package/dist/templates/cc-native/_cc-native/agents/CLAUDE.md +74 -1
  58. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-FEASIBILITY.md +67 -0
  59. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-GAPS.md +71 -0
  60. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-ORDERING.md +63 -0
  61. package/dist/templates/cc-native/_cc-native/agents/CONSTRAINT-VALIDATOR.md +73 -0
  62. package/dist/templates/cc-native/_cc-native/agents/DESIGN-ADR-VALIDATOR.md +62 -0
  63. package/dist/templates/cc-native/_cc-native/agents/DESIGN-SCALE-MATCHER.md +65 -0
  64. package/dist/templates/cc-native/_cc-native/agents/DEVILS-ADVOCATE.md +6 -9
  65. package/dist/templates/cc-native/_cc-native/agents/DOCUMENTATION-PHILOSOPHY.md +87 -0
  66. package/dist/templates/cc-native/_cc-native/agents/HANDOFF-READINESS.md +5 -9
  67. package/dist/templates/cc-native/_cc-native/agents/{HIDDEN-COMPLEXITY-DETECTOR.md → HIDDEN-COMPLEXITY.md} +6 -10
  68. package/dist/templates/cc-native/_cc-native/agents/INCREMENTAL-DELIVERY.md +67 -0
  69. package/dist/templates/cc-native/_cc-native/agents/PLAN-ORCHESTRATOR.md +91 -18
  70. package/dist/templates/cc-native/_cc-native/agents/RISK-DEPENDENCY.md +63 -0
  71. package/dist/templates/cc-native/_cc-native/agents/RISK-FMEA.md +67 -0
  72. package/dist/templates/cc-native/_cc-native/agents/RISK-PREMORTEM.md +72 -0
  73. package/dist/templates/cc-native/_cc-native/agents/RISK-REVERSIBILITY.md +75 -0
  74. package/dist/templates/cc-native/_cc-native/agents/SCOPE-BOUNDARY.md +78 -0
  75. package/dist/templates/cc-native/_cc-native/agents/SIMPLICITY-GUARDIAN.md +5 -9
  76. package/dist/templates/cc-native/_cc-native/agents/SKEPTIC.md +16 -12
  77. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-BEHAVIOR-AUDITOR.md +62 -0
  78. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-CHARACTERIZATION.md +72 -0
  79. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-FIRST-VALIDATOR.md +62 -0
  80. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-PYRAMID-ANALYZER.md +62 -0
  81. package/dist/templates/cc-native/_cc-native/agents/TRADEOFF-COSTS.md +68 -0
  82. package/dist/templates/cc-native/_cc-native/agents/TRADEOFF-STAKEHOLDERS.md +66 -0
  83. package/dist/templates/cc-native/_cc-native/agents/VERIFY-COVERAGE.md +75 -0
  84. package/dist/templates/cc-native/_cc-native/agents/VERIFY-STRENGTH.md +70 -0
  85. package/dist/templates/cc-native/_cc-native/hooks/__pycache__/cc-native-plan-review.cpython-313.pyc +0 -0
  86. package/dist/templates/cc-native/_cc-native/hooks/cc-native-plan-review.py +125 -40
  87. package/dist/templates/cc-native/_cc-native/lib/__pycache__/utils.cpython-313.pyc +0 -0
  88. package/dist/templates/cc-native/_cc-native/lib/utils.py +57 -13
  89. package/dist/templates/cc-native/_cc-native/plan-review.config.json +11 -7
  90. package/oclif.manifest.json +17 -2
  91. package/package.json +1 -1
  92. package/dist/lib/template-merger.d.ts +0 -47
  93. package/dist/lib/template-merger.js +0 -162
  94. package/dist/templates/cc-native/_cc-native/agents/ACCESSIBILITY-TESTER.md +0 -79
  95. package/dist/templates/cc-native/_cc-native/agents/ARCHITECT-REVIEWER.md +0 -48
  96. package/dist/templates/cc-native/_cc-native/agents/CODE-REVIEWER.md +0 -70
  97. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-CHECKER.md +0 -59
  98. package/dist/templates/cc-native/_cc-native/agents/CONTEXT-EXTRACTOR.md +0 -92
  99. package/dist/templates/cc-native/_cc-native/agents/DOCUMENTATION-REVIEWER.md +0 -51
  100. package/dist/templates/cc-native/_cc-native/agents/FEASIBILITY-ANALYST.md +0 -57
  101. package/dist/templates/cc-native/_cc-native/agents/FRESH-PERSPECTIVE.md +0 -54
  102. package/dist/templates/cc-native/_cc-native/agents/INCENTIVE-MAPPER.md +0 -61
  103. package/dist/templates/cc-native/_cc-native/agents/PENETRATION-TESTER.md +0 -79
  104. package/dist/templates/cc-native/_cc-native/agents/PERFORMANCE-ENGINEER.md +0 -75
  105. package/dist/templates/cc-native/_cc-native/agents/PRECEDENT-FINDER.md +0 -70
  106. package/dist/templates/cc-native/_cc-native/agents/REVERSIBILITY-ANALYST.md +0 -61
  107. package/dist/templates/cc-native/_cc-native/agents/RISK-ASSESSOR.md +0 -58
  108. package/dist/templates/cc-native/_cc-native/agents/SECOND-ORDER-ANALYST.md +0 -61
  109. package/dist/templates/cc-native/_cc-native/agents/STAKEHOLDER-ADVOCATE.md +0 -55
  110. package/dist/templates/cc-native/_cc-native/agents/TRADE-OFF-ILLUMINATOR.md +0 -204
@@ -0,0 +1,497 @@
1
+ /**
2
+ * Context selection — determines which context a prompt belongs to.
3
+ * See SPEC.md §8
4
+ *
5
+ * Single entry point: determineContext(prompt, sessionId, projectRoot)
6
+ * Returns [contextId, method, outputText].
7
+ *
8
+ * Selection priority:
9
+ * 1. session_match — session_id found in index.json sessions map
10
+ * 2. caret_command — prompt starts with ^ → parse and execute
11
+ * 3. plan_content_match — FALLBACK: match against has_plan contexts
12
+ * 3b. handoff_match — FALLBACK: match against has_handoff contexts
13
+ * 4. default — create new context
14
+ */
15
+
16
+ import * as crypto from "node:crypto";
17
+ import {
18
+ getContext,
19
+ getAllContexts,
20
+ getContextBySessionId,
21
+ createContextFromPrompt,
22
+ createContext,
23
+ completeContext,
24
+ bindSession,
25
+ updateMode,
26
+ } from "./context-store.js";
27
+ import {
28
+ formatActiveContextReminder,
29
+ formatContextCreated,
30
+ formatContextPickerStderr,
31
+ formatCommandFeedback,
32
+ formatHandoffContinuation,
33
+ formatPlanContinuation,
34
+ formatActiveContinuation,
35
+ } from "./context-formatter.js";
36
+ import { normalizePlanContent } from "./plan-manager.js";
37
+ import { isInternalCall } from "../base/subprocess-utils.js";
38
+ import { logDebug, logInfo, logWarn, logError } from "../base/logger.js";
39
+ import type { ContextState, CaretCommand } from "../types.js";
40
+
41
+ /** Minimum characters required for new context description. */
42
+ const MIN_NEW_CONTEXT_CHARS = 10;
43
+
44
+ /**
45
+ * Raised when the request should be blocked with a message to user.
46
+ * See SPEC.md §8.2
47
+ */
48
+ export class BlockRequest extends Error {
49
+ constructor(message: string) {
50
+ super(message);
51
+ this.name = "BlockRequest";
52
+ }
53
+ }
54
+
55
+ // ---------------------------------------------------------------------------
56
+ // Context prefix resolution
57
+ // ---------------------------------------------------------------------------
58
+
59
+ /**
60
+ * Resolve a context ID query to an index (1-based) using tiered matching.
61
+ * Match priority: exact > prefix > substring (all case-insensitive).
62
+ * Returns [index, null] on unique match, [null, error] on 0 or 2+ matches.
63
+ * See SPEC.md §8.3
64
+ */
65
+ export function resolveContextByPrefix(
66
+ query: string,
67
+ contexts: ContextState[],
68
+ ): [number | null, string | null] {
69
+ const q = query.toLowerCase();
70
+ const available = contexts.map(c => c.id).join(", ");
71
+
72
+ // Tier 1: Exact match
73
+ const exact = contexts
74
+ .map((ctx, i) => [i + 1, ctx] as const)
75
+ .filter(([, ctx]) => ctx.id.toLowerCase() === q);
76
+ if (exact.length === 1) return [exact[0]![0], null];
77
+
78
+ // Tier 2: Prefix match
79
+ const prefix = contexts
80
+ .map((ctx, i) => [i + 1, ctx] as const)
81
+ .filter(([, ctx]) => ctx.id.toLowerCase().startsWith(q));
82
+ if (prefix.length === 1) return [prefix[0]![0], null];
83
+ if (prefix.length > 1) {
84
+ return [null, `Ambiguous match '${query}' — ${prefix.length} prefix matches: ${prefix.map(([, c]) => c.id).join(", ")}. Be more specific.`];
85
+ }
86
+
87
+ // Tier 3: Substring match
88
+ const substr = contexts
89
+ .map((ctx, i) => [i + 1, ctx] as const)
90
+ .filter(([, ctx]) => ctx.id.toLowerCase().includes(q));
91
+ if (substr.length === 1) return [substr[0]![0], null];
92
+ if (substr.length > 1) {
93
+ return [null, `Ambiguous match '${query}' — ${substr.length} substring matches: ${substr.map(([, c]) => c.id).join(", ")}. Be more specific.`];
94
+ }
95
+
96
+ return [null, `No context matches '${query}'. Available: ${available}`];
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Caret command parsing
101
+ // ---------------------------------------------------------------------------
102
+
103
+ /**
104
+ * Parse chained caret commands from user prompt.
105
+ * See SPEC.md §8.4
106
+ */
107
+ export function parseChainedCaret(
108
+ prompt: string,
109
+ contexts: ContextState[],
110
+ ): [CaretCommand | null, string | null] {
111
+ if (!prompt.startsWith("^")) return [null, null];
112
+
113
+ const match = prompt.match(/^\^(\S+)(?:\s+(.*))?$/s);
114
+ if (!match) {
115
+ return [null, "Invalid prefix. Use ^E<N> to end, ^S<N> to select, or ^0 <desc> for new context."];
116
+ }
117
+
118
+ const commandStr = match[1]!;
119
+ const remaining = (match[2] ?? "").trim();
120
+
121
+ // ^N shorthand
122
+ if (/^\d+$/.test(commandStr)) {
123
+ const num = parseInt(commandStr, 10);
124
+ if (num === 0) {
125
+ if (remaining.length < MIN_NEW_CONTEXT_CHARS) {
126
+ return [null,
127
+ `Please provide a longer description for your new context.\n` +
128
+ `Your description '${remaining}' is only ${remaining.length} characters.\n` +
129
+ `Minimum required: ${MIN_NEW_CONTEXT_CHARS} characters.\n` +
130
+ `Example: ^0 implement user authentication with JWT tokens`,
131
+ ];
132
+ }
133
+ return [{ ends: [], select: null, new_context_desc: remaining, remaining_prompt: "" }, null];
134
+ }
135
+ if (num < 1 || num > contexts.length) {
136
+ if (contexts.length === 0) {
137
+ return [null, "No existing contexts. Use ^0 <description> to create a new one."];
138
+ }
139
+ return [null, `Invalid selection. Choose 1-${contexts.length} for existing contexts, or ^0 for new.`];
140
+ }
141
+ const ctx = contexts[num - 1]!;
142
+ return [{ ends: [], select: ctx.id, new_context_desc: null, remaining_prompt: remaining }, null];
143
+ }
144
+
145
+ // Parse chained commands
146
+ const ends: string[] = [];
147
+ let select: string | null = null;
148
+ let pos = 0;
149
+
150
+ while (pos < commandStr.length) {
151
+ const ch = commandStr[pos]!.toUpperCase();
152
+
153
+ if (ch === "E") {
154
+ pos++;
155
+ if (pos < commandStr.length && commandStr[pos] === "*") {
156
+ pos++;
157
+ if (contexts.length === 0) return [null, "No contexts to end."];
158
+ for (const ctx of contexts) {
159
+ if (!ends.includes(ctx.id)) ends.push(ctx.id);
160
+ }
161
+ } else if (pos < commandStr.length && commandStr[pos] === ":") {
162
+ pos++;
163
+ const prefixStart = pos;
164
+ while (pos < commandStr.length && !/[EeSs]/.test(commandStr[pos]!)) pos++;
165
+ const pfx = commandStr.slice(prefixStart, pos);
166
+ if (!pfx) return [null, "Expected ID query after 'E:'"];
167
+ const [idx, err] = resolveContextByPrefix(pfx, contexts);
168
+ if (err) return [null, err];
169
+ const ctx = contexts[idx! - 1]!;
170
+ if (!ends.includes(ctx.id)) ends.push(ctx.id);
171
+ } else {
172
+ const numStart = pos;
173
+ while (pos < commandStr.length && /\d/.test(commandStr[pos]!)) pos++;
174
+ if (numStart === pos) {
175
+ return [null, `Expected number, '*', or ':prefix' after 'E' at position ${numStart + 1}`];
176
+ }
177
+ const num = parseInt(commandStr.slice(numStart, pos), 10);
178
+ if (num < 1 || num > contexts.length) {
179
+ if (contexts.length === 0) return [null, "No contexts to end."];
180
+ return [null, `Context ^E${num} invalid. Choose 1-${contexts.length}.`];
181
+ }
182
+ if (pos < commandStr.length && commandStr[pos] === "+") {
183
+ pos++;
184
+ for (let i = num; i <= contexts.length; i++) {
185
+ const ctx = contexts[i - 1]!;
186
+ if (!ends.includes(ctx.id)) ends.push(ctx.id);
187
+ }
188
+ } else {
189
+ const ctx = contexts[num - 1]!;
190
+ if (!ends.includes(ctx.id)) ends.push(ctx.id);
191
+ }
192
+ }
193
+ } else if (ch === "S") {
194
+ pos++;
195
+ let ctx: ContextState;
196
+ if (pos < commandStr.length && commandStr[pos] === ":") {
197
+ pos++;
198
+ const prefixStart = pos;
199
+ while (pos < commandStr.length && !/[EeSs]/.test(commandStr[pos]!)) pos++;
200
+ const pfx = commandStr.slice(prefixStart, pos);
201
+ if (!pfx) return [null, "Expected ID query after 'S:'"];
202
+ const [idx, err] = resolveContextByPrefix(pfx, contexts);
203
+ if (err) return [null, err];
204
+ ctx = contexts[idx! - 1]!;
205
+ } else {
206
+ const numStart = pos;
207
+ while (pos < commandStr.length && /\d/.test(commandStr[pos]!)) pos++;
208
+ if (numStart === pos) {
209
+ return [null, `Expected number or ':prefix' after 'S' at position ${numStart + 1}`];
210
+ }
211
+ const num = parseInt(commandStr.slice(numStart, pos), 10);
212
+ if (num < 1 || num > contexts.length) {
213
+ if (contexts.length === 0) return [null, "No contexts to select."];
214
+ return [null, `Context ^S${num} invalid. Choose 1-${contexts.length}.`];
215
+ }
216
+ ctx = contexts[num - 1]!;
217
+ }
218
+ if (select === null) select = ctx.id;
219
+ } else {
220
+ return [null,
221
+ `Invalid command '${commandStr[pos]}' at position ${pos + 1}.\n` +
222
+ `Use E<N> to end, E<N>+ to end N and after, E* to end all, S<N> to select.\n` +
223
+ `Example: ^E1S2 (end 1, select 2), ^E2+ (end 2 and older), ^E* (end all)`,
224
+ ];
225
+ }
226
+ }
227
+
228
+ if (select !== null && ends.includes(select)) {
229
+ return [null, `Cannot select context '${select}' because it's being ended.`];
230
+ }
231
+
232
+ return [{ ends, select, new_context_desc: null, remaining_prompt: remaining }, null];
233
+ }
234
+
235
+ // ---------------------------------------------------------------------------
236
+ // Plan content matching (fallback)
237
+ // ---------------------------------------------------------------------------
238
+
239
+ function matchPlanContent(prompt: string, hasPlanContexts: ContextState[]): ContextState | null {
240
+ if (hasPlanContexts.length === 0) return null;
241
+
242
+ // Tier 1: Plan ID match
243
+ const idMatch = prompt.match(/<!-- plan-id: ([a-f0-9]+) -->/);
244
+ if (idMatch) {
245
+ const foundId = idMatch[1]!;
246
+ for (const ctx of hasPlanContexts) {
247
+ if (ctx.plan_id === foundId) {
248
+ logDebug("context_selector", `Tier 1 plan-id match: ${ctx.id} (id: ${foundId})`);
249
+ return ctx;
250
+ }
251
+ }
252
+ }
253
+
254
+ // Tier 2: Normalized hash match
255
+ const normalized = normalizePlanContent(prompt);
256
+ const normHash = crypto.createHash("sha256").update(normalized, "utf-8").digest("hex").slice(0, 12);
257
+ for (const ctx of hasPlanContexts) {
258
+ if (ctx.plan_hash && ctx.plan_hash === normHash) {
259
+ logDebug("context_selector", `Tier 2 normalized hash match: ${ctx.id} (hash: ${normHash})`);
260
+ return ctx;
261
+ }
262
+ }
263
+
264
+ // Tier 3: Multi-anchor signature match
265
+ for (const ctx of hasPlanContexts) {
266
+ const anchors = ctx.plan_anchors ?? [];
267
+ if (anchors.length > 0) {
268
+ const hits = anchors.filter(a => prompt.includes(a)).length;
269
+ if (hits >= 2 && hits >= Math.floor(anchors.length / 2)) {
270
+ logDebug("context_selector", `Tier 3 anchor match: ${ctx.id} (${hits}/${anchors.length} anchors)`);
271
+ return ctx;
272
+ }
273
+ }
274
+ }
275
+
276
+ // Tier 4 (legacy): Signature match
277
+ const promptHead = prompt.slice(0, 500);
278
+ for (const ctx of hasPlanContexts) {
279
+ if (ctx.plan_signature && promptHead.includes(ctx.plan_signature)) {
280
+ logDebug("context_selector", `Tier 4 legacy signature match: ${ctx.id}`);
281
+ return ctx;
282
+ }
283
+ }
284
+
285
+ return null;
286
+ }
287
+
288
+ // ---------------------------------------------------------------------------
289
+ // Context creation helper
290
+ // ---------------------------------------------------------------------------
291
+
292
+ function createNewContext(
293
+ prompt: string,
294
+ projectRoot?: string,
295
+ ): [string | null, string, string | null] {
296
+ try {
297
+ const newCtx = createContextFromPrompt(prompt, projectRoot);
298
+ updateMode(newCtx.id, "active", projectRoot);
299
+ newCtx.mode = "active";
300
+ logInfo("context_selector", `Auto-created context: ${newCtx.id}`);
301
+ return [newCtx.id, "auto_created", formatContextCreated(newCtx)];
302
+ } catch (e: any) {
303
+ logError("context_selector", `Primary context creation failed: ${e}`);
304
+ try {
305
+ const now = new Date();
306
+ const yy = String(now.getFullYear()).slice(2);
307
+ const mm = String(now.getMonth() + 1).padStart(2, "0");
308
+ const dd = String(now.getDate()).padStart(2, "0");
309
+ const hh = String(now.getHours()).padStart(2, "0");
310
+ const min = String(now.getMinutes()).padStart(2, "0");
311
+ const fallbackId = `${yy}${mm}${dd}-${hh}${min}-context`;
312
+ const newCtx = createContext(
313
+ fallbackId,
314
+ prompt.trim().slice(0, 200) || "New context",
315
+ "auto-created-fallback",
316
+ projectRoot,
317
+ ["auto-created", "fallback"],
318
+ );
319
+ updateMode(newCtx.id, "active", projectRoot);
320
+ newCtx.mode = "active";
321
+ logInfo("context_selector", `Fallback context created: ${newCtx.id}`);
322
+ return [newCtx.id, "auto_created_fallback", formatContextCreated(newCtx)];
323
+ } catch (e2: any) {
324
+ logError("context_selector", `ALL context creation failed: ${e2}`);
325
+ return [null, "creation_failed", null];
326
+ }
327
+ }
328
+ }
329
+
330
+ // ---------------------------------------------------------------------------
331
+ // Caret command handler
332
+ // ---------------------------------------------------------------------------
333
+
334
+ function handleCaretCommand(
335
+ prompt: string,
336
+ contexts: ContextState[],
337
+ projectRoot?: string,
338
+ ): [string | null, string, string | null] {
339
+ if (contexts.length === 0) {
340
+ const match = prompt.match(/^\^(\S+)(?:\s+(.*))?$/s);
341
+ if (!match) {
342
+ throw new BlockRequest(
343
+ "Invalid prefix. Use ^0 <description> to create a new context.\n" +
344
+ "Example: ^0 implement user authentication system",
345
+ );
346
+ }
347
+ const prefixValue = match[1]!;
348
+ const remaining = match[2] ?? "";
349
+ if (!/^\d+$/.test(prefixValue) || parseInt(prefixValue, 10) !== 0) {
350
+ throw new BlockRequest(
351
+ "No existing contexts to select. Use ^0 <description> to create a new context.\n" +
352
+ "Example: ^0 implement user authentication system",
353
+ );
354
+ }
355
+ const description = remaining.trim();
356
+ if (description.length < MIN_NEW_CONTEXT_CHARS) {
357
+ throw new BlockRequest(
358
+ `Please provide a longer description for your new context.\n` +
359
+ `Your description '${description}' is only ${description.length} characters.\n` +
360
+ `Minimum required: ${MIN_NEW_CONTEXT_CHARS} characters.\n` +
361
+ `Example: ^0 implement user authentication with JWT tokens`,
362
+ );
363
+ }
364
+ return createNewContext(description, projectRoot);
365
+ }
366
+
367
+ const [cmd, error] = parseChainedCaret(prompt, contexts);
368
+ if (error) throw new BlockRequest(error + "\n" + formatContextPickerStderr(contexts));
369
+ if (!cmd) throw new BlockRequest(formatContextPickerStderr(contexts));
370
+
371
+ const endedContexts: ContextState[] = [];
372
+ for (const ctxId of cmd.ends) {
373
+ const ctxToEnd = contexts.find(c => c.id === ctxId);
374
+ if (!ctxToEnd) {
375
+ throw new BlockRequest(`Context '${ctxId}' no longer exists.\n` + formatContextPickerStderr(contexts));
376
+ }
377
+ completeContext(ctxToEnd.id, projectRoot);
378
+ endedContexts.push(ctxToEnd);
379
+ logInfo("context_selector", `Ended context: ${ctxToEnd.id}`);
380
+ }
381
+
382
+ if (cmd.new_context_desc) {
383
+ const [ctxId, method, output] = createNewContext(cmd.new_context_desc, projectRoot);
384
+ if (ctxId && endedContexts.length > 0) {
385
+ const newCtx = getContext(ctxId, projectRoot);
386
+ const feedback = formatCommandFeedback(endedContexts, newCtx);
387
+ return [ctxId, method !== "creation_failed" ? "caret_new" : method, feedback];
388
+ }
389
+ return [ctxId, method !== "creation_failed" ? "caret_new" : method, output];
390
+ }
391
+
392
+ if (cmd.select) {
393
+ const selectedCtx = contexts.find(c => c.id === cmd.select);
394
+ if (!selectedCtx) {
395
+ throw new BlockRequest(`Context '${cmd.select}' no longer exists.\n` + formatContextPickerStderr(contexts));
396
+ }
397
+ logInfo("context_selector", `Caret-selected context: ${selectedCtx.id}`);
398
+ return [selectedCtx.id, "caret_select", formatCommandFeedback(endedContexts, selectedCtx)];
399
+ }
400
+
401
+ if (endedContexts.length > 0) {
402
+ const remainingContexts = getAllContexts("active", projectRoot);
403
+ const feedback = formatCommandFeedback(endedContexts, null);
404
+ if (remainingContexts.length === 0) {
405
+ throw new BlockRequest(
406
+ feedback + "\nAll contexts have been ended. No context selected.\n\n" +
407
+ "Just type your task to start a new context.\n" +
408
+ "Example: implement user authentication system",
409
+ );
410
+ }
411
+ throw new BlockRequest(
412
+ feedback + "\nNo context selected.\n\nSelect a context to continue:\n" +
413
+ formatContextPickerStderr(remainingContexts),
414
+ );
415
+ }
416
+
417
+ throw new BlockRequest(formatContextPickerStderr(contexts));
418
+ }
419
+
420
+ // ---------------------------------------------------------------------------
421
+ // Main entry point
422
+ // ---------------------------------------------------------------------------
423
+
424
+ /**
425
+ * Determine which context this prompt belongs to.
426
+ * See SPEC.md §8.5
427
+ *
428
+ * Returns [contextId, method, outputText].
429
+ * Throws BlockRequest when request should be blocked to show picker.
430
+ */
431
+ export function determineContext(
432
+ prompt: string,
433
+ sessionId?: string,
434
+ projectRoot?: string,
435
+ ): [string | null, string, string | null] {
436
+ if (isInternalCall()) {
437
+ logDebug("context_selector", "Skipping: internal subprocess call");
438
+ return [null, "skip_internal", null];
439
+ }
440
+
441
+ // --- Case 1: session_match ---
442
+ if (sessionId) {
443
+ const sessionContext = getContextBySessionId(sessionId, projectRoot);
444
+ if (sessionContext) {
445
+ logInfo("context_selector", `Session match: ${sessionContext.id}`);
446
+ return [
447
+ sessionContext.id,
448
+ "session_match",
449
+ formatActiveContextReminder(sessionContext, projectRoot),
450
+ ];
451
+ }
452
+ }
453
+
454
+ // --- Case 2: caret_command ---
455
+ if (prompt.trim() === "^") {
456
+ const contexts = getAllContexts("active", projectRoot);
457
+ if (contexts.length === 0) {
458
+ throw new BlockRequest(
459
+ "No contexts exist.\n\nJust type your task to start a new context.\n" +
460
+ "Example: implement user authentication system",
461
+ );
462
+ }
463
+ throw new BlockRequest(formatContextPickerStderr(contexts));
464
+ }
465
+
466
+ if (prompt.startsWith("^")) {
467
+ const contexts = getAllContexts("active", projectRoot);
468
+ return handleCaretCommand(prompt, contexts, projectRoot);
469
+ }
470
+
471
+ // --- Case 3: plan_content_match (fallback) ---
472
+ const hasPlanContexts = getAllContexts("active", projectRoot).filter(c => c.mode === "has_plan");
473
+ if (hasPlanContexts.length > 0) {
474
+ const matched = matchPlanContent(prompt, hasPlanContexts);
475
+ if (matched) {
476
+ if (sessionId) bindSession(matched.id, sessionId, projectRoot);
477
+ updateMode(matched.id, "active", projectRoot, { plan_consumed: true });
478
+ matched.mode = "active";
479
+ logInfo("context_selector", `Plan match (fallback): ${matched.id}`);
480
+ return [matched.id, "plan_content_match", formatPlanContinuation(matched, projectRoot)];
481
+ }
482
+ }
483
+
484
+ // --- Case 3b: handoff_match (fallback) ---
485
+ const hasHandoffContexts = getAllContexts("active", projectRoot).filter(c => c.mode === "has_handoff");
486
+ if (hasHandoffContexts.length > 0) {
487
+ const target = hasHandoffContexts[0]!;
488
+ if (sessionId) bindSession(target.id, sessionId, projectRoot);
489
+ updateMode(target.id, "active", projectRoot, { handoff_consumed: true });
490
+ target.mode = "active";
491
+ logInfo("context_selector", `Handoff match (fallback): ${target.id}`);
492
+ return [target.id, "handoff_match", formatHandoffContinuation(target, projectRoot)];
493
+ }
494
+
495
+ // --- Case 4: default ---
496
+ return createNewContext(prompt, projectRoot);
497
+ }