Repository navigation
Expand file tree
/
Copy pathsave.mjs
More file actions
210 lines (181 loc) · 7.4 KB
/
Copy pathsave.mjs
File metadata and controls
210 lines (181 loc) · 7.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env node
/**
* ck — Context Keeper v2
* save.mjs — write session data to context.json, regenerate CONTEXT.md,
* and write a native memory entry.
*
* Usage (regular save):
* echo '<json>' | node save.mjs
* JSON schema: { summary, leftOff, nextSteps[], decisions[{what,why}], blockers[], goal? }
*
* Usage (init — first registration):
* echo '<json>' | node save.mjs --init
* JSON schema: { name, path, description, stack[], goal, constraints[], repo? }
*
* stdout: confirmation message
* exit 0: success exit 1: error
*/
import { readFileSync, mkdirSync, writeFileSync } from 'fs';
import { resolve } from 'path';
import {
readProjects, writeProjects, loadContext, saveContext,
today, shortId, gitSummary, nativeMemoryDir,
CURRENT_SESSION,
} from './shared.mjs';
const isInit = process.argv.includes('--init');
const cwd = process.env.PWD || process.cwd();
// ── Read JSON from stdin ──────────────────────────────────────────────────────
let input;
try {
const raw = readFileSync(0, 'utf8').trim();
if (!raw) throw new Error('empty stdin');
input = JSON.parse(raw);
} catch (e) {
console.error(`ck save: invalid JSON on stdin — ${e.message}`);
console.log('Expected schema (save): {"summary":"...","leftOff":"...","nextSteps":["..."],"decisions":[{"what":"...","why":"..."}],"blockers":["..."]}');
console.log('Expected schema (--init): {"name":"...","path":"...","description":"...","stack":["..."],"goal":"...","constraints":["..."]}');
process.exit(1);
}
// ─────────────────────────────────────────────────────────────────────────────
// INIT MODE: first-time project registration
// ─────────────────────────────────────────────────────────────────────────────
if (isInit) {
const { name, path: projectPath, description, stack, goal, constraints, repo } = input;
if (!name || !projectPath) {
console.log('ck init: name and path are required.');
process.exit(1);
}
const projects = readProjects();
// Derive contextDir (lowercase, spaces→dashes, deduplicate)
let contextDir = name.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '');
let suffix = 2;
const existingDirs = Object.values(projects).map(p => p.contextDir);
while (existingDirs.includes(contextDir) && projects[projectPath]?.contextDir !== contextDir) {
contextDir = `${contextDir.replace(/-\d+$/, '')}-${suffix++}`;
}
const context = {
version: 2,
name: contextDir,
displayName: name,
path: projectPath,
description: description || null,
stack: Array.isArray(stack) ? stack : (stack ? [stack] : []),
goal: goal || null,
constraints: Array.isArray(constraints) ? constraints : [],
repo: repo || null,
createdAt: today(),
sessions: [],
};
saveContext(contextDir, context);
// Update projects.json
projects[projectPath] = {
name,
contextDir,
lastUpdated: today(),
};
writeProjects(projects);
console.log(`✓ Project '${name}' registered.`);
console.log(` Use /ck:save to save session state and /ck:resume to reload it next time.`);
process.exit(0);
}
// ─────────────────────────────────────────────────────────────────────────────
// SAVE MODE: record a session
// ─────────────────────────────────────────────────────────────────────────────
const projects = readProjects();
const projectEntry = projects[cwd];
if (!projectEntry) {
console.log("This project isn't registered yet. Run /ck:init first.");
process.exit(1);
}
const { contextDir } = projectEntry;
let context = loadContext(contextDir);
if (!context) {
console.log(`ck: context.json not found for '${contextDir}'. The install may be corrupted.`);
process.exit(1);
}
// Get session ID from current-session.json
let sessionId;
try {
const sess = JSON.parse(readFileSync(CURRENT_SESSION, 'utf8'));
sessionId = sess.sessionId || shortId();
} catch {
sessionId = shortId();
}
// Check for duplicate (re-save of same session)
const existingIdx = context.sessions.findIndex(s => s.id === sessionId);
const { summary, leftOff, nextSteps, decisions, blockers, goal } = input;
// Capture git activity since the last session
const lastSessionDate = context.sessions?.[context.sessions.length - 1]?.date;
const gitActivity = gitSummary(cwd, lastSessionDate);
const session = {
id: sessionId,
date: today(),
summary: summary || 'Session saved',
leftOff: leftOff || null,
nextSteps: Array.isArray(nextSteps) ? nextSteps : (nextSteps ? [nextSteps] : []),
decisions: Array.isArray(decisions) ? decisions : [],
blockers: Array.isArray(blockers) ? blockers.filter(Boolean) : [],
...(gitActivity ? { gitActivity } : {}),
};
if (existingIdx >= 0) {
// Update existing session (re-save)
context.sessions[existingIdx] = session;
} else {
context.sessions.push(session);
}
// Update goal if provided
if (goal && goal !== context.goal) {
context.goal = goal;
}
// Save context.json + regenerate CONTEXT.md
saveContext(contextDir, context);
// Update projects.json timestamp
projects[cwd].lastUpdated = today();
writeProjects(projects);
// ── Write to native memory ────────────────────────────────────────────────────
try {
const memDir = nativeMemoryDir(cwd);
mkdirSync(memDir, { recursive: true });
const memFile = resolve(memDir, `ck_${today()}_${sessionId.slice(0, 8)}.md`);
const decisionsBlock = session.decisions.length
? session.decisions.map(d => `- **${d.what}**: ${d.why || ''}`).join('\n')
: '- None this session';
const nextBlock = session.nextSteps.length
? session.nextSteps.map((s, i) => `${i + 1}. ${s}`).join('
5531
\n')
: '- None recorded';
const blockersBlock = session.blockers.length
? session.blockers.map(b => `- ${b}`).join('\n')
: '- None';
const memContent = [
`---`,
`name: Session ${today()} — ${session.summary}`,
`description: Key decisions and outcomes from ck session ${sessionId.slice(0, 8)}`,
`type: project`,
`source: ck`,
`sessionId: ${sessionId}`,
`---`,
``,
`# Session: ${session.summary}`,
``,
`## Decisions`,
decisionsBlock,
``,
`## Left Off`,
session.leftOff || '—',
``,
`## Next Steps`,
nextBlock,
``,
`## Blockers`,
blockersBlock,
``,
...(gitActivity ? [`## Git Activity`, gitActivity, ``] : []),
].join('\n');
writeFileSync(memFile, memContent, 'utf8');
} catch (e) {
// Non-fatal — native memory write failure should not block the save
process.stderr.write(`ck: warning — could not write native memory entry: ${e.message}\n`);
}
console.log(`✓ Saved. Session: ${sessionId.slice(0, 8)}`);
if (gitActivity) console.log(` Git: ${gitActivity}`);
console.log(` See you next time.`);