codexspec 0.7.27__tar.gz → 0.7.29__tar.gz

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 (144) hide show
  1. {codexspec-0.7.27 → codexspec-0.7.29}/PKG-INFO +1 -1
  2. {codexspec-0.7.27 → codexspec-0.7.29}/pyproject.toml +1 -1
  3. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/__init__.py +19 -5
  4. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/automation.py +43 -3
  5. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/commit_runtime.py +436 -4
  6. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/session.py +6 -3
  7. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/transaction.py +6 -3
  8. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/profile.py +5 -1
  9. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/commit-staged.md +11 -1
  10. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/distill.md +104 -0
  11. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/implement-tasks.md +9 -0
  12. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/pr.md +10 -1
  13. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/specify.md +23 -0
  14. {codexspec-0.7.27 → codexspec-0.7.29}/.gitignore +0 -0
  15. {codexspec-0.7.27 → codexspec-0.7.29}/LICENSE +0 -0
  16. {codexspec-0.7.27 → codexspec-0.7.29}/README.md +0 -0
  17. {codexspec-0.7.27 → codexspec-0.7.29}/codexspec-icon.svg +0 -0
  18. {codexspec-0.7.27 → codexspec-0.7.29}/codexspec-logo-dark.svg +0 -0
  19. {codexspec-0.7.27 → codexspec-0.7.29}/codexspec-logo-light.svg +0 -0
  20. {codexspec-0.7.27 → codexspec-0.7.29}/scripts/bash/check-i18n-completeness.sh +0 -0
  21. {codexspec-0.7.27 → codexspec-0.7.29}/scripts/bash/check-i18n-structure.sh +0 -0
  22. {codexspec-0.7.27 → codexspec-0.7.29}/scripts/bash/check-prerequisites.sh +0 -0
  23. {codexspec-0.7.27 → codexspec-0.7.29}/scripts/bash/common.sh +0 -0
  24. {codexspec-0.7.27 → codexspec-0.7.29}/scripts/bash/create-new-feature.sh +0 -0
  25. {codexspec-0.7.27 → codexspec-0.7.29}/scripts/bash/review-context.sh +0 -0
  26. {codexspec-0.7.27 → codexspec-0.7.29}/scripts/powershell/check-prerequisites.ps1 +0 -0
  27. {codexspec-0.7.27 → codexspec-0.7.29}/scripts/powershell/common.ps1 +0 -0
  28. {codexspec-0.7.27 → codexspec-0.7.29}/scripts/powershell/create-new-feature.ps1 +0 -0
  29. {codexspec-0.7.27 → codexspec-0.7.29}/scripts/powershell/review-context.ps1 +0 -0
  30. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/blueprint.py +0 -0
  31. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/commands/__init__.py +0 -0
  32. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/commands/installer.py +0 -0
  33. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/commit_guidance.py +0 -0
  34. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/__init__.py +0 -0
  35. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/app.js +0 -0
  36. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/ar.json +0 -0
  37. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/de.json +0 -0
  38. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/en.json +0 -0
  39. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/es.json +0 -0
  40. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/fr.json +0 -0
  41. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/hi.json +0 -0
  42. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/it.json +0 -0
  43. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/ja.json +0 -0
  44. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/ko.json +0 -0
  45. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/pt.json +0 -0
  46. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/ru.json +0 -0
  47. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/zh-CN.json +0 -0
  48. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/i18n/zh-TW.json +0 -0
  49. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/index.html +0 -0
  50. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/assets/styles.css +0 -0
  51. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/domain.py +0 -0
  52. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/lease.py +0 -0
  53. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/models.py +0 -0
  54. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/records.py +0 -0
  55. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/server.py +0 -0
  56. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/distill_review/terminal.py +0 -0
  57. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/i18n.py +0 -0
  58. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/idea.md +0 -0
  59. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/installations/__init__.py +0 -0
  60. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/installations/cli.py +0 -0
  61. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/installations/discovery.py +0 -0
  62. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/installations/metadata.py +0 -0
  63. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/installations/release.py +0 -0
  64. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/installations/render.py +0 -0
  65. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/installations/upgrade.py +0 -0
  66. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/installations/worker.py +0 -0
  67. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/integrations/__init__.py +0 -0
  68. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/integrations/base.py +0 -0
  69. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/integrations/claude.py +0 -0
  70. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/integrations/codex.py +0 -0
  71. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/merge_commits.py +0 -0
  72. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/review_maintenance.py +0 -0
  73. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/review_standards.py +0 -0
  74. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/specs_context.py +0 -0
  75. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/staged_commits.py +0 -0
  76. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/translator.py +0 -0
  77. {codexspec-0.7.27 → codexspec-0.7.29}/src/codexspec/worktrees.py +0 -0
  78. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/analyze.md +0 -0
  79. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/auto-dev.md +0 -0
  80. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/blueprint.md +0 -0
  81. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/checklist.md +0 -0
  82. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/clarify.md +0 -0
  83. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/config.md +0 -0
  84. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/constitution.md +0 -0
  85. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/debug.md +0 -0
  86. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/design-to-plan.md +0 -0
  87. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/evolve.md +0 -0
  88. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/generate-spec.md +0 -0
  89. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/onboard.md +0 -0
  90. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/plan-to-tasks.md +0 -0
  91. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/quick.md +0 -0
  92. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/release-notes.md +0 -0
  93. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/reverse-spec.md +0 -0
  94. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/review-code.md +0 -0
  95. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/review-design.md +0 -0
  96. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/review-plan.md +0 -0
  97. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/review-spec.md +0 -0
  98. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/review-tasks.md +0 -0
  99. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/spec-to-design.md +0 -0
  100. {codexspec-0.7.27 → codexspec-0.7.29}/templates/commands/tasks-to-issues.md +0 -0
  101. {codexspec-0.7.27 → codexspec-0.7.29}/templates/docs/checklist-template.md +0 -0
  102. {codexspec-0.7.27 → codexspec-0.7.29}/templates/docs/constitution-template.md +0 -0
  103. {codexspec-0.7.27 → codexspec-0.7.29}/templates/docs/design-template.md +0 -0
  104. {codexspec-0.7.27 → codexspec-0.7.29}/templates/docs/plan-template-detailed.md +0 -0
  105. {codexspec-0.7.27 → codexspec-0.7.29}/templates/docs/plan-template-simple.md +0 -0
  106. {codexspec-0.7.27 → codexspec-0.7.29}/templates/docs/requirements-template.md +0 -0
  107. {codexspec-0.7.27 → codexspec-0.7.29}/templates/docs/spec-template-detailed.md +0 -0
  108. {codexspec-0.7.27 → codexspec-0.7.29}/templates/docs/spec-template-simple.md +0 -0
  109. {codexspec-0.7.27 → codexspec-0.7.29}/templates/docs/tasks-template-detailed.md +0 -0
  110. {codexspec-0.7.27 → codexspec-0.7.29}/templates/docs/tasks-template-simple.md +0 -0
  111. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/change-review.md +0 -0
  112. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/common.md +0 -0
  113. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/dimensions/business-semantics.md +0 -0
  114. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/dimensions/concurrency.md +0 -0
  115. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/dimensions/logic.md +0 -0
  116. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/dimensions/maintainability.md +0 -0
  117. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/dimensions/performance.md +0 -0
  118. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/dimensions/robustness.md +0 -0
  119. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/dimensions/security.md +0 -0
  120. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/frameworks/react.md +0 -0
  121. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/index.md +0 -0
  122. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/c.md +0 -0
  123. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/cpp.md +0 -0
  124. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/csharp.md +0 -0
  125. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/go.md +0 -0
  126. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/java.md +0 -0
  127. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/javascript.md +0 -0
  128. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/kotlin.md +0 -0
  129. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/php.md +0 -0
  130. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/python.md +0 -0
  131. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/ruby.md +0 -0
  132. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/rust.md +0 -0
  133. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/shell.md +0 -0
  134. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/swift.md +0 -0
  135. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/languages/typescript.md +0 -0
  136. {codexspec-0.7.27 → codexspec-0.7.29}/templates/review-code/quality-assessment.md +0 -0
  137. {codexspec-0.7.27 → codexspec-0.7.29}/templates/translations/de.json +0 -0
  138. {codexspec-0.7.27 → codexspec-0.7.29}/templates/translations/en.json +0 -0
  139. {codexspec-0.7.27 → codexspec-0.7.29}/templates/translations/es.json +0 -0
  140. {codexspec-0.7.27 → codexspec-0.7.29}/templates/translations/fr.json +0 -0
  141. {codexspec-0.7.27 → codexspec-0.7.29}/templates/translations/ja.json +0 -0
  142. {codexspec-0.7.27 → codexspec-0.7.29}/templates/translations/ko.json +0 -0
  143. {codexspec-0.7.27 → codexspec-0.7.29}/templates/translations/pt-BR.json +0 -0
  144. {codexspec-0.7.27 → codexspec-0.7.29}/templates/translations/zh-CN.json +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codexspec
