sessionlog 0.0.1

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 (219) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +388 -0
  3. package/dist/agent/agents/claude-code.d.ts +76 -0
  4. package/dist/agent/agents/claude-code.d.ts.map +1 -0
  5. package/dist/agent/agents/claude-code.js +769 -0
  6. package/dist/agent/agents/claude-code.js.map +1 -0
  7. package/dist/agent/agents/cursor.d.ts +35 -0
  8. package/dist/agent/agents/cursor.d.ts.map +1 -0
  9. package/dist/agent/agents/cursor.js +294 -0
  10. package/dist/agent/agents/cursor.js.map +1 -0
  11. package/dist/agent/agents/gemini-cli.d.ts +62 -0
  12. package/dist/agent/agents/gemini-cli.d.ts.map +1 -0
  13. package/dist/agent/agents/gemini-cli.js +474 -0
  14. package/dist/agent/agents/gemini-cli.js.map +1 -0
  15. package/dist/agent/agents/opencode.d.ts +100 -0
  16. package/dist/agent/agents/opencode.d.ts.map +1 -0
  17. package/dist/agent/agents/opencode.js +423 -0
  18. package/dist/agent/agents/opencode.js.map +1 -0
  19. package/dist/agent/registry.d.ts +54 -0
  20. package/dist/agent/registry.d.ts.map +1 -0
  21. package/dist/agent/registry.js +123 -0
  22. package/dist/agent/registry.js.map +1 -0
  23. package/dist/agent/session-types.d.ts +45 -0
  24. package/dist/agent/session-types.d.ts.map +1 -0
  25. package/dist/agent/session-types.js +48 -0
  26. package/dist/agent/session-types.js.map +1 -0
  27. package/dist/agent/types.d.ts +126 -0
  28. package/dist/agent/types.d.ts.map +1 -0
  29. package/dist/agent/types.js +40 -0
  30. package/dist/agent/types.js.map +1 -0
  31. package/dist/cli.d.ts +12 -0
  32. package/dist/cli.d.ts.map +1 -0
  33. package/dist/cli.js +425 -0
  34. package/dist/cli.js.map +1 -0
  35. package/dist/commands/clean.d.ts +30 -0
  36. package/dist/commands/clean.d.ts.map +1 -0
  37. package/dist/commands/clean.js +98 -0
  38. package/dist/commands/clean.js.map +1 -0
  39. package/dist/commands/disable.d.ts +23 -0
  40. package/dist/commands/disable.d.ts.map +1 -0
  41. package/dist/commands/disable.js +57 -0
  42. package/dist/commands/disable.js.map +1 -0
  43. package/dist/commands/doctor.d.ts +43 -0
  44. package/dist/commands/doctor.d.ts.map +1 -0
  45. package/dist/commands/doctor.js +97 -0
  46. package/dist/commands/doctor.js.map +1 -0
  47. package/dist/commands/enable.d.ts +37 -0
  48. package/dist/commands/enable.d.ts.map +1 -0
  49. package/dist/commands/enable.js +133 -0
  50. package/dist/commands/enable.js.map +1 -0
  51. package/dist/commands/explain.d.ts +68 -0
  52. package/dist/commands/explain.d.ts.map +1 -0
  53. package/dist/commands/explain.js +182 -0
  54. package/dist/commands/explain.js.map +1 -0
  55. package/dist/commands/reset.d.ts +23 -0
  56. package/dist/commands/reset.d.ts.map +1 -0
  57. package/dist/commands/reset.js +68 -0
  58. package/dist/commands/reset.js.map +1 -0
  59. package/dist/commands/resume.d.ts +42 -0
  60. package/dist/commands/resume.d.ts.map +1 -0
  61. package/dist/commands/resume.js +133 -0
  62. package/dist/commands/resume.js.map +1 -0
  63. package/dist/commands/rewind.d.ts +34 -0
  64. package/dist/commands/rewind.d.ts.map +1 -0
  65. package/dist/commands/rewind.js +155 -0
  66. package/dist/commands/rewind.js.map +1 -0
  67. package/dist/commands/status.d.ts +51 -0
  68. package/dist/commands/status.d.ts.map +1 -0
  69. package/dist/commands/status.js +112 -0
  70. package/dist/commands/status.js.map +1 -0
  71. package/dist/config.d.ts +40 -0
  72. package/dist/config.d.ts.map +1 -0
  73. package/dist/config.js +127 -0
  74. package/dist/config.js.map +1 -0
  75. package/dist/git-operations.d.ts +191 -0
  76. package/dist/git-operations.d.ts.map +1 -0
  77. package/dist/git-operations.js +462 -0
  78. package/dist/git-operations.js.map +1 -0
  79. package/dist/hooks/git-hooks.d.ts +22 -0
  80. package/dist/hooks/git-hooks.d.ts.map +1 -0
  81. package/dist/hooks/git-hooks.js +139 -0
  82. package/dist/hooks/git-hooks.js.map +1 -0
  83. package/dist/hooks/lifecycle.d.ts +21 -0
  84. package/dist/hooks/lifecycle.d.ts.map +1 -0
  85. package/dist/hooks/lifecycle.js +179 -0
  86. package/dist/hooks/lifecycle.js.map +1 -0
  87. package/dist/index.d.ts +76 -0
  88. package/dist/index.d.ts.map +1 -0
  89. package/dist/index.js +166 -0
  90. package/dist/index.js.map +1 -0
  91. package/dist/security/redaction.d.ts +35 -0
  92. package/dist/security/redaction.d.ts.map +1 -0
  93. package/dist/security/redaction.js +239 -0
  94. package/dist/security/redaction.js.map +1 -0
  95. package/dist/session/state-machine.d.ts +90 -0
  96. package/dist/session/state-machine.d.ts.map +1 -0
  97. package/dist/session/state-machine.js +345 -0
  98. package/dist/session/state-machine.js.map +1 -0
  99. package/dist/store/checkpoint-store.d.ts +59 -0
  100. package/dist/store/checkpoint-store.d.ts.map +1 -0
  101. package/dist/store/checkpoint-store.js +321 -0
  102. package/dist/store/checkpoint-store.js.map +1 -0
  103. package/dist/store/native-store.d.ts +14 -0
  104. package/dist/store/native-store.d.ts.map +1 -0
  105. package/dist/store/native-store.js +159 -0
  106. package/dist/store/native-store.js.map +1 -0
  107. package/dist/store/provider-types.d.ts +78 -0
  108. package/dist/store/provider-types.d.ts.map +1 -0
  109. package/dist/store/provider-types.js +12 -0
  110. package/dist/store/provider-types.js.map +1 -0
  111. package/dist/store/session-store.d.ts +36 -0
  112. package/dist/store/session-store.d.ts.map +1 -0
  113. package/dist/store/session-store.js +193 -0
  114. package/dist/store/session-store.js.map +1 -0
  115. package/dist/strategy/attribution.d.ts +39 -0
  116. package/dist/strategy/attribution.d.ts.map +1 -0
  117. package/dist/strategy/attribution.js +225 -0
  118. package/dist/strategy/attribution.js.map +1 -0
  119. package/dist/strategy/common.d.ts +57 -0
  120. package/dist/strategy/common.d.ts.map +1 -0
  121. package/dist/strategy/common.js +156 -0
  122. package/dist/strategy/common.js.map +1 -0
  123. package/dist/strategy/content-overlap.d.ts +33 -0
  124. package/dist/strategy/content-overlap.d.ts.map +1 -0
  125. package/dist/strategy/content-overlap.js +176 -0
  126. package/dist/strategy/content-overlap.js.map +1 -0
  127. package/dist/strategy/manual-commit.d.ts +36 -0
  128. package/dist/strategy/manual-commit.d.ts.map +1 -0
  129. package/dist/strategy/manual-commit.js +717 -0
  130. package/dist/strategy/manual-commit.js.map +1 -0
  131. package/dist/strategy/types.d.ts +163 -0
  132. package/dist/strategy/types.d.ts.map +1 -0
  133. package/dist/strategy/types.js +48 -0
  134. package/dist/strategy/types.js.map +1 -0
  135. package/dist/summarize/claude-generator.d.ts +25 -0
  136. package/dist/summarize/claude-generator.d.ts.map +1 -0
  137. package/dist/summarize/claude-generator.js +87 -0
  138. package/dist/summarize/claude-generator.js.map +1 -0
  139. package/dist/summarize/summarize.d.ts +52 -0
  140. package/dist/summarize/summarize.d.ts.map +1 -0
  141. package/dist/summarize/summarize.js +335 -0
  142. package/dist/summarize/summarize.js.map +1 -0
  143. package/dist/types.d.ts +293 -0
  144. package/dist/types.d.ts.map +1 -0
  145. package/dist/types.js +94 -0
  146. package/dist/types.js.map +1 -0
  147. package/dist/utils/chunk-files.d.ts +25 -0
  148. package/dist/utils/chunk-files.d.ts.map +1 -0
  149. package/dist/utils/chunk-files.js +47 -0
  150. package/dist/utils/chunk-files.js.map +1 -0
  151. package/dist/utils/commit-message.d.ts +11 -0
  152. package/dist/utils/commit-message.d.ts.map +1 -0
  153. package/dist/utils/commit-message.js +54 -0
  154. package/dist/utils/commit-message.js.map +1 -0
  155. package/dist/utils/detect-agent.d.ts +19 -0
  156. package/dist/utils/detect-agent.d.ts.map +1 -0
  157. package/dist/utils/detect-agent.js +34 -0
  158. package/dist/utils/detect-agent.js.map +1 -0
  159. package/dist/utils/hook-managers.d.ts +24 -0
  160. package/dist/utils/hook-managers.d.ts.map +1 -0
  161. package/dist/utils/hook-managers.js +96 -0
  162. package/dist/utils/hook-managers.js.map +1 -0
  163. package/dist/utils/ide-tags.d.ts +12 -0
  164. package/dist/utils/ide-tags.d.ts.map +1 -0
  165. package/dist/utils/ide-tags.js +30 -0
  166. package/dist/utils/ide-tags.js.map +1 -0
  167. package/dist/utils/paths.d.ts +32 -0
  168. package/dist/utils/paths.d.ts.map +1 -0
  169. package/dist/utils/paths.js +55 -0
  170. package/dist/utils/paths.js.map +1 -0
  171. package/dist/utils/preview-rewind.d.ts +23 -0
  172. package/dist/utils/preview-rewind.d.ts.map +1 -0
  173. package/dist/utils/preview-rewind.js +63 -0
  174. package/dist/utils/preview-rewind.js.map +1 -0
  175. package/dist/utils/rewind-conflict.d.ts +52 -0
  176. package/dist/utils/rewind-conflict.d.ts.map +1 -0
  177. package/dist/utils/rewind-conflict.js +79 -0
  178. package/dist/utils/rewind-conflict.js.map +1 -0
  179. package/dist/utils/shadow-branch.d.ts +44 -0
  180. package/dist/utils/shadow-branch.d.ts.map +1 -0
  181. package/dist/utils/shadow-branch.js +93 -0
  182. package/dist/utils/shadow-branch.js.map +1 -0
  183. package/dist/utils/string-utils.d.ts +24 -0
  184. package/dist/utils/string-utils.d.ts.map +1 -0
  185. package/dist/utils/string-utils.js +47 -0
  186. package/dist/utils/string-utils.js.map +1 -0
  187. package/dist/utils/todo-extract.d.ts +52 -0
  188. package/dist/utils/todo-extract.d.ts.map +1 -0
  189. package/dist/utils/todo-extract.js +167 -0
  190. package/dist/utils/todo-extract.js.map +1 -0
  191. package/dist/utils/trailers.d.ts +36 -0
  192. package/dist/utils/trailers.d.ts.map +1 -0
  193. package/dist/utils/trailers.js +148 -0
  194. package/dist/utils/trailers.js.map +1 -0
  195. package/dist/utils/transcript-parse.d.ts +57 -0
  196. package/dist/utils/transcript-parse.d.ts.map +1 -0
  197. package/dist/utils/transcript-parse.js +126 -0
  198. package/dist/utils/transcript-parse.js.map +1 -0
  199. package/dist/utils/transcript-timestamp.d.ts +22 -0
  200. package/dist/utils/transcript-timestamp.d.ts.map +1 -0
  201. package/dist/utils/transcript-timestamp.js +56 -0
  202. package/dist/utils/transcript-timestamp.js.map +1 -0
  203. package/dist/utils/tree-ops.d.ts +47 -0
  204. package/dist/utils/tree-ops.d.ts.map +1 -0
  205. package/dist/utils/tree-ops.js +145 -0
  206. package/dist/utils/tree-ops.js.map +1 -0
  207. package/dist/utils/tty.d.ts +25 -0
  208. package/dist/utils/tty.d.ts.map +1 -0
  209. package/dist/utils/tty.js +70 -0
  210. package/dist/utils/tty.js.map +1 -0
  211. package/dist/utils/validation.d.ts +31 -0
  212. package/dist/utils/validation.d.ts.map +1 -0
  213. package/dist/utils/validation.js +59 -0
  214. package/dist/utils/validation.js.map +1 -0
  215. package/dist/utils/worktree.d.ts +16 -0
  216. package/dist/utils/worktree.d.ts.map +1 -0
  217. package/dist/utils/worktree.js +50 -0
  218. package/dist/utils/worktree.js.map +1 -0
  219. package/package.json +64 -0
