pcdd 0.4.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.
- pcdd-0.4.0.dist-info/METADATA +100 -0
- pcdd-0.4.0.dist-info/RECORD +18 -0
- pcdd-0.4.0.dist-info/WHEEL +5 -0
- pcdd-0.4.0.dist-info/entry_points.txt +2 -0
- pcdd-0.4.0.dist-info/licenses/LICENSE +21 -0
- pcdd-0.4.0.dist-info/top_level.txt +1 -0
- pcdd_toolkit/__init__.py +2 -0
- pcdd_toolkit/__main__.py +3 -0
- pcdd_toolkit/assets/change.md +25 -0
- pcdd_toolkit/assets/core.md +18 -0
- pcdd_toolkit/assets/skills/pcdd-commit/SKILL.md +30 -0
- pcdd_toolkit/assets/skills/pcdd-commit-review/SKILL.md +21 -0
- pcdd_toolkit/assets/skills/pcdd-review/SKILL.md +28 -0
- pcdd_toolkit/assets/skills/pcdd-work/SKILL.md +59 -0
- pcdd_toolkit/cli.py +415 -0
- pcdd_toolkit/locales/en.json +91 -0
- pcdd_toolkit/locales/es.json +91 -0
- pcdd_toolkit/presentation.py +261 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pcdd
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Progressive Change-Driven Development: a local toolkit for working with AI coding agents
|
|
5
|
+
Author: aledepaoligampel
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/aledepaoligampel/pcdd
|
|
8
|
+
Classifier: Environment :: Console
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Dynamic: license-file
|
|
14
|
+
|
|
15
|
+
# PCDD
|
|
16
|
+
|
|
17
|
+
**Progressive Change-Driven Development**
|
|
18
|
+
|
|
19
|
+
Each change, just enough process.
|
|
20
|
+
|
|
21
|
+
PCDD is a local toolkit for working with AI coding agents. It helps a person and an agent agree on a change, keep enough context to resume it, and verify the result before calling it done.
|
|
22
|
+
|
|
23
|
+
The idea is to add structure as the work needs it. A small, well-understood fix can proceed directly. A substantial change gets approved specifications, tasks, and evidence. A risky change gets independent review and verification before commit approval. Size alone does not determine risk.
|
|
24
|
+
|
|
25
|
+
## How it works
|
|
26
|
+
|
|
27
|
+
1. **Understand the request.** The agent reads relevant project context and resolves decisions that affect the work.
|
|
28
|
+
2. **Define the change.** For substantial work, record verifiable specifications and get approval before implementation.
|
|
29
|
+
3. **Implement and verify.** Use test-first development when there is a deterministic test and a clear expected result; otherwise record the alternative evidence. Run the project's checks.
|
|
30
|
+
4. **Keep continuity.** Record tasks, evidence, and the next step in a change document so a new session can pick up the work.
|
|
31
|
+
5. **Accept the result.** The user tests the outcome before the change is considered complete. Commits and publication follow the project's authorization rules.
|
|
32
|
+
|
|
33
|
+
The starting context stays small: a short core points the agent to relevant instructions and project files. Detailed skills are loaded when needed.
|
|
34
|
+
|
|
35
|
+
## PCDD, SDD, and ODD
|
|
36
|
+
|
|
37
|
+
These approaches overlap. The comparison below describes their organizing ideas; individual implementations can differ.
|
|
38
|
+
|
|
39
|
+
| Approach | Organizing idea | Practical emphasis |
|
|
40
|
+
| --- | --- | --- |
|
|
41
|
+
| **SDD — Spec-Driven Development** | Use a specification to guide implementation and verification. | Make intended behavior explicit and carry it through planning, code, and checks. |
|
|
42
|
+
| **ODD — Organic Driven Development** | Adapt the workflow to the request and available context. | Handle understood work directly and preserve context for substantial work. |
|
|
43
|
+
| **PCDD — Progressive Change-Driven Development** | Organize work around a change, adding definition and checks as needed. | Use approved specifications for substantial work, independent review for high risk, and local records for continuation and acceptance. |
|
|
44
|
+
|
|
45
|
+
PCDD uses specifications and adapts process to the work. Its concrete choices are a local CLI, Markdown change records, project-owned gates, and agent skills. It does not require an external memory service or a particular application stack. No comparative token, speed, or quality advantage has been established.
|
|
46
|
+
|
|
47
|
+
## What's included
|
|
48
|
+
|
|
49
|
+
- **Codex, Claude Code, and Antigravity adapters**, installed in the target project.
|
|
50
|
+
- **Four skills:** `pcdd-work`, `pcdd-review`, `pcdd-commit`, and `pcdd-commit-review`.
|
|
51
|
+
- **Installation and maintenance:** preview changes, check an installation, update managed files, and recover or roll back transactions.
|
|
52
|
+
- **Change records:** specifications, task states, verification evidence, and continuation notes.
|
|
53
|
+
- **Progress and time:** task counts and explicitly recorded work intervals, available as human-readable output or JSON.
|
|
54
|
+
- **English and Spanish CLI output.** Agent responses follow the user's language; project documents follow the project's conventions.
|
|
55
|
+
|
|
56
|
+
## Try it
|
|
57
|
+
|
|
58
|
+
Requires **Python 3.9+**, with no runtime dependencies. PCDD is not published to a package registry yet; install it from the Git repository with [uv](https://docs.astral.sh/uv/) (recommended) or [pipx](https://pipx.pypa.io/). Both put the `pcdd` command on your `PATH` in an isolated environment:
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
uv tool install pcdd --from git+https://github.com/aledepaoligampel/pcdd
|
|
62
|
+
# or
|
|
63
|
+
pipx install git+https://github.com/aledepaoligampel/pcdd
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
If you don't have uv, install it with `brew install uv` or `curl -LsSf https://astral.sh/uv/install.sh | sh` (see the [uv installation guide](https://docs.astral.sh/uv/getting-started/installation/) for Windows and other options). For pipx, use `brew install pipx && pipx ensurepath`. Open a new terminal afterwards so `pcdd` is on your `PATH`.
|
|
67
|
+
|
|
68
|
+
You can also install from a local checkout with `uv tool install /path/to/pcdd` or `pipx install /path/to/pcdd`. To upgrade, run `uv tool upgrade pcdd` or `pipx upgrade pcdd`.
|
|
69
|
+
|
|
70
|
+
Then work from the project where you want to use PCDD:
|
|
71
|
+
|
|
72
|
+
```sh
|
|
73
|
+
cd /path/to/your-project
|
|
74
|
+
pcdd init --dry-run
|
|
75
|
+
pcdd init
|
|
76
|
+
pcdd doctor
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
`init` installs Codex and Claude Code by default. Select Antigravity with `pcdd init --adapters antigravity`, or combine adapters with commas, such as `--adapters codex,claude,antigravity`. Codex and Antigravity share `AGENTS.md` and the four skills in `.agents/skills/`; Claude Code also uses `CLAUDE.md` and `.claude/skills/`. Review the preview before applying it. Existing installations keep their adapter selection when updated.
|
|
80
|
+
|
|
81
|
+
Without installing, you can run a checkout directly with `python3 /path/to/pcdd/pcdd.py` or add `/path/to/pcdd/bin` to your `PATH`; use `--project /path/to/your-project` before the subcommand to target a project without changing directories.
|
|
82
|
+
|
|
83
|
+
Open a new agent session in the target project and describe the change you want. The installed instructions guide the agent through the appropriate workflow. Configure real project checks before committing; a fresh installation has no gate commands yet.
|
|
84
|
+
|
|
85
|
+
To check the toolkit itself:
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
make ready
|
|
89
|
+
make package-check # builds and installs a wheel in a temporary venv; needs network
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
See [usage and recovery](USAGE.md), [design](docs/design.md), and the [roadmap](docs/roadmap.md) for details. These project documents are currently in Spanish.
|
|
93
|
+
|
|
94
|
+
PCDD is released under the [MIT License](LICENSE).
|
|
95
|
+
|
|
96
|
+
## Current scope
|
|
97
|
+
|
|
98
|
+
PCDD v0.4 is an early toolkit. Antigravity installation is covered by CLI tests, with a discovery and continuation pilot in Antigravity CLI. Behavior in the graphical IDE has not been verified; check discovery in the client you use. The CLI manages files and records; the instructions guide agent behavior. It does not technically enforce every workflow rule or guarantee that a model follows it.
|
|
99
|
+
|
|
100
|
+
Task counts measure completed tasks, not effort. Recorded time covers explicitly opened and closed intervals, not necessarily the full development duration. Project checks and human acceptance remain necessary.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
pcdd-0.4.0.dist-info/licenses/LICENSE,sha256=UUHGTPEipbcMEXVCzMoO_v8OxIzsHEpsGb5fZVpzQKM,1073
|
|
2
|
+
pcdd_toolkit/__init__.py,sha256=nHb7l4Y9fVgLQFro1ROIJoGs06TTVFmIHCZOteBPdZs,79
|
|
3
|
+
pcdd_toolkit/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
|
|
4
|
+
pcdd_toolkit/cli.py,sha256=UG21QJbbI2jHBQnpNsIPA69KhqglnCYCXJghHbcGsJQ,17170
|
|
5
|
+
pcdd_toolkit/presentation.py,sha256=L5HQxc9AtYW43FYF2p0gxxNKXbhfHuh2mC9zW7NynRg,11501
|
|
6
|
+
pcdd_toolkit/assets/change.md,sha256=7gfY2tDRgfochF0cWbzWylZ2S-AX8WzkxHtObo7Bmjg,594
|
|
7
|
+
pcdd_toolkit/assets/core.md,sha256=eEPJPPyeBlra27V6pjtMlXCJZbydk6N3cA8cDzvpPF4,5228
|
|
8
|
+
pcdd_toolkit/assets/skills/pcdd-commit/SKILL.md,sha256=3RPmOJmQZq6JGZpV8b57AGBEZGqa2CV_gOs17wN8bUA,5073
|
|
9
|
+
pcdd_toolkit/assets/skills/pcdd-commit-review/SKILL.md,sha256=aaN2ituLD2Exn6P9fsZFVxbQVaafoVYFeSb1EKhWO6U,3461
|
|
10
|
+
pcdd_toolkit/assets/skills/pcdd-review/SKILL.md,sha256=tTBGWBYnY__WTqGbK_LbjZFhE7qSvAcgjW2CqgTj47A,2565
|
|
11
|
+
pcdd_toolkit/assets/skills/pcdd-work/SKILL.md,sha256=l-XzG_H-FVsTPEuQj_yUA9-x35Oeoxkjn9_qbjY9xxM,9287
|
|
12
|
+
pcdd_toolkit/locales/en.json,sha256=6eYpRF5AMMyW9VIIbKn3bribQaMHWzGLNBWR0GWwT2g,5978
|
|
13
|
+
pcdd_toolkit/locales/es.json,sha256=fZZ3u27xBfOW9eXq6_KsAnYa97DPFua9tVTprHkd288,7243
|
|
14
|
+
pcdd-0.4.0.dist-info/METADATA,sha256=HDTxLcKHSvEKYMhVk15pYUHxwQ8ieQX6oHZN-v7yTE8,6769
|
|
15
|
+
pcdd-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
16
|
+
pcdd-0.4.0.dist-info/entry_points.txt,sha256=1oJh2tNbvxFU6VZCPmm_AOCuq_6SdOvcGteR-YqjZAs,47
|
|
17
|
+
pcdd-0.4.0.dist-info/top_level.txt,sha256=zhTfVUfy680C2E-gSgKWHvPh_rrvAhkfcqnFO7_UJho,13
|
|
18
|
+
pcdd-0.4.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 aledepaoligampel
|
|
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
|
+
pcdd_toolkit
|
pcdd_toolkit/__init__.py
ADDED
pcdd_toolkit/__main__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# {{name}}
|
|
2
|
+
|
|
3
|
+
<!-- Write project content in its agreed language, or the user's language if none is set.
|
|
4
|
+
Preserve original quotations verbatim. Keep the Tasks heading and task syntax unchanged:
|
|
5
|
+
the CLI parses them. Other headings may follow project conventions. -->
|
|
6
|
+
|
|
7
|
+
## Specs
|
|
8
|
+
|
|
9
|
+
<!-- S1: original user quotation, behavior, and verifiable acceptance criterion. -->
|
|
10
|
+
|
|
11
|
+
## Tasks
|
|
12
|
+
|
|
13
|
+
- [ ] T1 (S1) Define and approve scope
|
|
14
|
+
|
|
15
|
+
## Evidence
|
|
16
|
+
|
|
17
|
+
No evidence yet.
|
|
18
|
+
|
|
19
|
+
## Continuation
|
|
20
|
+
|
|
21
|
+
Next step: define specs. Stage: definition. Human acceptance: pending.
|
|
22
|
+
|
|
23
|
+
## Log
|
|
24
|
+
|
|
25
|
+
<!-- L1: verbatim request. Record actual approvals. -->
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# PCDD — Progressive Change-Driven Development
|
|
2
|
+
|
|
3
|
+
Each change, just enough process. Project-specific instructions override these defaults within the agent's constraints. This does not authorize external effects or expand the user's request.
|
|
4
|
+
|
|
5
|
+
The kit's instructions and source templates are maintained in English. Respond in the user's language and write project documents in the project's agreed language, falling back to the user's language if none is established. Preserve original quotations and approvals verbatim. Keep command names, identifiers, and machine-parsed syntax unchanged; the CLI language setting controls terminal output only.
|
|
6
|
+
|
|
7
|
+
1. Understand the request and discover context before asking the user for paths: inspect relevant files and locate project instructions, overview, planning, continuation notes, and manifests where available. Read only what the request needs. Do not require a particular context filename or load the entire history. If several active efforts fit the request, ask which one to continue. Questions and research do not authorize implementation. Well-understood, bounded work that can be resumed from the diff proceeds directly, without a separate change document or routine delegation. Assess risk independently of size.
|
|
8
|
+
2. For substantial work, read the `pcdd-work` skill installed for your agent. Use a document at `pcdd/changes/<name>.md`. Do not load all changes or their history at startup; resume from the continuation section and relevant specs/tasks. For requests to save progress or continue where work stopped, consult `pcdd-work` to preserve or recover the continuation point without loading the entire history. Recognize these requests in the user's language and preserve existing section names, including `Continuación` in older documents.
|
|
9
|
+
3. Before implementing a change, present verifiable specs with the user's quotations and wait for approval. Record the actual approval. Do not request approval again when already granted. An extension requires approval only for the new scope.
|
|
10
|
+
4. Use test-first development when a deterministic test and clear expected result exist: observe RED, GREEN, then refactor. Verify behavior through public interfaces. Otherwise explain the alternative evidence and what remains unverified.
|
|
11
|
+
5. Identify risk: (1) persisted data or irreversible effects; (2) security; (3) external contracts; (4) concurrency; (5) delivery/environment; (6) lack of coverage; (7) money/tax. Use `Risk: none` or `Risk: item N (reason)`. Prefer a coherent unit over an artificial 400-line split.
|
|
12
|
+
6. Before committing, run the gate configured in `.pcdd/config.json` and the database gate if applicable. If empty, investigate existing scripts and tools and configure real commands during authorized work, preserving the project's settings. If no application exists yet, define gates with its first scaffold and tests; do not use benchmarks as the product gate or invent commands. Ask only when a real decision is unresolved. Empty does not mean passed. High risk also requires `pcdd-review`, code review and independent verification after the gate, and human approval based on an understandable summary. For small risky work, create a minimal record of criteria, evidence, and approval.
|
|
13
|
+
7. For work tracked in a change, check the current session's exposed tools for native task tracking. When available, use them to mirror the change's tasks at startup/resumption and after state changes; preserve PCDD task IDs in labels and derive all states from the document. Update the document first; the native view is not a second plan. If the tools are absent or cannot represent the state, explain the limitation at startup or when encountered; do not claim text lists are native tasks. Also show a brief chat block when starting or resuming and when task status changes: completed count, relevant completed tasks, active task, and next step or blocker. During long operations, explain what is still running and what remains unknown without inventing progress. Use the CLI for task counts and measured time; show the confirmed closed duration when closing a work interval. Do not invent durations, savings, or ETAs. Close the interval before waiting for the user. Do not estimate the missing time of an interrupted session.
|
|
14
|
+
8. The user tests the result before the change is declared done. Completed tasks do not imply acceptance. Push, PR, merge, and publication require explicit instructions; commits follow the project's authorization rules.
|
|
15
|
+
|
|
16
|
+
For Git commits, use `pcdd-commit`; to organize pending changes into coherent commits, use `pcdd-commit-review`. These skills do not replace the high-risk review checkpoint. Review-only requests do not authorize index or history changes. Whether or not a commit skill is loaded, preserve the user's Git identity and never add `Co-Authored-By` trailers, textual signatures, or AI attribution to commits or PR descriptions. Respect the project's cryptographic signing configuration and hooks; cryptographic signatures are not AI attribution.
|
|
17
|
+
|
|
18
|
+
Configuration belongs to the project. Do not customize managed core or skill files; use `AGENTS.md` and `.pcdd/config.json`. PCDD requires no external memory, MCP, or particular editor.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: pcdd-commit
|
|
3
|
+
description: Create a coherent Git commit within the user's authorized scope, preserving unrelated work and staging. Use for commit requests or explicit invocation; a review-only request does not authorize Git writes.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# PCDD Commit
|
|
7
|
+
|
|
8
|
+
Read the current checkout's project instructions and `.pcdd/core.md`, unless already loaded. Discover applicable commit conventions and gate commands from that project; do not assume a package manager, directory layout, or separate command file. Resolve the root with `git rev-parse --show-toplevel` and work in that checkout, including worktrees.
|
|
9
|
+
|
|
10
|
+
## Scope and authorization
|
|
11
|
+
|
|
12
|
+
An explicit invocation or request to commit authorizes commits within the stated scope. Present the message and paths as an informative update and proceed without asking for equivalent approval again. An explicit push request may include preparing necessary commits for the named work, subject to project rules; preserve its specified destination. A commit request alone never authorizes push, PR, merge, or publication.
|
|
13
|
+
|
|
14
|
+
PCDD's high-risk control still applies: the candidate must pass its gate, receive code review and independent verification through `pcdd-review`, and receive human approval of the risk summary before committing. General commit authorization or spec approval does not replace that checkpoint. Preserve an approval already granted for the same candidate and scope.
|
|
15
|
+
|
|
16
|
+
If the request is only to review or propose, return findings without changing the index or history. If scope is ambiguous, inspect first and ask only about the unresolved part. Do not infer ownership or include another effort merely because it is dirty or staged.
|
|
17
|
+
|
|
18
|
+
## Prepare and commit
|
|
19
|
+
|
|
20
|
+
1. Inspect status, complete staged and unstaged diffs, and relevant untracked files. Check Git author and committer identity without replacing it with an agent identity. If identity is missing or inconsistent with the requested author, resolve that before committing; do not invent it.
|
|
21
|
+
2. Confirm that the changes express one coherent intent. If they need multiple commits, use `pcdd-commit-review`; the existing authorization remains valid for the same scope. Include related tests and documentation with each unit. Do not force a split by line count.
|
|
22
|
+
3. Run the project's applicable gates for the candidate, including its database gate when required. Existing evidence is reusable only if it covers this candidate and project rules allow it. Do not bypass failures, label missing checks as passed, or substitute an unrelated benchmark. Apply the high-risk checkpoint when relevant.
|
|
23
|
+
4. Exclude secrets, real environment files, private keys/certificates, generated dependencies, builds, and scratch files unless the project intentionally tracks an appropriate non-secret artifact. Review example environment files for real credentials. Preserve unrelated files and staged changes.
|
|
24
|
+
5. Follow the project's commit convention. If none exists, use English Conventional Commits: `type(scope): imperative description`, with a subject no longer than 72 characters and an optional body explaining why. Use an existing meaningful scope; do not invent a fixed module catalog. Reference the actual change document and task/spec IDs when relevant, without inventing them.
|
|
25
|
+
6. Show the message and included paths. Stage explicit paths or selected hunks, never indiscriminately run `git add .` or `git add -A`. A path can contain both authorized and unrelated edits: preserve those hunks and any pre-existing staging. Isolate the candidate safely; ask about the affected scope if that cannot be done without losing or including unrelated staging.
|
|
26
|
+
7. Review the entire candidate index and staged diff before committing. Keep the user's Git identity. Never add `Co-Authored-By` trailers, textual signatures, or AI attribution to commit messages or PR descriptions. Do not rewrite unrelated messages or history to enforce this on earlier commits.
|
|
27
|
+
8. Write the message literally to a temporary file and use `git commit -F <message-file>`, with no shell expansion of its contents. Respect configured cryptographic signing and hooks: do not disable signing, change persistent Git configuration, or bypass hooks to make a commit succeed. A signing or hook failure is a concrete blocker to resolve, not permission to bypass it.
|
|
28
|
+
9. Inspect the resulting commit's message, author/committer, and changed paths, then check remaining status and staging. Report its hash, summary, checks, and remaining work. If a hook changed the result unexpectedly, explain it and resolve within authorization; do not silently amend or reset history. Push only when explicitly authorized, to the specified destination; no force-push or history rewriting without specific authorization.
|
|
29
|
+
|
|
30
|
+
If no changes remain in scope, report that without creating an empty commit. Do not impose a PR, new branch, model switch, or routine delegation. Distinguish missing user authorization from an actual sandbox restriction. Respond in the user's language; follow the project's language convention for the commit message.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: pcdd-commit-review
|
|
3
|
+
description: Review pending Git changes and organize them into coherent commits by intent and dependency. Use for organizing commits or explicit invocation; honor review-only requests without changing the index or history.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# PCDD Commit Review
|
|
7
|
+
|
|
8
|
+
Read the current checkout's project instructions, `.pcdd/core.md`, and the installed `pcdd-commit` skill unless already loaded. The commit skill defines identity, attribution, signing, gates, and authorization rules for each resulting commit. Resolve paths from this checkout, including worktrees; there is no dependency on another repository's commands or conventions.
|
|
9
|
+
|
|
10
|
+
This skill organizes commits. `pcdd-review` provides independent code review and verification for high-risk changes; organizing the diff does not replace that control.
|
|
11
|
+
|
|
12
|
+
An explicit invocation authorizes organizing and creating commits within its stated scope, unless the user restricts the request to review or a proposal. In that case, inspect and return the plan without changing files, the index, or history. An ordinary request to review code alone does not authorize commits. Preserve prior authorization; do not ask to approve the same plan again merely because it contains several commits. High-risk approval remains a separate required checkpoint.
|
|
13
|
+
|
|
14
|
+
1. Inspect status, full staged and unstaged diffs, and relevant new files. Identify the authorized work; existing staging does not establish ownership or inclusion. Ask only about ambiguity that affects scope, and continue independent authorized work where possible.
|
|
15
|
+
2. Group changes by intent and dependencies. Each unit should make sense independently and contain its relevant tests and docs. Isolate high-risk work from unrelated changes; do not split a necessary dependency into a broken intermediate state or impose a line-count quota. A coherent initial scaffold can be one commit.
|
|
16
|
+
3. Present a numbered plan with each proposed message, paths or hunks, dependencies, and exclusions. Use the project's commit convention or the English Conventional Commits default from `pcdd-commit`. If only review was requested, stop here without staging or committing.
|
|
17
|
+
4. Order prerequisites before their consumers. Validate the actual candidate for each commit according to the project gates. A passing final working tree alone does not prove that an intermediate commit works. Reuse evidence only when it covers that candidate and project rules allow it; do not repeat costly tests without a change or unresolved concern.
|
|
18
|
+
5. Execute each authorized unit through the `pcdd-commit` workflow, preserving unrelated staging and work. Keep the user's identity; never add `Co-Authored-By`, textual signatures, or AI attribution. Respect cryptographic signing and hooks. Complete `pcdd-review` and obtain the required risk approval before any high-risk commit; do not simulate an independent review yourself.
|
|
19
|
+
6. Verify the resulting sequence, messages, paths, and remaining status against the plan. Report hashes and exclusions. Push only with explicit authorization and to its specified destination. On divergence, inspect and report the situation; do not force-push, rebase, or overwrite remote work without the required authorization.
|
|
20
|
+
|
|
21
|
+
Do not impose a PR, new branch, model switch, or routine subagents. Respond in the user's language. Ask only about unresolved scope, unauthorized destructive actions, required high-risk approval, or concrete environment blockers.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: pcdd-review
|
|
3
|
+
description: Independently review and verify a high-risk PCDD change after its gate passes and before requesting commit approval. Also supports explicit review requests without authorizing external writes.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# PCDD Review
|
|
7
|
+
|
|
8
|
+
The implementer first confirms that the candidate passes its gate. Do not launch reviews before that. The environment must provide code review and an independent verifier agent; if a capability is missing, report it and stop the high-risk commit. Do not simulate independence through self-review.
|
|
9
|
+
|
|
10
|
+
Follow the language policy in `.pcdd/core.md`: use the user's language for summaries, the project's agreed language for documents, and preserve original quotations verbatim. Keep the `PASS` and `CHANGES` verdicts unchanged.
|
|
11
|
+
|
|
12
|
+
The implementer prepares two bounded assignments: code review and public-interface verification. Use the native review command when available, otherwise a separate reviewer. Do not assume `/code-review` exists in every client.
|
|
13
|
+
|
|
14
|
+
Both receive only relevant specs, risk items, the diff including new files, conventions, and required commands. The verifier starts with fresh context, without Log, the implementer's narrative, or previous conclusions. There is no need to reread the entire history.
|
|
15
|
+
|
|
16
|
+
## Verifier assignment
|
|
17
|
+
|
|
18
|
+
- Try to demonstrate that a criterion is not met. Run targeted public-interface checks: HTTP, exit codes, output, or observable effects; reading code alone does not demonstrate behavior.
|
|
19
|
+
- Do not rerun the entire suite that already passed. Select edge cases relevant to the risk and regression tests for affected contracts.
|
|
20
|
+
- Do not modify existing files, configuration, or user data; use an isolated environment. You may deliver new tests in separate files for the implementer to evaluate.
|
|
21
|
+
- No cloud access, deployments, publications, stopping others' processes, or Git write operations.
|
|
22
|
+
- Return `PASS` or `CHANGES`, evidence per S#, reproducible findings, new tests, and limitations. A criterion without evidence remains unverified, not approved.
|
|
23
|
+
|
|
24
|
+
## Review closure
|
|
25
|
+
|
|
26
|
+
The implementer fixes findings and revalidates the final candidate. Adding tests or changing code requires rerunning the gate; material changes return to the relevant reviewer. An earlier review does not cover new changes.
|
|
27
|
+
|
|
28
|
+
Present a summary that does not require the user to read code: what changes, what could fail, what both reviews found, what was fixed, and what remains unverified. Wait for approval and record its quotation before committing. That approval does not authorize push or publication.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: pcdd-work
|
|
3
|
+
description: Define, implement, or resume a substantial change in a PCDD project, preserving specs, tasks, and evidence across sessions. Also handles requests to save progress or continue where work stopped, in the user's language.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# PCDD Work
|
|
7
|
+
|
|
8
|
+
Consult `.pcdd/core.md` if you have not read it yet. Do not reread the entire project. Use `--json` to consume CLI results, for example `pcdd --json time status <name>`; human output is not a parsing contract.
|
|
9
|
+
|
|
10
|
+
Follow the language policy in the core: respond in the user's language, write project content in its agreed language, and preserve quotations verbatim. Recognize save/resume requests by meaning in the user's language; no exact phrase is required. Translate user-facing examples below as appropriate. Keep `## Tasks`, task IDs, state markers, and command syntax unchanged because the CLI parses them. Preserve existing document headings; the continuation section may be called `Continuation`, `Continuación`, or the project's equivalent.
|
|
11
|
+
|
|
12
|
+
- If no change exists yet, recover scope from relevant documentation discovered through the core. A brief is context, not automatic approval: distinguish confirmed decisions from proposals before drafting specs. Do not require a fixed filename or ask again for information already documented.
|
|
13
|
+
- Identify the change in the roadmap if one exists. The roadmap tracks feature status; the change document tracks tasks. Do not create a roadmap just to duplicate a document.
|
|
14
|
+
- Create the document with `pcdd new <name>` (or `python3 /path/to/pcdd.py new <name>` if the CLI is not on PATH). The path resolves from the target project. Adapt the new template's prose to the project's language; do not rewrite existing documents merely to match the English template.
|
|
15
|
+
- Specs S#: original quotation, verifiable behavior, and acceptance criterion. Identify agent proposals; do not attribute them to the user. Adopt inherited rules explicitly.
|
|
16
|
+
- Before coding, obtain approval for new specs and record the quotation in Log. Link tasks to S#, with evidence and a commit when one exists. Do not invent hashes.
|
|
17
|
+
- Task format: `- [ ] T1 (S1) description`. States: space for pending, `>` in progress, `!` blocked, `x` completed. IDs must be unique. Keep only tasks in `## Tasks`; put detailed evidence in the evidence section.
|
|
18
|
+
- Complete a task when it meets its criterion and has evidence. Explain scope when tasks are added; a changed denominator does not automatically mean regression.
|
|
19
|
+
- Track time with `pcdd time start <name>`. Use `pause` or `stop` to close the interval before waiting for a reply or ending the turn. Tests and builds count as work; human waiting does not. Each start is an interval, not necessarily a chat session.
|
|
20
|
+
- On resuming, consult `pcdd time status <name>`. If an interval from another session remains open and its end is unknown, use `abandon`, not `stop`: it remains incomplete and excluded from the total. Do not estimate missing time. Then start a new interval.
|
|
21
|
+
- Check the tools exposed in the current session for native task tracking, such as `update_plan` or Claude Code's `TaskCreate`, `TaskUpdate`, and `TaskList`. Use available tools at startup/resumption and after task state changes to mirror the change document, updating the document first. Preserve the PCDD IDs in task labels even when the client assigns its own IDs. Reconcile existing entries for this change instead of duplicating them; preserve unrelated tasks. Native task entries are a derived view, never an independent plan. Map only supported states faithfully; if a state such as blocked has no native equivalent, keep the exact state and blocker explicit in the label or description. Do not mark a blocked task completed to fit the client.
|
|
22
|
+
- If native tools are absent, report at startup that progress will be shown in text. If a native update fails, report that limitation and continue with the document and chat block. Do not invent tools, equate Markdown lists with a native panel, or use goals, new sessions, background jobs, or external trackers as substitutes. Do not change client settings automatically. Tool calls verify task operations; visual rendering requires an interactive client check.
|
|
23
|
+
- When starting or resuming and whenever task status changes, show a brief, separate progress block. Use a heading such as `**PCDD** · 4/6 tasks completed`, followed by a few short lines with task IDs, concise descriptions and explicit states (completed, in progress, pending, blocked). Include relevant completed tasks, the active task or tasks, and the next step or blocker. For a long task list, show only the relevant subset; the CLI count still covers all tasks. If no task is active, say what is pending, including human acceptance when appropriate. Update the change document first and obtain the count through the CLI. Its Tasks section is the source of truth; never maintain a second independent plan in chat or client tools.
|
|
24
|
+
- During long operations, give occasional short updates naming the active task, what is still running, and what result or check is still pending. Do not invent intermediate percentages, repeat the full block for every command, or imply success before evidence arrives. Explain blockers plainly and name the next action that can resolve them. User-facing updates must not depend on a particular client's task UI.
|
|
25
|
+
- When closing a work interval, append the confirmed closed total to the block heading, for example `**PCDD** · 4/6 tasks completed · 18 min`. Use minutes and seconds when useful; do not invent unmeasured time. Omit timer status and recording details such as “recorded since the timer started” or “timer paused”. Explain missing or incomplete timing separately only when it materially affects the result. Do not confuse task counts with effort, ETAs or final acceptance.
|
|
26
|
+
- Before pausing, update the continuation section with the next step, blocker, and current evidence. Preserve original decisions in Log; consult it only to resolve uncertainty.
|
|
27
|
+
- At delivery, report behavior, validation, residual risks, recorded time and incomplete intervals, and human testing steps. Keep acceptance pending until the user tests and confirms.
|
|
28
|
+
|
|
29
|
+
If the CLI is missing or fails, report it; do not invent metrics or download tools automatically. Tasks can be maintained in Markdown while the limitation is resolved.
|
|
30
|
+
|
|
31
|
+
Example of a mid-work update (illustrative counts and tasks; translate for the user):
|
|
32
|
+
|
|
33
|
+
**PCDD** · 3/5 tasks completed
|
|
34
|
+
|
|
35
|
+
- Completed · T3 · Isolated proxy and measurement.
|
|
36
|
+
- In progress · T4 · Run comparison suite.
|
|
37
|
+
- Pending · T5 · Review results and prepare delivery.
|
|
38
|
+
|
|
39
|
+
The pilot passed. The comparison suite is still running; equivalence checks remain pending.
|
|
40
|
+
|
|
41
|
+
## Save progress
|
|
42
|
+
|
|
43
|
+
Keep the continuation section current when closing a unit of work; do not wait until context is exhausted. When the user asks to save progress, save a resumption point in the change document. If none exists and work must persist across sessions, create a minimal record using the project's format.
|
|
44
|
+
|
|
45
|
+
- Leave a short account of the current task and concrete next action; implemented versus verified work; blockers; relevant specs and references to recorded approvals. Preserve quotations in Log without duplicating or reinterpreting them.
|
|
46
|
+
- Record relevant modified files, branch/commit if available, checks run, and the state they covered. Distinguish uncommitted work from others' changes; do not invent ownership or hashes.
|
|
47
|
+
- Include discarded attempts only when they prevent repeating a mistake, and your own active processes if they affect continuation. Do not copy the conversation, secrets, or complete tool output.
|
|
48
|
+
- Close the known time interval before finishing; do not complete tasks or create commits merely to save progress. If saving or closing the timer fails, report what was not persisted.
|
|
49
|
+
- Verify that the document was saved. Identify the change and say, in the user's language: “Progress saved. You can open a new session and ask: ‘Continue where we left off.’” Include the change name in that phrase if several efforts are active.
|
|
50
|
+
|
|
51
|
+
## Continue where work stopped
|
|
52
|
+
|
|
53
|
+
- Identify the requested change. Use it if only one is active; ask which one if several are plausible. Do not choose solely by file date or read every Log.
|
|
54
|
+
- Read the continuation section, relevant tasks, and their specs. Consult referenced evidence or approvals only when needed.
|
|
55
|
+
- Compare the note with files, the diff, and Git status if available. Reconcile subsequent changes without overwriting them; ask only about contradictions that affect scope or authorization. Do not treat a test on different code as current evidence.
|
|
56
|
+
- Check the timer: abandon a previous interval with no known end as incomplete, never add estimated time. Start a new interval when work resumes.
|
|
57
|
+
- Preserve previous approvals and continue with the next action within their scope. Do not restart planning or ask to approve the same work again. Saving progress did not authorize new work.
|
|
58
|
+
|
|
59
|
+
The agent may suggest switching sessions at a stable point if the conversation has accumulated irrelevant context. Do not assume access to a context percentage or promise to open a new session automatically. These phrases are requests to the agent, not CLI subcommands.
|
pcdd_toolkit/cli.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
"""PCDD: local, dependency-free project workflow kit."""
|
|
2
|
+
import argparse
|
|
3
|
+
import base64
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
import tempfile
|
|
13
|
+
from contextlib import contextmanager
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .presentation import Presentation, build_parser, detect_language, preference_path, save_language
|
|
16
|
+
|
|
17
|
+
VERSION = __version__
|
|
18
|
+
ASSETS = Path(__file__).resolve().parent / 'assets'
|
|
19
|
+
BEGIN, END = '<!-- pcdd:begin -->', '<!-- pcdd:end -->'
|
|
20
|
+
INTERNAL = {'.pcdd/installation.json', '.pcdd/config.json'}
|
|
21
|
+
LEGACY_SKILLS = ('pcdd-work', 'pcdd-review')
|
|
22
|
+
SKILLS = LEGACY_SKILLS + ('pcdd-commit', 'pcdd-commit-review')
|
|
23
|
+
VERSION_SKILLS = {'0.1.0': LEGACY_SKILLS, '0.2.0': LEGACY_SKILLS,
|
|
24
|
+
'0.3.0': SKILLS, VERSION: SKILLS}
|
|
25
|
+
ADAPTER_FOLDERS = {'codex': '.agents', 'claude': '.claude', 'antigravity': '.agents'}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Conflict(Exception):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def digest(data):
|
|
33
|
+
return hashlib.sha256(data).hexdigest()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def encoded(value):
|
|
37
|
+
return None if value is None else base64.b64encode(value).decode()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def decoded(value):
|
|
41
|
+
return None if value is None else base64.b64decode(value, validate=True)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def json_bytes(value):
|
|
45
|
+
return (json.dumps(value, indent=2, ensure_ascii=False) + '\n').encode()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def managed_paths(adapters, skills=SKILLS):
|
|
49
|
+
paths = {'AGENTS.md', '.pcdd/core.md'} | INTERNAL
|
|
50
|
+
for adapter in adapters:
|
|
51
|
+
folder = ADAPTER_FOLDERS[adapter]
|
|
52
|
+
paths.update(f'{folder}/skills/{skill}/SKILL.md'
|
|
53
|
+
for skill in skills)
|
|
54
|
+
if 'claude' in adapters:
|
|
55
|
+
paths.add('CLAUDE.md')
|
|
56
|
+
return paths
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Project:
|
|
60
|
+
def __init__(self, root):
|
|
61
|
+
self.root = Path(root).resolve()
|
|
62
|
+
if not self.root.is_dir():
|
|
63
|
+
raise Conflict('Project directory does not exist')
|
|
64
|
+
|
|
65
|
+
def path(self, name):
|
|
66
|
+
relative = Path(name)
|
|
67
|
+
if relative.is_absolute() or '..' in relative.parts:
|
|
68
|
+
raise Conflict('Unsafe path: ' + name)
|
|
69
|
+
path = self.root
|
|
70
|
+
for part in relative.parts:
|
|
71
|
+
path = path / part
|
|
72
|
+
if path.is_symlink():
|
|
73
|
+
raise Conflict('Symlink is not managed: ' + name)
|
|
74
|
+
return path
|
|
75
|
+
|
|
76
|
+
def read(self, name):
|
|
77
|
+
path = self.path(name)
|
|
78
|
+
if path.exists() and not path.is_file():
|
|
79
|
+
raise Conflict('Expected regular file: ' + name)
|
|
80
|
+
return path.read_bytes() if path.exists() else None
|
|
81
|
+
|
|
82
|
+
def load(self, name):
|
|
83
|
+
value = self.read(name)
|
|
84
|
+
parsed = json.loads(value) if value else None
|
|
85
|
+
if parsed is not None and not isinstance(parsed, dict):
|
|
86
|
+
raise Conflict('Expected JSON object: ' + name)
|
|
87
|
+
return parsed
|
|
88
|
+
|
|
89
|
+
def write(self, name, data):
|
|
90
|
+
path = self.path(name)
|
|
91
|
+
if data is None:
|
|
92
|
+
path.unlink(missing_ok=True)
|
|
93
|
+
return
|
|
94
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
95
|
+
descriptor, filename = tempfile.mkstemp(prefix='.pcdd-write-', dir=path.parent)
|
|
96
|
+
temporary = Path(filename)
|
|
97
|
+
try:
|
|
98
|
+
with os.fdopen(descriptor, 'wb') as stream:
|
|
99
|
+
stream.write(data)
|
|
100
|
+
stream.flush()
|
|
101
|
+
os.fsync(stream.fileno())
|
|
102
|
+
os.replace(temporary, path)
|
|
103
|
+
finally:
|
|
104
|
+
temporary.unlink(missing_ok=True)
|
|
105
|
+
|
|
106
|
+
@contextmanager
|
|
107
|
+
def lock(self):
|
|
108
|
+
lock = self.path('.pcdd/lock')
|
|
109
|
+
lock.parent.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
try:
|
|
111
|
+
stream = lock.open('x')
|
|
112
|
+
except FileExistsError:
|
|
113
|
+
raise Conflict('Another operation or interrupted process owns .pcdd/lock; '
|
|
114
|
+
'verify it is stopped before removing that lock')
|
|
115
|
+
try:
|
|
116
|
+
stream.write(str(os.getpid()))
|
|
117
|
+
stream.close()
|
|
118
|
+
yield
|
|
119
|
+
finally:
|
|
120
|
+
lock.unlink(missing_ok=True)
|
|
121
|
+
|
|
122
|
+
def pending(self):
|
|
123
|
+
if self.read('.pcdd/pending.json'):
|
|
124
|
+
raise Conflict('Interrupted transaction: run recover before writing')
|
|
125
|
+
|
|
126
|
+
def transaction(self, changes):
|
|
127
|
+
if not changes:
|
|
128
|
+
return
|
|
129
|
+
record = {name: {'before': encoded(self.read(name)), 'after': encoded(data)}
|
|
130
|
+
for name, data in changes.items()}
|
|
131
|
+
self.write('.pcdd/pending.json', json_bytes(record))
|
|
132
|
+
# A crash leaves the journal for explicit recovery, not a false success.
|
|
133
|
+
for name, data in changes.items():
|
|
134
|
+
self.write(name, data)
|
|
135
|
+
self.write('.pcdd/last-update.json', json_bytes(record))
|
|
136
|
+
self.write('.pcdd/pending.json', None)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def bridge(original, text):
|
|
140
|
+
original = original or b''
|
|
141
|
+
start, end = BEGIN.encode(), END.encode()
|
|
142
|
+
if original.count(start) != original.count(end) or original.count(start) > 1:
|
|
143
|
+
raise Conflict('Invalid or duplicate PCDD markers')
|
|
144
|
+
block = (BEGIN + '\n' + text + '\n' + END).encode()
|
|
145
|
+
if start not in original:
|
|
146
|
+
separator = b'' if not original or original.endswith(b'\n') else b'\n'
|
|
147
|
+
return original + separator + block + b'\n'
|
|
148
|
+
left, right = original.index(start), original.index(end)
|
|
149
|
+
if left > right:
|
|
150
|
+
raise Conflict('Invalid PCDD marker order')
|
|
151
|
+
return original[:left] + block + original[right + len(end):]
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def block_hash(data):
|
|
155
|
+
if data is None or data.count(BEGIN.encode()) != 1 or data.count(END.encode()) != 1:
|
|
156
|
+
raise Conflict('Missing or duplicate PCDD bridge')
|
|
157
|
+
left, right = data.index(BEGIN.encode()), data.index(END.encode())
|
|
158
|
+
if left > right:
|
|
159
|
+
raise Conflict('Invalid PCDD marker order')
|
|
160
|
+
return digest(data[left:right + len(END)])
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def hash_file(name, data):
|
|
164
|
+
return block_hash(data) if name in ('AGENTS.md', 'CLAUDE.md') else digest(data)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def installation(project):
|
|
168
|
+
manifest = project.load('.pcdd/installation.json')
|
|
169
|
+
if not manifest or manifest.get('schema') != 1:
|
|
170
|
+
raise Conflict('Missing or unsupported installation; run init')
|
|
171
|
+
skills = VERSION_SKILLS.get(manifest.get('version'))
|
|
172
|
+
if skills is None:
|
|
173
|
+
raise Conflict('Invalid managed file list')
|
|
174
|
+
adapters = manifest.get('adapters', [])
|
|
175
|
+
supported = ADAPTER_FOLDERS if manifest['version'] == VERSION else ('codex', 'claude')
|
|
176
|
+
if (not isinstance(adapters, list) or not adapters
|
|
177
|
+
or any(not isinstance(a, str) or a not in supported for a in adapters)
|
|
178
|
+
or len(set(adapters)) != len(adapters)):
|
|
179
|
+
raise Conflict('Invalid adapters')
|
|
180
|
+
expected = managed_paths(adapters, skills) - INTERNAL
|
|
181
|
+
if not isinstance(manifest.get('files'), dict) or set(manifest['files']) != expected:
|
|
182
|
+
raise Conflict('Invalid managed file list')
|
|
183
|
+
return manifest
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def verify_files(project, manifest):
|
|
187
|
+
for name, expected in manifest['files'].items():
|
|
188
|
+
data = project.read(name)
|
|
189
|
+
if data is None or hash_file(name, data) != expected:
|
|
190
|
+
raise Conflict('Managed file changed or missing: ' + name)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def install(project, args):
|
|
194
|
+
project.pending()
|
|
195
|
+
project.read('.pcdd/last-update.json') # Preflight metadata destinations too.
|
|
196
|
+
previous = project.load('.pcdd/installation.json')
|
|
197
|
+
if args.command == 'update' and not previous:
|
|
198
|
+
raise Conflict('Not installed; run init')
|
|
199
|
+
if previous:
|
|
200
|
+
previous = installation(project)
|
|
201
|
+
verify_files(project, previous)
|
|
202
|
+
adapters = previous['adapters']
|
|
203
|
+
if args.adapters and args.adapters.split(',') != adapters:
|
|
204
|
+
raise Conflict('Adapter changes require a separate installation plan')
|
|
205
|
+
else:
|
|
206
|
+
adapters = (args.adapters or 'codex,claude').split(',')
|
|
207
|
+
if len(set(adapters)) != len(adapters) or any(a not in ADAPTER_FOLDERS for a in adapters):
|
|
208
|
+
raise Conflict('Adapters must be a comma-separated selection of codex, claude, antigravity')
|
|
209
|
+
desired = {'.pcdd/core.md': (ASSETS / 'core.md').read_bytes()}
|
|
210
|
+
desired['AGENTS.md'] = bridge(project.read('AGENTS.md'),
|
|
211
|
+
'Read `.pcdd/core.md` for the workflow. Load only relevant skills.')
|
|
212
|
+
if 'claude' in adapters:
|
|
213
|
+
desired['CLAUDE.md'] = bridge(project.read('CLAUDE.md'),
|
|
214
|
+
'Read `AGENTS.md` and `.pcdd/core.md` before working on this project.')
|
|
215
|
+
for adapter in adapters:
|
|
216
|
+
folder = ADAPTER_FOLDERS[adapter]
|
|
217
|
+
for skill in SKILLS:
|
|
218
|
+
desired[f'{folder}/skills/{skill}/SKILL.md'] = (ASSETS / 'skills' / skill / 'SKILL.md').read_bytes()
|
|
219
|
+
owned = previous['files'] if previous else {}
|
|
220
|
+
for name in desired:
|
|
221
|
+
if name not in ('AGENTS.md', 'CLAUDE.md') and name not in owned and project.read(name) is not None:
|
|
222
|
+
raise Conflict('Unowned file already exists: ' + name)
|
|
223
|
+
if not previous:
|
|
224
|
+
if project.read('.pcdd/config.json') is None:
|
|
225
|
+
desired['.pcdd/config.json'] = json_bytes({'schema': 1, 'gate': [], 'database_gate': []})
|
|
226
|
+
config = project.load('.pcdd/config.json')
|
|
227
|
+
if previous and config is None:
|
|
228
|
+
raise Conflict('Missing project configuration')
|
|
229
|
+
if config is not None and (config.get('schema') != 1 or
|
|
230
|
+
not isinstance(config.get('gate'), list)):
|
|
231
|
+
raise Conflict('Invalid project configuration')
|
|
232
|
+
manifest = {'schema': 1, 'version': VERSION, 'adapters': adapters,
|
|
233
|
+
'files': {name: hash_file(name, data) for name, data in desired.items()
|
|
234
|
+
if name not in INTERNAL}}
|
|
235
|
+
desired['.pcdd/installation.json'] = json_bytes(manifest)
|
|
236
|
+
changes = {name: data for name, data in desired.items() if project.read(name) != data}
|
|
237
|
+
actions = {'create': [], 'update': [], 'preserve': []}
|
|
238
|
+
for name in desired:
|
|
239
|
+
action = 'preserve' if name not in changes else ('create' if project.read(name) is None else 'update')
|
|
240
|
+
actions[action].append(name)
|
|
241
|
+
if not args.dry_run:
|
|
242
|
+
project.transaction(changes)
|
|
243
|
+
return {'version': VERSION, 'dry_run': args.dry_run, 'files': list(changes), 'actions': actions}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def restore(project, recovery=False):
|
|
247
|
+
project.read('.pcdd/last-update.json')
|
|
248
|
+
project.read('.pcdd/pending.json')
|
|
249
|
+
if not recovery:
|
|
250
|
+
project.pending()
|
|
251
|
+
source = '.pcdd/pending.json' if recovery else '.pcdd/last-update.json'
|
|
252
|
+
record = project.load(source)
|
|
253
|
+
if not record:
|
|
254
|
+
raise Conflict('No transaction to restore')
|
|
255
|
+
allowed = managed_paths(ADAPTER_FOLDERS)
|
|
256
|
+
changes = {}
|
|
257
|
+
for name, entry in record.items():
|
|
258
|
+
if name not in allowed:
|
|
259
|
+
raise Conflict('Unsafe journal path: ' + name)
|
|
260
|
+
before, after = decoded(entry['before']), decoded(entry['after'])
|
|
261
|
+
current = project.read(name)
|
|
262
|
+
if current != after and not (recovery and current == before):
|
|
263
|
+
raise Conflict('Later edit prevents restore: ' + name)
|
|
264
|
+
changes[name] = before
|
|
265
|
+
# Recovery is repeatable after another interruption.
|
|
266
|
+
if not recovery:
|
|
267
|
+
project.write('.pcdd/pending.json', json_bytes({
|
|
268
|
+
name: {'before': encoded(data), 'after': record[name]['after']}
|
|
269
|
+
for name, data in changes.items()}))
|
|
270
|
+
for name, data in changes.items():
|
|
271
|
+
project.write(name, data)
|
|
272
|
+
project.write('.pcdd/last-update.json', None)
|
|
273
|
+
project.write('.pcdd/pending.json', None)
|
|
274
|
+
return {'restored': True}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def change_path(name):
|
|
278
|
+
if not re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*', name):
|
|
279
|
+
raise Conflict('Change name must use lowercase letters, digits and hyphens')
|
|
280
|
+
return f'pcdd/changes/{name}.md'
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def progress(project, name):
|
|
284
|
+
data = project.read(change_path(name))
|
|
285
|
+
if data is None:
|
|
286
|
+
raise Conflict('Change document not found')
|
|
287
|
+
section = re.search(r'^## Tasks\s*\n(.*?)(?=^## |\Z)', data.decode(), re.M | re.S)
|
|
288
|
+
if not section:
|
|
289
|
+
raise Conflict('Missing Tasks section')
|
|
290
|
+
tasks = {}
|
|
291
|
+
for line in section[1].splitlines():
|
|
292
|
+
if not line.strip() or line.startswith('<!--'):
|
|
293
|
+
continue
|
|
294
|
+
match = re.fullmatch(r'- \[([ x>!])\] (T\d+) (.+)', line)
|
|
295
|
+
if not match or match[2] in tasks:
|
|
296
|
+
raise Conflict('Invalid or duplicate task: ' + line)
|
|
297
|
+
tasks[match[2]] = {'state': match[1], 'description': match[3]}
|
|
298
|
+
return tasks
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def timing(project, args):
|
|
302
|
+
project.pending()
|
|
303
|
+
installation(project)
|
|
304
|
+
tasks = progress(project, args.change)
|
|
305
|
+
filename = f'.pcdd/time/{args.change}.json'
|
|
306
|
+
state = project.load(filename) or {'schema': 1, 'seconds': 0, 'sessions': 0,
|
|
307
|
+
'active': None, 'incomplete': 0}
|
|
308
|
+
if state.get('schema') != 1 or any(
|
|
309
|
+
not isinstance(state.get(key), (int, float)) or
|
|
310
|
+
not math.isfinite(state[key]) or state[key] < 0
|
|
311
|
+
for key in ('seconds', 'sessions', 'incomplete')):
|
|
312
|
+
raise Conflict('Invalid time record')
|
|
313
|
+
if state.get('active') is not None and (
|
|
314
|
+
not isinstance(state['active'], (int, float)) or
|
|
315
|
+
not math.isfinite(state['active']) or state['active'] < 0):
|
|
316
|
+
raise Conflict('Invalid open interval')
|
|
317
|
+
now = time.time()
|
|
318
|
+
if args.action == 'start':
|
|
319
|
+
if state['active'] is not None:
|
|
320
|
+
raise Conflict('Open interval; stop if accurate, or abandon if interrupted')
|
|
321
|
+
state['active'] = now
|
|
322
|
+
state['sessions'] += 1
|
|
323
|
+
elif args.action in ('stop', 'pause'):
|
|
324
|
+
if state['active'] is None:
|
|
325
|
+
raise Conflict('No open interval')
|
|
326
|
+
state['seconds'] += max(0, now - state['active'])
|
|
327
|
+
state['active'] = None
|
|
328
|
+
elif args.action == 'abandon':
|
|
329
|
+
if state['active'] is None:
|
|
330
|
+
raise Conflict('No open interval')
|
|
331
|
+
state['active'] = None
|
|
332
|
+
state['incomplete'] += 1
|
|
333
|
+
if args.action != 'status':
|
|
334
|
+
project.write(filename, json_bytes(state))
|
|
335
|
+
return {'change': args.change,
|
|
336
|
+
'completed': sum(t['state'] == 'x' for t in tasks.values()),
|
|
337
|
+
'total': len(tasks), 'tasks': tasks,
|
|
338
|
+
'recorded_seconds': round(state['seconds'], 2),
|
|
339
|
+
'open_interval_seconds': round(max(0, now - state['active']), 2)
|
|
340
|
+
if state['active'] is not None else None,
|
|
341
|
+
'intervals': state['sessions'], 'incomplete_intervals': state['incomplete'],
|
|
342
|
+
'acceptance': 'requires_user_confirmation'}
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def main():
|
|
346
|
+
argv = sys.argv[1:]
|
|
347
|
+
machine = '--json' in argv
|
|
348
|
+
ui = Presentation('es', machine)
|
|
349
|
+
try:
|
|
350
|
+
explicit = None
|
|
351
|
+
for index, item in enumerate(argv):
|
|
352
|
+
if item == '--lang' and index + 1 < len(argv):
|
|
353
|
+
explicit = argv[index + 1]
|
|
354
|
+
elif item.startswith('--lang='):
|
|
355
|
+
explicit = item.split('=', 1)[1]
|
|
356
|
+
ui = Presentation(detect_language(explicit), machine)
|
|
357
|
+
parser = build_parser(ui, VERSION)
|
|
358
|
+
args = parser.parse_args(argv)
|
|
359
|
+
if args.command == 'language':
|
|
360
|
+
if args.language:
|
|
361
|
+
save_language(args.language)
|
|
362
|
+
ui.result('language', {'language': args.language or ui.language,
|
|
363
|
+
'path': str(preference_path()), 'saved': bool(args.language)})
|
|
364
|
+
return
|
|
365
|
+
run_project(args, ui)
|
|
366
|
+
except (Conflict, OSError, ValueError, KeyError, TypeError) as error:
|
|
367
|
+
ui.error(error, 'conflict' if isinstance(error, Conflict) else 'invalid_state')
|
|
368
|
+
raise SystemExit(1)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def run_project(args, ui):
|
|
372
|
+
project = Project(args.project)
|
|
373
|
+
readonly = getattr(args, 'dry_run', False) or args.command == 'doctor' or (
|
|
374
|
+
args.command == 'time' and args.action == 'status')
|
|
375
|
+
if args.command in ('init', 'update'):
|
|
376
|
+
ui.logo()
|
|
377
|
+
|
|
378
|
+
def execute():
|
|
379
|
+
if args.command in ('init', 'update'):
|
|
380
|
+
return install(project, args)
|
|
381
|
+
elif args.command in ('rollback', 'recover'):
|
|
382
|
+
return restore(project, args.command == 'recover')
|
|
383
|
+
elif args.command == 'doctor':
|
|
384
|
+
if project.read('.pcdd/lock') is not None:
|
|
385
|
+
raise Conflict('Active or stale lock: verify owning process before removing .pcdd/lock')
|
|
386
|
+
project.pending()
|
|
387
|
+
manifest = installation(project)
|
|
388
|
+
verify_files(project, manifest)
|
|
389
|
+
config = project.load('.pcdd/config.json')
|
|
390
|
+
if not config or config.get('schema') != 1 or not isinstance(config.get('gate'), list):
|
|
391
|
+
raise Conflict('Invalid project configuration')
|
|
392
|
+
return {'installed': manifest['version'], 'cli': VERSION,
|
|
393
|
+
'adapters': manifest['adapters'],
|
|
394
|
+
'warnings': [] if config['gate'] else ['Configure project gate before committing']}
|
|
395
|
+
elif args.command == 'new':
|
|
396
|
+
project.pending()
|
|
397
|
+
installation(project)
|
|
398
|
+
name = change_path(args.change)
|
|
399
|
+
if project.read(name) is not None:
|
|
400
|
+
raise Conflict('Change already exists')
|
|
401
|
+
project.write(name, (ASSETS / 'change.md').read_bytes().replace(b'{{name}}', args.change.encode()))
|
|
402
|
+
return {'path': name}
|
|
403
|
+
else:
|
|
404
|
+
return timing(project, args)
|
|
405
|
+
with ui.step(args.command):
|
|
406
|
+
if readonly:
|
|
407
|
+
report = execute()
|
|
408
|
+
else:
|
|
409
|
+
with project.lock():
|
|
410
|
+
report = execute()
|
|
411
|
+
ui.result(args.command, report)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
if __name__ == '__main__':
|
|
415
|
+
main()
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
{
|
|
2
|
+
"tagline": "each change, just enough.",
|
|
3
|
+
"preview": "Preview · No files will be changed",
|
|
4
|
+
"ready": "PCDD is ready.",
|
|
5
|
+
"unchanged": "No pending changes.",
|
|
6
|
+
"create": "Create",
|
|
7
|
+
"update": "Update",
|
|
8
|
+
"preserve": "Preserve",
|
|
9
|
+
"preserved": "Your own content is preserved.",
|
|
10
|
+
"apply": "Apply with pcdd init or pcdd update, without --dry-run.",
|
|
11
|
+
"next": "Open a new agent session in this project and describe what you want to do.\nPCDD guides it to find the relevant context and prepare validation commands.",
|
|
12
|
+
"healthy": "Valid installation · PCDD {version}",
|
|
13
|
+
"gate_warning": "Validation commands are not configured yet. You can start: the agent will define them while preparing development, before the first commit.",
|
|
14
|
+
"restored": "Previous files restored; changes and time records preserved.",
|
|
15
|
+
"change_created": "Change created: {path}\nDefine specs before implementing.",
|
|
16
|
+
"language_saved": "Language preference saved: {language}\n{path}",
|
|
17
|
+
"language_current": "Effective language: {language}\nPreferences: {path}",
|
|
18
|
+
"progress": "{done}/{total} tasks completed · {seconds} s recorded",
|
|
19
|
+
"open_interval": "Open interval: {seconds} s (provisional)",
|
|
20
|
+
"incomplete": "Incomplete intervals excluded from total: {count}",
|
|
21
|
+
"acceptance": "Check the change document for user acceptance.",
|
|
22
|
+
"unexpected": "Could not complete the operation. Check file permissions and formats; if a transaction is pending, run pcdd recover.",
|
|
23
|
+
"error_hint": "See pcdd --help. Do not force overwrites of your own files.",
|
|
24
|
+
"usage": "Usage",
|
|
25
|
+
"commands": "Commands",
|
|
26
|
+
"options": "Options",
|
|
27
|
+
"help": "Show this help and exit",
|
|
28
|
+
"lang_help": "Select the language for this invocation only",
|
|
29
|
+
"json_help": "Stable JSON output, without welcome or animation",
|
|
30
|
+
"description": "PCDD: proportional process, small context and evidence.",
|
|
31
|
+
"version_help": "Show version",
|
|
32
|
+
"project_help": "Project directory (default: current)",
|
|
33
|
+
"dry_help": "Show the plan without changing files",
|
|
34
|
+
"adapters_help": "Adapters (comma-separated): codex, claude, antigravity (default: codex,claude)",
|
|
35
|
+
"change_help": "Change name, lowercase and hyphenated",
|
|
36
|
+
"time_help": "Start, pause, stop, abandon or inspect an interval",
|
|
37
|
+
"preference_help": "Save es/en or auto to resume language detection",
|
|
38
|
+
"command_init": "Install PCDD in the project",
|
|
39
|
+
"working_init": "Install PCDD in the project",
|
|
40
|
+
"command_update": "Update managed files",
|
|
41
|
+
"working_update": "Update managed files",
|
|
42
|
+
"command_doctor": "Check installation without writing",
|
|
43
|
+
"working_doctor": "Check installation without writing",
|
|
44
|
+
"command_rollback": "Revert the last installation or update",
|
|
45
|
+
"working_rollback": "Revert the last installation or update",
|
|
46
|
+
"command_recover": "Restore files after an interruption",
|
|
47
|
+
"working_recover": "Restore files after an interruption",
|
|
48
|
+
"command_new": "Create a change document",
|
|
49
|
+
"working_new": "Create a change document",
|
|
50
|
+
"command_time": "Record or inspect time and progress",
|
|
51
|
+
"working_time": "Record or inspect time and progress",
|
|
52
|
+
"command_language": "Inspect or save your language preference",
|
|
53
|
+
"working_language": "Inspect or save your language preference",
|
|
54
|
+
"errors": {
|
|
55
|
+
"Project directory does not exist": "Project directory does not exist",
|
|
56
|
+
"Unsafe path: ": "Unsafe path: ",
|
|
57
|
+
"Symlink is not managed: ": "Symlink is not managed: ",
|
|
58
|
+
"Expected regular file: ": "Expected regular file: ",
|
|
59
|
+
"Another operation or interrupted process owns .pcdd/lock; verify it is stopped before removing that lock": "Another operation or interrupted process owns .pcdd/lock; verify it is stopped before removing that lock",
|
|
60
|
+
"Interrupted transaction: run recover before writing": "Interrupted transaction: run recover before writing",
|
|
61
|
+
"Invalid or duplicate PCDD markers": "Invalid or duplicate PCDD markers",
|
|
62
|
+
"Invalid PCDD marker order": "Invalid PCDD marker order",
|
|
63
|
+
"Missing or duplicate PCDD bridge": "Missing or duplicate PCDD bridge",
|
|
64
|
+
"Missing or unsupported installation; run init": "Missing or unsupported installation; run init",
|
|
65
|
+
"Invalid adapters": "Invalid adapters",
|
|
66
|
+
"Invalid managed file list": "Invalid managed file list",
|
|
67
|
+
"Managed file changed or missing: ": "Managed file changed or missing: ",
|
|
68
|
+
"Not installed; run init": "Not installed; run init",
|
|
69
|
+
"Adapter changes require a separate installation plan": "Adapter changes require a separate installation plan",
|
|
70
|
+
"Unowned file already exists: ": "Unowned file already exists: ",
|
|
71
|
+
"Missing project configuration": "Missing project configuration",
|
|
72
|
+
"Invalid project configuration": "Invalid project configuration",
|
|
73
|
+
"No transaction to restore": "No transaction to restore",
|
|
74
|
+
"Unsafe journal path: ": "Unsafe journal path: ",
|
|
75
|
+
"Later edit prevents restore: ": "Later edit prevents restore: ",
|
|
76
|
+
"Change name must use lowercase letters, digits and hyphens": "Change name must use lowercase letters, digits and hyphens",
|
|
77
|
+
"Change document not found": "Change document not found",
|
|
78
|
+
"Missing Tasks section": "Missing Tasks section",
|
|
79
|
+
"Invalid or duplicate task: ": "Invalid or duplicate task: ",
|
|
80
|
+
"Invalid time record": "Invalid time record",
|
|
81
|
+
"Invalid open interval": "Invalid open interval",
|
|
82
|
+
"Open interval; stop if accurate, or abandon if interrupted": "Open interval; stop if accurate, or abandon if interrupted",
|
|
83
|
+
"No open interval": "No open interval",
|
|
84
|
+
"Active or stale lock: verify owning process before removing .pcdd/lock": "Active or stale lock: verify owning process before removing .pcdd/lock",
|
|
85
|
+
"Change already exists": "Change already exists",
|
|
86
|
+
"Unsafe preference path": "Unsafe preference path",
|
|
87
|
+
"Invalid language preference": "Invalid language preference",
|
|
88
|
+
"Invalid arguments; run pcdd --help": "Invalid arguments; run pcdd --help",
|
|
89
|
+
"Adapters must be a comma-separated selection of codex, claude, antigravity": "Adapters must be a comma-separated selection of codex, claude, antigravity"
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
{
|
|
2
|
+
"tagline": "cada cambio, el proceso justo.",
|
|
3
|
+
"preview": "Vista previa · No se modificará ningún archivo",
|
|
4
|
+
"ready": "PCDD está listo.",
|
|
5
|
+
"unchanged": "Sin cambios pendientes.",
|
|
6
|
+
"create": "Crear",
|
|
7
|
+
"update": "Actualizar",
|
|
8
|
+
"preserve": "Conservar",
|
|
9
|
+
"preserved": "Tu contenido propio se conserva.",
|
|
10
|
+
"apply": "Para aplicar: pcdd init o pcdd update, sin --dry-run.",
|
|
11
|
+
"next": "Abrí una sesión nueva de tu agente en este proyecto y contale qué querés hacer.\nPCDD le indica cómo encontrar el contexto y preparar las validaciones necesarias.",
|
|
12
|
+
"healthy": "Instalación válida · PCDD {version}",
|
|
13
|
+
"gate_warning": "Todavía no hay comandos de validación configurados. Podés empezar: el agente los definirá al preparar el desarrollo, antes del primer commit.",
|
|
14
|
+
"restored": "Archivos previos restaurados; se conservaron los changes y tiempos.",
|
|
15
|
+
"change_created": "Change creado: {path}\nDefiní las specs antes de implementar.",
|
|
16
|
+
"language_saved": "Preferencia de idioma guardada: {language}\n{path}",
|
|
17
|
+
"language_current": "Idioma efectivo: {language}\nPreferencias: {path}",
|
|
18
|
+
"progress": "{done}/{total} tareas completadas · {seconds} s registrados",
|
|
19
|
+
"open_interval": "Intervalo abierto: {seconds} s (provisional)",
|
|
20
|
+
"incomplete": "Intervalos incompletos excluidos del total: {count}",
|
|
21
|
+
"acceptance": "La aceptación del usuario se consulta en el documento del change.",
|
|
22
|
+
"unexpected": "No se pudo completar la operación. Revisá permisos y formato de los archivos; si hay una transacción pendiente, ejecutá pcdd recover.",
|
|
23
|
+
"error_hint": "Consultá pcdd --help. No fuerces la sobrescritura de archivos propios.",
|
|
24
|
+
"usage": "Uso",
|
|
25
|
+
"commands": "Comandos",
|
|
26
|
+
"options": "Opciones",
|
|
27
|
+
"help": "Mostrar esta ayuda y salir",
|
|
28
|
+
"lang_help": "Elegir el idioma solo para esta ejecución",
|
|
29
|
+
"json_help": "Salida JSON estable, sin bienvenida ni animación",
|
|
30
|
+
"description": "PCDD: proceso proporcional, contexto pequeño y evidencia.",
|
|
31
|
+
"version_help": "Mostrar la versión",
|
|
32
|
+
"project_help": "Directorio del proyecto (por defecto: actual)",
|
|
33
|
+
"dry_help": "Mostrar el plan sin modificar archivos",
|
|
34
|
+
"adapters_help": "Adaptadores separados por coma: codex, claude, antigravity (por defecto: codex,claude)",
|
|
35
|
+
"change_help": "Nombre del change, en minúsculas y con guiones",
|
|
36
|
+
"time_help": "Iniciar, pausar, cerrar, abandonar o consultar un intervalo",
|
|
37
|
+
"preference_help": "Guardar es/en o auto para volver a detectar el idioma",
|
|
38
|
+
"command_init": "Instalar PCDD en el proyecto",
|
|
39
|
+
"working_init": "Instalar PCDD en el proyecto",
|
|
40
|
+
"command_update": "Actualizar archivos administrados",
|
|
41
|
+
"working_update": "Actualizar archivos administrados",
|
|
42
|
+
"command_doctor": "Revisar la instalación sin escribir",
|
|
43
|
+
"working_doctor": "Revisar la instalación sin escribir",
|
|
44
|
+
"command_rollback": "Revertir la última instalación o actualización",
|
|
45
|
+
"working_rollback": "Revertir la última instalación o actualización",
|
|
46
|
+
"command_recover": "Restaurar archivos después de una interrupción",
|
|
47
|
+
"working_recover": "Restaurar archivos después de una interrupción",
|
|
48
|
+
"command_new": "Crear un documento de change",
|
|
49
|
+
"working_new": "Crear un documento de change",
|
|
50
|
+
"command_time": "Registrar o consultar tiempo y progreso",
|
|
51
|
+
"working_time": "Registrar o consultar tiempo y progreso",
|
|
52
|
+
"command_language": "Consultar o guardar tu preferencia de idioma",
|
|
53
|
+
"working_language": "Consultar o guardar tu preferencia de idioma",
|
|
54
|
+
"errors": {
|
|
55
|
+
"Project directory does not exist": "El directorio del proyecto no existe",
|
|
56
|
+
"Unsafe path: ": "Ruta insegura: ",
|
|
57
|
+
"Symlink is not managed: ": "No se administra el enlace simbólico: ",
|
|
58
|
+
"Expected regular file: ": "Se esperaba un archivo regular: ",
|
|
59
|
+
"Another operation or interrupted process owns .pcdd/lock; verify it is stopped before removing that lock": "Otra operación o un proceso interrumpido conserva .pcdd/lock; verificá que esté detenido antes de quitar ese archivo",
|
|
60
|
+
"Interrupted transaction: run recover before writing": "Transacción interrumpida: ejecutá pcdd recover antes de escribir",
|
|
61
|
+
"Invalid or duplicate PCDD markers": "Marcadores de PCDD inválidos o duplicados; revisá los bloques de instrucciones",
|
|
62
|
+
"Invalid PCDD marker order": "Orden de marcadores PCDD inválido; revisá los bloques de instrucciones",
|
|
63
|
+
"Missing or duplicate PCDD bridge": "Referencia de PCDD ausente o duplicada; revisá los bloques de instrucciones",
|
|
64
|
+
"Missing or unsupported installation; run init": "No hay una instalación compatible; ejecutá pcdd init",
|
|
65
|
+
"Invalid adapters": "Adaptadores inválidos; revisá el manifiesto de instalación",
|
|
66
|
+
"Invalid managed file list": "Lista de archivos administrados inválida; revisá el manifiesto",
|
|
67
|
+
"Managed file changed or missing: ": "Archivo administrado modificado o ausente; conservá tu personalización antes de restaurar el original: ",
|
|
68
|
+
"Not installed; run init": "PCDD no está instalado; ejecutá pcdd init",
|
|
69
|
+
"Adapter changes require a separate installation plan": "Cambiar adaptadores requiere un plan de instalación separado",
|
|
70
|
+
"Unowned file already exists: ": "Ya existe un archivo del cliente; no se sobrescribirá: ",
|
|
71
|
+
"Missing project configuration": "Falta .pcdd/config.json; restaurá la configuración del proyecto",
|
|
72
|
+
"Invalid project configuration": "Configuración del proyecto inválida; revisá .pcdd/config.json",
|
|
73
|
+
"No transaction to restore": "No hay una transacción para restaurar",
|
|
74
|
+
"Unsafe journal path: ": "Ruta insegura en el registro de recuperación: ",
|
|
75
|
+
"Later edit prevents restore: ": "Una edición posterior impide restaurar; conservá tus cambios primero: ",
|
|
76
|
+
"Change name must use lowercase letters, digits and hyphens": "El nombre del change debe usar minúsculas, números y guiones",
|
|
77
|
+
"Change document not found": "No se encontró el documento del change; crealo con pcdd new",
|
|
78
|
+
"Missing Tasks section": "Falta la sección Tasks en el documento del change",
|
|
79
|
+
"Invalid or duplicate task: ": "Tarea inválida o duplicada; revisá el documento: ",
|
|
80
|
+
"Invalid time record": "Registro de tiempo inválido; revisá .pcdd/time",
|
|
81
|
+
"Invalid open interval": "Intervalo abierto inválido; revisá .pcdd/time",
|
|
82
|
+
"Open interval; stop if accurate, or abandon if interrupted": "Hay un intervalo abierto: usá time stop si es correcto o time abandon si se interrumpió",
|
|
83
|
+
"No open interval": "No hay un intervalo abierto; usá time start para iniciar uno",
|
|
84
|
+
"Active or stale lock: verify owning process before removing .pcdd/lock": "Lock activo o abandonado: verificá el proceso propietario antes de quitar .pcdd/lock",
|
|
85
|
+
"Change already exists": "El change ya existe; elegí otro nombre o retomá el documento existente",
|
|
86
|
+
"Unsafe preference path": "Ruta de preferencias insegura; no se permiten enlaces simbólicos en preferences.json ni su carpeta pcdd",
|
|
87
|
+
"Invalid language preference": "Preferencia de idioma inválida; revisá preferences.json",
|
|
88
|
+
"Invalid arguments; run pcdd --help": "Argumentos inválidos; ejecutá pcdd --help",
|
|
89
|
+
"Adapters must be a comma-separated selection of codex, claude, antigravity": "Elegí adaptadores separados por coma: codex, claude, antigravity"
|
|
90
|
+
}
|
|
91
|
+
}
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""Localized terminal presentation; machine responses remain language-independent."""
|
|
2
|
+
import argparse
|
|
3
|
+
from contextlib import contextmanager
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
import threading
|
|
12
|
+
|
|
13
|
+
LOCALES = Path(__file__).resolve().parent / 'locales'
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def language_code(value):
|
|
17
|
+
return re.split(r'[-_.@]', value.strip().lower())[0]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def preference_path():
|
|
21
|
+
base = os.environ.get('XDG_CONFIG_HOME')
|
|
22
|
+
root = Path(base) if base and Path(base).is_absolute() else Path.home() / '.config'
|
|
23
|
+
return root / 'pcdd' / 'preferences.json'
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def preferences():
|
|
27
|
+
path = preference_path()
|
|
28
|
+
if path.is_symlink() or path.parent.is_symlink():
|
|
29
|
+
raise ValueError('Unsafe preference path')
|
|
30
|
+
if not path.exists():
|
|
31
|
+
return {}
|
|
32
|
+
data = json.loads(path.read_text(encoding='utf-8'))
|
|
33
|
+
if not isinstance(data, dict) or data.get('language', 'auto') not in ('es', 'en', 'auto'):
|
|
34
|
+
raise ValueError('Invalid language preference')
|
|
35
|
+
return data
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def save_language(language):
|
|
39
|
+
path = preference_path()
|
|
40
|
+
if path.is_symlink() or path.parent.is_symlink():
|
|
41
|
+
raise ValueError('Unsafe preference path')
|
|
42
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
43
|
+
lock = path.with_suffix('.lock')
|
|
44
|
+
with lock.open('x'):
|
|
45
|
+
pass
|
|
46
|
+
temporary = None
|
|
47
|
+
try:
|
|
48
|
+
data = preferences()
|
|
49
|
+
data['language'] = language
|
|
50
|
+
descriptor, filename = tempfile.mkstemp(prefix='.preferences-', dir=path.parent)
|
|
51
|
+
temporary = Path(filename)
|
|
52
|
+
with os.fdopen(descriptor, 'w', encoding='utf-8') as stream:
|
|
53
|
+
json.dump(data, stream, indent=2)
|
|
54
|
+
stream.write('\n')
|
|
55
|
+
stream.flush()
|
|
56
|
+
os.fsync(stream.fileno())
|
|
57
|
+
os.replace(temporary, path)
|
|
58
|
+
finally:
|
|
59
|
+
if temporary is not None:
|
|
60
|
+
temporary.unlink(missing_ok=True)
|
|
61
|
+
lock.unlink(missing_ok=True)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def detect_language(explicit=None):
|
|
65
|
+
if explicit:
|
|
66
|
+
return explicit if explicit in ('es', 'en') else 'es'
|
|
67
|
+
saved = preferences().get('language', 'auto')
|
|
68
|
+
if saved != 'auto':
|
|
69
|
+
return saved
|
|
70
|
+
# POSIX precedence: the first nonempty locale owns the choice. C/POSIX
|
|
71
|
+
# carries no user language, so macOS can supply the preference instead.
|
|
72
|
+
selected = next((os.environ[key] for key in ('LC_ALL', 'LC_MESSAGES', 'LANG')
|
|
73
|
+
if os.environ.get(key)), '')
|
|
74
|
+
code = language_code(selected)
|
|
75
|
+
if code not in ('', 'c', 'posix'):
|
|
76
|
+
return code if code in ('es', 'en') else 'es'
|
|
77
|
+
if sys.platform == 'darwin':
|
|
78
|
+
try:
|
|
79
|
+
result = subprocess.run(['/usr/bin/defaults', 'read', '-g', 'AppleLanguages'],
|
|
80
|
+
capture_output=True, text=True, timeout=1)
|
|
81
|
+
matches = re.findall(r'[\s(" ,]([a-z]{2,3})(?:[-_][A-Za-z0-9]+)*', result.stdout)
|
|
82
|
+
if result.returncode == 0 and matches:
|
|
83
|
+
return matches[0] if matches[0] in ('es', 'en') else 'es'
|
|
84
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
85
|
+
pass
|
|
86
|
+
return 'es'
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def safe_print(text, stream=sys.stdout, **kwargs):
|
|
90
|
+
encoding = stream.encoding or 'utf-8'
|
|
91
|
+
# Keep redirects and ASCII-only terminals usable, including paths/accents.
|
|
92
|
+
print(text.encode(encoding, errors='replace').decode(encoding), file=stream, **kwargs)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Presentation:
|
|
96
|
+
def __init__(self, language='es', machine=False):
|
|
97
|
+
self.language = language
|
|
98
|
+
self.machine = machine
|
|
99
|
+
self.messages = json.loads((LOCALES / (language + '.json')).read_text(encoding='utf-8'))
|
|
100
|
+
|
|
101
|
+
def text(self, key, **values):
|
|
102
|
+
return self.messages[key].format(**values)
|
|
103
|
+
|
|
104
|
+
def styled(self, text, tone, stream=None):
|
|
105
|
+
stream = stream or sys.stdout
|
|
106
|
+
if (self.machine or not stream.isatty() or 'NO_COLOR' in os.environ
|
|
107
|
+
or os.environ.get('TERM', '') in ('', 'dumb')):
|
|
108
|
+
return text
|
|
109
|
+
codes = {'brand': '1;36', 'success': '32', 'warning': '33',
|
|
110
|
+
'error': '31', 'secondary': '2'}
|
|
111
|
+
return '\x1b[' + codes[tone] + 'm' + text + '\x1b[0m'
|
|
112
|
+
|
|
113
|
+
def logo(self):
|
|
114
|
+
if self.machine:
|
|
115
|
+
return
|
|
116
|
+
symbol = '›_'
|
|
117
|
+
try:
|
|
118
|
+
symbol.encode(sys.stdout.encoding or 'utf-8')
|
|
119
|
+
except UnicodeEncodeError:
|
|
120
|
+
symbol = '>_'
|
|
121
|
+
safe_print('\n ' + self.styled(symbol + ' pcdd', 'brand') +
|
|
122
|
+
'\n Progressive Change-Driven Development\n ' +
|
|
123
|
+
self.styled(self.text('tagline'), 'secondary') + '\n')
|
|
124
|
+
|
|
125
|
+
@contextmanager
|
|
126
|
+
def step(self, command):
|
|
127
|
+
enabled = (not self.machine and sys.stdout.isatty() and sys.stderr.isatty()
|
|
128
|
+
and os.environ.get('TERM', '') != 'dumb' and 'NO_COLOR' not in os.environ)
|
|
129
|
+
if not enabled:
|
|
130
|
+
yield
|
|
131
|
+
return
|
|
132
|
+
message = self.text('working_' + command)
|
|
133
|
+
stopped = threading.Event()
|
|
134
|
+
|
|
135
|
+
def animate():
|
|
136
|
+
frames = '|/-\\'
|
|
137
|
+
index = 0
|
|
138
|
+
while not stopped.is_set():
|
|
139
|
+
safe_print('\r ' + frames[index % 4] + ' ' + message,
|
|
140
|
+
stream=sys.stderr, end='', flush=True)
|
|
141
|
+
index += 1
|
|
142
|
+
stopped.wait(0.08)
|
|
143
|
+
worker = threading.Thread(target=animate, daemon=True)
|
|
144
|
+
worker.start()
|
|
145
|
+
try:
|
|
146
|
+
yield
|
|
147
|
+
finally:
|
|
148
|
+
stopped.set()
|
|
149
|
+
worker.join()
|
|
150
|
+
safe_print('\r' + ' ' * (len(message) + 5) + '\r', stream=sys.stderr,
|
|
151
|
+
end='', flush=True)
|
|
152
|
+
|
|
153
|
+
def result(self, command, data):
|
|
154
|
+
if self.machine:
|
|
155
|
+
print(json.dumps(data, ensure_ascii=True))
|
|
156
|
+
return
|
|
157
|
+
if command in ('init', 'update'):
|
|
158
|
+
safe_print(self.styled(self.text('preview'), 'warning') if data['dry_run']
|
|
159
|
+
else self.styled(self.text('ready'), 'success'))
|
|
160
|
+
if not data['files']:
|
|
161
|
+
safe_print(self.styled(self.text('unchanged'), 'secondary'))
|
|
162
|
+
for action, paths in data['actions'].items():
|
|
163
|
+
for path in paths:
|
|
164
|
+
tone = {'create': 'success', 'update': 'warning', 'preserve': 'secondary'}[action]
|
|
165
|
+
safe_print(' ' + self.styled(self.text(action), tone) + ' ' + path)
|
|
166
|
+
safe_print('\n' + self.styled(self.text('preserved'), 'secondary'))
|
|
167
|
+
safe_print(self.text('apply') if data['dry_run'] else self.text('next'))
|
|
168
|
+
elif command == 'doctor':
|
|
169
|
+
safe_print(self.styled(self.text('healthy', version=data['installed']), 'success'))
|
|
170
|
+
for warning in data['warnings']:
|
|
171
|
+
safe_print(self.styled(self.text('gate_warning'), 'warning'))
|
|
172
|
+
elif command in ('rollback', 'recover'):
|
|
173
|
+
safe_print(self.styled(self.text('restored'), 'success'))
|
|
174
|
+
elif command == 'new':
|
|
175
|
+
safe_print(self.text('change_created', path=data['path']))
|
|
176
|
+
elif command == 'language':
|
|
177
|
+
safe_print(self.text('language_saved' if data['saved'] else 'language_current',
|
|
178
|
+
language=data['language'], path=data['path']))
|
|
179
|
+
elif command == 'time':
|
|
180
|
+
safe_print(self.text('progress', done=data['completed'], total=data['total'],
|
|
181
|
+
seconds=data['recorded_seconds']))
|
|
182
|
+
if data['open_interval_seconds'] is not None:
|
|
183
|
+
safe_print(self.text('open_interval', seconds=data['open_interval_seconds']))
|
|
184
|
+
if data['incomplete_intervals']:
|
|
185
|
+
safe_print(self.text('incomplete', count=data['incomplete_intervals']))
|
|
186
|
+
safe_print(self.text('acceptance'))
|
|
187
|
+
|
|
188
|
+
def error(self, error, code='conflict'):
|
|
189
|
+
message = str(error)
|
|
190
|
+
if self.machine:
|
|
191
|
+
print(json.dumps({'error': {'code': code, 'message': message}}, ensure_ascii=True))
|
|
192
|
+
return
|
|
193
|
+
translations = self.messages['errors']
|
|
194
|
+
translated = None
|
|
195
|
+
for prefix in sorted(translations, key=len, reverse=True):
|
|
196
|
+
if message.startswith(prefix):
|
|
197
|
+
translated = translations[prefix] + message[len(prefix):]
|
|
198
|
+
break
|
|
199
|
+
if translated is None:
|
|
200
|
+
translated = self.text('unexpected')
|
|
201
|
+
if isinstance(error, OSError) and error.filename:
|
|
202
|
+
translated += ' ' + str(error.filename)
|
|
203
|
+
safe_print(self.styled('PCDD: ' + translated, 'error', sys.stderr), stream=sys.stderr)
|
|
204
|
+
safe_print(self.text('error_hint'), stream=sys.stderr)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def build_parser(ui, version):
|
|
208
|
+
class Formatter(argparse.HelpFormatter):
|
|
209
|
+
def _format_usage(self, usage, actions, groups, prefix):
|
|
210
|
+
return super()._format_usage(usage, actions, groups,
|
|
211
|
+
ui.text('usage') + ': ' if prefix is None else prefix)
|
|
212
|
+
|
|
213
|
+
class Parser(argparse.ArgumentParser):
|
|
214
|
+
def __init__(self, *args, **kwargs):
|
|
215
|
+
kwargs.update(add_help=False, formatter_class=Formatter, allow_abbrev=False)
|
|
216
|
+
super().__init__(*args, **kwargs)
|
|
217
|
+
self._positionals.title = ui.text('commands')
|
|
218
|
+
self._optionals.title = ui.text('options')
|
|
219
|
+
self.add_argument('-h', '--help', action='help', help=ui.text('help'))
|
|
220
|
+
self.add_argument('--lang', choices=['es', 'en'], default=argparse.SUPPRESS,
|
|
221
|
+
help=ui.text('lang_help'))
|
|
222
|
+
self.add_argument('--json', action='store_true', default=argparse.SUPPRESS,
|
|
223
|
+
help=ui.text('json_help'))
|
|
224
|
+
|
|
225
|
+
def error(self, message):
|
|
226
|
+
if not ui.machine:
|
|
227
|
+
self.print_usage(sys.stderr)
|
|
228
|
+
ui.error(ValueError('Invalid arguments; run pcdd --help'), 'arguments')
|
|
229
|
+
raise SystemExit(2)
|
|
230
|
+
|
|
231
|
+
def print_help(self, file=None):
|
|
232
|
+
if ui.machine:
|
|
233
|
+
print(json.dumps({'help': self.format_help()}, ensure_ascii=True))
|
|
234
|
+
else:
|
|
235
|
+
safe_print(self.format_help(), stream=file or sys.stdout, end='')
|
|
236
|
+
|
|
237
|
+
class Version(argparse.Action):
|
|
238
|
+
def __call__(self, parser, namespace, values, option_string=None):
|
|
239
|
+
print(json.dumps({'version': version}) if ui.machine else version)
|
|
240
|
+
parser.exit()
|
|
241
|
+
|
|
242
|
+
parser = Parser(prog='pcdd', description=ui.text('description'))
|
|
243
|
+
parser.add_argument('--version', action=Version, nargs=0, help=ui.text('version_help'))
|
|
244
|
+
parser.add_argument('--project', default='.', help=ui.text('project_help'))
|
|
245
|
+
subs = parser.add_subparsers(dest='command', required=True)
|
|
246
|
+
for command in ('init', 'update', 'doctor', 'rollback', 'recover', 'new', 'time', 'language'):
|
|
247
|
+
child = subs.add_parser(command, help=ui.text('command_' + command),
|
|
248
|
+
description=ui.text('command_' + command))
|
|
249
|
+
if command in ('init', 'update'):
|
|
250
|
+
child.add_argument('--dry-run', action='store_true', help=ui.text('dry_help'))
|
|
251
|
+
child.add_argument('--adapters', help=ui.text('adapters_help'))
|
|
252
|
+
elif command == 'new':
|
|
253
|
+
child.add_argument('change', help=ui.text('change_help'))
|
|
254
|
+
elif command == 'time':
|
|
255
|
+
child.add_argument('action', choices=['start', 'pause', 'stop', 'abandon', 'status'],
|
|
256
|
+
help=ui.text('time_help'))
|
|
257
|
+
child.add_argument('change', help=ui.text('change_help'))
|
|
258
|
+
elif command == 'language':
|
|
259
|
+
child.add_argument('language', nargs='?', choices=['es', 'en', 'auto'],
|
|
260
|
+
help=ui.text('preference_help'))
|
|
261
|
+
return parser
|