intent-cli-python 0.5.0__py3-none-any.whl

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.
intent_cli/__init__.py ADDED
@@ -0,0 +1,29 @@
1
+ """Intent CLI package."""
2
+
3
+ from importlib import metadata
4
+ from pathlib import Path
5
+ import re
6
+ from typing import Optional
7
+
8
+
9
+ PACKAGE_NAME = "intent-cli-python"
10
+ REPO_ROOT = Path(__file__).resolve().parents[2]
11
+ PYPROJECT_PATH = REPO_ROOT / "pyproject.toml"
12
+ VERSION_PATTERN = re.compile(r'^version\s*=\s*"([^"]+)"\s*$', re.MULTILINE)
13
+
14
+
15
+ def version_from_checkout() -> Optional[str]:
16
+ if not PYPROJECT_PATH.exists():
17
+ return None
18
+ match = VERSION_PATTERN.search(PYPROJECT_PATH.read_text(encoding="utf-8"))
19
+ if not match:
20
+ return None
21
+ return match.group(1)
22
+
23
+
24
+ __version__ = version_from_checkout()
25
+ if __version__ is None:
26
+ try:
27
+ __version__ = metadata.version(PACKAGE_NAME)
28
+ except metadata.PackageNotFoundError:
29
+ __version__ = "0.4.0"
intent_cli/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ from .cli import main
2
+
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())
intent_cli/cli.py ADDED
@@ -0,0 +1,162 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any, Dict, Optional
7
+
8
+ from . import __version__
9
+ from .constants import EXIT_GENERAL_FAILURE, EXIT_SUCCESS
10
+ from .core import IntentRepository
11
+ from .errors import IntentError
12
+
13
+
14
+ def emit(payload: Dict[str, Any]) -> None:
15
+ print(json.dumps(payload, indent=2))
16
+
17
+
18
+ def ok(action: str, result: Any, **extra: Any) -> Dict[str, Any]:
19
+ payload: Dict[str, Any] = {"ok": True, "action": action, "result": result}
20
+ payload.update(extra)
21
+ return payload
22
+
23
+
24
+ def build_parser() -> argparse.ArgumentParser:
25
+ parser = argparse.ArgumentParser(
26
+ prog="itt",
27
+ description="Intent CLI — semantic history for agents.",
28
+ )
29
+ parser.add_argument("--version", action="version", version=f"intent-cli {__version__}")
30
+ sub = parser.add_subparsers(dest="command", required=True, title="commands")
31
+
32
+ sub.add_parser("version", help="Show version")
33
+
34
+ sub.add_parser("init", help="Initialize Intent in the current Git repository")
35
+
36
+ start_p = sub.add_parser("start", help="Create and activate an intent")
37
+ start_p.add_argument("title")
38
+
39
+ snap_p = sub.add_parser("snap", help="Record a snap (adopted by default)")
40
+ snap_p.add_argument("title")
41
+ snap_p.add_argument("-m", "--message", help="Rationale for this snap")
42
+ snap_p.add_argument("--candidate", action="store_true", help="Record as candidate without adopting")
43
+
44
+ adopt_p = sub.add_parser("adopt", help="Adopt a candidate snap")
45
+ adopt_p.add_argument("snap_id", nargs="?")
46
+ adopt_p.add_argument("-m", "--message", help="Rationale for adoption")
47
+
48
+ revert_p = sub.add_parser("revert", help="Revert the latest adopted snap")
49
+ revert_p.add_argument("-m", "--message", help="Rationale for revert")
50
+
51
+ sub.add_parser("suspend", help="Suspend the active intent")
52
+
53
+ resume_p = sub.add_parser("resume", help="Resume a suspended intent")
54
+ resume_p.add_argument("intent_id", nargs="?")
55
+
56
+ done_p = sub.add_parser("done", help="Close the active intent")
57
+ done_p.add_argument("intent_id", nargs="?")
58
+
59
+ sub.add_parser("inspect", help="Machine-readable workspace snapshot")
60
+
61
+ list_p = sub.add_parser("list", help="List objects")
62
+ list_p.add_argument("type", choices=["intent", "snap"])
63
+ list_p.add_argument("--intent", dest="intent_id", help="Filter snaps by intent ID")
64
+
65
+ show_p = sub.add_parser("show", help="Show a single object by ID")
66
+ show_p.add_argument("id")
67
+
68
+ return parser
69
+
70
+
71
+ def main(argv: Optional[list[str]] = None) -> int:
72
+ parser = build_parser()
73
+ args = parser.parse_args(argv)
74
+ repo = IntentRepository(Path.cwd())
75
+
76
+ try:
77
+ if args.command == "version":
78
+ emit(ok("version", {"version": __version__}))
79
+ return EXIT_SUCCESS
80
+
81
+ if args.command == "init":
82
+ repo.ensure_git()
83
+ config, state = repo.init_workspace()
84
+ emit(ok("init", {"config": config, "state": state}))
85
+ return EXIT_SUCCESS
86
+
87
+ if args.command == "start":
88
+ intent, warnings = repo.create_intent(args.title)
89
+ emit(ok("start", intent, warnings=warnings))
90
+ return EXIT_SUCCESS
91
+
92
+ if args.command == "snap":
93
+ snap, warnings = repo.create_snap(
94
+ args.title,
95
+ rationale=args.message,
96
+ candidate=args.candidate,
97
+ )
98
+ emit(ok("snap", snap, warnings=warnings))
99
+ return EXIT_SUCCESS
100
+
101
+ if args.command == "adopt":
102
+ snap, warnings = repo.adopt_snap(
103
+ snap_id=args.snap_id,
104
+ rationale=args.message,
105
+ )
106
+ emit(ok("adopt", snap, warnings=warnings))
107
+ return EXIT_SUCCESS
108
+
109
+ if args.command == "revert":
110
+ snap, warnings = repo.revert_snap(rationale=args.message)
111
+ emit(ok("revert", snap, warnings=warnings))
112
+ return EXIT_SUCCESS
113
+
114
+ if args.command == "suspend":
115
+ intent, warnings = repo.suspend_intent()
116
+ emit(ok("suspend", intent, warnings=warnings))
117
+ return EXIT_SUCCESS
118
+
119
+ if args.command == "resume":
120
+ intent, warnings = repo.resume_intent(intent_id=args.intent_id)
121
+ emit(ok("resume", intent, warnings=warnings))
122
+ return EXIT_SUCCESS
123
+
124
+ if args.command == "done":
125
+ intent, warnings = repo.close_intent(intent_id=args.intent_id)
126
+ emit(ok("done", intent, warnings=warnings))
127
+ return EXIT_SUCCESS
128
+
129
+ if args.command == "inspect":
130
+ emit(repo.inspect())
131
+ return EXIT_SUCCESS
132
+
133
+ if args.command == "list":
134
+ items = repo.list_objects(args.type, intent_id=getattr(args, "intent_id", None))
135
+ emit(ok("list", items, count=len(items)))
136
+ return EXIT_SUCCESS
137
+
138
+ if args.command == "show":
139
+ obj = repo.show_object(args.id)
140
+ emit(ok("show", obj))
141
+ return EXIT_SUCCESS
142
+
143
+ parser.error("unknown command")
144
+ return 2
145
+
146
+ except IntentError as error:
147
+ emit(error.to_json())
148
+ return error.exit_code
149
+ except Exception as error:
150
+ emit({
151
+ "ok": False,
152
+ "error": {
153
+ "code": "INTERNAL_ERROR",
154
+ "message": str(error),
155
+ "details": {},
156
+ },
157
+ })
158
+ return EXIT_GENERAL_FAILURE
159
+
160
+
161
+ if __name__ == "__main__":
162
+ raise SystemExit(main())
@@ -0,0 +1,19 @@
1
+ from __future__ import annotations
2
+
3
+ SCHEMA_VERSION = "0.2"
4
+
5
+ EXIT_SUCCESS = 0
6
+ EXIT_GENERAL_FAILURE = 1
7
+ EXIT_INVALID_INPUT = 2
8
+ EXIT_STATE_CONFLICT = 3
9
+ EXIT_OBJECT_NOT_FOUND = 4
10
+
11
+ DIR_NAMES = {
12
+ "intent": "intents",
13
+ "snap": "snaps",
14
+ }
15
+
16
+ ID_PREFIXES = {
17
+ "intent": "intent",
18
+ "snap": "snap",
19
+ }
intent_cli/core.py ADDED
@@ -0,0 +1,443 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any, Dict, List, Optional, Tuple
5
+
6
+ from .constants import EXIT_OBJECT_NOT_FOUND, EXIT_STATE_CONFLICT, SCHEMA_VERSION
7
+ from .errors import IntentError
8
+ from .git import build_git_context, ensure_git_worktree
9
+ from .helpers import object_sort_key, utc_now
10
+ from .store import IntentStore
11
+
12
+
13
+ class IntentRepository:
14
+ def __init__(self, cwd: Path) -> None:
15
+ self.cwd = cwd
16
+ self.store = IntentStore(cwd)
17
+
18
+ # --- guards ---
19
+
20
+ def ensure_git(self) -> None:
21
+ ensure_git_worktree(self.cwd)
22
+
23
+ def ensure_initialized(self) -> None:
24
+ self.store.ensure_initialized()
25
+
26
+ # --- init ---
27
+
28
+ def init_workspace(self) -> Tuple[Dict[str, Any], Dict[str, Any]]:
29
+ self.ensure_git()
30
+ return self.store.init_workspace()
31
+
32
+ # --- state helpers ---
33
+
34
+ def _load_state(self) -> Dict[str, Any]:
35
+ return self.store.load_state()
36
+
37
+ def _save_state(self, state: Dict[str, Any]) -> None:
38
+ self.store.save_state(state)
39
+
40
+ def _active_intent(self, state: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
41
+ state = state or self._load_state()
42
+ return self.store.load_object("intent", state.get("active_intent_id"))
43
+
44
+ def _require_active_intent(self, state: Dict[str, Any]) -> Dict[str, Any]:
45
+ intent = self._active_intent(state)
46
+ if not intent:
47
+ raise IntentError(
48
+ EXIT_STATE_CONFLICT,
49
+ "STATE_CONFLICT",
50
+ "No active intent.",
51
+ suggested_fix='itt start "Describe the problem"',
52
+ )
53
+ return intent
54
+
55
+ def _candidate_snaps(self, intent_id: str) -> List[Dict[str, Any]]:
56
+ return sorted(
57
+ [
58
+ s for s in self.store.list_objects("snap")
59
+ if s.get("intent_id") == intent_id and s.get("status") == "candidate"
60
+ ],
61
+ key=object_sort_key,
62
+ )
63
+
64
+ def _latest_adopted(self, intent_id: str) -> Optional[Dict[str, Any]]:
65
+ adopted = [
66
+ s for s in self.store.list_objects("snap")
67
+ if s.get("intent_id") == intent_id and s.get("status") == "adopted"
68
+ ]
69
+ if not adopted:
70
+ return None
71
+ return sorted(adopted, key=object_sort_key, reverse=True)[0]
72
+
73
+ def _derive_workspace_status(self, state: Dict[str, Any]) -> str:
74
+ intent = self._active_intent(state)
75
+ if not intent:
76
+ return "idle"
77
+ candidates = self._candidate_snaps(intent["id"])
78
+ if len(candidates) > 1:
79
+ return "conflict"
80
+ return "active"
81
+
82
+ # --- intent lifecycle ---
83
+
84
+ def create_intent(self, title: str) -> Tuple[Dict[str, Any], List[str]]:
85
+ self.ensure_git()
86
+ self.ensure_initialized()
87
+ state = self._load_state()
88
+
89
+ current = self._active_intent(state)
90
+ if current and current.get("status") == "open":
91
+ raise IntentError(
92
+ EXIT_STATE_CONFLICT,
93
+ "STATE_CONFLICT",
94
+ f"Intent '{current['id']}' is still open.",
95
+ suggested_fix="itt done or itt suspend",
96
+ )
97
+
98
+ intent_id = self.store.next_id("intent")
99
+ now = utc_now()
100
+ intent = {
101
+ "id": intent_id,
102
+ "object": "intent",
103
+ "schema_version": SCHEMA_VERSION,
104
+ "created_at": now,
105
+ "updated_at": now,
106
+ "title": title,
107
+ "status": "open",
108
+ }
109
+ self.store.save_object("intent", intent)
110
+
111
+ state["active_intent_id"] = intent_id
112
+ state["workspace_status"] = "active"
113
+ self._save_state(state)
114
+ return intent, []
115
+
116
+ def close_intent(self, intent_id: Optional[str] = None) -> Tuple[Dict[str, Any], List[str]]:
117
+ self.ensure_git()
118
+ self.ensure_initialized()
119
+ state = self._load_state()
120
+
121
+ if intent_id:
122
+ intent = self.store.require_object("intent", intent_id)
123
+ else:
124
+ intent = self._require_active_intent(state)
125
+
126
+ if intent.get("status") == "done":
127
+ raise IntentError(
128
+ EXIT_STATE_CONFLICT,
129
+ "STATE_CONFLICT",
130
+ f"Intent '{intent['id']}' is already done.",
131
+ )
132
+
133
+ intent["status"] = "done"
134
+ intent["updated_at"] = utc_now()
135
+ self.store.save_object("intent", intent)
136
+
137
+ if intent["id"] == state.get("active_intent_id"):
138
+ state["active_intent_id"] = None
139
+ state["workspace_status"] = "idle"
140
+ self._save_state(state)
141
+
142
+ return intent, []
143
+
144
+ def suspend_intent(self) -> Tuple[Dict[str, Any], List[str]]:
145
+ self.ensure_git()
146
+ self.ensure_initialized()
147
+ state = self._load_state()
148
+ intent = self._require_active_intent(state)
149
+
150
+ intent["status"] = "suspended"
151
+ intent["updated_at"] = utc_now()
152
+ self.store.save_object("intent", intent)
153
+
154
+ state["active_intent_id"] = None
155
+ state["workspace_status"] = "idle"
156
+ self._save_state(state)
157
+ return intent, []
158
+
159
+ def resume_intent(self, intent_id: Optional[str] = None) -> Tuple[Dict[str, Any], List[str]]:
160
+ self.ensure_git()
161
+ self.ensure_initialized()
162
+ state = self._load_state()
163
+
164
+ current = self._active_intent(state)
165
+ if current and current.get("status") == "open":
166
+ raise IntentError(
167
+ EXIT_STATE_CONFLICT,
168
+ "STATE_CONFLICT",
169
+ f"Intent '{current['id']}' is still open.",
170
+ suggested_fix="itt suspend or itt done",
171
+ )
172
+
173
+ suspended = [
174
+ i for i in self.store.list_objects("intent")
175
+ if i.get("status") == "suspended"
176
+ ]
177
+
178
+ if intent_id:
179
+ intent = self.store.require_object("intent", intent_id)
180
+ if intent.get("status") != "suspended":
181
+ raise IntentError(
182
+ EXIT_STATE_CONFLICT,
183
+ "STATE_CONFLICT",
184
+ f"Intent '{intent_id}' is not suspended.",
185
+ )
186
+ elif len(suspended) == 1:
187
+ intent = suspended[0]
188
+ elif len(suspended) == 0:
189
+ raise IntentError(
190
+ EXIT_STATE_CONFLICT,
191
+ "STATE_CONFLICT",
192
+ "No suspended intents to resume.",
193
+ suggested_fix='itt start "Describe the problem"',
194
+ )
195
+ else:
196
+ raise IntentError(
197
+ EXIT_STATE_CONFLICT,
198
+ "STATE_CONFLICT",
199
+ "Multiple suspended intents. Specify which one to resume.",
200
+ details={
201
+ "suspended": [{"id": i["id"], "title": i["title"]} for i in suspended],
202
+ },
203
+ suggested_fix=f"itt resume {suspended[-1]['id']}",
204
+ )
205
+
206
+ intent["status"] = "open"
207
+ intent["updated_at"] = utc_now()
208
+ self.store.save_object("intent", intent)
209
+
210
+ state["active_intent_id"] = intent["id"]
211
+ state["workspace_status"] = "active"
212
+ self._save_state(state)
213
+ return intent, []
214
+
215
+ # --- snap lifecycle ---
216
+
217
+ def create_snap(
218
+ self,
219
+ title: str,
220
+ rationale: Optional[str] = None,
221
+ candidate: bool = False,
222
+ ) -> Tuple[Dict[str, Any], List[str]]:
223
+ self.ensure_git()
224
+ self.ensure_initialized()
225
+ state = self._load_state()
226
+ intent = self._require_active_intent(state)
227
+
228
+ git_payload, warnings = build_git_context(self.cwd)
229
+ snap_id = self.store.next_id("snap")
230
+ now = utc_now()
231
+ status = "candidate" if candidate else "adopted"
232
+ snap = {
233
+ "id": snap_id,
234
+ "object": "snap",
235
+ "schema_version": SCHEMA_VERSION,
236
+ "created_at": now,
237
+ "updated_at": now,
238
+ "title": title,
239
+ "rationale": rationale or "",
240
+ "status": status,
241
+ "intent_id": intent["id"],
242
+ "git": git_payload,
243
+ }
244
+ self.store.save_object("snap", snap)
245
+
246
+ state["workspace_status"] = self._derive_workspace_status(state)
247
+ self._save_state(state)
248
+ return snap, warnings
249
+
250
+ def adopt_snap(
251
+ self,
252
+ snap_id: Optional[str] = None,
253
+ rationale: Optional[str] = None,
254
+ ) -> Tuple[Dict[str, Any], List[str]]:
255
+ self.ensure_git()
256
+ self.ensure_initialized()
257
+ state = self._load_state()
258
+ intent = self._require_active_intent(state)
259
+
260
+ candidates = self._candidate_snaps(intent["id"])
261
+
262
+ if snap_id:
263
+ snap = self.store.require_object("snap", snap_id)
264
+ if snap.get("intent_id") != intent["id"]:
265
+ raise IntentError(
266
+ EXIT_STATE_CONFLICT,
267
+ "STATE_CONFLICT",
268
+ "Snap does not belong to the active intent.",
269
+ details={"snap_id": snap_id, "intent_id": intent["id"]},
270
+ )
271
+ if snap.get("status") != "candidate":
272
+ raise IntentError(
273
+ EXIT_STATE_CONFLICT,
274
+ "STATE_CONFLICT",
275
+ f"Snap '{snap_id}' is not a candidate.",
276
+ )
277
+ elif len(candidates) == 1:
278
+ snap = candidates[0]
279
+ elif len(candidates) == 0:
280
+ raise IntentError(
281
+ EXIT_STATE_CONFLICT,
282
+ "STATE_CONFLICT",
283
+ "No candidate snaps to adopt.",
284
+ suggested_fix='itt snap "Describe the step" --candidate',
285
+ )
286
+ else:
287
+ raise IntentError(
288
+ EXIT_STATE_CONFLICT,
289
+ "STATE_CONFLICT",
290
+ "Multiple candidates exist. Specify which one to adopt.",
291
+ details={
292
+ "candidates": [{"id": c["id"], "title": c["title"]} for c in candidates],
293
+ },
294
+ suggested_fix=f"itt adopt {candidates[-1]['id']}",
295
+ )
296
+
297
+ snap["status"] = "adopted"
298
+ if rationale:
299
+ snap["rationale"] = rationale
300
+ snap["updated_at"] = utc_now()
301
+ self.store.save_object("snap", snap)
302
+
303
+ state["workspace_status"] = self._derive_workspace_status(state)
304
+ self._save_state(state)
305
+ return snap, []
306
+
307
+ def revert_snap(self, rationale: Optional[str] = None) -> Tuple[Dict[str, Any], List[str]]:
308
+ self.ensure_git()
309
+ self.ensure_initialized()
310
+ state = self._load_state()
311
+ intent = self._require_active_intent(state)
312
+
313
+ latest = self._latest_adopted(intent["id"])
314
+ if not latest:
315
+ raise IntentError(
316
+ EXIT_STATE_CONFLICT,
317
+ "STATE_CONFLICT",
318
+ "No adopted snap to revert.",
319
+ suggested_fix='itt snap "Describe the step"',
320
+ )
321
+
322
+ latest["status"] = "reverted"
323
+ if rationale:
324
+ latest["rationale"] = rationale
325
+ latest["updated_at"] = utc_now()
326
+ self.store.save_object("snap", latest)
327
+
328
+ state["workspace_status"] = self._derive_workspace_status(state)
329
+ self._save_state(state)
330
+ return latest, []
331
+
332
+ # --- read ---
333
+
334
+ def inspect(self) -> Dict[str, Any]:
335
+ self.ensure_git()
336
+ self.ensure_initialized()
337
+ state = self._load_state()
338
+ intent = self._active_intent(state)
339
+ git_payload, git_warnings = build_git_context(self.cwd)
340
+
341
+ latest_snap = None
342
+ candidate_snaps: List[Dict[str, Any]] = []
343
+ if intent:
344
+ latest_snap = self._latest_adopted(intent["id"])
345
+ candidate_snaps = [
346
+ {"id": c["id"], "title": c["title"]}
347
+ for c in self._candidate_snaps(intent["id"])
348
+ ]
349
+
350
+ suspended_intents = [
351
+ {"id": i["id"], "title": i["title"]}
352
+ for i in self.store.list_objects("intent")
353
+ if i.get("status") == "suspended"
354
+ ]
355
+
356
+ workspace_status = self._derive_workspace_status(state)
357
+ if workspace_status != state.get("workspace_status"):
358
+ state["workspace_status"] = workspace_status
359
+ self._save_state(state)
360
+
361
+ def brief(obj: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
362
+ if not obj:
363
+ return None
364
+ return {k: obj[k] for k in ("id", "title", "status", "rationale") if k in obj}
365
+
366
+ action = self._next_action(intent, candidate_snaps, suspended_intents)
367
+
368
+ return {
369
+ "ok": True,
370
+ "schema_version": SCHEMA_VERSION,
371
+ "workspace_status": workspace_status,
372
+ "intent": brief(intent),
373
+ "latest_snap": brief(latest_snap),
374
+ "candidate_snaps": candidate_snaps,
375
+ "suspended_intents": suspended_intents,
376
+ "suggested_next_action": action,
377
+ "git": {
378
+ "branch": git_payload["branch"],
379
+ "head": git_payload["head"],
380
+ "working_tree": git_payload["working_tree"],
381
+ },
382
+ "warnings": git_warnings,
383
+ }
384
+
385
+ def list_objects(self, object_name: str, intent_id: Optional[str] = None) -> List[Dict[str, Any]]:
386
+ self.ensure_git()
387
+ self.ensure_initialized()
388
+ if object_name not in ("intent", "snap"):
389
+ raise IntentError(
390
+ EXIT_STATE_CONFLICT,
391
+ "STATE_CONFLICT",
392
+ f"Unknown object type: {object_name}",
393
+ suggested_fix="Use 'intent' or 'snap'.",
394
+ )
395
+ items = self.store.list_objects(object_name)
396
+ if intent_id and object_name == "snap":
397
+ items = [s for s in items if s.get("intent_id") == intent_id]
398
+ return sorted(items, key=object_sort_key, reverse=True)
399
+
400
+ def show_object(self, object_id: str) -> Dict[str, Any]:
401
+ self.ensure_git()
402
+ self.ensure_initialized()
403
+ object_name = self._type_from_id(object_id)
404
+ return self.store.require_object(object_name, object_id)
405
+
406
+ # --- internal ---
407
+
408
+ def _type_from_id(self, object_id: str) -> str:
409
+ if object_id.startswith("intent-"):
410
+ return "intent"
411
+ if object_id.startswith("snap-"):
412
+ return "snap"
413
+ raise IntentError(
414
+ EXIT_OBJECT_NOT_FOUND,
415
+ "OBJECT_NOT_FOUND",
416
+ f"Cannot determine type for id '{object_id}'.",
417
+ suggested_fix="Use a valid id like 'intent-001' or 'snap-001'.",
418
+ )
419
+
420
+ def _next_action(
421
+ self,
422
+ intent: Optional[Dict[str, Any]],
423
+ candidates: List[Dict[str, Any]],
424
+ suspended: Optional[List[Dict[str, Any]]] = None,
425
+ ) -> Optional[Dict[str, Any]]:
426
+ if not intent or intent.get("status") != "open":
427
+ if suspended:
428
+ return {
429
+ "command": f"itt resume {suspended[-1]['id']}",
430
+ "reason": "Suspended intents exist.",
431
+ }
432
+ return {"command": "itt start 'Describe the problem'", "reason": "No active intent."}
433
+ if len(candidates) > 1:
434
+ return {
435
+ "command": f"itt adopt {candidates[-1]['id']}",
436
+ "reason": "Multiple candidates — pick one to adopt.",
437
+ }
438
+ if len(candidates) == 1:
439
+ return {
440
+ "command": f"itt adopt {candidates[0]['id']}",
441
+ "reason": "One candidate ready for adoption.",
442
+ }
443
+ return {"command": "itt snap 'Describe the step'", "reason": "Intent is active."}
intent_cli/errors.py ADDED
@@ -0,0 +1,33 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, Optional
4
+
5
+
6
+ class IntentError(Exception):
7
+ def __init__(
8
+ self,
9
+ exit_code: int,
10
+ code: str,
11
+ message: str,
12
+ details: Optional[Dict[str, Any]] = None,
13
+ suggested_fix: Optional[str] = None,
14
+ ) -> None:
15
+ super().__init__(message)
16
+ self.exit_code = exit_code
17
+ self.code = code
18
+ self.message = message
19
+ self.details = details or {}
20
+ self.suggested_fix = suggested_fix
21
+
22
+ def to_json(self) -> Dict[str, Any]:
23
+ payload = {
24
+ "ok": False,
25
+ "error": {
26
+ "code": self.code,
27
+ "message": self.message,
28
+ "details": self.details,
29
+ },
30
+ }
31
+ if self.suggested_fix:
32
+ payload["error"]["suggested_fix"] = self.suggested_fix
33
+ return payload
intent_cli/git.py ADDED
@@ -0,0 +1,83 @@
1
+ from __future__ import annotations
2
+
3
+ import subprocess
4
+ from pathlib import Path
5
+ from typing import Any, Dict, List, Optional, Tuple
6
+
7
+ from .constants import EXIT_GENERAL_FAILURE
8
+ from .errors import IntentError
9
+
10
+
11
+ def run_git(cwd: Path, *args: str) -> subprocess.CompletedProcess[str]:
12
+ return subprocess.run(
13
+ ["git", *args],
14
+ cwd=str(cwd),
15
+ check=False,
16
+ capture_output=True,
17
+ text=True,
18
+ )
19
+
20
+
21
+ def ensure_git_worktree(cwd: Path) -> None:
22
+ result = run_git(cwd, "rev-parse", "--is-inside-work-tree")
23
+ if result.returncode != 0 or result.stdout.strip() != "true":
24
+ raise IntentError(
25
+ EXIT_GENERAL_FAILURE,
26
+ "GIT_STATE_INVALID",
27
+ "Intent requires a Git repository",
28
+ suggested_fix="git init",
29
+ )
30
+
31
+
32
+ def git_branch(cwd: Path) -> str:
33
+ result = run_git(cwd, "branch", "--show-current")
34
+ if result.returncode == 0:
35
+ value = result.stdout.strip()
36
+ if value:
37
+ return value
38
+ result = run_git(cwd, "rev-parse", "--abbrev-ref", "HEAD")
39
+ if result.returncode == 0 and result.stdout.strip():
40
+ return result.stdout.strip()
41
+ return "unknown"
42
+
43
+
44
+ def git_head(cwd: Path, ref: str = "HEAD") -> Optional[str]:
45
+ result = run_git(cwd, "rev-parse", "--short", ref)
46
+ if result.returncode == 0:
47
+ value = result.stdout.strip()
48
+ return value or None
49
+ return None
50
+
51
+
52
+ def git_working_tree(cwd: Path) -> str:
53
+ result = run_git(cwd, "status", "--porcelain")
54
+ if result.returncode != 0:
55
+ return "unknown"
56
+ return "clean" if not result.stdout.strip() else "dirty"
57
+
58
+
59
+ def build_git_context(cwd: Path) -> Tuple[Dict[str, Any], List[str]]:
60
+ branch = git_branch(cwd)
61
+ working_tree = git_working_tree(cwd)
62
+ warnings: List[str] = []
63
+
64
+ head = git_head(cwd)
65
+ if head and working_tree == "clean":
66
+ linkage_quality = "stable_commit"
67
+ else:
68
+ linkage_quality = "working_tree_context"
69
+ if not head:
70
+ warnings.append("Git HEAD could not be resolved; recording working tree context only.")
71
+
72
+ if working_tree == "dirty":
73
+ warnings.append("Git working tree is dirty; recording working tree context.")
74
+
75
+ return (
76
+ {
77
+ "branch": branch,
78
+ "head": head,
79
+ "working_tree": working_tree,
80
+ "linkage_quality": linkage_quality,
81
+ },
82
+ warnings,
83
+ )
intent_cli/helpers.py ADDED
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from datetime import datetime, timezone
5
+ from pathlib import Path
6
+ from typing import Any, Dict, Tuple
7
+
8
+
9
+ def utc_now() -> str:
10
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
11
+
12
+
13
+ def read_json(path: Path) -> Dict[str, Any]:
14
+ return json.loads(path.read_text())
15
+
16
+
17
+ def write_json(path: Path, payload: Dict[str, Any]) -> None:
18
+ path.write_text(json.dumps(payload, indent=2) + "\n")
19
+
20
+
21
+ def object_sort_key(item: Dict[str, Any]) -> Tuple[str, int]:
22
+ object_id = item.get("id", "")
23
+ suffix = object_id.rsplit("-", 1)[-1]
24
+ number = int(suffix) if suffix.isdigit() else 0
25
+ return (item.get("created_at", ""), number)
intent_cli/store.py ADDED
@@ -0,0 +1,102 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Any, Dict, List, Optional, Tuple
5
+
6
+ from .constants import DIR_NAMES, EXIT_GENERAL_FAILURE, EXIT_OBJECT_NOT_FOUND, ID_PREFIXES, SCHEMA_VERSION
7
+ from .errors import IntentError
8
+ from .helpers import read_json, utc_now, write_json
9
+
10
+
11
+ class IntentStore:
12
+ def __init__(self, cwd: Path) -> None:
13
+ self.cwd = cwd
14
+ self.intent_dir = cwd / ".intent"
15
+ self.config_path = self.intent_dir / "config.json"
16
+ self.state_path = self.intent_dir / "state.json"
17
+
18
+ def is_initialized(self) -> bool:
19
+ return self.intent_dir.exists() and self.config_path.exists() and self.state_path.exists()
20
+
21
+ def ensure_initialized(self) -> None:
22
+ if not self.is_initialized():
23
+ raise IntentError(
24
+ EXIT_GENERAL_FAILURE,
25
+ "NOT_INITIALIZED",
26
+ "Intent is not initialized in this repository.",
27
+ suggested_fix="itt init",
28
+ )
29
+
30
+ def object_dir(self, object_name: str) -> Path:
31
+ return self.intent_dir / DIR_NAMES[object_name]
32
+
33
+ def init_workspace(self) -> Tuple[Dict[str, Any], Dict[str, Any]]:
34
+ if self.intent_dir.exists():
35
+ raise IntentError(
36
+ EXIT_GENERAL_FAILURE,
37
+ "ALREADY_EXISTS",
38
+ "Intent is already initialized in this repository.",
39
+ )
40
+
41
+ self.intent_dir.mkdir()
42
+ for dir_name in DIR_NAMES.values():
43
+ (self.intent_dir / dir_name).mkdir()
44
+
45
+ config: Dict[str, Any] = {"schema_version": SCHEMA_VERSION}
46
+ state: Dict[str, Any] = {
47
+ "schema_version": SCHEMA_VERSION,
48
+ "active_intent_id": None,
49
+ "workspace_status": "idle",
50
+ "updated_at": utc_now(),
51
+ }
52
+ write_json(self.config_path, config)
53
+ write_json(self.state_path, state)
54
+
55
+ return config, state
56
+
57
+ def load_state(self) -> Dict[str, Any]:
58
+ self.ensure_initialized()
59
+ return read_json(self.state_path)
60
+
61
+ def save_state(self, state: Dict[str, Any]) -> None:
62
+ state["updated_at"] = utc_now()
63
+ write_json(self.state_path, state)
64
+
65
+ def next_id(self, object_name: str) -> str:
66
+ directory = self.object_dir(object_name)
67
+ prefix = ID_PREFIXES[object_name]
68
+ max_index = 0
69
+ for path in directory.glob(f"{prefix}-*.json"):
70
+ suffix = path.stem[len(prefix) + 1:]
71
+ if suffix.isdigit():
72
+ max_index = max(max_index, int(suffix))
73
+ return f"{prefix}-{max_index + 1:03d}"
74
+
75
+ def save_object(self, object_name: str, payload: Dict[str, Any]) -> None:
76
+ path = self.object_dir(object_name) / f"{payload['id']}.json"
77
+ write_json(path, payload)
78
+
79
+ def load_object(self, object_name: str, object_id: Optional[str]) -> Optional[Dict[str, Any]]:
80
+ if not object_id:
81
+ return None
82
+ path = self.object_dir(object_name) / f"{object_id}.json"
83
+ if not path.exists():
84
+ return None
85
+ return read_json(path)
86
+
87
+ def require_object(self, object_name: str, object_id: str) -> Dict[str, Any]:
88
+ payload = self.load_object(object_name, object_id)
89
+ if payload is None:
90
+ raise IntentError(
91
+ EXIT_OBJECT_NOT_FOUND,
92
+ "OBJECT_NOT_FOUND",
93
+ f"{object_name.capitalize()} '{object_id}' was not found.",
94
+ details={"id": object_id, "object": object_name},
95
+ )
96
+ return payload
97
+
98
+ def list_objects(self, object_name: str) -> List[Dict[str, Any]]:
99
+ directory = self.object_dir(object_name)
100
+ if not directory.exists():
101
+ return []
102
+ return [read_json(path) for path in directory.glob("*.json")]
@@ -0,0 +1,155 @@
1
+ Metadata-Version: 2.4
2
+ Name: intent-cli-python
3
+ Version: 0.5.0
4
+ Summary: Semantic history for agent-driven development. Records what you did and why.
5
+ Author: Zeng Deyang
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/dozybot001/Intent
8
+ Project-URL: Repository, https://github.com/dozybot001/Intent
9
+ Keywords: agent,git,semantic-history,intent,developer-tools
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Version Control :: Git
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Dynamic: license-file
24
+
25
+ English | [简体中文](https://github.com/dozybot001/Intent/blob/main/README.CN.md)
26
+
27
+ # Intent
28
+
29
+ > Git records code changes. Intent records why.
30
+
31
+ ## The Problem
32
+
33
+ Agent-driven development produces code fast, but reasoning disappears between sessions. Every new session starts from zero — the agent doesn't know what problem was being solved, what was tried, or why a path was chosen.
34
+
35
+ ## What's Missing
36
+
37
+ Git records *what* changed. Commit messages and comments add some context. But three things consistently fall through:
38
+
39
+ **Goal continuity.** Commits are isolated snapshots. There's no structure connecting five commits to one task, or saying "this is what we're trying to accomplish."
40
+
41
+ **Decision rationale.** Why JWT over cookies? Why 15-minute expiry? This rarely makes it into commit messages — and when it does, it's unstructured text that agents must parse and guess from.
42
+
43
+ **Work state.** `git status` can be clean while a task is half-done. The next session has no signal that work was interrupted or what comes next.
44
+
45
+ ## The Solution
46
+
47
+ Intent adds a `.intent/` directory to your repository — structured, machine-readable metadata that captures semantic history alongside code history.
48
+
49
+ ```
50
+ .git/ ← how code changed
51
+ .intent/ ← what you were doing and why
52
+ ```
53
+
54
+ Two objects: **intent** (the goal) and **snap** (a step taken, with rationale). All JSON. Any agent platform can read it.
55
+
56
+ ### What changes
57
+
58
+ **Without `.intent/`** — new agent session opens. It reads `git log` and source code. Understands what the code does *now*, but doesn't know the JWT migration was for compliance (might revert it), doesn't know the refresh token is intentionally incomplete, can't tell there's unfinished work. Asks: *"What would you like me to do?"*
59
+
60
+ **With `.intent/`** — new agent session opens. Runs `itt inspect`. Sees an active intent ("Migrate auth to JWT"), last snap ("Add refresh token — incomplete"), and rationale ("token rotation not done, security priority"). Says: *"I'll implement the token rotation next."*
61
+
62
+ The difference: 10 seconds of reading structured metadata vs. minutes of re-explaining context.
63
+
64
+ ## Core Loop
65
+
66
+ ```
67
+ start → snap → done
68
+ ```
69
+
70
+ - `start` — open an intent (what problem you're solving)
71
+ - `snap` — record a snap (what you did and why)
72
+ - `done` — close when complete
73
+
74
+ ## Example
75
+
76
+ ```bash
77
+ pipx install intent-cli-python
78
+ itt init # creates .intent/
79
+ itt start "Fix login timeout"
80
+ itt snap "Increase timeout to 30s" -m "5s too short for slow networks"
81
+ git add . && git commit -m "fix timeout"
82
+ itt done
83
+ ```
84
+
85
+ ## Why Not Just…
86
+
87
+ | Approach | What it does well | What falls through |
88
+ | --- | --- | --- |
89
+ | **Git commit messages** | Records what changed per commit | No goal structure across commits; rationale is afterthought; no work-in-progress state |
90
+ | **CLAUDE.md / .cursorrules** | Gives agents project-level instructions | Static — doesn't track active tasks, decisions, or progress; must be manually maintained |
91
+ | **TODO comments** | Marks incomplete work in-place | Scattered across files; no lifecycle; no rationale; agents must grep and guess priority |
92
+ | **Notion / Linear / Jira** | Rich project tracking for humans | External to the repo; agents can't read them without API integration; overhead is high for solo/agent workflows |
93
+ | **Agent memory** (e.g. Claude Code memory) | Persists user preferences across sessions | Tied to one platform; not versioned with code; not shareable across agents or teammates |
94
+ | **Ad-hoc context files** (e.g. `context.md`) | Quick, zero-tooling setup | No schema — every project invents its own format; no lifecycle management; grows stale silently |
95
+
96
+ **Intent occupies a specific gap**: structured, versioned, task-scoped context that lives *in the repo* and works across any agent platform.
97
+
98
+ - **Structured** — JSON objects with defined schema, not free text an agent must interpret
99
+ - **Task-scoped** — an intent has a lifecycle (`open → done`); snaps are ordered steps, not a pile of notes
100
+ - **Versioned** — `.intent/` is committed alongside code; `git blame` works on your decisions too
101
+ - **Platform-agnostic** — any agent that reads JSON can use it; no vendor lock-in
102
+ - **Minimal** — two objects (intent, snap), one CLI, zero dependencies; adds seconds to a workflow, not minutes
103
+
104
+ The closest alternative is writing a `context.md` by hand. Intent trades that flexibility for consistency: a schema agents can rely on without per-project prompt engineering.
105
+
106
+ ## Where This Is Going
107
+
108
+ `.intent/` is a protocol, not just a tool.
109
+
110
+ 1. **Agent memory** — agents read `.intent/` on startup, recover last session's context in seconds
111
+ 2. **Context exchange** — `.intent/` becomes the standard way to hand off work between agent platforms
112
+ 3. **Network effects** — when enough repos contain `.intent/`, new tooling emerges: intent-aware review, decision archaeology, semantic dashboards
113
+
114
+ ## Install
115
+
116
+ **Users:**
117
+
118
+ ```bash
119
+ pipx install intent-cli-python
120
+ ```
121
+
122
+ **Configure your agent:** Install the Intent skill so your agent knows the workflow:
123
+
124
+ ```bash
125
+ npx skills add dozybot001/Intent
126
+ ```
127
+
128
+ **Contributors:**
129
+
130
+ ```bash
131
+ git clone https://github.com/dozybot001/Intent.git
132
+ cd Intent
133
+ python3 ./itt # dev entry point, no install needed
134
+ ```
135
+
136
+ ## Commands
137
+
138
+ | Command | Purpose |
139
+ | --- | --- |
140
+ | `itt init` | Initialize `.intent/` |
141
+ | `itt start <title>` | Open an intent |
142
+ | `itt snap <title> [-m why]` | Record a snap |
143
+ | `itt done` | Close the active intent |
144
+ | `itt inspect` | Machine-readable workspace snapshot |
145
+ | `itt list <intent\|snap>` | List objects |
146
+ | `itt show <id>` | Show a single object |
147
+ | `itt suspend` | Suspend the active intent |
148
+ | `itt resume [id]` | Resume a suspended intent |
149
+ | `itt adopt [id]` | Adopt a candidate snap |
150
+ | `itt revert` | Revert the latest snap |
151
+
152
+ ## Documentation
153
+
154
+ - [CLI spec](https://github.com/dozybot001/Intent/blob/main/docs/cli.EN.md) — objects, commands, JSON output contract
155
+ - [Dogfooding](https://github.com/dozybot001/Intent/blob/main/docs/dogfooding.md) — how we built Intent with Intent
@@ -0,0 +1,15 @@
1
+ intent_cli/__init__.py,sha256=3RRXF1SMBw3Gq4QPSGrQNlMFpaxi_7ZhX56TeRc_zG8,773
2
+ intent_cli/__main__.py,sha256=PSQ4rpL0dG6f-qH4N7H-gD9igQkdHzH4yVZDcW8lfZo,80
3
+ intent_cli/cli.py,sha256=0nEOOpdtLOb3Ex5DsSXKPF2IS8yvRFUkSq8Ha6GzKEI,5482
4
+ intent_cli/constants.py,sha256=yOFDntL9kUqoB6ByKjUe5U6kcSVPn17nI2ywKWuuukM,301
5
+ intent_cli/core.py,sha256=kMF25qAxh6cqj384nhbve-gMU1-QINiPMiy2uOZWsfg,15489
6
+ intent_cli/errors.py,sha256=ZmfE5cf07vjoHNSKvjEqxQN0YQ_09nXD9KB3W82-xu8,892
7
+ intent_cli/git.py,sha256=79eTLQoelp7X44nDam4l4gLmh73M7hcrofIWmG_VVfc,2402
8
+ intent_cli/helpers.py,sha256=b1MWHFv3BGLO99SNq-ejNLuwtHbxy9p3rlYJRjXrzI4,718
9
+ intent_cli/store.py,sha256=pJB0vqjBn44eeKITDSBbucN5H1Lg1BS7TpaDP156TY0,3767
10
+ intent_cli_python-0.5.0.dist-info/licenses/LICENSE,sha256=XWjTStLaoDw-UgLwMecejVxeaHH8JibnSFYARGzRc6I,1068
11
+ intent_cli_python-0.5.0.dist-info/METADATA,sha256=pAci1T_SKJ8MoD0WOq9zhoITFhrIHeogNbYJQlqQOYI,7041
12
+ intent_cli_python-0.5.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
13
+ intent_cli_python-0.5.0.dist-info/entry_points.txt,sha256=Y1kziqgaGUgTHg3CCfc2Su1XoDvIMJ2vi-dPEDZfuTo,44
14
+ intent_cli_python-0.5.0.dist-info/top_level.txt,sha256=jkyOMCXA-G6FlEj69GA4SKn3RoO1KNL9w2iit7OUpuU,11
15
+ intent_cli_python-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ itt = intent_cli.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zeng Deyang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ intent_cli