3
- Version: 0.7.27
3
+ Version: 0.7.29
4
4
  Summary: CodexSpec - A Requirements-First SDD toolkit for Claude Code
5
5
  Project-URL: Homepage, https://github.com/Zts0hg/codexspec
6
6
  Project-URL: Repository, https://github.com/Zts0hg/codexspec
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "codexspec"
3
- version = "0.7.27"
3
+ version = "0.7.29"
4
4
  description = "CodexSpec - A Requirements-First SDD toolkit for Claude Code"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -80,7 +80,7 @@ from .worktrees import (
80
80
  )
81
81
 
82
82
  # Version info
83
- __version__ = "0.7.27"
83
+ __version__ = "0.7.29"
84
84
  __author__ = "CodexSpec Team"
85
85
 
86
86
  # Constitution file path constants
@@ -412,11 +412,16 @@ def _analysis_request(body: dict[str, Any], *, token: bool = False) -> None:
412
412
 
413
413
  @app.command("_commit-staged-helper", hidden=True)
414
414
  def commit_staged_helper(action: str = typer.Argument(...)) -> None:
415
- """Snapshot or commit the original index without staging files."""
415
+ """Guard original-index commits and explicitly owned automatic profile deltas."""
416
416
  from .commit_runtime import dispatch
417
417
 
