Skip to content

armgit / cogit

Public Imported from GitHub
0

Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.

feat(cli): add init, config get/set and epoch add commands

Erenebc3843be6ab
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2a0fa8e..080dcb5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,11 +1,12 @@
# Changelog
-Bu projenin kayda değer tüm değişiklikleri burada belgelenir.
-Format [Keep a Changelog](https://keepachangelog.com/tr/1.1.0/) temellidir;
-sürümleme [SemVer](https://semver.org/lang/tr/)'e uyar.
-Tek bump yolu `./release` — elle `VERSION`/tag düzenlemeyin.
+All notable changes to this project are documented here.
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- `codelineage` CLI skeleton (`--version`, `--help`), MIT license.
+- `codelineage init`: creates `.codelineage/`, registers the project, asks for git policy, Claude Code transcript retention (`cleanupPeriodDays`, with backup) and summary language; `--yes` and per-question flags for non-interactive use.
+- `codelineage config get/set` and `codelineage epoch add`.
diff --git a/package-lock.json b/package-lock.json
index c46d6cf..a0f2abc 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -732,6 +732,334 @@
"node": ">=18"
}
},
+ "node_modules/@inquirer/ansi": {
+ "version": "2.0.9",
+ "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.9.tgz",
+ "integrity": "sha512-0Ywt3S8tqM6TWUcsRlBFQ1x+X3/o8kktX0ZiKAnByYb9GFDknnOhse1PVtfiD2BXPI8ar+BWx9PV9R0lQIcygw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ }
+ },
+ "node_modules/@inquirer/checkbox": {
+ "version": "5.2.7",
+ "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-5.2.7.tgz",
+ "integrity": "sha512-/+QmGE/9bvE/EobaZDnzYe+T+QWoJrnmxwBQNtoi2OVSUR9d1znYsNyEoUrOZvFSxDYttrhzRIpXpaLkN+iIsg==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/ansi": "^2.0.9",
+ "@inquirer/core": "^12.0.5",
+ "@inquirer/figures": "^2.0.9",
+ "@inquirer/type": "4.2.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/confirm": {
+ "version": "6.3.4",
+ "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.3.4.tgz",
+ "integrity": "sha512-ZwnaZZDa1zxsyVrN32s447ydMnKcw7e8WWNT+R+Qsu0zAn8Rs6yi9d1B80Kob1Ul2cfUi7t8JD2t4/K7uEZpqA==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^12.0.5",
+ "@inquirer/type": "4.2.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/core": {
+ "version": "12.0.5",
+ "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-12.0.5.tgz",
+ "integrity": "sha512-c0ZSnO9oVk/IlEGoZK3u8b3IZQeu9I6jUkXJSQnQEVRXsjKvtAq3AGqFL2LgfJhlzMZne08pZHWRWasIcI3Rew==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/ansi": "^2.0.9",
+ "@inquirer/figures": "^2.0.9",
+ "@inquirer/type": "4.2.0",
+ "cli-width": "^4.1.0",
+ "fast-wrap-ansi": "^0.2.0",
+ "mute-stream": "^3.0.0",
+ "signal-exit": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/editor": {
+ "version": "5.3.5",
+ "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-5.3.5.tgz",
+ "integrity": "sha512-6lU3/pPx5z3lHWejFW061MV4qZooBQYv/+EeGhNOPiP/i+hrYsHfxxBnnDGsAfg8YdLUd69YckoeOjtr3QuAUg==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^12.0.5",
+ "@inquirer/external-editor": "^3.0.6",
+ "@inquirer/type": "4.2.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/expand": {
+ "version": "5.1.7",
+ "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.1.7.tgz",
+ "integrity": "sha512-eiJ31YFCaB6fLoJCqLIn8S6eqUyME6vwr8KcP5h8cxmA+bV9RRVPO+kywoxb7G63HduDXV6sN/SM7o2R+ahEcQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^12.0.5",
+ "@inquirer/type": "4.2.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/external-editor": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-3.0.6.tgz",
+ "integrity": "sha512-rWmw6WG8JZ7LMn/srXEylYGhL6EXXJeROE7/4x4GREh6NgzqJBDbIgpNGsYoLPfobeb4VZtEYzPGnT5EFNYhiQ==",
+ "license": "MIT",
+ "dependencies": {
+ "chardet": "^2.1.1",
+ "iconv-lite": "^0.7.2"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/figures": {
+ "version": "2.0.9",
+ "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.9.tgz",
+ "integrity": "sha512-EAWgUTGQ/Umgga51dE3B2PUHbufuXarDfg86uVgoSgNHNNQnyFKcOrQLWVqYMghuSyHh8+2HUH0Js9cTC1WAdg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ }
+ },
+ "node_modules/@inquirer/input": {
+ "version": "5.1.8",
+ "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-5.1.8.tgz",
+ "integrity": "sha512-psOSTgkL8y/OtgJJYbqJ0oISr2QBE0U1Ro/qQdA/EKjeJiwiUTQgQmq8o4ESNzVOWthIeh3YLD7BCUR9dKnR5g==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^12.0.5",
+ "@inquirer/type": "4.2.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/number": {
+ "version": "4.2.5",
+ "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-4.2.5.tgz",
+ "integrity": "sha512-lEy7LWsdF5qHx5QjHZqabUqM9P7i5uTMCt8GRzqxmwXXKbapKJDA+ucVflVVPAyj4snD5DTAD4L+sct85XOlOQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^12.0.5",
+ "@inquirer/type": "4.2.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/password": {
+ "version": "5.2.4",
+ "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-5.2.4.tgz",
+ "integrity": "sha512-T7ir3fflSSVCYEVqNyMBq+pIMsilQRtbZcD5gxn6Ewsin5TJWBxrGBdXveWtmeXVAeoInfhS+BhBUZaL4sFSDg==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/ansi": "^2.0.9",
+ "@inquirer/core": "^12.0.5",
+ "@inquirer/type": "4.2.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/prompts": {
+ "version": "8.7.4",
+ "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-8.7.4.tgz",
+ "integrity": "sha512-SAJt+QhY5rOJAIgZBw9TrHWfgrp6wsb9cqRCyqax+Hl6EiFfRXmD9EsIWkST8yq/dQ8H46Is2Sr/JG7Ls/LQ+Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/checkbox": "^5.2.7",
+ "@inquirer/confirm": "^6.3.4",
+ "@inquirer/editor": "^5.3.5",
+ "@inquirer/expand": "^5.1.7",
+ "@inquirer/input": "^5.1.8",
+ "@inquirer/number": "^4.2.5",
+ "@inquirer/password": "^5.2.4",
+ "@inquirer/rawlist": "^5.3.7",
+ "@inquirer/search": "^4.3.5",
+ "@inquirer/select": "^5.2.7"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/rawlist": {
+ "version": "5.3.7",
+ "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-5.3.7.tgz",
+ "integrity": "sha512-XveEe8v3BHj9ec00n+9i8FHjWhXjS6+jCTizYvXCqKUKtgkrq9xid8S5j3mYGW96qfxG3mwNoud3m3v8GDk9Pw==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^12.0.5",
+ "@inquirer/type": "4.2.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/search": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-4.3.5.tgz",
+ "integrity": "sha512-kIUecMugEN2YTvTmff+uYz0nAE0f9RFNDVZknfrh264vAQM9P8tnsXiUp7z8XbGuNIBEtFMJhvc9QquawpC46A==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/core": "^12.0.5",
+ "@inquirer/figures": "^2.0.9",
+ "@inquirer/type": "4.2.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/select": {
+ "version": "5.2.7",
+ "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.2.7.tgz",
+ "integrity": "sha512-pRDWO4dTqSAvFQdO8yclKMtXNDm9K9HmvWB5UZmT3clw2OlOBNXveHzhyFmO/0d0yJMqlPcNITus1Jtpm6t8VQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@inquirer/ansi": "^2.0.9",
+ "@inquirer/core": "^12.0.5",
+ "@inquirer/figures": "^2.0.9",
+ "@inquirer/type": "4.2.0"
+ },
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@inquirer/type": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.2.0.tgz",
+ "integrity": "sha512-2rnHX8RPo4glJYqnFc/v3nQeIhDcjyRRyaT7MGcfL/8xv/8K03SXYoA2tX06WVSKywWOE/ncbG3dtuzLjR5TCQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=23.5.0 || ^22.13.0 || ^20.17.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">=18"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -1516,7 +1844,7 @@
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
- "dev": true,
+ "devOptional": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
@@ -2040,6 +2368,12 @@
"node": ">=18"
}
},
+ "node_modules/chardet": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.2.0.tgz",
+ "integrity": "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA==",
+ "license": "MIT"
+ },
"node_modules/chokidar": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz",
@@ -2056,6 +2390,15 @@
"url": "https://paulmillr.com/funding/"
}
},
+ "node_modules/cli-width": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz",
+ "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
"node_modules/codelineage": {
"resolved": "packages/cli",
"link": true
@@ -2167,6 +2510,30 @@
"node": ">=12.0.0"
}
},
+ "node_modules/fast-string-truncated-width": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz",
+ "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==",
+ "license": "MIT"
+ },
+ "node_modules/fast-string-width": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz",
+ "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-string-truncated-width": "^3.0.2"
+ }
+ },
+ "node_modules/fast-wrap-ansi": {
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz",
+ "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-string-width": "^3.0.2"
+ }
+ },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -2212,6 +2579,22 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
+ "node_modules/iconv-lite": {
+ "version": "0.7.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
+ "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
"node_modules/joycon": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",
@@ -2579,6 +2962,15 @@
"ufo": "^1.6.3"
}
},
+ "node_modules/mute-stream": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz",
+ "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==",
+ "license": "ISC",
+ "engines": {
+ "node": "^20.17.0 || >=22.9.0"
+ }
+ },
"node_modules/mz": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz",
@@ -2862,6 +3254,24 @@
"fsevents": "~2.3.2"
}
},
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "license": "MIT"
+ },
+ "node_modules/signal-exit": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
+ "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
"node_modules/source-map-js": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
@@ -3088,7 +3498,7 @@
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
- "dev": true,
+ "devOptional": true,
"license": "MIT"
},
"node_modules/vite": {
@@ -3290,6 +3700,7 @@
"version": "0.1.0",
"license": "MIT",
"dependencies": {
+ "@inquirer/prompts": "^8.7.4",
"commander": "^15.0.0",
"zod": "^4.6.7"
},
diff --git a/package.json b/package.json
index 0a90015..fe0df99 100644
--- a/package.json
+++ b/package.json
@@ -6,7 +6,7 @@
"packages/*"
],
"engines": {
- "node": ">=22.12.0"
+ "node": ">=22.13.0"
},
"scripts": {
"build": "npm run build --workspaces --if-present",
diff --git a/packages/cli/package.json b/packages/cli/package.json
index d36fa56..5870647 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -11,7 +11,7 @@
"dist"
],
"engines": {
- "node": ">=22.12.0"
+ "node": ">=22.13.0"
},
"scripts": {
"build": "tsup"
@@ -20,6 +20,7 @@
"tsup": "^9.0.0"
},
"dependencies": {
+ "@inquirer/prompts": "^8.7.4",
"commander": "^15.0.0",
"zod": "^4.6.7"
}
diff --git a/packages/cli/src/claude-settings.ts b/packages/cli/src/claude-settings.ts
new file mode 100644
index 0000000..8afde5e
--- /dev/null
+++ b/packages/cli/src/claude-settings.ts
@@ -0,0 +1,52 @@
+import { copyFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { atomicWriteJson, readJson } from "./store/fs.js";
+
+/** Claude Code's own default, see the cleanupPeriodDays docs. */
+export const CLAUDE_DEFAULT_RETENTION = 30;
+
+export function claudeSettingsPath(env: NodeJS.ProcessEnv): string {
+ return join(env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude"), "settings.json");
+}
+
+async function readSettings(file: string): Promise<Record<string, unknown> | undefined> {
+ const read = await readJson(file);
+ if (!read.found) return {};
+ if ("error" in read) return undefined;
+ const v = read.value;
+ return typeof v === "object" && v !== null && !Array.isArray(v)
+ ? (v as Record<string, unknown>)
+ : undefined;
+}
+
+/** Current transcript retention in days; undefined if the settings file is unreadable. */
+export async function readRetention(env: NodeJS.ProcessEnv): Promise<number | undefined> {
+ const settings = await readSettings(claudeSettingsPath(env));
+ if (!settings) return undefined;
+ const days = settings.cleanupPeriodDays;
+ return typeof days === "number" ? days : CLAUDE_DEFAULT_RETENTION;
+}
+
+/**
+ * Sets `cleanupPeriodDays` in the user's Claude Code settings, keeping every other
+ * key. Backs up an existing file first; refuses to touch a file it cannot parse.
+ */
+export async function setRetention(
+ days: number,
+ env: NodeJS.ProcessEnv,
+ stamp: string,
+): Promise<{ file: string; backup?: string }> {
+ if (!Number.isInteger(days) || days < 1)
+ throw new Error("retention must be a whole number of days, at least 1");
+ const file = claudeSettingsPath(env);
+ const settings = await readSettings(file);
+ if (!settings) throw new Error(`${file} is not a valid JSON object; not changing it`);
+ let backup: string | undefined;
+ if (Object.keys(settings).length > 0) {
+ backup = `${file}.codelineage-bak-${stamp.replace(/[:.]/g, "-")}`;
+ await copyFile(file, backup);
+ }
+ await atomicWriteJson(file, { ...settings, cleanupPeriodDays: days });
+ return backup ? { file, backup } : { file };
+}
diff --git a/packages/cli/src/commands/config.ts b/packages/cli/src/commands/config.ts
new file mode 100644
index 0000000..7f93028
--- /dev/null
+++ b/packages/cli/src/commands/config.ts
@@ -0,0 +1,50 @@
+import { CliError, type Io } from "../io.js";
+import { Config } from "../schema/config.js";
+import { loadConfig, updateConfig } from "../store/stores.js";
+
+export const CONFIG_KEYS = Object.keys(Config.shape).filter((k) => k !== "schema") as Exclude<
+ keyof Config,
+ "schema"
+>[];
+
+function assertKey(key: string): asserts key is (typeof CONFIG_KEYS)[number] {
+ if (!(CONFIG_KEYS as string[]).includes(key)) {
+ throw new CliError(`unknown key "${key}"; one of: ${CONFIG_KEYS.join(", ")}`);
+ }
+}
+
+/** Command-line text to a value: JSON when it parses, comma lists for arrays, else a string. */
+function parseValue(key: string, raw: string): unknown {
+ if (key === "agents" && !raw.trim().startsWith("[")) {
+ return raw
+ .split(",")
+ .map((s) => s.trim())
+ .filter(Boolean);
+ }
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return raw;
+ }
+}
+
+export async function configGet(key: string | undefined, io: Io): Promise<void> {
+ const config = await loadConfig(io.env);
+ if (key === undefined) {
+ for (const k of CONFIG_KEYS) io.out(`${k} = ${JSON.stringify(config[k])}`);
+ return;
+ }
+ assertKey(key);
+ io.out(JSON.stringify(config[key]));
+}
+
+export async function configSet(key: string, raw: string, io: Io): Promise<void> {
+ assertKey(key);
+ const value = parseValue(key, raw);
+ const next = Config.safeParse({ ...(await loadConfig(io.env)), [key]: value });
+ if (!next.success) {
+ throw new CliError(`invalid value for ${key}: ${next.error.issues[0]?.message ?? "rejected"}`);
+ }
+ await updateConfig((c) => ({ ...c, [key]: next.data[key] }), io.env);
+ io.out(`${key} = ${JSON.stringify(next.data[key])}`);
+}
diff --git a/packages/cli/src/commands/epoch.ts b/packages/cli/src/commands/epoch.ts
new file mode 100644
index 0000000..689e3d7
--- /dev/null
+++ b/packages/cli/src/commands/epoch.ts
@@ -0,0 +1,30 @@
+import { resolve } from "node:path";
+import { CliError, type Io } from "../io.js";
+import { Slug } from "../schema/common.js";
+import { loadProject, updateProject } from "../store/stores.js";
+
+export async function epochAdd(dir: string, id: string, title: string, io: Io): Promise<void> {
+ const root = resolve(dir);
+ if (!Slug.safeParse(id).success) {
+ throw new CliError(`invalid epoch id "${id}": use letters, digits, _ . -`);
+ }
+ const project = await loadProject(root);
+ if (!project.found)
+ throw new CliError(`${root} is not initialized; run \`codelineage init\` first`);
+ if (!project.ok) throw new CliError(project.error);
+
+ let added = false;
+ await updateProject(root, (cur) => {
+ const p = cur ?? project.data;
+ const same = p.epochs.find((e) => e.id === id);
+ if (same) {
+ if (same.title !== title) {
+ throw new CliError(`epoch "${id}" already exists with title "${same.title}"`);
+ }
+ return p;
+ }
+ added = true;
+ return { ...p, epochs: [...p.epochs, { id, title, createdAt: io.now() }] };
+ });
+ io.out(added ? `Added epoch ${id}: ${title}` : `Epoch ${id} already exists`);
+}
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
new file mode 100644
index 0000000..9ff56b1
--- /dev/null
+++ b/packages/cli/src/commands/init.ts
@@ -0,0 +1,138 @@
+import { mkdir } from "node:fs/promises";
+import { basename, resolve } from "node:path";
+import { CLAUDE_DEFAULT_RETENTION, readRetention, setRetention } from "../claude-settings.js";
+import { ensureGitignore, findGitRoot, type GitPolicy } from "../git.js";
+import { CliError, type Io } from "../io.js";
+import { readJson } from "../store/fs.js";
+import { globalPaths, projectPaths } from "../store/paths.js";
+import {
+ loadConfig,
+ loadProject,
+ updateConfig,
+ updateProject,
+ updateRegistry,
+} from "../store/stores.js";
+
+export interface InitOptions {
+ name?: string;
+ git?: GitPolicy;
+ language?: string;
+ /** Days, or "keep" to leave Claude Code's setting alone. */
+ retention?: number | "keep";
+}
+
+/** Below this, init offers to raise Claude Code's transcript retention. */
+const RETENTION_FLOOR = 90;
+
+async function bestEffort(io: Io, what: string, fn: () => Promise<unknown>): Promise<boolean> {
+ try {
+ await fn();
+ return true;
+ } catch (err) {
+ io.warn(`${what}: ${(err as Error).message}`);
+ return false;
+ }
+}
+
+async function askRetention(io: Io, opts: InitOptions): Promise<void> {
+ const current = await readRetention(io.env);
+ if (current === undefined) {
+ io.warn("could not read Claude Code settings; transcript retention left unchanged");
+ return;
+ }
+ let choice = opts.retention;
+ if (choice === undefined) {
+ if (current >= RETENTION_FLOOR) {
+ io.out(`Claude Code keeps transcripts for ${current} days.`);
+ return;
+ }
+ const picked = await io.prompt.select(
+ `Claude Code deletes transcripts after ${current} days${current === CLAUDE_DEFAULT_RETENTION ? " (its default)" : ""}. ` +
+ "Older sessions can then no longer be resumed or backfilled. Keep them longer?",
+ [
+ { value: "keep", name: `Keep ${current} days` },
+ { value: "90", name: "90 days" },
+ { value: "365", name: "1 year" },
+ { value: "3650", name: "10 years" },
+ ],
+ "keep",
+ );
+ choice = picked === "keep" ? "keep" : Number(picked);
+ }
+ if (choice === "keep" || choice === current) return;
+ const { file, backup } = await setRetention(choice, io.env, io.now());
+ io.out(`Set cleanupPeriodDays to ${choice} in ${file}${backup ? ` (backup: ${backup})` : ""}.`);
+}
+
+async function askLanguage(io: Io, opts: InitOptions): Promise<void> {
+ const firstRun = !(await readJson(globalPaths(io.env).config)).found;
+ if (!firstRun && opts.language === undefined) return;
+ let language = opts.language;
+ if (language === undefined) {
+ const mode = await io.prompt.select(
+ "Language for session summaries?",
+ [
+ { value: "auto", name: "Same as the conversation (auto)" },
+ { value: "fixed", name: "Always one language" },
+ ],
+ "auto",
+ );
+ language = mode === "auto" ? "auto" : await io.prompt.input("Which language?", "English");
+ }
+ const lang = language;
+ await bestEffort(io, "could not save global config", () =>
+ updateConfig((c) => ({ ...c, language: lang }), io.env),
+ );
+}
+
+async function register(io: Io, root: string, name: string): Promise<void> {
+ await bestEffort(io, "could not register the project in the global panel", () =>
+ updateRegistry(
+ (r) =>
+ r.projects.some((p) => p.path === root)
+ ? r
+ : { ...r, projects: [...r.projects, { path: root, name, addedAt: io.now() }] },
+ io.env,
+ ),
+ );
+}
+
+export async function init(dir: string, opts: InitOptions, io: Io): Promise<void> {
+ const root = resolve(dir);
+ const existing = await loadProject(root);
+ if (existing.found) {
+ if (!existing.ok) throw new CliError(`${projectPaths(root).project}: ${existing.error}`);
+ await register(io, root, existing.data.name);
+ io.out(`Already initialized: ${existing.data.name} (${root})`);
+ return;
+ }
+
+ const name = opts.name ?? (await io.prompt.input("Project name?", basename(root)));
+
+ const gitRoot = await findGitRoot(root);
+ if (gitRoot) {
+ const fallback = (await loadConfig(io.env)).gitPolicy;
+ const policy =
+ opts.git ??
+ (await io.prompt.select<GitPolicy>(
+ "This is a git repository. Commit the lineage records?",
+ [
+ { value: "ignore", name: "No, keep .codelineage/ out of git (private)" },
+ { value: "commit", name: "Yes, commit session records (local state stays ignored)" },
+ ],
+ fallback,
+ ));
+ const added = await ensureGitignore(root, policy);
+ if (added.length > 0) io.out(`Added to .gitignore: ${added.join(", ")}`);
+ }
+
+ await askRetention(io, opts);
+ await askLanguage(io, opts);
+
+ await updateProject(root, (cur) => cur ?? { schema: 1, name, epochs: [] });
+ await mkdir(projectPaths(root).sessions, { recursive: true });
+ await register(io, root, name);
+
+ io.out(`Initialized ${name} in ${projectPaths(root).base}`);
+ io.out("Next: install the Claude Code plugin, then run `codelineage open` after a session.");
+}
diff --git a/packages/cli/src/git.ts b/packages/cli/src/git.ts
new file mode 100644
index 0000000..b350eed
--- /dev/null
+++ b/packages/cli/src/git.ts
@@ -0,0 +1,46 @@
+import { readFile, stat } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { atomicWrite } from "./store/fs.js";
+
+export type GitPolicy = "ignore" | "commit";
+
+/** Walks up from `dir` looking for `.git` (a directory, or a file in worktrees). */
+export async function findGitRoot(dir: string): Promise<string | undefined> {
+ for (let cur = dir; ; cur = dirname(cur)) {
+ if (
+ await stat(join(cur, ".git")).then(
+ () => true,
+ () => false,
+ )
+ )
+ return cur;
+ if (dirname(cur) === cur) return undefined;
+ }
+}
+
+const HEADER = "# codelineage";
+
+/** Machine-local data that must never be committed, whatever the policy. */
+const ALWAYS = [
+ "/.codelineage/state/",
+ "/.codelineage/snapshots/",
+ "/.codelineage/locks/",
+ "/.codelineage/lineage.html",
+];
+
+export function gitignoreLines(policy: GitPolicy): string[] {
+ return policy === "ignore" ? ["/.codelineage/"] : ALWAYS;
+}
+
+/** Appends the policy's lines to `<root>/.gitignore`, skipping lines already there. */
+export async function ensureGitignore(root: string, policy: GitPolicy): Promise<string[]> {
+ const file = join(root, ".gitignore");
+ const text = await readFile(file, "utf8").catch(() => "");
+ const present = new Set(text.split(/\r?\n/).map((l) => l.trim()));
+ const missing = gitignoreLines(policy).filter((l) => !present.has(l));
+ if (missing.length === 0) return [];
+ const block = [present.has(HEADER) ? [] : [HEADER], missing].flat().join("\n");
+ const sep = text === "" || text.endsWith("\n") ? "" : "\n";
+ await atomicWrite(file, `${text}${sep}${block}\n`);
+ return missing;
+}
diff --git a/packages/cli/src/io.ts b/packages/cli/src/io.ts
new file mode 100644
index 0000000..665e089
--- /dev/null
+++ b/packages/cli/src/io.ts
@@ -0,0 +1,46 @@
+import { confirm, input, select } from "@inquirer/prompts";
+
+export class CliError extends Error {}
+
+export interface Choice<T extends string> {
+ value: T;
+ name: string;
+}
+
+/** Interactive questions; tests and `--yes` swap in non-interactive versions. */
+export interface Prompter {
+ select<T extends string>(message: string, choices: Choice<T>[], fallback: T): Promise<T>;
+ input(message: string, fallback: string): Promise<string>;
+ confirm(message: string, fallback: boolean): Promise<boolean>;
+}
+
+export interface Io {
+ prompt: Prompter;
+ out: (line: string) => void;
+ warn: (line: string) => void;
+ env: NodeJS.ProcessEnv;
+ now: () => string;
+}
+
+export const inquirerPrompter: Prompter = {
+ select: (message, choices, fallback) => select({ message, choices, default: fallback }),
+ input: (message, fallback) => input({ message, default: fallback }),
+ confirm: (message, fallback) => confirm({ message, default: fallback }),
+};
+
+/** Answers every question with its default. */
+export const defaultsPrompter: Prompter = {
+ select: async (_m, _c, fallback) => fallback,
+ input: async (_m, fallback) => fallback,
+ confirm: async (_m, fallback) => fallback,
+};
+
+export function processIo(interactive: boolean): Io {
+ return {
+ prompt: interactive ? inquirerPrompter : defaultsPrompter,
+ out: (line) => process.stdout.write(`${line}\n`),
+ warn: (line) => process.stderr.write(`warning: ${line}\n`),
+ env: process.env,
+ now: () => new Date().toISOString(),
+ };
+}
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index 8661082..a8461c4 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -1,6 +1,77 @@
-import { Command } from "commander";
+import { Command, InvalidArgumentError, Option } from "commander";
import pkg from "../package.json" with { type: "json" };
+import { configGet, configSet } from "./commands/config.js";
+import { epochAdd } from "./commands/epoch.js";
+import { type InitOptions, init } from "./commands/init.js";
+import { CliError, type Io, processIo } from "./io.js";
-export function createProgram(): Command {
- return new Command().name("codelineage").description(pkg.description).version(pkg.version);
+export type IoFactory = (interactive: boolean) => Io;
+
+function retention(value: string): number | "keep" {
+ if (value === "keep") return value;
+ const days = Number(value);
+ if (!Number.isInteger(days) || days < 1) throw new InvalidArgumentError("days (>= 1) or keep");
+ return days;
+}
+
+export function createProgram(makeIo: IoFactory = processIo): Command {
+ const program = new Command()
+ .name("codelineage")
+ .description(pkg.description)
+ .version(pkg.version);
+
+ /** Errors meant for the user print as one line and set exit code 1. */
+ const run =
+ <A extends unknown[]>(fn: (...args: A) => Promise<void>) =>
+ async (...args: A) => {
+ try {
+ await fn(...args);
+ } catch (err) {
+ if (!(err instanceof CliError)) throw err;
+ program.error(`error: ${err.message}`, { exitCode: 1 });
+ }
+ };
+
+ program
+ .command("init")
+ .description("set up .codelineage/ in a project and register it")
+ .argument("[dir]", "project directory", ".")
+ .option("--name <name>", "project name")
+ .addOption(
+ new Option("--git <policy>", "commit or ignore .codelineage/").choices(["ignore", "commit"]),
+ )
+ .option("--language <lang>", 'summary language: "auto" or a language')
+ .option("--retention <days>", 'Claude Code transcript retention, or "keep"', retention)
+ .option("-y, --yes", "accept defaults for every question")
+ .action(
+ run(async (dir: string, opts: InitOptions & { yes?: boolean }) => {
+ const { yes, ...rest } = opts;
+ await init(dir, rest, makeIo(!yes && process.stdin.isTTY === true));
+ }),
+ );
+
+ const config = program.command("config").description("read or change global settings");
+ config
+ .command("get")
+ .argument("[key]")
+ .action(run(async (key?: string) => configGet(key, makeIo(false))));
+ config
+ .command("set")
+ .argument("<key>")
+ .argument("<value>")
+ .action(run(async (key: string, value: string) => configSet(key, value, makeIo(false))));
+
+ const epoch = program.command("epoch").description("manage epochs (features, epics)");
+ epoch
+ .command("add")
+ .argument("<id>", "short id, e.g. e2e")
+ .argument("<title>")
+ .option("-C, --dir <dir>", "project directory", ".")
+ .action(
+ run(async (id: string, title: string, opts: { dir: string }) =>
+ epochAdd(opts.dir, id, title, makeIo(false)),
+ ),
+ );
+
+ return program;
}
diff --git a/packages/cli/src/store/fs.ts b/packages/cli/src/store/fs.ts
index 15c841c..809dd39 100644
--- a/packages/cli/src/store/fs.ts
+++ b/packages/cli/src/store/fs.ts
@@ -37,7 +37,9 @@ export async function readJson(file: string): Promise<JsonRead> {
try {
text = await readFile(file, "utf8");
} catch (err) {
- if ((err as NodeJS.ErrnoException).code === "ENOENT") return { found: false };
+ // ENOTDIR: a path component is a file, so this file cannot exist either
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code === "ENOENT" || code === "ENOTDIR") return { found: false };
throw err;
}
try {
diff --git a/packages/cli/test/bundle.test.ts b/packages/cli/test/bundle.test.ts
new file mode 100644
index 0000000..13d542e
--- /dev/null
+++ b/packages/cli/test/bundle.test.ts
@@ -0,0 +1,31 @@
+import { execFile } from "node:child_process";
+import { mkdir } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { promisify } from "node:util";
+import { beforeAll, describe, expect, it } from "vitest";
+import pkg from "../package.json" with { type: "json" };
+import { envFor, tempDir } from "./helpers.js";
+
+const run = promisify(execFile);
+const pkgDir = join(dirname(fileURLToPath(import.meta.url)), "..");
+
+// Bundling can break at runtime in ways unit tests never see (CJS deps in ESM).
+describe("bundled CLI", () => {
+ let out: string;
+ beforeAll(async () => {
+ out = await tempDir();
+ await run("npx", ["tsup", "--out-dir", out, "--silent"], { cwd: pkgDir });
+ }, 60_000);
+
+ it("starts and runs init end to end", async () => {
+ const dir = await tempDir();
+ const root = join(dir, "proj");
+ await mkdir(root);
+ const env = { ...process.env, ...envFor(dir) };
+ const cli = (...args: string[]) =>
+ run("node", [join(out, "cli.js"), ...args], { env, cwd: root });
+ expect((await cli("--version")).stdout.trim()).toBe(pkg.version);
+ expect((await cli("init", "--yes")).stdout).toMatch(/Initialized proj/);
+ });
+});
diff --git a/packages/cli/test/config-epoch.test.ts b/packages/cli/test/config-epoch.test.ts
new file mode 100644
index 0000000..903c2e0
--- /dev/null
+++ b/packages/cli/test/config-epoch.test.ts
@@ -0,0 +1,77 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+import { configGet, configSet } from "../src/commands/config.js";
+import { epochAdd } from "../src/commands/epoch.js";
+import { init } from "../src/commands/init.js";
+import { CliError } from "../src/io.js";
+import { loadConfig, loadProject } from "../src/store/stores.js";
+import { envFor, fakeIo, tempDir } from "./helpers.js";
+
+let dir: string;
+let env: NodeJS.ProcessEnv;
+beforeEach(async () => {
+ dir = await tempDir();
+ env = envFor(dir);
+});
+
+describe("config", () => {
+ it("prints all settings or one", async () => {
+ const io = fakeIo(env);
+ await configGet(undefined, io);
+ expect(io.lines).toContain("updateEveryTurns = 5");
+ await configGet("gitPolicy", io);
+ expect(io.lines.at(-1)).toBe('"ignore"');
+ });
+
+ it("sets numbers, booleans, strings and agent lists", async () => {
+ const io = fakeIo(env);
+ await configSet("updateEveryTurns", "3", io);
+ await configSet("sessionEndCatchUp", "false", io);
+ await configSet("language", "Turkish", io);
+ await configSet("agents", "claude-code, codex", io);
+ expect(await loadConfig(env)).toMatchObject({
+ updateEveryTurns: 3,
+ sessionEndCatchUp: false,
+ language: "Turkish",
+ agents: ["claude-code", "codex"],
+ });
+ await configSet("agents", '["claude-code"]', io);
+ expect((await loadConfig(env)).agents).toEqual(["claude-code"]);
+ });
+
+ it("rejects unknown keys and invalid values", async () => {
+ await expect(configSet("schema", "2", fakeIo(env))).rejects.toThrow(/unknown key/);
+ await expect(configGet("nope", fakeIo(env))).rejects.toBeInstanceOf(CliError);
+ await expect(configSet("updateEveryTurns", "0", fakeIo(env))).rejects.toThrow(/invalid value/);
+ await expect(configSet("gitPolicy", "maybe", fakeIo(env))).rejects.toThrow(/invalid value/);
+ });
+});
+
+describe("epoch add", () => {
+ let root: string;
+ beforeEach(async () => {
+ root = join(dir, "proj");
+ await mkdir(root);
+ });
+
+ it("adds an epoch once and accepts a repeat with the same title", async () => {
+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(env));
+ const io = fakeIo(env);
+ await epochAdd(root, "e2e", "E2E setup", io);
+ await epochAdd(root, "e2e", "E2E setup", io);
+ expect(io.lines).toEqual(["Added epoch e2e: E2E setup", "Epoch e2e already exists"]);
+ expect(await loadProject(root)).toMatchObject({
+ data: { epochs: [{ id: "e2e", title: "E2E setup", createdAt: "2026-10-21T10:00:00.000Z" }] },
+ });
+ await expect(epochAdd(root, "e2e", "Other", io)).rejects.toThrow(/already exists/);
+ });
+
+ it("rejects bad ids and uninitialized or corrupt projects", async () => {
+ await expect(epochAdd(root, "../x", "t", fakeIo(env))).rejects.toThrow(/invalid epoch id/);
+ await expect(epochAdd(root, "e1", "t", fakeIo(env))).rejects.toThrow(/not initialized/);
+ await mkdir(join(root, ".codelineage"));
+ await writeFile(join(root, ".codelineage", "project.json"), '{"schema":1}');
+ await expect(epochAdd(root, "e1", "t", fakeIo(env))).rejects.toThrow(/name/);
+ });
+});
diff --git a/packages/cli/test/helpers.ts b/packages/cli/test/helpers.ts
new file mode 100644
index 0000000..e704449
--- /dev/null
+++ b/packages/cli/test/helpers.ts
@@ -0,0 +1,53 @@
+import { mkdtemp } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type { Io, Prompter } from "../src/io.js";
+
+export const T0 = "2026-10-21T10:00:00.000Z";
+
+export async function tempDir(): Promise<string> {
+ return mkdtemp(join(tmpdir(), "codelineage-"));
+}
+
+export interface FakeIo extends Io {
+ lines: string[];
+ warnings: string[];
+ asked: string[];
+}
+
+/**
+ * Answers questions in order from `answers`; an exhausted queue falls back to the
+ * question's default. Pass `strict` to fail on any question at all.
+ */
+export function fakeIo(env: NodeJS.ProcessEnv, answers: string[] = [], strict = false): FakeIo {
+ const asked: string[] = [];
+ const next = <T>(message: string, fallback: T): T => {
+ if (strict) throw new Error(`unexpected question: ${message}`);
+ asked.push(message);
+ const a = answers.shift();
+ return (a === undefined ? fallback : a) as T;
+ };
+ const prompt: Prompter = {
+ select: async (m, _c, f) => next(m, f),
+ input: async (m, f) => next(m, f),
+ confirm: async (m, f) => {
+ const a = next<string | boolean>(m, f);
+ return a === true || a === "yes";
+ },
+ };
+ const io: FakeIo = {
+ prompt,
+ lines: [],
+ warnings: [],
+ asked,
+ env,
+ now: () => T0,
+ out: (l) => io.lines.push(l),
+ warn: (l) => io.warnings.push(l),
+ };
+ return io;
+}
+
+export function envFor(dir: string): NodeJS.ProcessEnv {
+ return { CODELINEAGE_HOME: join(dir, "home"), CLAUDE_CONFIG_DIR: join(dir, "claude") };
+}
diff --git a/packages/cli/test/init.test.ts b/packages/cli/test/init.test.ts
new file mode 100644
index 0000000..5c56797
--- /dev/null
+++ b/packages/cli/test/init.test.ts
@@ -0,0 +1,169 @@
+import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
+import { basename, join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+import { readRetention, setRetention } from "../src/claude-settings.js";
+import { init } from "../src/commands/init.js";
+import { ensureGitignore, findGitRoot } from "../src/git.js";
+import { loadConfig, loadProject, loadRegistry } from "../src/store/stores.js";
+import { envFor, fakeIo, T0, tempDir } from "./helpers.js";
+
+let dir: string;
+let root: string;
+let env: NodeJS.ProcessEnv;
+beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "proj");
+ await mkdir(root);
+ env = envFor(dir);
+});
+
+const settingsFile = () => join(dir, "claude", "settings.json");
+const readText = (f: string) => readFile(f, "utf8");
+
+describe("init", () => {
+ it("creates the project with defaults and registers it", async () => {
+ const io = fakeIo(env);
+ await init(root, {}, io);
+ expect(await loadProject(root)).toMatchObject({ ok: true, data: { name: "proj", epochs: [] } });
+ expect(await readdir(join(root, ".codelineage"))).toContain("sessions");
+ expect(await loadRegistry(env)).toMatchObject({
+ ok: true,
+ data: { projects: [{ path: root, name: "proj" }] },
+ });
+ expect((await loadConfig(env)).language).toBe("auto");
+ // not a git repo: name, retention and language were asked
+ expect(io.asked).toHaveLength(3);
+ expect(io.lines.at(-2)).toMatch(/^Initialized proj/);
+ });
+
+ it("asks nothing when every answer is given as an option", async () => {
+ await mkdir(join(root, ".git"));
+ const io = fakeIo(env, [], true);
+ await init(root, { name: "P", git: "commit", retention: "keep", language: "Turkish" }, io);
+ expect((await loadConfig(env)).language).toBe("Turkish");
+ expect(await readText(join(root, ".gitignore"))).toContain("/.codelineage/snapshots/");
+ });
+
+ it("asks for the git policy in a repo and writes .gitignore", async () => {
+ await mkdir(join(root, ".git"));
+ const io = fakeIo(env, ["proj", "ignore"]);
+ await init(root, {}, io);
+ expect(await readText(join(root, ".gitignore"))).toBe("# codelineage\n/.codelineage/\n");
+ expect(io.lines).toContain("Added to .gitignore: /.codelineage/");
+ });
+
+ it("raises transcript retention when asked, keeping other settings", async () => {
+ await mkdir(join(dir, "claude"));
+ await writeFile(settingsFile(), JSON.stringify({ model: "x" }));
+ const io = fakeIo(env, ["proj", "365"]);
+ await init(root, {}, io);
+ expect(JSON.parse(await readText(settingsFile()))).toEqual({
+ model: "x",
+ cleanupPeriodDays: 365,
+ });
+ const files = await readdir(join(dir, "claude"));
+ expect(files.some((f) => f.startsWith("settings.json.codelineage-bak-"))).toBe(true);
+ expect(io.lines.some((l) => l.includes("Set cleanupPeriodDays to 365"))).toBe(true);
+ });
+
+ it("does not ask about retention when it is already long", async () => {
+ await mkdir(join(dir, "claude"));
+ await writeFile(settingsFile(), JSON.stringify({ cleanupPeriodDays: 365 }));
+ const io = fakeIo(env);
+ await init(root, {}, io);
+ expect(io.lines).toContain("Claude Code keeps transcripts for 365 days.");
+ expect(io.asked).toHaveLength(2);
+ });
+
+ it("applies a retention option without asking, and skips an unchanged one", async () => {
+ await init(root, { name: "p", retention: 90, language: "auto" }, fakeIo(env, [], true));
+ expect(await readRetention(env)).toBe(90);
+ const again = join(dir, "other");
+ await mkdir(again);
+ const io = fakeIo(env, [], true);
+ await init(again, { name: "o", retention: 90 }, io);
+ expect(io.lines.some((l) => l.includes("cleanupPeriodDays"))).toBe(false);
+ });
+
+ it("warns and moves on when Claude Code settings are unreadable", async () => {
+ await mkdir(join(dir, "claude"));
+ await writeFile(settingsFile(), "{oops");
+ const io = fakeIo(env);
+ await init(root, {}, io);
+ expect(io.warnings[0]).toMatch(/retention left unchanged/);
+ expect(await readText(settingsFile())).toBe("{oops");
+ });
+
+ it("asks which fixed language on the first run only", async () => {
+ await init(root, {}, fakeIo(env, ["proj", "keep", "fixed", "Turkish"]));
+ expect((await loadConfig(env)).language).toBe("Turkish");
+ const second = join(dir, "second");
+ await mkdir(second);
+ const io = fakeIo(env);
+ await init(second, {}, io);
+ expect(io.asked.some((q) => q.startsWith("Language"))).toBe(false);
+ });
+
+ it("is idempotent for an initialized project", async () => {
+ await init(root, {}, fakeIo(env));
+ const io = fakeIo(env, [], true);
+ await init(root, {}, io);
+ expect(io.lines).toEqual([`Already initialized: proj (${root})`]);
+ const reg = await loadRegistry(env);
+ expect(reg.found && reg.ok && reg.data.projects).toHaveLength(1);
+ });
+
+ it("refuses a corrupt project.json", async () => {
+ await mkdir(join(root, ".codelineage"));
+ await writeFile(join(root, ".codelineage", "project.json"), "[]");
+ await expect(init(root, {}, fakeIo(env))).rejects.toThrow(/not a JSON object/);
+ });
+
+ it("still initializes when the global dir is not writable", async () => {
+ await writeFile(join(dir, "home"), "a file, not a dir");
+ const io = fakeIo(env);
+ await init(root, {}, io);
+ expect(io.warnings.map((w) => w.split(":")[0])).toEqual([
+ "could not save global config",
+ "could not register the project in the global panel",
+ ]);
+ expect(await loadProject(root)).toMatchObject({ ok: true });
+ });
+});
+
+describe("git helpers", () => {
+ it("finds the repo root from a subdirectory, also for worktree .git files", async () => {
+ await writeFile(join(root, ".git"), "gitdir: /elsewhere");
+ const sub = join(root, "a", "b");
+ await mkdir(sub, { recursive: true });
+ expect(await findGitRoot(sub)).toBe(root);
+ expect(await findGitRoot("/")).toBeUndefined();
+ });
+
+ it("appends only missing lines and keeps existing content", async () => {
+ const gi = join(root, ".gitignore");
+ await writeFile(gi, "node_modules/");
+ expect(await ensureGitignore(root, "commit")).toHaveLength(4);
+ expect(await ensureGitignore(root, "commit")).toEqual([]);
+ expect(await ensureGitignore(root, "ignore")).toEqual(["/.codelineage/"]);
+ const text = await readText(gi);
+ expect(text.startsWith("node_modules/\n# codelineage\n")).toBe(true);
+ expect(text.match(/# codelineage/g)).toHaveLength(1);
+ expect(basename(gi)).toBe(".gitignore");
+ });
+});
+
+describe("setRetention", () => {
+ it("rejects invalid day counts and unparsable files", async () => {
+ await expect(setRetention(0, env, T0)).rejects.toThrow(/at least 1/);
+ await mkdir(join(dir, "claude"));
+ await writeFile(settingsFile(), "[1]");
+ await expect(setRetention(90, env, T0)).rejects.toThrow(/not a valid JSON object/);
+ expect(await readRetention(env)).toBeUndefined();
+ });
+
+ it("creates the settings file without a backup when there was none", async () => {
+ expect(await setRetention(90, env, T0)).toEqual({ file: settingsFile() });
+ expect(await readRetention(env)).toBe(90);
+ });
+});
diff --git a/packages/cli/test/io.test.ts b/packages/cli/test/io.test.ts
new file mode 100644
index 0000000..db7e292
--- /dev/null
+++ b/packages/cli/test/io.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@inquirer/prompts", () => ({
+ select: vi.fn(async () => "picked"),
+ input: vi.fn(async () => "typed"),
+ confirm: vi.fn(async () => true),
+}));
+
+const { defaultsPrompter, inquirerPrompter, processIo } = await import("../src/io.js");
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("prompters", () => {
+ it("forwards questions to inquirer", async () => {
+ expect(await inquirerPrompter.select("q", [{ value: "a", name: "A" }], "a")).toBe("picked");
+ expect(await inquirerPrompter.input("q", "d")).toBe("typed");
+ expect(await inquirerPrompter.confirm("q", false)).toBe(true);
+ });
+
+ it("answers with defaults", async () => {
+ expect(await defaultsPrompter.select("q", [], "x")).toBe("x");
+ expect(await defaultsPrompter.input("q", "d")).toBe("d");
+ expect(await defaultsPrompter.confirm("q", false)).toBe(false);
+ });
+});
+
+describe("processIo", () => {
+ it("writes to stdout and stderr and picks the prompter", () => {
+ const out = vi.spyOn(process.stdout, "write").mockReturnValue(true);
+ const err = vi.spyOn(process.stderr, "write").mockReturnValue(true);
+ const io = processIo(true);
+ io.out("hi");
+ io.warn("careful");
+ expect(out).toHaveBeenCalledWith("hi\n");
+ expect(err).toHaveBeenCalledWith("warning: careful\n");
+ expect(io.prompt).toBe(inquirerPrompter);
+ expect(processIo(false).prompt).toBe(defaultsPrompter);
+ expect(io.now()).toMatch(/^\d{4}-\d\d-\d\dT/);
+ });
+});
diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.ts
new file mode 100644
index 0000000..025a91b
--- /dev/null
+++ b/packages/cli/test/program-commands.test.ts
@@ -0,0 +1,71 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+import { createProgram } from "../src/program.js";
+import { loadConfig, loadProject } from "../src/store/stores.js";
+import { envFor, type FakeIo, fakeIo, tempDir } from "./helpers.js";
+
+let dir: string;
+let root: string;
+let io: FakeIo;
+let interactive: boolean[];
+
+beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "proj");
+ await mkdir(root);
+ io = fakeIo(envFor(dir));
+ interactive = [];
+});
+
+async function cli(...args: string[]): Promise<string> {
+ let err = "";
+ const program = createProgram((i) => {
+ interactive.push(i);
+ return io;
+ });
+ program.exitOverride().configureOutput({ writeErr: (s) => (err += s), writeOut: () => {} });
+ for (const c of program.commands)
+ c.exitOverride().configureOutput({ writeErr: (s) => (err += s) });
+ for (const c of program.commands.flatMap((c) => c.commands)) {
+ c.exitOverride().configureOutput({ writeErr: (s) => (err += s) });
+ }
+ try {
+ await program.parseAsync(args, { from: "user" });
+ } catch (e) {
+ if (!err) throw e;
+ }
+ return err;
+}
+
+describe("commands through the CLI", () => {
+ it("init --yes runs non-interactively with options", async () => {
+ await cli("init", root, "--yes", "--name", "P", "--retention", "keep", "--language", "auto");
+ expect(interactive).toEqual([false]);
+ expect(await loadProject(root)).toMatchObject({ ok: true, data: { name: "P" } });
+ });
+
+ it("rejects a bad --retention value", async () => {
+ expect(await cli("init", root, "--retention", "0")).toMatch(/days \(>= 1\) or keep/);
+ expect(await cli("init", root, "--yes", "--retention", "90", "--language", "auto")).toBe("");
+ });
+
+ it("runs config get/set and epoch add", async () => {
+ await cli("config", "set", "updateEveryTurns", "7");
+ expect((await loadConfig(io.env)).updateEveryTurns).toBe(7);
+ await cli("config", "get", "updateEveryTurns");
+ expect(io.lines.at(-1)).toBe("7");
+ await cli("init", root, "--yes", "--retention", "keep");
+ await cli("epoch", "add", "e1", "First", "-C", root);
+ expect(io.lines.at(-1)).toBe("Added epoch e1: First");
+ });
+
+ it("prints user errors as one line", async () => {
+ expect(await cli("config", "get", "nope")).toMatch(/^error: unknown key "nope"/);
+ });
+
+ it("lets unexpected errors through", async () => {
+ await writeFile(join(dir, "home"), "file");
+ await expect(cli("config", "set", "language", "x")).rejects.toThrow(/ENOTDIR|EEXIST/);
+ });
+});
diff --git a/packages/cli/tsup.config.ts b/packages/cli/tsup.config.ts
index 1030995..6490cee 100644
--- a/packages/cli/tsup.config.ts
+++ b/packages/cli/tsup.config.ts
@@ -8,5 +8,12 @@ export default defineConfig({
bundle: true,
noExternal: [/.*/],
clean: true,
- banner: { js: "#!/usr/bin/env node" },
+ // CJS deps bundled into ESM still call require() for node builtins
+ banner: {
+ js: [
+ "#!/usr/bin/env node",
+ 'import { createRequire as __cl_createRequire } from "node:module";',
+ "const require = __cl_createRequire(import.meta.url);",
+ ].join("\n"),
+ },
});