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.
- package/dist/commands/clean.js +1 -0
- package/dist/commands/clear.d.ts +19 -2
- package/dist/commands/clear.js +351 -160
- package/dist/commands/init/index.d.ts +1 -17
- package/dist/commands/init/index.js +19 -104
- package/dist/lib/gitignore-manager.d.ts +9 -0
- package/dist/lib/gitignore-manager.js +121 -0
- package/dist/lib/template-installer.d.ts +7 -12
- package/dist/lib/template-installer.js +69 -193
- package/dist/lib/template-settings-reconstructor.d.ts +35 -0
- package/dist/lib/template-settings-reconstructor.js +130 -0
- package/dist/templates/_shared/hooks/__pycache__/archive_plan.cpython-313.pyc +0 -0
- package/dist/templates/_shared/hooks/__pycache__/session_end.cpython-313.pyc +0 -0
- package/dist/templates/_shared/hooks/archive_plan.py +10 -2
- package/dist/templates/_shared/hooks/session_end.py +37 -29
- package/dist/templates/_shared/lib/base/__pycache__/hook_utils.cpython-313.pyc +0 -0
- package/dist/templates/_shared/lib/base/__pycache__/inference.cpython-313.pyc +0 -0
- package/dist/templates/_shared/lib/base/__pycache__/logger.cpython-313.pyc +0 -0
- package/dist/templates/_shared/lib/base/__pycache__/stop_words.cpython-313.pyc +0 -0
- package/dist/templates/_shared/lib/base/__pycache__/utils.cpython-313.pyc +0 -0
- package/dist/templates/_shared/lib/base/hook_utils.py +8 -10
- package/dist/templates/_shared/lib/base/inference.py +51 -62
- package/dist/templates/_shared/lib/base/logger.py +35 -21
- package/dist/templates/_shared/lib/base/stop_words.py +8 -0
- package/dist/templates/_shared/lib/base/utils.py +29 -8
- package/dist/templates/_shared/lib/context/__pycache__/plan_manager.cpython-313.pyc +0 -0
- package/dist/templates/_shared/lib/context/plan_manager.py +101 -2
- package/dist/templates/_shared/lib-ts/base/atomic-write.ts +138 -0
- package/dist/templates/_shared/lib-ts/base/constants.ts +299 -0
- package/dist/templates/_shared/lib-ts/base/git-state.ts +58 -0
- package/dist/templates/_shared/lib-ts/base/hook-utils.ts +360 -0
- package/dist/templates/_shared/lib-ts/base/inference.ts +245 -0
- package/dist/templates/_shared/lib-ts/base/logger.ts +234 -0
- package/dist/templates/_shared/lib-ts/base/state-io.ts +114 -0
- package/dist/templates/_shared/lib-ts/base/stop-words.ts +184 -0
- package/dist/templates/_shared/lib-ts/base/subprocess-utils.ts +23 -0
- package/dist/templates/_shared/lib-ts/base/utils.ts +184 -0
- package/dist/templates/_shared/lib-ts/context/context-formatter.ts +432 -0
- package/dist/templates/_shared/lib-ts/context/context-selector.ts +497 -0
- package/dist/templates/_shared/lib-ts/context/context-store.ts +679 -0
- package/dist/templates/_shared/lib-ts/context/plan-manager.ts +292 -0
- package/dist/templates/_shared/lib-ts/context/task-tracker.ts +181 -0
- package/dist/templates/_shared/lib-ts/handoff/document-generator.ts +215 -0
- package/dist/templates/_shared/lib-ts/package.json +21 -0
- package/dist/templates/_shared/lib-ts/templates/formatters.ts +102 -0
- package/dist/templates/_shared/lib-ts/templates/plan-context.ts +65 -0
- package/dist/templates/_shared/lib-ts/tsconfig.json +13 -0
- package/dist/templates/_shared/lib-ts/types.ts +151 -0
- package/dist/templates/_shared/scripts/__pycache__/status_line.cpython-313.pyc +0 -0
- package/dist/templates/_shared/scripts/save_handoff.ts +359 -0
- package/dist/templates/_shared/scripts/status_line.py +17 -2
- package/dist/templates/cc-native/_cc-native/agents/ARCH-EVOLUTION.md +63 -0
- package/dist/templates/cc-native/_cc-native/agents/ARCH-PATTERNS.md +62 -0
- package/dist/templates/cc-native/_cc-native/agents/ARCH-STRUCTURE.md +63 -0
- package/dist/templates/cc-native/_cc-native/agents/{ASSUMPTION-CHAIN-TRACER.md → ASSUMPTION-TRACER.md} +6 -10
- package/dist/templates/cc-native/_cc-native/agents/CLARITY-AUDITOR.md +6 -10
- package/dist/templates/cc-native/_cc-native/agents/CLAUDE.md +74 -1
- package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-FEASIBILITY.md +67 -0
- package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-GAPS.md +71 -0
- package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-ORDERING.md +63 -0
- package/dist/templates/cc-native/_cc-native/agents/CONSTRAINT-VALIDATOR.md +73 -0
- package/dist/templates/cc-native/_cc-native/agents/DESIGN-ADR-VALIDATOR.md +62 -0
- package/dist/templates/cc-native/_cc-native/agents/DESIGN-SCALE-MATCHER.md +65 -0
- package/dist/templates/cc-native/_cc-native/agents/DEVILS-ADVOCATE.md +6 -9
- package/dist/templates/cc-native/_cc-native/agents/DOCUMENTATION-PHILOSOPHY.md +87 -0
- package/dist/templates/cc-native/_cc-native/agents/HANDOFF-READINESS.md +5 -9
- package/dist/templates/cc-native/_cc-native/agents/{HIDDEN-COMPLEXITY-DETECTOR.md → HIDDEN-COMPLEXITY.md} +6 -10
- package/dist/templates/cc-native/_cc-native/agents/INCREMENTAL-DELIVERY.md +67 -0
- package/dist/templates/cc-native/_cc-native/agents/PLAN-ORCHESTRATOR.md +91 -18
- package/dist/templates/cc-native/_cc-native/agents/RISK-DEPENDENCY.md +63 -0
- package/dist/templates/cc-native/_cc-native/agents/RISK-FMEA.md +67 -0
- package/dist/templates/cc-native/_cc-native/agents/RISK-PREMORTEM.md +72 -0
- package/dist/templates/cc-native/_cc-native/agents/RISK-REVERSIBILITY.md +75 -0
- package/dist/templates/cc-native/_cc-native/agents/SCOPE-BOUNDARY.md +78 -0
- package/dist/templates/cc-native/_cc-native/agents/SIMPLICITY-GUARDIAN.md +5 -9
- package/dist/templates/cc-native/_cc-native/agents/SKEPTIC.md +16 -12
- package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-BEHAVIOR-AUDITOR.md +62 -0
- package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-CHARACTERIZATION.md +72 -0
- package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-FIRST-VALIDATOR.md +62 -0
- package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-PYRAMID-ANALYZER.md +62 -0
- package/dist/templates/cc-native/_cc-native/agents/TRADEOFF-COSTS.md +68 -0
- package/dist/templates/cc-native/_cc-native/agents/TRADEOFF-STAKEHOLDERS.md +66 -0
- package/dist/templates/cc-native/_cc-native/agents/VERIFY-COVERAGE.md +75 -0
- package/dist/templates/cc-native/_cc-native/agents/VERIFY-STRENGTH.md +70 -0
- package/dist/templates/cc-native/_cc-native/hooks/__pycache__/cc-native-plan-review.cpython-313.pyc +0 -0
- package/dist/templates/cc-native/_cc-native/hooks/cc-native-plan-review.py +125 -40
- package/dist/templates/cc-native/_cc-native/lib/__pycache__/utils.cpython-313.pyc +0 -0
- package/dist/templates/cc-native/_cc-native/lib/utils.py +57 -13
- package/dist/templates/cc-native/_cc-native/plan-review.config.json +11 -7
- package/oclif.manifest.json +17 -2
- package/package.json +1 -1
- package/dist/lib/template-merger.d.ts +0 -47
- package/dist/lib/template-merger.js +0 -162
- package/dist/templates/cc-native/_cc-native/agents/ACCESSIBILITY-TESTER.md +0 -79
- package/dist/templates/cc-native/_cc-native/agents/ARCHITECT-REVIEWER.md +0 -48
- package/dist/templates/cc-native/_cc-native/agents/CODE-REVIEWER.md +0 -70
- package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-CHECKER.md +0 -59
- package/dist/templates/cc-native/_cc-native/agents/CONTEXT-EXTRACTOR.md +0 -92
- package/dist/templates/cc-native/_cc-native/agents/DOCUMENTATION-REVIEWER.md +0 -51
- package/dist/templates/cc-native/_cc-native/agents/FEASIBILITY-ANALYST.md +0 -57
- package/dist/templates/cc-native/_cc-native/agents/FRESH-PERSPECTIVE.md +0 -54
- package/dist/templates/cc-native/_cc-native/agents/INCENTIVE-MAPPER.md +0 -61
- package/dist/templates/cc-native/_cc-native/agents/PENETRATION-TESTER.md +0 -79
- package/dist/templates/cc-native/_cc-native/agents/PERFORMANCE-ENGINEER.md +0 -75
- package/dist/templates/cc-native/_cc-native/agents/PRECEDENT-FINDER.md +0 -70
- package/dist/templates/cc-native/_cc-native/agents/REVERSIBILITY-ANALYST.md +0 -61
- package/dist/templates/cc-native/_cc-native/agents/RISK-ASSESSOR.md +0 -58
- package/dist/templates/cc-native/_cc-native/agents/SECOND-ORDER-ANALYST.md +0 -61
- package/dist/templates/cc-native/_cc-native/agents/STAKEHOLDER-ADVOCATE.md +0 -55
- package/dist/templates/cc-native/_cc-native/agents/TRADE-OFF-ILLUMINATOR.md +0 -204
|
@@ -0,0 +1,679 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Context store — 2-layer CRUD for context state management.
|
|
3
|
+
* See SPEC.md §7
|
|
4
|
+
*
|
|
5
|
+
* Replaces context_manager's 3-layer approach with a simpler 2-layer model:
|
|
6
|
+
* state.json (per context folder — SOURCE OF TRUTH)
|
|
7
|
+
* index.json (at _output/ root — fast session→context lookup)
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import * as fs from "node:fs";
|
|
11
|
+
import * as path from "node:path";
|
|
12
|
+
import { readStateJson, writeStateJson, toDict, dictToState } from "../base/state-io.js";
|
|
13
|
+
import { atomicWrite } from "../base/atomic-write.js";
|
|
14
|
+
import {
|
|
15
|
+
getContextDir,
|
|
16
|
+
getContextsDir,
|
|
17
|
+
getIndexPath,
|
|
18
|
+
getArchiveDir,
|
|
19
|
+
getArchiveContextDir,
|
|
20
|
+
getArchiveIndexPath,
|
|
21
|
+
validateContextId,
|
|
22
|
+
} from "../base/constants.js";
|
|
23
|
+
import { logDebug, logInfo, logWarn, logError, setContextPath } from "../base/logger.js";
|
|
24
|
+
import { nowIso, generateContextId } from "../base/utils.js";
|
|
25
|
+
import type { ContextState, IndexFile, IndexEntry, Mode } from "../types.js";
|
|
26
|
+
|
|
27
|
+
const INDEX_VERSION = "3.0";
|
|
28
|
+
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Internal helpers
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
function loadIndex(projectRoot?: string): IndexFile {
|
|
34
|
+
const indexPath = getIndexPath(projectRoot);
|
|
35
|
+
if (fs.existsSync(indexPath)) {
|
|
36
|
+
try {
|
|
37
|
+
const raw = fs.readFileSync(indexPath, "utf-8");
|
|
38
|
+
return JSON.parse(raw) as IndexFile;
|
|
39
|
+
} catch (e: any) {
|
|
40
|
+
logWarn("context_store", `Failed to read index, recreating: ${e}`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return { version: INDEX_VERSION, updated_at: nowIso(), sessions: {}, contexts: {} };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function saveIndex(index: IndexFile, projectRoot?: string): boolean {
|
|
47
|
+
index.updated_at = nowIso();
|
|
48
|
+
const content = JSON.stringify(index, null, 2);
|
|
49
|
+
const [success, error] = atomicWrite(getIndexPath(projectRoot), content);
|
|
50
|
+
if (!success) {
|
|
51
|
+
logWarn("context_store", `Failed to write index: ${error}`);
|
|
52
|
+
}
|
|
53
|
+
return success;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function toIndexEntry(state: ContextState): IndexEntry {
|
|
57
|
+
return {
|
|
58
|
+
summary: state.summary,
|
|
59
|
+
mode: state.mode,
|
|
60
|
+
last_active: state.last_active,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Backward compat: read legacy context.json and convert to ContextState.
|
|
66
|
+
*/
|
|
67
|
+
function migrateContextJson(contextId: string, projectRoot?: string): ContextState | null {
|
|
68
|
+
const legacyPath = path.join(getContextDir(contextId, projectRoot), "context.json");
|
|
69
|
+
if (!fs.existsSync(legacyPath)) return null;
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
const data = JSON.parse(fs.readFileSync(legacyPath, "utf-8"));
|
|
73
|
+
const inFlight = data.in_flight ?? {};
|
|
74
|
+
const oldMode = inFlight.mode ?? "none";
|
|
75
|
+
const MODE_MIGRATION: Record<string, string> = {
|
|
76
|
+
none: "idle",
|
|
77
|
+
planning: "idle",
|
|
78
|
+
pending_implementation: "has_plan",
|
|
79
|
+
implementing: "active",
|
|
80
|
+
};
|
|
81
|
+
const mode = (MODE_MIGRATION[oldMode] ?? "idle") as Mode;
|
|
82
|
+
|
|
83
|
+
const sessionIds: string[] = inFlight.session_ids ??
|
|
84
|
+
(inFlight.session_id ? [inFlight.session_id] : []);
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
id: data.id ?? contextId,
|
|
88
|
+
status: data.status ?? "active",
|
|
89
|
+
summary: data.summary ?? "",
|
|
90
|
+
method: data.method ?? "",
|
|
91
|
+
tags: data.tags ?? [],
|
|
92
|
+
created_at: data.created_at ?? "",
|
|
93
|
+
last_active: data.last_active ?? "",
|
|
94
|
+
mode,
|
|
95
|
+
plan_path: inFlight.artifact_path ?? null,
|
|
96
|
+
plan_hash: inFlight.artifact_hash ?? null,
|
|
97
|
+
plan_signature: null,
|
|
98
|
+
plan_id: null,
|
|
99
|
+
plan_anchors: [],
|
|
100
|
+
plan_consumed: false,
|
|
101
|
+
handoff_path: inFlight.handoff_path ?? null,
|
|
102
|
+
handoff_consumed: false,
|
|
103
|
+
session_ids: sessionIds,
|
|
104
|
+
last_session: null,
|
|
105
|
+
tasks: [],
|
|
106
|
+
};
|
|
107
|
+
} catch (e: any) {
|
|
108
|
+
logWarn("context_store", `Failed to migrate context.json for '${contextId}': ${e}`);
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
// Core CRUD
|
|
115
|
+
// ---------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Read state.json for a context. Falls back to context.json for migration.
|
|
119
|
+
* See SPEC.md §7.2
|
|
120
|
+
*/
|
|
121
|
+
export function loadState(contextId: string, projectRoot?: string): ContextState | null {
|
|
122
|
+
const state = readStateJson(contextId, projectRoot);
|
|
123
|
+
if (state) return state;
|
|
124
|
+
|
|
125
|
+
// Backward compat: migrate from legacy context.json
|
|
126
|
+
return migrateContextJson(contextId, projectRoot);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Atomically write state.json AND update index.json.
|
|
131
|
+
* See SPEC.md §7.3
|
|
132
|
+
*/
|
|
133
|
+
export function saveState(
|
|
134
|
+
contextId: string,
|
|
135
|
+
state: ContextState,
|
|
136
|
+
projectRoot?: string,
|
|
137
|
+
): [boolean, string | null] {
|
|
138
|
+
// Ensure the state ID matches
|
|
139
|
+
state.id = contextId;
|
|
140
|
+
|
|
141
|
+
const [success, error] = writeStateJson(contextId, state, projectRoot);
|
|
142
|
+
if (!success) {
|
|
143
|
+
logWarn("context_store", `Failed to write state.json for '${contextId}': ${error}`);
|
|
144
|
+
return [false, error];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Update index.json
|
|
148
|
+
const index = loadIndex(projectRoot);
|
|
149
|
+
index.contexts[contextId] = toIndexEntry(state);
|
|
150
|
+
// Keep session mappings in sync
|
|
151
|
+
for (const sid of state.session_ids) {
|
|
152
|
+
if (!index.sessions) index.sessions = {} as Record<string, string>;
|
|
153
|
+
index.sessions[sid] = contextId;
|
|
154
|
+
}
|
|
155
|
+
const indexOk = saveIndex(index, projectRoot);
|
|
156
|
+
if (!indexOk) {
|
|
157
|
+
return [true, "state.json saved but index.json update failed"];
|
|
158
|
+
}
|
|
159
|
+
return [true, null];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Create a new context folder + state.json + index entry.
|
|
164
|
+
* Throws ValueError-equivalent if context already exists.
|
|
165
|
+
* See SPEC.md §7.4
|
|
166
|
+
*/
|
|
167
|
+
export function createContext(
|
|
168
|
+
contextId: string | null,
|
|
169
|
+
summary: string,
|
|
170
|
+
method = "",
|
|
171
|
+
projectRoot?: string,
|
|
172
|
+
tags?: string[],
|
|
173
|
+
): ContextState {
|
|
174
|
+
// Generate ID if needed
|
|
175
|
+
if (!contextId) {
|
|
176
|
+
const existingIds = new Set<string>();
|
|
177
|
+
const contextsDir = getContextsDir(projectRoot);
|
|
178
|
+
if (fs.existsSync(contextsDir)) {
|
|
179
|
+
for (const entry of fs.readdirSync(contextsDir)) {
|
|
180
|
+
const fullPath = path.join(contextsDir, entry);
|
|
181
|
+
try {
|
|
182
|
+
if (fs.statSync(fullPath).isDirectory()) {
|
|
183
|
+
existingIds.add(entry);
|
|
184
|
+
}
|
|
185
|
+
} catch { /* ignore */ }
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
// generateContextId is async but we need sync here — use a simple fallback
|
|
189
|
+
const now = new Date();
|
|
190
|
+
const yy = String(now.getFullYear()).slice(2);
|
|
191
|
+
const mm = String(now.getMonth() + 1).padStart(2, "0");
|
|
192
|
+
const dd = String(now.getDate()).padStart(2, "0");
|
|
193
|
+
const hh = String(now.getHours()).padStart(2, "0");
|
|
194
|
+
const min = String(now.getMinutes()).padStart(2, "0");
|
|
195
|
+
const timestamp = `${yy}${mm}${dd}-${hh}${min}`;
|
|
196
|
+
const words = summary.toLowerCase().split(/\s+/).filter(w => w.length > 2).slice(0, 6);
|
|
197
|
+
const slug = words.length > 0 ? words.join("-").replace(/[^a-z0-9-]/g, "").slice(0, 50) : "context";
|
|
198
|
+
contextId = `${timestamp}-${slug}`;
|
|
199
|
+
|
|
200
|
+
if (existingIds.has(contextId)) {
|
|
201
|
+
let counter = 2;
|
|
202
|
+
while (existingIds.has(`${contextId}-${counter}`)) counter++;
|
|
203
|
+
contextId = `${contextId}-${counter}`;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
contextId = validateContextId(contextId);
|
|
208
|
+
const contextDir = getContextDir(contextId, projectRoot);
|
|
209
|
+
|
|
210
|
+
if (fs.existsSync(contextDir)) {
|
|
211
|
+
throw new Error(`Context '${contextId}' already exists`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
fs.mkdirSync(contextDir, { recursive: true });
|
|
215
|
+
|
|
216
|
+
const now = nowIso();
|
|
217
|
+
const state: ContextState = {
|
|
218
|
+
id: contextId,
|
|
219
|
+
status: "active",
|
|
220
|
+
summary,
|
|
221
|
+
method,
|
|
222
|
+
tags: tags ?? [],
|
|
223
|
+
created_at: now,
|
|
224
|
+
last_active: now,
|
|
225
|
+
mode: "idle",
|
|
226
|
+
plan_path: null,
|
|
227
|
+
plan_hash: null,
|
|
228
|
+
plan_signature: null,
|
|
229
|
+
plan_id: null,
|
|
230
|
+
plan_anchors: [],
|
|
231
|
+
plan_consumed: false,
|
|
232
|
+
handoff_path: null,
|
|
233
|
+
handoff_consumed: false,
|
|
234
|
+
session_ids: [],
|
|
235
|
+
last_session: null,
|
|
236
|
+
tasks: [],
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
saveState(contextId, state, projectRoot);
|
|
240
|
+
logInfo("context_store", `Created context: ${contextId}`);
|
|
241
|
+
return state;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Load a single context by ID.
|
|
246
|
+
* See SPEC.md §7.5
|
|
247
|
+
*/
|
|
248
|
+
export function getContext(contextId: string, projectRoot?: string): ContextState | null {
|
|
249
|
+
try {
|
|
250
|
+
contextId = validateContextId(contextId);
|
|
251
|
+
} catch {
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
return loadState(contextId, projectRoot);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* List contexts from index.json, loading each state.json.
|
|
259
|
+
* Falls back to scanning context folders if index is missing.
|
|
260
|
+
* Results sorted by last_active descending.
|
|
261
|
+
* See SPEC.md §7.6
|
|
262
|
+
*/
|
|
263
|
+
export function getAllContexts(
|
|
264
|
+
status?: string,
|
|
265
|
+
projectRoot?: string,
|
|
266
|
+
): ContextState[] {
|
|
267
|
+
const results: ContextState[] = [];
|
|
268
|
+
const contextsDir = getContextsDir(projectRoot);
|
|
269
|
+
if (!fs.existsSync(contextsDir)) return [];
|
|
270
|
+
|
|
271
|
+
// Try index-driven path first
|
|
272
|
+
const index = loadIndex(projectRoot);
|
|
273
|
+
const ctxMap = index.contexts;
|
|
274
|
+
|
|
275
|
+
if (ctxMap && typeof ctxMap === "object" && Object.keys(ctxMap).length > 0) {
|
|
276
|
+
for (const cid of Object.keys(ctxMap)) {
|
|
277
|
+
const state = loadState(cid, projectRoot);
|
|
278
|
+
if (state && (!status || state.status === status)) {
|
|
279
|
+
results.push(state);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
} else {
|
|
283
|
+
// Fallback: scan folders
|
|
284
|
+
try {
|
|
285
|
+
for (const entry of fs.readdirSync(contextsDir)) {
|
|
286
|
+
if (entry.startsWith("_")) continue;
|
|
287
|
+
const fullPath = path.join(contextsDir, entry);
|
|
288
|
+
try {
|
|
289
|
+
if (!fs.statSync(fullPath).isDirectory()) continue;
|
|
290
|
+
} catch { continue; }
|
|
291
|
+
const state = loadState(entry, projectRoot);
|
|
292
|
+
if (state && (!status || state.status === status)) {
|
|
293
|
+
results.push(state);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
} catch { /* empty dir */ }
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
results.sort((a, b) => (b.last_active || "").localeCompare(a.last_active || ""));
|
|
300
|
+
return results;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Update allowed metadata fields (summary, tags, method) on a context.
|
|
305
|
+
* See SPEC.md §7.7
|
|
306
|
+
*/
|
|
307
|
+
export function updateContext(
|
|
308
|
+
contextId: string,
|
|
309
|
+
updates: Partial<Pick<ContextState, "summary" | "tags" | "method">>,
|
|
310
|
+
projectRoot?: string,
|
|
311
|
+
): ContextState | null {
|
|
312
|
+
const state = getContext(contextId, projectRoot);
|
|
313
|
+
if (!state) return null;
|
|
314
|
+
|
|
315
|
+
let changed = false;
|
|
316
|
+
if (updates.summary !== undefined) { state.summary = updates.summary; changed = true; }
|
|
317
|
+
if (updates.tags !== undefined) { state.tags = updates.tags; changed = true; }
|
|
318
|
+
if (updates.method !== undefined) { state.method = updates.method; changed = true; }
|
|
319
|
+
|
|
320
|
+
if (!changed) return state;
|
|
321
|
+
|
|
322
|
+
state.last_active = nowIso();
|
|
323
|
+
saveState(contextId, state, projectRoot);
|
|
324
|
+
return state;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// ---------------------------------------------------------------------------
|
|
328
|
+
// Session binding & mode updates
|
|
329
|
+
// ---------------------------------------------------------------------------
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* O(1) lookup: check index.json sessions map first.
|
|
333
|
+
* Side effect: sets logger context path for per-context log routing.
|
|
334
|
+
* See SPEC.md §7.8
|
|
335
|
+
*/
|
|
336
|
+
export function getContextBySessionId(
|
|
337
|
+
sessionId: string,
|
|
338
|
+
projectRoot?: string,
|
|
339
|
+
): ContextState | null {
|
|
340
|
+
if (!sessionId || sessionId === "unknown") return null;
|
|
341
|
+
|
|
342
|
+
const index = loadIndex(projectRoot);
|
|
343
|
+
const cid = index.sessions?.[sessionId];
|
|
344
|
+
if (cid) {
|
|
345
|
+
const state = loadState(cid, projectRoot);
|
|
346
|
+
if (state) {
|
|
347
|
+
setLoggerContext(state.id, projectRoot);
|
|
348
|
+
return state;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Fallback: scan all contexts
|
|
353
|
+
for (const state of getAllContexts("active", projectRoot)) {
|
|
354
|
+
if (state.session_ids.includes(sessionId)) {
|
|
355
|
+
setLoggerContext(state.id, projectRoot);
|
|
356
|
+
return state;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function setLoggerContext(contextId: string, projectRoot?: string): void {
|
|
363
|
+
try {
|
|
364
|
+
const ctxDir = getContextDir(contextId, projectRoot);
|
|
365
|
+
if (fs.existsSync(ctxDir)) {
|
|
366
|
+
setContextPath(ctxDir);
|
|
367
|
+
}
|
|
368
|
+
} catch {
|
|
369
|
+
// Never crash on logging setup
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Add session_id to both index.json sessions map and state.json session_ids.
|
|
375
|
+
* See SPEC.md §7.9
|
|
376
|
+
*/
|
|
377
|
+
export function bindSession(
|
|
378
|
+
contextId: string,
|
|
379
|
+
sessionId: string,
|
|
380
|
+
projectRoot?: string,
|
|
381
|
+
): boolean {
|
|
382
|
+
if (!sessionId || sessionId === "unknown") return false;
|
|
383
|
+
|
|
384
|
+
const state = getContext(contextId, projectRoot);
|
|
385
|
+
if (!state) return false;
|
|
386
|
+
|
|
387
|
+
if (!state.session_ids.includes(sessionId)) {
|
|
388
|
+
state.session_ids.push(sessionId);
|
|
389
|
+
}
|
|
390
|
+
state.last_active = nowIso();
|
|
391
|
+
|
|
392
|
+
const [success] = saveState(contextId, state, projectRoot);
|
|
393
|
+
return success;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Change the mode field, optionally setting plan/handoff fields.
|
|
398
|
+
* See SPEC.md §7.10
|
|
399
|
+
*/
|
|
400
|
+
export function updateMode(
|
|
401
|
+
contextId: string,
|
|
402
|
+
mode: Mode,
|
|
403
|
+
projectRoot?: string,
|
|
404
|
+
opts?: {
|
|
405
|
+
plan_path?: string;
|
|
406
|
+
plan_hash?: string;
|
|
407
|
+
plan_signature?: string;
|
|
408
|
+
plan_id?: string;
|
|
409
|
+
plan_anchors?: string[];
|
|
410
|
+
plan_consumed?: boolean;
|
|
411
|
+
handoff_consumed?: boolean;
|
|
412
|
+
},
|
|
413
|
+
): ContextState | null {
|
|
414
|
+
const state = getContext(contextId, projectRoot);
|
|
415
|
+
if (!state) return null;
|
|
416
|
+
|
|
417
|
+
state.mode = mode;
|
|
418
|
+
state.last_active = nowIso();
|
|
419
|
+
|
|
420
|
+
if (opts) {
|
|
421
|
+
if (opts.plan_path !== undefined) state.plan_path = opts.plan_path;
|
|
422
|
+
if (opts.plan_hash !== undefined) state.plan_hash = opts.plan_hash;
|
|
423
|
+
if (opts.plan_signature !== undefined) state.plan_signature = opts.plan_signature;
|
|
424
|
+
if (opts.plan_id !== undefined) state.plan_id = opts.plan_id;
|
|
425
|
+
if (opts.plan_anchors !== undefined) state.plan_anchors = opts.plan_anchors;
|
|
426
|
+
if (opts.plan_consumed !== undefined) state.plan_consumed = opts.plan_consumed;
|
|
427
|
+
if (opts.handoff_consumed !== undefined) state.handoff_consumed = opts.handoff_consumed;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// Clear plan/handoff fields when returning to idle
|
|
431
|
+
if (mode === "idle") {
|
|
432
|
+
state.plan_path = null;
|
|
433
|
+
state.plan_hash = null;
|
|
434
|
+
state.plan_signature = null;
|
|
435
|
+
state.plan_id = null;
|
|
436
|
+
state.plan_anchors = [];
|
|
437
|
+
state.plan_consumed = false;
|
|
438
|
+
state.handoff_consumed = false;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
saveState(contextId, state, projectRoot);
|
|
442
|
+
return state;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Transition idle/has_plan/has_handoff → active, unless in plan mode.
|
|
447
|
+
* See SPEC.md §7.11
|
|
448
|
+
*/
|
|
449
|
+
export function maybeActivate(
|
|
450
|
+
contextId: string,
|
|
451
|
+
permissionMode: string,
|
|
452
|
+
projectRoot?: string,
|
|
453
|
+
caller = "",
|
|
454
|
+
): boolean {
|
|
455
|
+
if (permissionMode === "plan") return false;
|
|
456
|
+
|
|
457
|
+
const state = getContext(contextId, projectRoot);
|
|
458
|
+
if (!state) return false;
|
|
459
|
+
|
|
460
|
+
if (state.mode === "idle" || state.mode === "has_plan" || state.mode === "has_handoff") {
|
|
461
|
+
const oldMode = state.mode;
|
|
462
|
+
const opts: Record<string, any> = {};
|
|
463
|
+
if (oldMode === "has_plan") opts.plan_consumed = true;
|
|
464
|
+
else if (oldMode === "has_handoff") opts.handoff_consumed = true;
|
|
465
|
+
updateMode(contextId, "active", projectRoot, opts);
|
|
466
|
+
logInfo("context_store", `maybe_activate (${caller}): ${contextId} ${oldMode} -> active`);
|
|
467
|
+
return true;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
return false;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// ---------------------------------------------------------------------------
|
|
474
|
+
// Lifecycle
|
|
475
|
+
// ---------------------------------------------------------------------------
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Mark context completed and archive it.
|
|
479
|
+
* See SPEC.md §7.12
|
|
480
|
+
*/
|
|
481
|
+
export function completeContext(contextId: string, projectRoot?: string): ContextState | null {
|
|
482
|
+
const state = getContext(contextId, projectRoot);
|
|
483
|
+
if (!state) return null;
|
|
484
|
+
|
|
485
|
+
if (state.status === "completed") {
|
|
486
|
+
logInfo("context_store", `Context '${contextId}' already completed`);
|
|
487
|
+
return state;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
state.status = "completed";
|
|
491
|
+
state.last_active = nowIso();
|
|
492
|
+
saveState(contextId, state, projectRoot);
|
|
493
|
+
logInfo("context_store", `Completed context: ${contextId}`);
|
|
494
|
+
|
|
495
|
+
const archived = archiveContext(contextId, projectRoot);
|
|
496
|
+
return archived ?? state;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Move completed context folder to _archive/, update indices.
|
|
501
|
+
* See SPEC.md §7.13
|
|
502
|
+
*/
|
|
503
|
+
export function archiveContext(contextId: string, projectRoot?: string): ContextState | null {
|
|
504
|
+
const state = getContext(contextId, projectRoot);
|
|
505
|
+
if (!state) {
|
|
506
|
+
logWarn("context_store", `Cannot archive: context '${contextId}' not found`);
|
|
507
|
+
return null;
|
|
508
|
+
}
|
|
509
|
+
if (state.status !== "completed") {
|
|
510
|
+
logWarn("context_store", `Cannot archive: context '${contextId}' not completed`);
|
|
511
|
+
return null;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
const sourceDir = getContextDir(contextId, projectRoot);
|
|
515
|
+
const archiveDest = getArchiveContextDir(contextId, projectRoot);
|
|
516
|
+
|
|
517
|
+
if (fs.existsSync(archiveDest)) {
|
|
518
|
+
logWarn("context_store", `Cannot archive: archive folder already exists for '${contextId}'`);
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
const archiveParent = path.dirname(archiveDest);
|
|
523
|
+
fs.mkdirSync(archiveParent, { recursive: true });
|
|
524
|
+
|
|
525
|
+
try {
|
|
526
|
+
fs.renameSync(sourceDir, archiveDest);
|
|
527
|
+
} catch (e: any) {
|
|
528
|
+
logError("context_store", `Failed to move context to archive: ${e}`);
|
|
529
|
+
return null;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// Remove from main index
|
|
533
|
+
const index = loadIndex(projectRoot);
|
|
534
|
+
delete index.contexts[contextId];
|
|
535
|
+
const sessions = index.sessions ?? {};
|
|
536
|
+
for (const [sid, cid] of Object.entries(sessions)) {
|
|
537
|
+
if (cid === contextId) delete sessions[sid];
|
|
538
|
+
}
|
|
539
|
+
saveIndex(index, projectRoot);
|
|
540
|
+
|
|
541
|
+
// Add to archive index
|
|
542
|
+
updateArchiveIndex(state, projectRoot);
|
|
543
|
+
|
|
544
|
+
logInfo("context_store", `Archived context: ${contextId}`);
|
|
545
|
+
return state;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Reopen a completed/archived context.
|
|
550
|
+
* See SPEC.md §7.14
|
|
551
|
+
*/
|
|
552
|
+
export function reopenContext(contextId: string, projectRoot?: string): ContextState | null {
|
|
553
|
+
let state = getContext(contextId, projectRoot);
|
|
554
|
+
|
|
555
|
+
if (!state) {
|
|
556
|
+
state = restoreFromArchive(contextId, projectRoot);
|
|
557
|
+
}
|
|
558
|
+
if (!state) return null;
|
|
559
|
+
|
|
560
|
+
if (state.status === "active") {
|
|
561
|
+
logInfo("context_store", `Context '${contextId}' already active`);
|
|
562
|
+
return state;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
state.status = "active";
|
|
566
|
+
state.last_active = nowIso();
|
|
567
|
+
saveState(contextId, state, projectRoot);
|
|
568
|
+
logInfo("context_store", `Reopened context: ${contextId}`);
|
|
569
|
+
return state;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// ---------------------------------------------------------------------------
|
|
573
|
+
// Auto-creation from prompt
|
|
574
|
+
// ---------------------------------------------------------------------------
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* Auto-create a context from the user's prompt.
|
|
578
|
+
* See SPEC.md §7.15
|
|
579
|
+
*/
|
|
580
|
+
export function createContextFromPrompt(
|
|
581
|
+
userPrompt: string,
|
|
582
|
+
projectRoot?: string,
|
|
583
|
+
): ContextState {
|
|
584
|
+
let summary = userPrompt.trim().slice(0, 2000);
|
|
585
|
+
if (userPrompt.trim().length > 2000) {
|
|
586
|
+
summary += "...";
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
return createContext(
|
|
590
|
+
null,
|
|
591
|
+
summary,
|
|
592
|
+
"auto-created",
|
|
593
|
+
projectRoot,
|
|
594
|
+
["auto-created"],
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// ---------------------------------------------------------------------------
|
|
599
|
+
// Archive helpers
|
|
600
|
+
// ---------------------------------------------------------------------------
|
|
601
|
+
|
|
602
|
+
function updateArchiveIndex(state: ContextState, projectRoot?: string): boolean {
|
|
603
|
+
const archiveDir = getArchiveDir(projectRoot);
|
|
604
|
+
const archiveIndexPath = getArchiveIndexPath(projectRoot);
|
|
605
|
+
fs.mkdirSync(archiveDir, { recursive: true });
|
|
606
|
+
|
|
607
|
+
let archiveIndex: IndexFile = {
|
|
608
|
+
version: INDEX_VERSION,
|
|
609
|
+
updated_at: nowIso(),
|
|
610
|
+
sessions: {},
|
|
611
|
+
contexts: {},
|
|
612
|
+
};
|
|
613
|
+
|
|
614
|
+
if (fs.existsSync(archiveIndexPath)) {
|
|
615
|
+
try {
|
|
616
|
+
archiveIndex = JSON.parse(fs.readFileSync(archiveIndexPath, "utf-8"));
|
|
617
|
+
} catch (e: any) {
|
|
618
|
+
logWarn("context_store", `Failed to read archive index, recreating: ${e}`);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
archiveIndex.contexts[state.id] = toIndexEntry(state);
|
|
623
|
+
archiveIndex.updated_at = nowIso();
|
|
624
|
+
|
|
625
|
+
const content = JSON.stringify(archiveIndex, null, 2);
|
|
626
|
+
const [success, error] = atomicWrite(archiveIndexPath, content);
|
|
627
|
+
if (!success) {
|
|
628
|
+
logWarn("context_store", `Failed to write archive index: ${error}`);
|
|
629
|
+
}
|
|
630
|
+
return success;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
function restoreFromArchive(contextId: string, projectRoot?: string): ContextState | null {
|
|
634
|
+
const archiveDir = getArchiveContextDir(contextId, projectRoot);
|
|
635
|
+
const activeDir = getContextDir(contextId, projectRoot);
|
|
636
|
+
|
|
637
|
+
if (!fs.existsSync(archiveDir)) return null;
|
|
638
|
+
if (fs.existsSync(activeDir)) {
|
|
639
|
+
logWarn("context_store", `Cannot restore: active folder already exists for '${contextId}'`);
|
|
640
|
+
return null;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
try {
|
|
644
|
+
fs.renameSync(archiveDir, activeDir);
|
|
645
|
+
} catch (e: any) {
|
|
646
|
+
logError("context_store", `Failed to restore context from archive: ${e}`);
|
|
647
|
+
return null;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// Remove from archive index
|
|
651
|
+
removeFromArchiveIndex(contextId, projectRoot);
|
|
652
|
+
|
|
653
|
+
const state = loadState(contextId, projectRoot);
|
|
654
|
+
logInfo("context_store", `Restored context from archive: ${contextId}`);
|
|
655
|
+
return state;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function removeFromArchiveIndex(contextId: string, projectRoot?: string): boolean {
|
|
659
|
+
const archiveIndexPath = getArchiveIndexPath(projectRoot);
|
|
660
|
+
if (!fs.existsSync(archiveIndexPath)) return true;
|
|
661
|
+
|
|
662
|
+
try {
|
|
663
|
+
const archiveIndex = JSON.parse(fs.readFileSync(archiveIndexPath, "utf-8")) as IndexFile;
|
|
664
|
+
if (archiveIndex.contexts[contextId]) {
|
|
665
|
+
delete archiveIndex.contexts[contextId];
|
|
666
|
+
archiveIndex.updated_at = nowIso();
|
|
667
|
+
const content = JSON.stringify(archiveIndex, null, 2);
|
|
668
|
+
const [success, error] = atomicWrite(archiveIndexPath, content);
|
|
669
|
+
if (!success) {
|
|
670
|
+
logWarn("context_store", `Failed to write archive index: ${error}`);
|
|
671
|
+
return false;
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
return true;
|
|
675
|
+
} catch (e: any) {
|
|
676
|
+
logWarn("context_store", `Failed to read archive index: ${e}`);
|
|
677
|
+
return false;
|
|
678
|
+
}
|
|
679
|
+
}
|