418
418
  try:
419
- _machine_json(dispatch(action, _stdin_json() if action == "commit" else None))
419
+ _machine_json(
420
+ dispatch(
421
+ action,
422
+ _stdin_json() if action in {"commit", "distill-prepare", "distill-commit", "distill-close"} else None,
423
+ )
424
+ )
420
425
  except (AutomationError, OSError, ValueError) as exc:
421
426
  _automation_failure(exc)
422
427
 
@@ -514,7 +519,16 @@ def _validate_auto_dev_request(action: str, body: dict[str, Any]) -> None:
514
519
  raise AutomationError("invalid_continue_sync_request")
515
520
  elif action == "prepare-feature":
516
521
  if (
517
- set(body) != {"token", "feature_id", "paths"}
522
+ set(body) not in ({"token", "feature_id", "paths"}, {"token", "feature_id", "paths", "distill"})
523
+ or (
524
+ "distill" in body
525
+ and (
526
+ not isinstance(body["distill"], dict)
527
+ or set(body["distill"]) != {"transaction", "analysis"}
528
+ or not isinstance(body["distill"]["transaction"], str)
529
+ or not isinstance(body["distill"]["analysis"], dict)
530
+ )
531
+ )
518
532
  or not isinstance(body["feature_id"], str)
519
533
  or not isinstance(body["paths"], list)
520
534
  or not all(isinstance(path, str) for path in body["paths"])
@@ -588,7 +602,7 @@ def auto_dev_helper(action: str = typer.Argument(..., help="Internal helper acti
588
602
  token, checks_passed=body["checks_passed"], analysis=body.get("analysis"), message=body.get("message")
589
603
  )
590
604
  elif action == "prepare-feature":
591
- result = service.prepare_feature(token, body["feature_id"], body["paths"])
605
+ result = service.prepare_feature(token, body["feature_id"], body["paths"], distill=body.get("distill"))
592
606
  elif action == "commit-feature":
593
607
  result = service.commit_feature(token, body["preparation_id"], body["analyzed_tree"], body["message"])
594
608
  elif action == "discard-feature":
@@ -862,7 +862,9 @@ class AutoDevGit:
862
862
  if (self.workspace.repository.coordination_dir / "blueprint-transaction.json").exists():
863
863
  raise AutomationError("blueprint_recovery_required")
864
864
 
865
- def prepare_feature(self, token: str, feature_id: str, paths: Sequence[str]) -> dict[str, Any]:
865
+ def prepare_feature(
866
+ self, token: str, feature_id: str, paths: Sequence[str], *, distill: dict[str, Any] | None = None
867
+ ) -> dict[str, Any]:
866
868
  from .staged_commits import PreparedCommits
867
869
 
868
870
  self.ownership.assert_owner(token)
@@ -874,12 +876,24 @@ class AutoDevGit:
874
876
  with _git_write_lock(self.workspace.repository):
875
877
  with self.ownership.guard(token):
876
878
  self._assert_commit_ready()
877
- return PreparedCommits(self.workspace).prepare(
879
+ from .commit_runtime import validate_distill_binding
880
+
881
+ if distill is not None:
882
+ owned = validate_distill_binding(self.workspace.path, self.git, distill)
883
+ if set(normalized) != set(owned["files"]):
884
+ raise AutomationError("stale_analysis", "capture paths changed at handoff")
885
+ store = PreparedCommits(self.workspace)
886
+ prepared = store.prepare(
878
887
  normalized,
879
888
  kind="feature",
880
889
  scope=feature_id,
881
890
  token=token,
891
+ payload={"distill": distill} if distill is not None else None,
882
892
  )
893
+ if distill is not None and any(prepared[key] != distill["analysis"][key] for key in ("head", "tree")):
894
+ store.discard(prepared["preparation_id"], kind="feature", token=token)
895
+ raise AutomationError("stale_analysis", "capture content changed at handoff")
896
+ return prepared
883
897
 
884
898
  def commit_feature(
885
899
  self,
@@ -895,12 +909,38 @@ class AutoDevGit:
895
909
  with self.ownership.guard(token):
896
910
  self._assert_commit_ready()
897
911
  store = PreparedCommits(self.workspace)
898
- record = store.load(preparation_id, kind="feature", token=token)
912
+ record = store.load(preparation_id, kind="feature", token=token, validate_current=False)
899
913
  if not _FEATURE_ID_RE.fullmatch(record["scope"]):
900
914
  raise AutomationError("invalid_feature_id")
901
915
  validate_message(message, record["scope"])
902
916
  if record["tree"] != analyzed_tree:
903
917
  raise AutomationError("stale_analysis")
918
+ if "distill" in record["payload"]:
919
+ from .commit_runtime import _distill_commit
920
+
921
+ owner_index = Path(store.response(record)["index_file"])
922
+ if (
923
+ self.git.run(self.workspace.path, "write-tree", index_file=owner_index).stdout.strip()
924
+ != analyzed_tree
925
+ ):
926
+ raise AutomationError("stale_analysis", "owner preparation changed")
927
+ binding = record["payload"]["distill"]
928
+ if (
929
+ not isinstance(binding, dict)
930
+ or not isinstance(binding.get("analysis"), dict)
931
+ or any(binding["analysis"].get(key) != record[key] for key in ("head", "tree"))
932
+ ):
933
+ raise AutomationError("stale_analysis", "capture binding changed")
934
+ result = _distill_commit(
935
+ self.workspace.path,
936
+ self.git,
937
+ {**binding, "message": message},
938
+ required_scope=record["scope"],
939
+ preserve_configuration=False,
940
+ )
941
+ store.discard(preparation_id, kind="feature", token=token)
942
+ return {**result, "paths": record["paths"]}
943
+ store.load(preparation_id, kind="feature", token=token)
904
944
  current = store.prepare(record["paths"], kind="feature", scope=record["scope"], token=token)
905
945
  store.discard(current["preparation_id"], kind="feature", token=token)
906
946
  if current["tree"] != analyzed_tree:
@@ -1,19 +1,24 @@
1
1
  """Shared, standalone staged-commit guard; requires only Python 3.11+ and Git.
2
2
 
3
- The agent supplies the message. This module never selects or stages files.
4
- CLI imports and installed byte-identical copies execute this same implementation.
3
+ The agent supplies the message. Original-index snapshot/commit never stage files.
4
+ Automatic distill callers can prepare and finalize their explicitly owned profile
5
+ delta through the separate distill actions. CLI and installed byte-identical
6
+ copies execute this same implementation.
5
7
  """
6
8
 
7
9
  from __future__ import annotations
8
10
 
11
+ import hashlib
9
12
  import json
10
13
  import os
11
14
  import re
12
15
  import shlex
16
+ import shutil
13
17
  import subprocess
14
18
  import sys
15
19
  import tempfile
16
- from collections.abc import Mapping
20
+ from collections.abc import Iterator, Mapping
21
+ from contextlib import contextmanager
17
22
  from pathlib import Path
18
23
  from typing import Any, Sequence
19
24
 
@@ -458,6 +463,427 @@ def _hook_main(manifest_path: str, name: str, arguments: list[str]) -> int:
458
463
  return 0
459
464
 
460
465
 
466
+ _PROFILE_CATEGORIES = {"constraints", "conventions", "pitfalls", "decisions", "strategies", "runbooks"}
467
+
468
+
469
+ def _distill_safe(path: Path) -> None:
470
+ # Windows junctions are not symlinks on supported Python 3.11.
471
+ if path.resolve() != path.absolute():
472
+ raise AutomationError("linked_distill_path", str(path))
473
+ for part in (path, *path.parents):
474
+ if part.is_symlink():
475
+ raise AutomationError("linked_distill_path", str(part))
476
+ if path.exists() and (not path.is_file() or path.stat().st_nlink != 1):
477
+ raise AutomationError("shared_distill_file", str(path))
478
+
479
+
480
+ def _distill_path(repository: Path, name: str) -> Path:
481
+ if not isinstance(name, str):
482
+ raise AutomationError("invalid_distill_path")
483
+ parts = name.split("/")
484
+ if (
485
+ len(parts) != 4
486
+ or parts[:2] != [".codexspec", "profile"]
487
+ or parts[2] not in _PROFILE_CATEGORIES
488
+ or parts[3] in {"", ".", ".."}
489
+ or not parts[3].endswith(".md")
490
+ or any(c in name for c in "\\\0\r\n")
491
+ ):
492
+ raise AutomationError("invalid_distill_path", name)
493
+ path = repository.joinpath(*parts)
494
+ _distill_safe(path)
495
+ if not path.resolve().is_relative_to(repository):
496
+ raise AutomationError("invalid_distill_path", "resolved path escapes the workspace")
497
+ return path
498
+
499
+
500
+ def _distill_hash(path: Path) -> str | None:
501
+ _distill_safe(path)
502
+ return hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else None
503
+
504
+
505
+ def _distill_entries(repository: Path, git: GitRunner, index: Path | None = None) -> dict[str, str]:
506
+ entries: dict[str, str] = {}
507
+ for entry in git.run(repository, "ls-files", "--stage", "-z", index_file=index).stdout.split("\0"):
508
+ if entry:
509
+ header, name = entry.split("\t", 1)
510
+ entries[name] = entries.get(name, "") + header + "\n"
511
+ for entry in git.run(repository, "ls-files", "-v", "-z", index_file=index).stdout.split("\0"):
512
+ if entry:
513
+ entries[entry[2:]] = entries.get(entry[2:], "") + entry[0]
514
+ return entries
515
+
516
+
517
+ def _distill_identity(repository: Path, git: GitRunner) -> tuple[str, str]:
518
+ if Path(git.run(repository, "rev-parse", "--show-toplevel").stdout.strip()).resolve() != repository:
519
+ raise AutomationError("invalid_distill_workspace")
520
+ for name in ("MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply", "sequencer"):
521
+ path = Path(git.run(repository, "rev-parse", "--path-format=absolute", "--git-path", name).stdout.strip())
522
+ if path.exists():
523
+ raise AutomationError("integration_in_progress", name)
524
+ head = _head(repository, git)
525
+ branch = git.run(repository, "symbolic-ref", "--quiet", "HEAD", check=False)
526
+ if head is None or branch.returncode:
527
+ raise AutomationError("distill_requires_existing_branch")
528
+ return head, branch.stdout.strip()
529
+
530
+
531
+ def _distill_save(transaction: Path, record: dict[str, Any]) -> None:
532
+ _distill_safe(transaction)
533
+ temporary = transaction.with_suffix(".next")
534
+ _distill_safe(temporary)
535
+ temporary.write_text(json.dumps(record, ensure_ascii=True), encoding="utf-8", newline="\n")
536
+ temporary.chmod(0o600)
537
+ os.replace(temporary, transaction)
538
+
539
+
540
+ def _distill_start(repository: Path, git: GitRunner) -> dict[str, Any]:
541
+ head, branch = _distill_identity(repository, git)
542
+ if os.environ.get("GIT_INDEX_FILE"):
543
+ raise AutomationError("distill_requires_original_index")
544
+ index = Path(git.run(repository, "rev-parse", "--path-format=absolute", "--git-path", "index").stdout.strip())
545
+ _distill_safe(index)
546
+ entries = _distill_entries(repository, git)
547
+ head_entries: dict[str, tuple[str, str]] = {}
548
+ for item in git.run(repository, "ls-tree", "-r", "-z", head, "--", ".codexspec/profile").stdout.split("\0"):
549
+ if item:
550
+ header, name = item.split("\t", 1)
551
+ mode, kind, blob = header.split()
552
+ if kind == "blob" and name.endswith(".md"):
553
+ head_entries[name] = (mode, blob)
554
+ profile = repository / ".codexspec/profile"
555
+ for parent in (profile, profile.parent):
556
+ if parent.is_symlink():
557
+ raise AutomationError("linked_distill_path", str(parent))
558
+ names = set(head_entries)
559
+ names.update(
560
+ name
561
+ for name in entries
562
+ if len(name.split("/")) == 4
563
+ and name.split("/")[:2] == [".codexspec", "profile"]
564
+ and name.split("/")[2] in _PROFILE_CATEGORIES
565
+ and name.endswith(".md")
566
+ )
567
+ if profile.exists():
568
+ for category in _PROFILE_CATEGORIES:
569
+ directory = profile / category
570
+ if directory.is_symlink():
571
+ raise AutomationError("linked_distill_path", str(directory))
572
+ if directory.exists():
573
+ names.update(p.relative_to(repository).as_posix() for p in directory.glob("*.md"))
574
+ before, dirty = {}, []
575
+ tracks_mode = (
576
+ git.run(repository, "config", "--bool", "--get", "core.filemode", check=False).stdout.strip() != "false"
577
+ )
578
+ for name in sorted(names):
579
+ path = _distill_path(repository, name)
580
+ before[name] = _distill_hash(path)
581
+ mode, blob = head_entries.get(name, ("", ""))
582
+ entry = entries.get(name, "")
583
+ clean_index = entry == f"{mode} {blob} 0\nH"
584
+ actual_blob = git.run(repository, "hash-object", f"--path={name}", name).stdout.strip() if path.exists() else ""
585
+ actual_mode = "100755" if path.exists() and path.stat().st_mode & 0o111 else "100644"
586
+ if not clean_index or actual_blob != blob or (tracks_mode and actual_mode != mode):
587
+ dirty.append(name)
588
+ directory = Path(tempfile.mkdtemp(prefix="codexspec-distill-")).resolve()
589
+ try:
590
+ shutil.copyfile(index, directory / "before.index")
591
+ if entries != _distill_entries(repository, git, directory / "before.index"):
592
+ raise AutomationError("stale_distill_index")
593
+ transaction = directory / "state.json"
594
+ _distill_save(
595
+ transaction,
596
+ {
597
+ "workspace": str(repository),
598
+ "head": head,
599
+ "branch": branch,
600
+ "before": before,
601
+ "dirty": dirty,
602
+ "prepared": None,
603
+ "attempts": 0,
604
+ "committed": None,
605
+ },
606
+ )
607
+ return {"state": "started", "workspace": str(repository), "transaction": str(transaction), "dirty": dirty}
608
+ except BaseException:
609
+ shutil.rmtree(directory)
610
+ raise
611
+
612
+
613
+ def _distill_load(repository: Path, body: Any, keys: set[str]) -> tuple[Path, dict[str, Any]]:
614
+ if not isinstance(body, dict) or set(body) != keys or not isinstance(body.get("transaction"), str):
615
+ raise AutomationError("invalid_distill_request")
616
+ transaction = Path(body["transaction"])
617
+ if (
618
+ not transaction.is_absolute()
619
+ or transaction.name != "state.json"
620
+ or not transaction.parent.name.startswith("codexspec-distill-")
621
+ or transaction.parent.parent != Path(tempfile.gettempdir()).resolve()
622
+ ):
623
+ raise AutomationError("invalid_distill_transaction")
624
+ _distill_safe(transaction)
625
+ record = json.loads(transaction.read_text(encoding="utf-8"))
626
+ if (
627
+ not isinstance(record, dict)
628
+ or set(record) != {"workspace", "head", "branch", "before", "dirty", "prepared", "attempts", "committed"}
629
+ or record["workspace"] != str(repository)
630
+ or not isinstance(record["before"], dict)
631
+ or not isinstance(record["dirty"], list)
632
+ or type(record["attempts"]) is not int
633
+ ):
634
+ raise AutomationError("invalid_distill_transaction")
635
+ return transaction, record
636
+
637
+
638
+ def _distill_check_state(
639
+ repository: Path,
640
+ git: GitRunner,
641
+ transaction: Path,
642
+ record: dict[str, Any],
643
+ paths: set[str],
644
+ *,
645
+ completed: str | None = None,
646
+ ) -> None:
647
+ if _distill_identity(repository, git) != (completed or record["head"], record["branch"]):
648
+ raise AutomationError("stale_distill_identity")
649
+ baseline = transaction.parent / "before.index"
650
+ _distill_safe(baseline)
651
+ original = _distill_entries(repository, git, baseline)
652
+ current = _distill_entries(repository, git)
653
+ if {p: e for p, e in original.items() if p not in paths} != {p: e for p, e in current.items() if p not in paths}:
654
+ raise AutomationError("stale_distill_staging", "unrelated staging changed")
655
+ for path in paths:
656
+ if current.get(path) != original.get(path):
657
+ raise AutomationError("stale_distill_staging", path)
658
+
659
+
660
+ def _distill_prepare(repository: Path, git: GitRunner, body: Any) -> dict[str, Any]:
661
+ transaction, record = _distill_load(repository, body, {"transaction", "files"})
662
+ if record["committed"]:
663
+ raise AutomationError("distill_already_committed")
664
+ files = body["files"]
665
+ if not isinstance(files, dict):
666
+ raise AutomationError("invalid_distill_request")
667
+ changed: dict[str, str | None] = {}
668
+ for name, expected in files.items():
669
+ path = _distill_path(repository, name)
670
+ for original_name in record["before"]:
671
+ original_path = repository / original_name
672
+ if original_name != name and path.exists() and original_path.exists() and path.samefile(original_path):
673
+ raise AutomationError("invalid_distill_path", "aliases a pre-existing profile file")
674
+ if expected is not None and (not isinstance(expected, str) or not re.fullmatch("[0-9a-f]{64}", expected)):
675
+ raise AutomationError("invalid_distill_request")
676
+ if _distill_hash(path) != expected:
677
+ raise AutomationError("stale_distill_content", name)
678
+ if record["before"].get(name) != expected:
679
+ if name in record["dirty"]:
680
+ raise AutomationError("preexisting_profile_changes", name)
681
+ changed[name] = expected
682
+ _distill_check_state(repository, git, transaction, record, set(changed))
683
+ if not changed:
684
+ return {"state": "unchanged", "paths": []}
685
+ index = transaction.parent / "analysis.index"
686
+ _distill_safe(index)
687
+ git.run(repository, "read-tree", record["head"], index_file=index)
688
+ git.run(repository, "--literal-pathspecs", "add", "-A", "--", *sorted(changed), index_file=index)
689
+ tree = git.run(repository, "write-tree", index_file=index).stdout.strip()
690
+ actual_paths = set(
691
+ git.run(repository, "diff", "--no-renames", "--name-only", "-z", record["head"], tree).stdout.split("\0")
692
+ ) - {""}
693
+ if actual_paths - set(changed):
694
+ raise AutomationError("invalid_distill_path", "prepared tree changes unowned paths")
695
+ if tree == git.run(repository, "rev-parse", f"{record['head']}^{{tree}}").stdout.strip():
696
+ return {"state": "unchanged", "paths": []}
697
+ analysis = {"workspace": str(repository), "index_file": str(index), "head": record["head"], "tree": tree}
698
+ record["prepared"] = {
699
+ "analysis": analysis,
700
+ "files": changed,
701
+ }
702
+ _distill_save(transaction, record)
703
+ return {"state": "prepared", "analysis": analysis, "paths": sorted(changed), "required_scope": "profile"}
704
+
705
+
706
+ def _distill_completed(repository: Path, git: GitRunner, record: dict[str, Any], message: str) -> str | None:
707
+ head, branch = _distill_identity(repository, git)
708
+ if branch != record["branch"] or head == record["head"]:
709
+ return None
710
+ analysis = record["prepared"]["analysis"]
711
+ submitted = record["prepared"].get("submitted_message")
712
+ if not isinstance(submitted, str) or submitted.rstrip("\n") != message.rstrip("\n"):
713
+ return None
714
+ if (
715
+ git.run(repository, "show", "-s", "--format=%P", head).stdout.strip() == record["head"]
716
+ and git.run(repository, "rev-parse", f"{head}^{{tree}}").stdout.strip() == analysis["tree"]
717
+ ):
718
+ return head
719
+ return None
720
+
721
+
722
+ def validate_distill_binding(repository: Path, git: GitRunner, binding: Any) -> dict[str, Any]:
723
+ """Validate the original capture, including across a helper-owned handoff."""
724
+ transaction, record = _distill_load(repository, binding, {"transaction", "analysis"})
725
+ prepared = record["prepared"]
726
+ if not isinstance(prepared, dict) or binding["analysis"] != prepared["analysis"]:
727
+ raise AutomationError("stale_analysis")
728
+ _distill_check_state(repository, git, transaction, record, set(prepared["files"]))
729
+ for name, expected in prepared["files"].items():
730
+ if _distill_hash(_distill_path(repository, name)) != expected:
731
+ raise AutomationError("stale_distill_content", name)
732
+ index = transaction.parent / "analysis.index"
733
+ _distill_safe(index)
734
+ if (
735
+ prepared["analysis"]["index_file"] != str(index)
736
+ or git.run(repository, "write-tree", index_file=index).stdout.strip() != prepared["analysis"]["tree"]
737
+ ):
738
+ raise AutomationError("stale_analysis")
739
+ return prepared
740
+
741
+
742
+ def _distill_index_signature(path: Path) -> dict[str, Any]:
743
+ """Identify the exact original index file, not only its logical Git entries."""
744
+ _distill_safe(path)
745
+ info = path.stat()
746
+ return {
747
+ "device": info.st_dev,
748
+ "inode": info.st_ino,
749
+ "mtime_ns": info.st_mtime_ns,
750
+ "ctime_ns": info.st_ctime_ns,
751
+ "size": info.st_size,
752
+ "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
753
+ }
754
+
755
+
756
+ @contextmanager
757
+ def _distill_locked_index(repository: Path, git: GitRunner, paths: set[str]) -> Iterator[dict[str, Any]]:
758
+ """Hold Git's native writer lock; publish only explicitly completed work."""
759
+ original = Path(git.run(repository, "rev-parse", "--path-format=absolute", "--git-path", "index").stdout.strip())
760
+ lock = original.with_name(original.name + ".lock")
761
+ _distill_safe(original)
762
+ _distill_safe(lock)
763
+ try:
764
+ descriptor = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
765
+ except FileExistsError as exc:
766
+ raise AutomationError("distill_index_busy", "another Git writer owns index.lock") from exc
767
+ identity = os.fstat(descriptor)
768
+ try:
769
+ with (
770
+ os.fdopen(descriptor, "wb") as output,
771
+ tempfile.TemporaryDirectory(prefix="codexspec-distill-index-") as temporary,
772
+ ):
773
+ index = Path(temporary) / "index"
774
+ source = _distill_index_signature(original)
775
+ shutil.copyfile(original, index)
776
+ before = _distill_entries(repository, git, original)
777
+ prepared = {"index": index, "source": source, "publish": False}
778
+ yield prepared
779
+ if not prepared["publish"]:
780
+ return
781
+ after = _distill_entries(repository, git, index)
782
+ if {p: e for p, e in before.items() if p not in paths} != {
783
+ p: e for p, e in after.items() if p not in paths
784
+ }:
785
+ raise AutomationError("stale_distill_staging", "finalization changed unrelated entries")
786
+ output.write(index.read_bytes())
787
+ output.flush()
788
+ os.fsync(output.fileno())
789
+ # Close before replace: Windows does not allow replacing an open file.
790
+ _distill_safe(lock)
791
+ try:
792
+ current = lock.lstat()
793
+ except FileNotFoundError as exc:
794
+ raise AutomationError("lost_distill_index_lock") from exc
795
+ if (current.st_dev, current.st_ino) != (identity.st_dev, identity.st_ino):
796
+ raise AutomationError("lost_distill_index_lock")
797
+ _distill_safe(original)
798
+ os.replace(lock, original)
799
+ finally:
800
+ if lock.exists():
801
+ current = lock.lstat()
802
+ if (current.st_dev, current.st_ino) == (identity.st_dev, identity.st_ino):
803
+ lock.unlink()
804
+
805
+
806
+ def _distill_commit(
807
+ repository: Path,
808
+ git: GitRunner,
809
+ body: Any,
810
+ *,
811
+ required_scope: str = "profile",
812
+ preserve_configuration: bool = True,
813
+ ) -> dict[str, Any]:
814
+ transaction, record = _distill_load(repository, body, {"transaction", "analysis", "message"})
815
+ prepared = record["prepared"]
816
+ if not isinstance(prepared, dict) or body["analysis"] != prepared["analysis"]:
817
+ raise AutomationError("stale_analysis")
818
+ validate_message(body["message"], required_scope)
819
+ completed = _distill_completed(repository, git, record, body["message"])
820
+ if completed is not None and record["committed"] == completed:
821
+ # The index was already published. Later caller staging belongs to the caller.
822
+ return {"state": "committed", "commit": completed}
823
+ paths = sorted(prepared["files"])
824
+ with _distill_locked_index(repository, git, set(paths)) as current:
825
+ index = current["index"]
826
+ if completed is not None:
827
+ # Repair only the exact file held before the interrupted commit. A later
828
+ # Git write, even one restoring identical entries, is caller-owned.
829
+ if current["source"] == prepared.get("finalizing_index"):
830
+ _distill_check_state(repository, git, transaction, record, set(paths), completed=completed)
831
+ git.run(
832
+ repository, "--literal-pathspecs", "reset", "--quiet", completed, "--", *paths, index_file=index
833
+ )
834
+ current["publish"] = True
835
+ commit = completed
836
+ else:
837
+ validate_distill_binding(repository, git, {"transaction": str(transaction), "analysis": body["analysis"]})
838
+ if record["attempts"] >= 3:
839
+ raise AutomationError("distill_retry_limit")
840
+ record["attempts"] += 1
841
+ prepared["finalizing_index"] = current["source"]
842
+ prepared["submitted_message"] = body["message"]
843
+ _distill_save(transaction, record)
844
+ git.run(repository, "--literal-pathspecs", "add", "-A", "--", *paths, index_file=index)
845
+ try:
846
+ commit = guarded_commit(
847
+ repository,
848
+ record["head"],
849
+ prepared["analysis"]["tree"],
850
+ body["message"],
851
+ paths=paths,
852
+ index_file=index,
853
+ preserve_configuration=preserve_configuration,
854
+ )
855
+ except AutomationError:
856
+ commit = _distill_completed(repository, git, record, body["message"])
857
+ if commit is None:
858
+ raise
859
+ current["publish"] = True
860
+ # This marker means publication settled, not merely that HEAD advanced.
861
+ record["committed"] = commit
862
+ _distill_save(transaction, record)
863
+ return {"state": "committed", "commit": commit}
864
+
865
+
866
+ def _distill_dispatch(repository: Path, action: str, body: Any) -> dict[str, Any]:
867
+ git = GitRunner(preserve_configuration=True)
868
+ if action == "distill-start":
869
+ if body is not None:
870
+ raise AutomationError("invalid_distill_request")
871
+ return _distill_start(repository, git)
872
+ if action == "distill-prepare":
873
+ return _distill_prepare(repository, git, body)
874
+ if action == "distill-commit":
875
+ return _distill_commit(repository, git, body)
876
+ if action == "distill-close":
877
+ transaction, _ = _distill_load(repository, body, {"transaction"})
878
+ for path in transaction.parent.iterdir():
879
+ _distill_safe(path)
880
+ if path.name not in {"state.json", "before.index", "analysis.index"}:
881
+ raise AutomationError("distill_preparation_busy", path.name)
882
+ shutil.rmtree(transaction.parent)
883
+ return {"state": "closed"}
884
+ raise AutomationError("unsupported_commit_staged_action", action)
885
+
886
+
461
887
  def dispatch(action: str, body: Any = None) -> dict[str, Any]:
462
888
  """Serve the same strict machine protocol through CLI and standalone entry."""
463
889
  if action == "snapshot":
@@ -466,6 +892,8 @@ def dispatch(action: str, body: Any = None) -> dict[str, Any]:
466
892
  if not isinstance(body, dict) or set(body) != {"analysis", "message"} or not isinstance(body["analysis"], dict):
467
893
  raise AutomationError("analysis_required")
468
894
  return commit_snapshot(Path.cwd(), body["analysis"], body["message"])
895
+ if action.startswith("distill-"):
896
+ return _distill_dispatch(Path.cwd().resolve(), action, body)
469
897
  raise AutomationError("unsupported_commit_staged_action", action)
470
898
 
471
899
 
@@ -489,7 +917,11 @@ def main(arguments: list[str]) -> int:
489
917
  return _hook_main(arguments[1], arguments[2], arguments[3:])
490
918
  if len(arguments) != 1:
491
919
  raise AutomationError("invalid_arguments", "expected snapshot or commit")
492
- body = json.loads(sys.stdin.buffer.read().decode("utf-8")) if arguments[0] == "commit" else None
920
+ body = (
921
+ json.loads(sys.stdin.buffer.read().decode("utf-8"))
922
+ if arguments[0] in {"commit", "distill-prepare", "distill-commit", "distill-close"}
923
+ else None
924
+ )
493
925
  print(json.dumps(dispatch(arguments[0], body)))
494
926
  return 0
495
927
  except (AutomationError, OSError, ValueError) as exc:
@@ -219,9 +219,12 @@ class SessionStore:
219
219
  os.fsync(directory)
220
220
  finally:
221
221
  try:
222
- os.unlink(temporary, dir_fd=directory)
223
- except FileNotFoundError:
224
- pass
222
+ os.close(descriptor)
223
+ finally:
224
+ try:
225
+ os.unlink(temporary, dir_fd=directory)
226
+ except FileNotFoundError:
227
+ pass
225
228
 
226
229
  def _write_runtime(self, name: str, content: bytes) -> None:
227
230
  with self._runtime_directory(create=True) as directory:
@@ -487,9 +487,12 @@ class ProfileTransaction:
487
487
  os.fsync(directory)
488
488
  finally:
489
489
  try:
490
- os.unlink(temporary_name, dir_fd=directory)
491
- except FileNotFoundError:
492
- pass
490
+ os.close(descriptor)
491
+ finally:
492
+ try:
493
+ os.unlink(temporary_name, dir_fd=directory)
494
+ except FileNotFoundError:
495
+ pass
493
496
 
494
497
  def _write_target(
495
498
  self,