@@ -0,0 +1,717 @@
1
+ /**
2
+ * Manual Commit Strategy
3
+ *
4
+ * Core strategy implementation that orchestrates session tracking,
5
+ * checkpoint creation, condensation, and git hook integration.
6
+ *
7
+ * Data flow:
8
+ * 1. InitializeSession -> Creates SessionState, calculates initial attribution
9
+ * 2. SaveStep/SaveTaskStep -> Writes to shadow branch via CheckpointStore
10
+ * 3. PrepareCommitMsg -> Adds Entire-Checkpoint trailer to commit messages
11
+ * 4. PostCommit -> Condenses session data, handles carry-forward
12
+ * 5. PrePush -> Pushes metadata branch alongside user push
13
+ */
14
+ import * as fs from 'node:fs';
15
+ import * as path from 'node:path';
16
+ import { addTokenUsage, CHECKPOINTS_BRANCH, SHADOW_BRANCH_PREFIX, validateCheckpointID, } from '../types.js';
17
+ import { git, gitSafe, getHead, getCurrentBranch, getWorktreeRoot, getGitAuthor, getUntrackedFiles, refExists, pushBranch, hasUncommittedChanges, listBranches, showFile, lsTree, deleteBranch, updateRef, diffNameOnly, } from '../git-operations.js';
18
+ import { parseCheckpoint, formatShadowCommit, CheckpointTrailerKey } from '../utils/trailers.js';
19
+ import { filesOverlapWithContent, stagedFilesOverlapWithContent, filesWithRemainingAgentChanges, } from './content-overlap.js';
20
+ import { STRATEGY_NAME_MANUAL_COMMIT, formatSubagentEndMessage } from './types.js';
21
+ export function createManualCommitStrategy(config) {
22
+ const { sessionStore, checkpointStore, cwd, sessionRepoCwd } = config;
23
+ /** The cwd for operations on the committed checkpoints branch */
24
+ const committedCwd = sessionRepoCwd ?? cwd;
25
+ /** Branch name for committed checkpoints */
26
+ const cpBranch = config.checkpointsBranch ?? CHECKPOINTS_BRANCH;
27
+ // ========================================================================
28
+ // Session State Helpers
29
+ // ========================================================================
30
+ async function loadSession(sessionID) {
31
+ return sessionStore.load(sessionID);
32
+ }
33
+ async function saveSession(state) {
34
+ await sessionStore.save(state);
35
+ }
36
+ async function listAllSessions() {
37
+ return sessionStore.list();
38
+ }
39
+ async function findSessionsForCommit(baseCommitSHA) {
40
+ const all = await listAllSessions();
41
+ return all.filter((s) => s.baseCommit === baseCommitSHA);
42
+ }
43
+ function getShadowBranchName(baseCommit, worktreeID) {
44
+ return checkpointStore.getShadowBranchName(baseCommit, worktreeID);
45
+ }
46
+ // ========================================================================
47
+ // File Merging Helpers
48
+ // ========================================================================
49
+ function mergeFilesTouched(existing, ...fileLists) {
50
+ const seen = new Set(existing);
51
+ for (const list of fileLists) {
52
+ for (const f of list)
53
+ seen.add(f);
54
+ }
55
+ return Array.from(seen).sort();
56
+ }
57
+ // ========================================================================
58
+ // Strategy Implementation
59
+ // ========================================================================
60
+ const strategy = {
61
+ name: STRATEGY_NAME_MANUAL_COMMIT,
62
+ // ======================================================================
63
+ // PrepareCommitMsg - Add checkpoint trailer to commit messages
64
+ // ======================================================================
65
+ async prepareCommitMsg(commitMsgFile, source, _sha) {
66
+ // Read the current commit message
67
+ const commitMsg = fs.readFileSync(commitMsgFile, 'utf-8');
68
+ // Skip merge commits
69
+ if (source === 'merge')
70
+ return;
71
+ // Handle amend: preserve existing checkpoint trailer
72
+ if (source === 'commit') {
73
+ const [cpID, found] = parseCheckpoint(commitMsg);
74
+ if (found && cpID) {
75
+ // Trailer already present, nothing to do
76
+ return;
77
+ }
78
+ }
79
+ // Get current HEAD
80
+ const head = await getHead(cwd);
81
+ // Find active sessions for this commit
82
+ const sessions = await findSessionsForCommit(head);
83
+ if (sessions.length === 0)
84
+ return;
85
+ // Get staged files
86
+ const stagedOutput = await gitSafe(['diff', '--cached', '--name-only', '--diff-filter=ACMRD'], { cwd });
87
+ if (!stagedOutput)
88
+ return;
89
+ const stagedFiles = stagedOutput
90
+ .trim()
91
+ .split('\n')
92
+ .filter((f) => f.length > 0);
93
+ if (stagedFiles.length === 0)
94
+ return;
95
+ // Check if any session has overlapping work
96
+ let hasOverlap = false;
97
+ let overlappingSession = null;
98
+ for (const state of sessions) {
99
+ if (state.stepCount === 0 || state.filesTouched.length === 0)
100
+ continue;
101
+ const shadowBranch = getShadowBranchName(state.baseCommit, state.worktreeID);
102
+ const exists = await refExists(`refs/heads/${shadowBranch}`, cwd);
103
+ if (!exists)
104
+ continue;
105
+ // Content-aware overlap check
106
+ const overlap = await stagedFilesOverlapWithContent(shadowBranch, stagedFiles, state.filesTouched, cwd);
107
+ if (overlap) {
108
+ hasOverlap = true;
109
+ overlappingSession = state;
110
+ break;
111
+ }
112
+ }
113
+ if (!hasOverlap || !overlappingSession)
114
+ return;
115
+ // Generate or reuse checkpoint ID
116
+ let cpID;
117
+ if (overlappingSession.lastCheckpointID &&
118
+ validateCheckpointID(overlappingSession.lastCheckpointID)) {
119
+ cpID = overlappingSession.lastCheckpointID;
120
+ }
121
+ else {
122
+ cpID = await checkpointStore.generateID();
123
+ }
124
+ // Inject trailer into commit message
125
+ const trailer = `${CheckpointTrailerKey}: ${cpID}`;
126
+ const injected = injectCheckpointTrailer(commitMsg, trailer);
127
+ fs.writeFileSync(commitMsgFile, injected, 'utf-8');
128
+ },
129
+ // ======================================================================
130
+ // PostCommit - Condense session data after commit
131
+ // ======================================================================
132
+ async postCommit() {
133
+ // Read HEAD commit message
134
+ const headHash = await getHead(cwd);
135
+ const commitMsg = await git(['log', '-1', '--format=%B', headHash], { cwd });
136
+ // Check for checkpoint trailer
137
+ const [cpID, found] = parseCheckpoint(commitMsg);
138
+ if (!found || !cpID)
139
+ return;
140
+ // Find sessions for the parent commit (our base)
141
+ const parentHash = await gitSafe(['rev-parse', `${headHash}^`], { cwd });
142
+ if (!parentHash)
143
+ return;
144
+ const sessions = await findSessionsForCommit(parentHash.trim());
145
+ if (sessions.length === 0)
146
+ return;
147
+ // Get files changed in this commit
148
+ const { added, modified, deleted } = await diffNameOnly(`${headHash}^`, headHash, cwd);
149
+ const committedFiles = new Set([...added, ...modified, ...deleted]);
150
+ // Process each session
151
+ for (const state of sessions) {
152
+ if (state.stepCount === 0 || state.filesTouched.length === 0)
153
+ continue;
154
+ const shadowBranch = getShadowBranchName(state.baseCommit, state.worktreeID);
155
+ const exists = await refExists(`refs/heads/${shadowBranch}`, cwd);
156
+ if (!exists)
157
+ continue;
158
+ // Check overlap with committed files
159
+ const overlap = await filesOverlapWithContent(shadowBranch, headHash, parentHash.trim(), state.filesTouched, cwd);
160
+ if (!overlap)
161
+ continue;
162
+ // Condense this session
163
+ try {
164
+ await condenseSession(state, cpID, committedFiles);
165
+ }
166
+ catch {
167
+ // Log but continue with other sessions
168
+ }
169
+ // Handle carry-forward for remaining files
170
+ const remaining = await filesWithRemainingAgentChanges(shadowBranch, headHash, state.filesTouched, committedFiles, cwd);
171
+ if (remaining.length === 0) {
172
+ // All files committed - clean up shadow branch
173
+ try {
174
+ await checkpointStore.deleteShadowBranch(shadowBranch);
175
+ }
176
+ catch {
177
+ // Best effort cleanup
178
+ }
179
+ // Update session for new base commit
180
+ state.baseCommit = headHash;
181
+ state.stepCount = 0;
182
+ state.filesTouched = [];
183
+ state.promptAttributions = [];
184
+ state.lastCheckpointID = cpID;
185
+ await saveSession(state);
186
+ }
187
+ else {
188
+ // Carry forward: update state for remaining files
189
+ state.baseCommit = headHash;
190
+ state.filesTouched = remaining;
191
+ state.stepCount = 0;
192
+ state.promptAttributions = [];
193
+ state.lastCheckpointID = cpID;
194
+ await saveSession(state);
195
+ }
196
+ }
197
+ },
198
+ // ======================================================================
199
+ // CommitMsg - Strip trailer if no user content (prevents empty commits)
200
+ // ======================================================================
201
+ async commitMsg(commitMsgFile) {
202
+ let content;
203
+ try {
204
+ content = fs.readFileSync(commitMsgFile, 'utf-8');
205
+ }
206
+ catch {
207
+ return; // Hook must be silent on failure
208
+ }
209
+ // Check if our trailer is present
210
+ const [, found] = parseCheckpoint(content);
211
+ if (!found)
212
+ return;
213
+ // Check if there's any user content (non-comment, non-trailer lines)
214
+ if (!hasUserContent(content)) {
215
+ // No user content - strip the trailer so git aborts the commit
216
+ const stripped = stripCheckpointTrailer(content);
217
+ try {
218
+ fs.writeFileSync(commitMsgFile, stripped, 'utf-8');
219
+ }
220
+ catch {
221
+ // Hook must be silent on failure
222
+ }
223
+ }
224
+ },
225
+ // ======================================================================
226
+ // PrePush - Push metadata branch alongside user push
227
+ // ======================================================================
228
+ async prePush(remote) {
229
+ const pushCwd = committedCwd;
230
+ const branchExists = await refExists(`refs/heads/${cpBranch}`, pushCwd);
231
+ if (!branchExists)
232
+ return;
233
+ try {
234
+ await pushBranch(remote, cpBranch, false, pushCwd);
235
+ }
236
+ catch {
237
+ // Non-fatal: metadata push failure shouldn't block user push
238
+ }
239
+ },
240
+ // ======================================================================
241
+ // SaveStep - Create session checkpoint on shadow branch
242
+ // ======================================================================
243
+ async saveStep(step) {
244
+ const sessionID = path.basename(step.metadataDir);
245
+ let state = await loadSession(sessionID);
246
+ // Initialize if needed
247
+ if (!state || !state.baseCommit) {
248
+ const head = await getHead(cwd);
249
+ const untrackedFiles = await getUntrackedFiles(cwd);
250
+ const worktreeRoot = await getWorktreeRoot(cwd);
251
+ state = {
252
+ sessionID,
253
+ baseCommit: head,
254
+ attributionBaseCommit: head,
255
+ startedAt: new Date().toISOString(),
256
+ phase: 'active',
257
+ turnCheckpointIDs: [],
258
+ stepCount: 0,
259
+ checkpointTranscriptStart: 0,
260
+ untrackedFilesAtStart: untrackedFiles,
261
+ filesTouched: [],
262
+ agentType: step.agentType,
263
+ worktreePath: worktreeRoot,
264
+ };
265
+ await saveSession(state);
266
+ }
267
+ // Migrate shadow branch if HEAD changed (rebase/pull mid-session)
268
+ await migrateAndPersist(state);
269
+ // Write temporary checkpoint
270
+ const isFirstCheckpoint = state.stepCount === 0;
271
+ const result = await checkpointStore.writeTemporary({
272
+ sessionID,
273
+ baseCommit: state.baseCommit,
274
+ worktreeID: state.worktreeID,
275
+ modifiedFiles: step.modifiedFiles,
276
+ newFiles: step.newFiles,
277
+ deletedFiles: step.deletedFiles,
278
+ metadataDir: step.metadataDir,
279
+ metadataDirAbs: step.metadataDirAbs,
280
+ commitMessage: step.commitMessage,
281
+ authorName: step.authorName,
282
+ authorEmail: step.authorEmail,
283
+ isFirstCheckpoint,
284
+ });
285
+ if (result.skipped)
286
+ return;
287
+ // Update session state
288
+ state.stepCount++;
289
+ state.filesTouched = mergeFilesTouched(state.filesTouched, step.modifiedFiles, step.newFiles, step.deletedFiles);
290
+ if (state.stepCount === 1 && step.stepTranscriptIdentifier) {
291
+ state.transcriptIdentifierAtStart = step.stepTranscriptIdentifier;
292
+ }
293
+ if (step.tokenUsage) {
294
+ state.tokenUsage = state.tokenUsage
295
+ ? addTokenUsage(state.tokenUsage, step.tokenUsage)
296
+ : step.tokenUsage;
297
+ }
298
+ await saveSession(state);
299
+ },
300
+ // ======================================================================
301
+ // SaveTaskStep - Create task checkpoint on shadow branch
302
+ // ======================================================================
303
+ async saveTaskStep(step) {
304
+ let state = await loadSession(step.sessionID);
305
+ if (!state || !state.baseCommit) {
306
+ const head = await getHead(cwd);
307
+ const untrackedFiles = await getUntrackedFiles(cwd);
308
+ const worktreeRoot = await getWorktreeRoot(cwd);
309
+ state = {
310
+ sessionID: step.sessionID,
311
+ baseCommit: head,
312
+ attributionBaseCommit: head,
313
+ startedAt: new Date().toISOString(),
314
+ phase: 'active',
315
+ turnCheckpointIDs: [],
316
+ stepCount: 0,
317
+ checkpointTranscriptStart: 0,
318
+ untrackedFilesAtStart: untrackedFiles,
319
+ filesTouched: [],
320
+ agentType: step.agentType,
321
+ worktreePath: worktreeRoot,
322
+ };
323
+ await saveSession(state);
324
+ }
325
+ // Migrate shadow branch if HEAD changed (rebase/pull mid-session)
326
+ await migrateAndPersist(state);
327
+ // Generate commit message for task checkpoint
328
+ const shortToolUseID = step.toolUseID.length > 7 ? step.toolUseID.slice(0, 7) : step.toolUseID;
329
+ const messageSubject = formatSubagentEndMessage(step.subagentType, step.taskDescription, shortToolUseID);
330
+ const metadataDir = `.entire/metadata/${step.sessionID}/tasks/${step.toolUseID}`;
331
+ const commitMsg = formatShadowCommit(messageSubject, metadataDir, step.sessionID);
332
+ // Write temporary checkpoint
333
+ await checkpointStore.writeTemporary({
334
+ sessionID: step.sessionID,
335
+ baseCommit: state.baseCommit,
336
+ worktreeID: state.worktreeID,
337
+ modifiedFiles: step.modifiedFiles,
338
+ newFiles: step.newFiles,
339
+ deletedFiles: step.deletedFiles,
340
+ metadataDir,
341
+ metadataDirAbs: path.resolve(cwd ?? '.', metadataDir),
342
+ commitMessage: commitMsg,
343
+ authorName: step.authorName,
344
+ authorEmail: step.authorEmail,
345
+ isFirstCheckpoint: state.stepCount === 0,
346
+ });
347
+ // Update session state
348
+ state.filesTouched = mergeFilesTouched(state.filesTouched, step.modifiedFiles, step.newFiles, step.deletedFiles);
349
+ await saveSession(state);
350
+ },
351
+ // ======================================================================
352
+ // Rewind operations
353
+ // ======================================================================
354
+ async getRewindPoints(limit) {
355
+ const head = await getHead(cwd);
356
+ const sessions = await findSessionsForCommit(head);
357
+ const allPoints = [];
358
+ for (const state of sessions) {
359
+ const shadowBranch = getShadowBranchName(state.baseCommit, state.worktreeID);
360
+ const exists = await refExists(`refs/heads/${shadowBranch}`, cwd);
361
+ if (!exists)
362
+ continue;
363
+ // List temporary checkpoints
364
+ const temps = await checkpointStore.listTemporary();
365
+ for (const temp of temps) {
366
+ if (temp.baseCommit !== state.baseCommit)
367
+ continue;
368
+ allPoints.push({
369
+ id: temp.latestCommit,
370
+ message: `Checkpoint on ${shadowBranch}`,
371
+ date: new Date(temp.timestamp),
372
+ isTaskCheckpoint: false,
373
+ isLogsOnly: false,
374
+ agent: state.agentType,
375
+ sessionID: state.sessionID,
376
+ sessionPrompt: state.firstPrompt,
377
+ sessionCount: 1,
378
+ sessionIDs: [state.sessionID],
379
+ });
380
+ }
381
+ }
382
+ // Sort by date descending
383
+ allPoints.sort((a, b) => b.date.getTime() - a.date.getTime());
384
+ // Also add logs-only points from commit history
385
+ const logsOnlyPoints = await getLogsOnlyRewindPoints(limit);
386
+ const existingIDs = new Set(allPoints.map((p) => p.id));
387
+ for (const p of logsOnlyPoints) {
388
+ if (!existingIDs.has(p.id)) {
389
+ allPoints.push(p);
390
+ }
391
+ }
392
+ // Re-sort and trim
393
+ allPoints.sort((a, b) => b.date.getTime() - a.date.getTime());
394
+ return allPoints.slice(0, limit);
395
+ },
396
+ async rewind(point) {
397
+ if (point.isLogsOnly) {
398
+ throw new Error('Use restoreLogsOnly for logs-only rewind points');
399
+ }
400
+ // Read checkpoint tree and restore files
401
+ const treeEntries = await lsTree(point.id, undefined, cwd);
402
+ const worktreeRoot = await getWorktreeRoot(cwd);
403
+ for (const entry of treeEntries) {
404
+ if (entry.name.startsWith('.entire/'))
405
+ continue;
406
+ try {
407
+ const content = await showFile(point.id, entry.name, cwd);
408
+ const absPath = path.join(worktreeRoot, entry.name);
409
+ const dir = path.dirname(absPath);
410
+ fs.mkdirSync(dir, { recursive: true });
411
+ const perm = entry.mode === '100755' ? 0o755 : 0o644;
412
+ fs.writeFileSync(absPath, content, { mode: perm });
413
+ }
414
+ catch {
415
+ // Skip files that can't be restored
416
+ }
417
+ }
418
+ },
419
+ async canRewind() {
420
+ const hasChanges = await hasUncommittedChanges(cwd);
421
+ if (hasChanges) {
422
+ return [
423
+ true,
424
+ 'Warning: You have uncommitted changes that will be overwritten by the rewind.',
425
+ ];
426
+ }
427
+ return [true, ''];
428
+ },
429
+ // ======================================================================
430
+ // Condensation
431
+ // ======================================================================
432
+ async condense(sessionID) {
433
+ const state = await loadSession(sessionID);
434
+ if (!state) {
435
+ throw new Error(`Session not found: ${sessionID}`);
436
+ }
437
+ const cpID = await checkpointStore.generateID();
438
+ const committedFiles = new Set(state.filesTouched);
439
+ return condenseSession(state, cpID, committedFiles);
440
+ },
441
+ // ======================================================================
442
+ // Validation & Cleanup
443
+ // ======================================================================
444
+ async validateRepository() {
445
+ const { validateRepository: validate } = await import('./common.js');
446
+ await validate(cwd);
447
+ },
448
+ async listOrphanedItems() {
449
+ const items = [];
450
+ // Find orphaned shadow branches
451
+ const allBranches = await listBranches(cwd);
452
+ for (const branch of allBranches) {
453
+ if (branch.startsWith(SHADOW_BRANCH_PREFIX) && branch !== CHECKPOINTS_BRANCH) {
454
+ items.push({
455
+ type: 'shadow-branch',
456
+ id: branch,
457
+ reason: 'shadow branch (should have been auto-cleaned)',
458
+ });
459
+ }
460
+ }
461
+ return items;
462
+ },
463
+ };
464
+ // ========================================================================
465
+ // Internal: Condensation
466
+ // ========================================================================
467
+ async function condenseSession(state, checkpointID, committedFiles) {
468
+ const author = await getGitAuthor(cwd);
469
+ const branch = await getCurrentBranch(cwd);
470
+ // Filter filesTouched to committed subset
471
+ const filesTouched = state.filesTouched.filter((f) => committedFiles.has(f));
472
+ // Build transcript and prompts from shadow branch
473
+ let transcript = Buffer.alloc(0);
474
+ let prompts = [];
475
+ let context = Buffer.alloc(0);
476
+ const shadowBranch = getShadowBranchName(state.baseCommit, state.worktreeID);
477
+ const shadowExists = await refExists(`refs/heads/${shadowBranch}`, cwd);
478
+ if (shadowExists) {
479
+ // Read transcript from shadow branch metadata
480
+ try {
481
+ const metadataDir = `.entire/metadata/${state.sessionID}`;
482
+ const fullContent = await gitSafe(['show', `refs/heads/${shadowBranch}:${metadataDir}/full.jsonl`], { cwd });
483
+ if (fullContent) {
484
+ transcript = Buffer.from(fullContent, 'utf-8');
485
+ }
486
+ }
487
+ catch {
488
+ // Use empty transcript
489
+ }
490
+ // Read prompts
491
+ try {
492
+ const metadataDir = `.entire/metadata/${state.sessionID}`;
493
+ const promptContent = await gitSafe(['show', `refs/heads/${shadowBranch}:${metadataDir}/prompt.txt`], { cwd });
494
+ if (promptContent) {
495
+ prompts = promptContent.split('\n---\n').filter((p) => p.trim().length > 0);
496
+ }
497
+ }
498
+ catch {
499
+ // Use empty prompts
500
+ }
501
+ }
502
+ // If we have a live transcript path, try to read from there
503
+ if (transcript.length === 0 && state.transcriptPath) {
504
+ try {
505
+ transcript = fs.readFileSync(state.transcriptPath);
506
+ }
507
+ catch {
508
+ // Keep empty
509
+ }
510
+ }
511
+ // Generate context from prompts
512
+ if (prompts.length > 0) {
513
+ const contextLines = prompts.map((p, i) => `## Prompt ${i + 1}\n\n${p}`);
514
+ context = Buffer.from(contextLines.join('\n\n---\n\n'), 'utf-8');
515
+ }
516
+ // Write committed checkpoint
517
+ await checkpointStore.writeCommitted({
518
+ checkpointID,
519
+ sessionID: state.sessionID,
520
+ strategy: STRATEGY_NAME_MANUAL_COMMIT,
521
+ branch: branch ?? undefined,
522
+ transcript,
523
+ prompts,
524
+ context,
525
+ filesTouched,
526
+ checkpointsCount: state.stepCount,
527
+ authorName: author.name,
528
+ authorEmail: author.email,
529
+ agent: state.agentType,
530
+ turnID: state.turnID,
531
+ transcriptIdentifierAtStart: state.transcriptIdentifierAtStart,
532
+ checkpointTranscriptStart: state.checkpointTranscriptStart,
533
+ tokenUsage: state.tokenUsage,
534
+ });
535
+ return {
536
+ checkpointID,
537
+ sessionsCondensed: 1,
538
+ checkpointsCount: state.stepCount,
539
+ filesTouched,
540
+ tokenUsage: state.tokenUsage,
541
+ };
542
+ }
543
+ // ========================================================================
544
+ // Internal: Logs-only rewind points from commit history
545
+ // ========================================================================
546
+ async function getLogsOnlyRewindPoints(limit) {
547
+ const points = [];
548
+ // Check if checkpoints branch exists (in session repo if configured)
549
+ const branchExists = await refExists(`refs/heads/${cpBranch}`, committedCwd);
550
+ if (!branchExists)
551
+ return points;
552
+ // Get committed checkpoints
553
+ const committed = await checkpointStore.listCommitted(limit);
554
+ if (committed.length === 0)
555
+ return points;
556
+ // Build map of checkpoint IDs
557
+ const cpMap = new Map();
558
+ for (const cp of committed) {
559
+ if (cp.checkpointID) {
560
+ cpMap.set(cp.checkpointID, cp);
561
+ }
562
+ }
563
+ // Walk commit history looking for checkpoint trailers
564
+ const head = await getHead(cwd);
565
+ const logOutput = await gitSafe(['log', '--format=%H %s%n%b', `--max-count=${limit * 2}`, head], { cwd });
566
+ if (!logOutput)
567
+ return points;
568
+ // Parse log output looking for checkpoint trailers
569
+ const commits = logOutput.split('\n\n').filter((c) => c.trim().length > 0);
570
+ for (const commitBlock of commits) {
571
+ const lines = commitBlock.split('\n');
572
+ if (lines.length === 0)
573
+ continue;
574
+ const firstLine = lines[0];
575
+ const spaceIdx = firstLine.indexOf(' ');
576
+ if (spaceIdx < 0)
577
+ continue;
578
+ const sha = firstLine.slice(0, spaceIdx);
579
+ const message = firstLine.slice(spaceIdx + 1);
580
+ const body = lines.slice(1).join('\n');
581
+ const fullMessage = `${message}\n${body}`;
582
+ const [cpID, found] = parseCheckpoint(fullMessage);
583
+ if (!found || !cpID)
584
+ continue;
585
+ const cpInfo = cpMap.get(cpID);
586
+ if (!cpInfo)
587
+ continue;
588
+ points.push({
589
+ id: sha,
590
+ message,
591
+ date: new Date(),
592
+ isLogsOnly: true,
593
+ isTaskCheckpoint: false,
594
+ checkpointID: cpID,
595
+ sessionCount: cpInfo.sessions?.length ?? 1,
596
+ sessionIDs: [],
597
+ });
598
+ if (points.length >= limit)
599
+ break;
600
+ }
601
+ return points;
602
+ }
603
+ // ========================================================================
604
+ // Internal: Shadow branch migration
605
+ // ========================================================================
606
+ /**
607
+ * Check if HEAD has changed since the session started and migrate the
608
+ * shadow branch to the new base commit if needed.
609
+ *
610
+ * This handles the scenario where the agent performs a rebase, pull, or
611
+ * other git operation that changes HEAD mid-session. Without migration,
612
+ * checkpoints would be saved to an orphaned shadow branch.
613
+ */
614
+ async function migrateShadowBranchIfNeeded(state) {
615
+ if (!state.baseCommit)
616
+ return false;
617
+ const currentHead = await getHead(cwd);
618
+ if (state.baseCommit === currentHead)
619
+ return false;
620
+ const oldShadowBranch = getShadowBranchName(state.baseCommit, state.worktreeID);
621
+ const newShadowBranch = getShadowBranchName(currentHead, state.worktreeID);
622
+ // Guard: if both commits produce the same shadow branch name
623
+ // (same 7-char prefix), just update state
624
+ if (oldShadowBranch === newShadowBranch) {
625
+ state.baseCommit = currentHead;
626
+ return true;
627
+ }
628
+ const oldExists = await refExists(`refs/heads/${oldShadowBranch}`, cwd);
629
+ if (!oldExists) {
630
+ // Old shadow branch doesn't exist — just update baseCommit
631
+ state.baseCommit = currentHead;
632
+ return true;
633
+ }
634
+ // Old shadow branch exists — rename it to the new base
635
+ try {
636
+ // Read the current tip of the old branch
637
+ const oldTip = await git(['rev-parse', `refs/heads/${oldShadowBranch}`], { cwd });
638
+ // Create new branch pointing to same commit
639
+ await updateRef(`refs/heads/${newShadowBranch}`, oldTip.trim(), cwd);
640
+ // Delete old branch (best effort)
641
+ try {
642
+ await deleteBranch(oldShadowBranch, false, cwd);
643
+ }
644
+ catch {
645
+ // Non-fatal
646
+ }
647
+ }
648
+ catch {
649
+ // If rename fails, just update state
650
+ }
651
+ state.baseCommit = currentHead;
652
+ return true;
653
+ }
654
+ /**
655
+ * Check for HEAD changes, migrate shadow branch if needed, and persist.
656
+ */
657
+ async function migrateAndPersist(state) {
658
+ const migrated = await migrateShadowBranchIfNeeded(state);
659
+ if (migrated) {
660
+ await saveSession(state);
661
+ }
662
+ }
663
+ return strategy;
664
+ }
665
+ // ============================================================================
666
+ // Helpers
667
+ // ============================================================================
668
+ /**
669
+ * Inject a checkpoint trailer before any git comments in the commit message.
670
+ */
671
+ function injectCheckpointTrailer(message, trailer) {
672
+ const lines = message.split('\n');
673
+ // Find where git comments start (lines beginning with #)
674
+ let insertIndex = lines.length;
675
+ for (let i = 0; i < lines.length; i++) {
676
+ if (lines[i].startsWith('#')) {
677
+ insertIndex = i;
678
+ break;
679
+ }
680
+ }
681
+ // Insert trailer before comments, with a blank line separator
682
+ const before = lines.slice(0, insertIndex);
683
+ const after = lines.slice(insertIndex);
684
+ // Ensure there's a blank line before the trailer
685
+ while (before.length > 0 && before[before.length - 1].trim() === '') {
686
+ before.pop();
687
+ }
688
+ return [...before, '', trailer, '', ...after].join('\n');
689
+ }
690
+ /**
691
+ * Check if a commit message has any content besides comments and our trailer.
692
+ */
693
+ export function hasUserContent(message) {
694
+ const trailerPrefix = CheckpointTrailerKey + ':';
695
+ for (const line of message.split('\n')) {
696
+ const trimmed = line.trim();
697
+ if (!trimmed)
698
+ continue;
699
+ if (trimmed.startsWith('#'))
700
+ continue;
701
+ if (trimmed.startsWith(trailerPrefix))
702
+ continue;
703
+ return true;
704
+ }
705
+ return false;
706
+ }
707
+ /**
708
+ * Remove the Entire-Checkpoint trailer line from a commit message.
709
+ */
710
+ export function stripCheckpointTrailer(message) {
711
+ const trailerPrefix = CheckpointTrailerKey + ':';
712
+ return message
713
+ .split('\n')
714
+ .filter((line) => !line.trim().startsWith(trailerPrefix))
715
+ .join('\n');
716
+ }
717
+ //# sourceMappingURL=manual-commit.js.map