promptmigrate-cli 0.1.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.
Files changed (42) hide show
  1. promptmigrate/__init__.py +21 -0
  2. promptmigrate/__main__.py +3 -0
  3. promptmigrate/apply.py +116 -0
  4. promptmigrate/cli.py +123 -0
  5. promptmigrate/commands/__init__.py +5 -0
  6. promptmigrate/commands/check.py +65 -0
  7. promptmigrate/commands/current.py +25 -0
  8. promptmigrate/commands/diff.py +19 -0
  9. promptmigrate/commands/downgrade.py +36 -0
  10. promptmigrate/commands/env.py +35 -0
  11. promptmigrate/commands/get.py +48 -0
  12. promptmigrate/commands/history.py +41 -0
  13. promptmigrate/commands/init.py +43 -0
  14. promptmigrate/commands/plan.py +51 -0
  15. promptmigrate/commands/restamp.py +47 -0
  16. promptmigrate/commands/revision.py +97 -0
  17. promptmigrate/commands/upgrade.py +36 -0
  18. promptmigrate/commands/validate.py +96 -0
  19. promptmigrate/core.py +30 -0
  20. promptmigrate/draftdiff.py +41 -0
  21. promptmigrate/errors.py +91 -0
  22. promptmigrate/output.py +122 -0
  23. promptmigrate/plan.py +112 -0
  24. promptmigrate/project.py +160 -0
  25. promptmigrate/protocol/__init__.py +9 -0
  26. promptmigrate/protocol/equality.py +15 -0
  27. promptmigrate/protocol/jsonloader.py +92 -0
  28. promptmigrate/protocol/limits.py +9 -0
  29. promptmigrate/protocol/rules.py +80 -0
  30. promptmigrate/revisions.py +181 -0
  31. promptmigrate/secretscan.py +195 -0
  32. promptmigrate/store/__init__.py +13 -0
  33. promptmigrate/store/environments.py +181 -0
  34. promptmigrate/store/events.py +70 -0
  35. promptmigrate/store/lock.py +66 -0
  36. promptmigrate/store/sqlite.py +147 -0
  37. promptmigrate_cli-0.1.0.dist-info/METADATA +247 -0
  38. promptmigrate_cli-0.1.0.dist-info/RECORD +42 -0
  39. promptmigrate_cli-0.1.0.dist-info/WHEEL +5 -0
  40. promptmigrate_cli-0.1.0.dist-info/entry_points.txt +2 -0
  41. promptmigrate_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
  42. promptmigrate_cli-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ """PromptMigrate: declarative, reversible AI prompt configuration migrations."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .core import ( # noqa: E402 (the public facade, after the version so tooling can read it without imports)
6
+ ALLOWLIST_FILE, DriftError, InitializationError, IntegrityError, LegacyRevisionWarning, MigrationConflictError,
7
+ MigrationError, PendingRevisionsError, Revision, RevisionGraphError, SchemaError, SecretDetectedError,
8
+ SecretInHistoryWarning, SecretRedactedWarning, StaleAllowlistWarning, StorageError, TargetError, audit_secrets,
9
+ canonical, check, downgrade, draft_diff, env_add, env_list, get_config, init, load_allowlist, load_revisions,
10
+ pretty, read_drafts, redacted_config, redacted_diff, redacted_history, replay_revisions, require_init, revision,
11
+ root_dir, same, upgrade,
12
+ )
13
+
14
+ __all__ = [
15
+ "ALLOWLIST_FILE", "DriftError", "InitializationError", "IntegrityError", "LegacyRevisionWarning",
16
+ "MigrationConflictError", "MigrationError", "PendingRevisionsError", "Revision", "RevisionGraphError",
17
+ "SchemaError", "SecretDetectedError", "SecretInHistoryWarning", "SecretRedactedWarning", "StaleAllowlistWarning",
18
+ "StorageError", "TargetError", "audit_secrets", "canonical", "check", "downgrade", "draft_diff", "env_add",
19
+ "env_list", "get_config", "init", "load_allowlist", "load_revisions", "pretty", "read_drafts", "redacted_config",
20
+ "redacted_diff", "redacted_history", "replay_revisions", "require_init", "revision", "root_dir", "same", "upgrade",
21
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
promptmigrate/apply.py ADDED
@@ -0,0 +1,116 @@
1
+ """Applied environment state: verify the ledger and rows against source history, and write revisions to them.
2
+
3
+ Callers own the connection and the transaction (store.connect_readonly / store.connect_write, BEGIN IMMEDIATE).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import sqlite3
10
+ from collections.abc import Iterator
11
+ from datetime import datetime, timezone
12
+ from typing import Any
13
+
14
+ from . import protocol, revisions
15
+ from .errors import DriftError, IntegrityError, StorageError
16
+ from .protocol import canonical # imported by name: tests patch apply.canonical to fail a write without touching same()
17
+ from .store import events
18
+
19
+
20
+ def _applied(db: sqlite3.Connection) -> list[tuple[str, str]]:
21
+ return [(rid, checksum) for rid, checksum in db.execute(
22
+ "SELECT revision, checksum FROM applied_revisions ORDER BY seq"
23
+ ).fetchall()]
24
+
25
+
26
+ def _actual(db: sqlite3.Connection) -> dict[str, dict[str, Any]]:
27
+ return {name: json.loads(config) for name, config in db.execute(
28
+ "SELECT name, config FROM prompts"
29
+ ).fetchall()}
30
+
31
+
32
+ def _stored_state(db: sqlite3.Connection) -> dict[str, dict[str, Any]]:
33
+ """Read the `prompts` rows, raising `StorageError` when the store cannot be read or holds invalid JSON."""
34
+ try:
35
+ return _actual(db)
36
+ except (sqlite3.Error, ValueError, TypeError, RecursionError) as exc:
37
+ raise StorageError("Corrupt environment state") from exc
38
+
39
+
40
+ def _ledger_rows(db: sqlite3.Connection, revisions_: list[revisions.Revision]) -> Iterator[tuple[revisions.Revision, str]]:
41
+ """Yield each ledger row as (source revision, stored checksum), in order, while its id matches source history."""
42
+ try:
43
+ applied = _applied(db)
44
+ except sqlite3.Error as exc:
45
+ raise StorageError("Corrupt environment state") from exc
46
+ if len(applied) > len(revisions_):
47
+ raise IntegrityError("Environment contains more applied revisions than source history")
48
+ for index, (rid, checksum) in enumerate(applied):
49
+ if rid != revisions_[index].revision:
50
+ raise IntegrityError(f"Applied revisions diverge from source history at index {index}")
51
+ yield revisions_[index], checksum
52
+
53
+
54
+ def _verify(db: sqlite3.Connection, revisions_: list[revisions.Revision], env: str | None = None) -> int:
55
+ count = 0
56
+ for source, checksum in _ledger_rows(db, revisions_):
57
+ if checksum != source.checksum:
58
+ if checksum in source.line_ending_checksums:
59
+ # Diagnosis only: the row still fails closed until `restamp` accepts it (ADR-027).
60
+ raise IntegrityError(f"Migration file was modified after apply: {source.revision} (line endings only; "
61
+ f"run `promptmigrate restamp --env {env or '<env>'}` to accept)")
62
+ raise IntegrityError(f"Migration file was modified after apply: {source.revision}")
63
+ count += 1
64
+ expected = revisions.replay_revisions(revisions_[:count])
65
+ actual = _stored_state(db)
66
+ names = sorted(name for name in actual.keys() | expected.keys()
67
+ if not protocol.same(actual.get(name), expected.get(name)))
68
+ if names:
69
+ raise DriftError(f"Environment drift detected for prompts: {', '.join(names)}")
70
+ return count
71
+
72
+
73
+ def line_ending_only(db: sqlite3.Connection, revisions_: list[revisions.Revision]) -> list[revisions.Revision]:
74
+ """The applied v0 revisions whose ledger checksum matches their file only after a line-ending change (ADR-027).
75
+
76
+ Any other mismatch, a v1 row included, raises the IntegrityError `_verify` would raise for it.
77
+ """
78
+ stale = []
79
+ for source, checksum in _ledger_rows(db, revisions_):
80
+ if checksum == source.checksum:
81
+ continue
82
+ if source.format_version != 0 or checksum not in source.line_ending_checksums:
83
+ raise IntegrityError(f"Migration file was modified after apply: {source.revision}")
84
+ stale.append(source)
85
+ return stale
86
+
87
+
88
+ def migrate(db: sqlite3.Connection, steps: list[revisions.Revision], *, backward: bool = False) -> None:
89
+ """Write each revision's rows and ledger entry in order, re-checking every precondition as it goes.
90
+
91
+ Forward steps write each `after` and append to the ledger; backward steps (already in reverse order) write each
92
+ `before` and remove the ledger row. Each step also appends one `events` row (ADR-029) in the same transaction.
93
+ """
94
+ state = _stored_state(db)
95
+ if steps:
96
+ events.ensure(db) # adopts an old DB in this transaction; skipped on a no-op (ADR-029)
97
+ for r in steps:
98
+ revisions._apply_changes(state, r, backward=backward)
99
+ for name, change in r.changes.items():
100
+ value = change["before"] if backward else change["after"]
101
+ if value is None:
102
+ db.execute("DELETE FROM prompts WHERE name=?", (name,))
103
+ else:
104
+ db.execute(
105
+ "INSERT INTO prompts(name, config) VALUES(?, ?) "
106
+ "ON CONFLICT(name) DO UPDATE SET config=excluded.config",
107
+ (name, canonical(value)),
108
+ )
109
+ if backward:
110
+ db.execute("DELETE FROM applied_revisions WHERE revision=?", (r.revision,))
111
+ else:
112
+ db.execute(
113
+ "INSERT INTO applied_revisions(revision, checksum, applied_at) VALUES(?, ?, ?)",
114
+ (r.revision, r.checksum, datetime.now(timezone.utc).isoformat()),
115
+ )
116
+ events.record(db, "downgrade" if backward else "upgrade", r.revision, r.checksum)
promptmigrate/cli.py ADDED
@@ -0,0 +1,123 @@
1
+ """Command line entry point."""
2
+
3
+ import argparse
4
+ import importlib.metadata
5
+ import sqlite3
6
+ import sys
7
+ import warnings
8
+ from . import __version__, output
9
+ from .commands import (
10
+ check, current, diff, downgrade, env, get, history, init, plan, restamp, revision, upgrade, validate,
11
+ )
12
+ from .errors import PromptMigrateWarning
13
+
14
+ COMMANDS = {
15
+ "init": init, "revision": revision, "history": history, "diff": diff, "current": current,
16
+ "upgrade": upgrade, "downgrade": downgrade, "check": check, "get": get, "env": env, "plan": plan,
17
+ "restamp": restamp, "validate": validate,
18
+ }
19
+
20
+
21
+ def _get_version() -> str:
22
+ """Read package version via importlib.metadata with fallback to static __version__."""
23
+ try:
24
+ return importlib.metadata.version("promptmigrate-cli")
25
+ except importlib.metadata.PackageNotFoundError:
26
+ return __version__
27
+
28
+
29
+ def build_parser() -> argparse.ArgumentParser:
30
+ """The argument parser: global flags, then one subparser per command."""
31
+ p = argparse.ArgumentParser(prog="promptmigrate", description="Alembic-style prompt configuration migrations")
32
+ p.add_argument("--version", action="version", version=f"%(prog)s {_get_version()}")
33
+ p.add_argument("--project", default=".", help="Project directory, default: current directory")
34
+ p.add_argument("--output", choices=output.FORMATS, default="text", help="Output format, default: text")
35
+ sub = p.add_subparsers(dest="command", required=True)
36
+ sub.add_parser("init", help="Create .promptmigrate/ scaffold")
37
+ rev = sub.add_parser("revision", help="Generate a migration from draft changes")
38
+ rev.add_argument("-m", "--message", required=True)
39
+ sub.add_parser("history", help="Show source migration revisions")
40
+ sub.add_parser("diff", help="Compare drafts to the latest source revision")
41
+ current = sub.add_parser("current", help="Show applied revision in an environment")
42
+ current.add_argument("--env", default="dev")
43
+ up = sub.add_parser("upgrade", help="Upgrade an environment to head or revision")
44
+ up.add_argument("target", nargs="?", default="head")
45
+ up.add_argument("--env", default="dev")
46
+ down = sub.add_parser("downgrade", help="Revert environment to -1, base or revision")
47
+ down.add_argument("target", nargs="?", default="-1")
48
+ down.add_argument("--env", default="dev")
49
+ pln = sub.add_parser("plan", help="Preview upgrade/downgrade to a target without changing anything")
50
+ pln.add_argument("--target", default="head", help="head, -1, base or a revision id (default: head)")
51
+ pln.add_argument("--env", default="dev")
52
+ chk = sub.add_parser("check", help="Verify no drift or edited-applied migrations")
53
+ chk.add_argument("--env", default="dev")
54
+ chk.add_argument("--require-head", action="store_true", help="Fail if migration(s) pending")
55
+ rst = sub.add_parser("restamp", help="Accept line-ending-only changes to applied v0 revisions")
56
+ rst.add_argument("--env", default="dev")
57
+ val = sub.add_parser("validate", help="Check source history, drafts and manifests; never reads env state")
58
+ val.add_argument("--strict", action="store_true", help="Fail if any warning is raised")
59
+ val.add_argument("--drafts-clean", action="store_true", help="Fail if drafts differ from head")
60
+ get = sub.add_parser("get", help="Read a config from a local environment")
61
+ get.add_argument("name")
62
+ get.add_argument("--env", default="dev")
63
+ env = sub.add_parser("env", help="Manage declared local environments")
64
+ env_sub = env.add_subparsers(dest="env_command", required=True)
65
+ add_env = env_sub.add_parser("add", help="Declare a local environment")
66
+ add_env.add_argument("name")
67
+ env_sub.add_parser("list", help="List declared environments and local state files")
68
+ return p
69
+
70
+
71
+ def main(argv: list[str] | None = None) -> int:
72
+ """Parse, run the command, render the result or handled error, and return the exit code."""
73
+ args = build_parser().parse_args(argv)
74
+ result = error = unhandled = None
75
+ with warnings.catch_warnings(record=True) as caught:
76
+ warnings.simplefilter("always")
77
+ try:
78
+ result = COMMANDS[args.command].execute(args)
79
+ except output.HANDLED as e:
80
+ error = e
81
+ except BaseException as e:
82
+ # Printing here, while warnings.showwarning is still catch_warnings' own recorder, would make
83
+ # _print_warnings append back onto `caught` while iterating it. Defer to after the `with` exits
84
+ # (which restores showwarning), but still before this propagates.
85
+ unhandled = e
86
+ if args.output == "json" and unhandled is None:
87
+ for w in caught: # JSON lists PromptMigrate warnings itself; anything else still goes to stderr
88
+ if not issubclass(w.category, PromptMigrateWarning):
89
+ warnings.showwarning(w.message, w.category, w.filename, w.lineno)
90
+ else: # text mode, or a crash that leaves no envelope to list them in
91
+ _print_warnings(caught)
92
+ if unhandled is not None:
93
+ raise unhandled
94
+ warned = output.collect_warnings(caught)
95
+ try:
96
+ if error is not None:
97
+ return output.emit_error(error, args.output, *output.describe(args), warned)
98
+ # Reaching here means `execute` returned instead of raising, so `result` is a Result.
99
+ # Narrowing it with an assert keeps the call type-checked without a cast; a shared
100
+ # CommandResult protocol would remove the need for the narrowing entirely.
101
+ assert result is not None, "emit_result reached without a result"
102
+ output.emit_result(result, args.output, warned)
103
+ except OSError as e: # writing the result failed: a closed pipe or a full destination
104
+ print(f"Error: {e}", file=sys.stderr)
105
+ return 5
106
+ return 0
107
+
108
+
109
+ def _print_warnings(caught: list[warnings.WarningMessage]) -> None:
110
+ """Print each distinct PromptMigrate warning once, in first-seen order; pass other warnings through."""
111
+ seen = set()
112
+ for w in caught:
113
+ if not issubclass(w.category, PromptMigrateWarning):
114
+ warnings.showwarning(w.message, w.category, w.filename, w.lineno)
115
+ continue
116
+ key = (w.category, str(w.message))
117
+ if key not in seen:
118
+ seen.add(key)
119
+ print(f"Warning: {w.message}", file=sys.stderr)
120
+
121
+
122
+ if __name__ == "__main__":
123
+ sys.exit(main())
@@ -0,0 +1,5 @@
1
+ """One module per CLI verb.
2
+
3
+ Each module holds the verb's use-case function (re-exported by promptmigrate.core) and `run(args)`, which cli.py
4
+ dispatches to and which prints the verb's text output.
5
+ """
@@ -0,0 +1,65 @@
1
+ """`check`: verify an environment against source history, and warn about secrets in history."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import warnings
7
+ from pathlib import Path
8
+
9
+ from .. import apply, output, project, revisions, secretscan, store
10
+ from ..errors import PendingRevisionsError, SchemaError, SecretInHistoryWarning, StaleAllowlistWarning
11
+
12
+
13
+ def check(project_dir: Path, env: str, require_head: bool = False) -> tuple[int, int]:
14
+ env = store.resolve_environment(project_dir, env)
15
+ revisions_ = revisions.load_revisions(project_dir)
16
+ with store.connect_readonly(project_dir, env) as db:
17
+ count = apply._verify(db, revisions_, env) if db is not None else 0
18
+ if require_head and count != len(revisions_):
19
+ raise PendingRevisionsError(f"Environment is behind head: {len(revisions_) - count} pending revisions")
20
+ return count, len(revisions_)
21
+
22
+
23
+ def audit_secrets(project_dir: Path) -> None:
24
+ """Warn about secret-like values in source history and about allowlist entries that match nothing.
25
+
26
+ Warnings only: `check` verifies integrity, not hygiene. Secrets in history stay in Git and must be rotated.
27
+ """
28
+ revisions_ = revisions.load_revisions(project_dir)
29
+ allow = project.load_allowlist(project_dir)
30
+ used: set[secretscan.AllowEntry] = set()
31
+ for r in revisions_:
32
+ seen: list[secretscan.Finding] = []
33
+ seen += [f for f in secretscan.scan("(message)", {"message": r.message}, allow, used) if f not in seen]
34
+ for name, change in r.changes.items():
35
+ for side in ("before", "after"):
36
+ if change[side] is not None:
37
+ seen += [f for f in secretscan.scan(name, change[side], allow, used) if f not in seen]
38
+ for finding in seen:
39
+ warnings.warn(f"revision {r.revision}: {finding.name} {finding.path} {finding.rule}",
40
+ SecretInHistoryWarning, stacklevel=2)
41
+ try:
42
+ drafts = project.read_drafts(project_dir)
43
+ except SchemaError:
44
+ return # an unreadable draft is reported by diff/revision; without drafts, staleness is unknown
45
+ for name, config in drafts.items():
46
+ secretscan.scan(name, config, allow, used)
47
+ for entry in allow:
48
+ if entry not in used:
49
+ warnings.warn(f"secret allowlist entry {entry.name} {entry.path} {entry.rule} matched nothing in drafts "
50
+ "or history", StaleAllowlistWarning, stacklevel=2)
51
+
52
+
53
+ def execute(args: argparse.Namespace) -> output.Result:
54
+ """Run `check` and return its text and JSON result."""
55
+ project_dir = Path(args.project)
56
+ label = store.display_name(project_dir, args.env)
57
+ audit_secrets(project_dir)
58
+ n, total = check(project_dir, args.env, args.require_head)
59
+ data = {"consistent": True, "applied": n, "total": total}
60
+ return output.Result("check", data, f"OK: {label} is consistent ({n}/{total} revisions applied)\n", label)
61
+
62
+
63
+ def run(args: argparse.Namespace) -> None:
64
+ """Run `check` and print its text output."""
65
+ output.emit_result(execute(args), "text", [])
@@ -0,0 +1,25 @@
1
+ """`current`: show the revision an environment is at."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ from .. import output, revisions, store
9
+ from . import check
10
+
11
+
12
+ def execute(args: argparse.Namespace) -> output.Result:
13
+ """Run `current` and return its text and JSON result."""
14
+ project_dir = Path(args.project)
15
+ label = store.display_name(project_dir, args.env)
16
+ n, total = check.check(project_dir, args.env)
17
+ revisions_ = revisions.load_revisions(project_dir)
18
+ head = revisions_[n - 1].revision if n else None
19
+ data = {"revision": head, "applied": n, "total": total}
20
+ return output.Result("current", data, f"{label}: {head or 'base'} ({n}/{total} applied)\n", label)
21
+
22
+
23
+ def run(args: argparse.Namespace) -> None:
24
+ """Run `current` and print its text output."""
25
+ output.emit_result(execute(args), "text", [])
@@ -0,0 +1,19 @@
1
+ """`diff`: show drafts compared with the source head, with secret-like values redacted."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ from .. import draftdiff, output, project
9
+
10
+
11
+ def execute(args: argparse.Namespace) -> output.Result:
12
+ """Run `diff` and return its text and JSON result."""
13
+ changes, redacted = draftdiff.redacted_diff(Path(args.project))
14
+ return output.Result("diff", {"changes": changes, "redacted": redacted}, project.pretty(changes) + "\n")
15
+
16
+
17
+ def run(args: argparse.Namespace) -> None:
18
+ """Run `diff` and print its text output."""
19
+ output.emit_result(execute(args), "text", [])
@@ -0,0 +1,36 @@
1
+ """`downgrade`: revert applied revisions in an environment, to -1, base or a target revision."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ from .. import apply, output, plan, revisions, store
9
+
10
+
11
+ def downgrade(project_dir: Path, env: str, target: str = "-1") -> list[str]:
12
+ env = store.resolve_environment(project_dir, env)
13
+ revisions_ = revisions.load_revisions(project_dir)
14
+ with store.connect_write(project_dir, env) as db:
15
+ db.execute("BEGIN IMMEDIATE")
16
+ applied_count = apply._verify(db, revisions_, env)
17
+ target_count = plan.downgrade_count(revisions_, applied_count, target)
18
+ reversed_revisions = plan.downgrade_steps(revisions_, applied_count, target_count)
19
+ apply.migrate(db, reversed_revisions, backward=True)
20
+ store.adopt_environments(project_dir)
21
+ return [r.revision for r in reversed_revisions]
22
+
23
+
24
+ def execute(args: argparse.Namespace) -> output.Result:
25
+ """Run `downgrade` and return its text and JSON result."""
26
+ project_dir = Path(args.project)
27
+ label = store.display_name(project_dir, args.env)
28
+ ids = downgrade(project_dir, args.env, args.target)
29
+ data = {"direction": "down", "target": args.target, "revisions": ids}
30
+ text = f"{label}: reverted {len(ids)} revision(s): {', '.join(ids) or '(nothing to revert)'}\n"
31
+ return output.Result("downgrade", data, text, label)
32
+
33
+
34
+ def run(args: argparse.Namespace) -> None:
35
+ """Run `downgrade` and print its text output."""
36
+ output.emit_result(execute(args), "text", [])
@@ -0,0 +1,35 @@
1
+ """`env add` / `env list`: manage declared local environments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ from .. import output, project, store
9
+
10
+
11
+ def env_add(project_dir: Path, name: str) -> Path:
12
+ project.require_init(project_dir)
13
+ return store.add_environment(project_dir, name)
14
+
15
+
16
+ def env_list(project_dir: Path) -> list[tuple[str, bool]]:
17
+ project.require_init(project_dir)
18
+ return store.list_environments(project_dir)
19
+
20
+
21
+ def execute(args: argparse.Namespace) -> output.Result:
22
+ """Run `env` and return its text and JSON result."""
23
+ project_dir = Path(args.project)
24
+ if args.env_command == "add":
25
+ env_add(project_dir, args.name)
26
+ return output.Result("env add", {"name": args.name}, f"Added environment: {args.name}\n")
27
+ listed = env_list(project_dir)
28
+ data = {"environments": [{"name": name, "has_state": has_state} for name, has_state in listed]}
29
+ text = "".join(f"{name}: {'state exists' if has_state else 'no state'}\n" for name, has_state in listed)
30
+ return output.Result("env list", data, text)
31
+
32
+
33
+ def run(args: argparse.Namespace) -> None:
34
+ """Run `env` and print its text output."""
35
+ output.emit_result(execute(args), "text", [])
@@ -0,0 +1,48 @@
1
+ """`get`: read one config from an environment, with secret-like values redacted for display."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import warnings
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from .. import apply, output, project, revisions, secretscan, store
12
+ from ..errors import SecretRedactedWarning, TargetError
13
+
14
+
15
+ def get_config(project_dir: Path, env: str, name: str) -> dict[str, Any]:
16
+ env = store.resolve_environment(project_dir, env)
17
+ revisions_ = revisions.load_revisions(project_dir)
18
+ with store.connect_readonly(project_dir, env) as db:
19
+ if db is None:
20
+ row = None
21
+ else:
22
+ apply._verify(db, revisions_, env)
23
+ row = db.execute("SELECT config FROM prompts WHERE name=?", (name,)).fetchone()
24
+ if not row:
25
+ raise TargetError(f"No prompt named {name!r} in environment {env!r}")
26
+ return json.loads(row[0])
27
+
28
+
29
+ def redacted_config(project_dir: Path, env: str, name: str) -> tuple[dict[str, Any], list[str]]:
30
+ """get_config() for display: secret-like values replaced by "<redacted:RULE>", plus the redacted paths."""
31
+ config, paths = secretscan.redact(name, get_config(project_dir, env, name), project.load_allowlist(project_dir))
32
+ if paths:
33
+ warnings.warn(secretscan._REDACTED.format(count=len(paths)), SecretRedactedWarning, stacklevel=2)
34
+ return config, paths
35
+
36
+
37
+ def execute(args: argparse.Namespace) -> output.Result:
38
+ """Run `get` and return its text and JSON result."""
39
+ project_dir = Path(args.project)
40
+ label = store.display_name(project_dir, args.env)
41
+ config, paths = redacted_config(project_dir, args.env, args.name)
42
+ data = {"name": args.name, "config": config, "redacted": paths}
43
+ return output.Result("get", data, project.pretty(config), label)
44
+
45
+
46
+ def run(args: argparse.Namespace) -> None:
47
+ """Run `get` and print its text output."""
48
+ output.emit_result(execute(args), "text", [])
@@ -0,0 +1,41 @@
1
+ """`history`: list source revisions, oldest first."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import dataclasses
7
+ import warnings
8
+ from pathlib import Path
9
+
10
+ from .. import output, project, revisions, secretscan
11
+ from ..errors import SecretRedactedWarning
12
+
13
+
14
+ def redacted_history(project_dir: Path, load=None) -> tuple[list[revisions.Revision], list[str]]:
15
+ """load_revisions() for display: a secret-like message is replaced by "<redacted:RULE>"; returns the ids redacted."""
16
+ allow = project.load_allowlist(project_dir)
17
+ shown, redacted = [], []
18
+ for r in (load or revisions.load_revisions)(project_dir):
19
+ value, paths = secretscan.redact("(message)", {"message": r.message}, allow)
20
+ if paths:
21
+ r = dataclasses.replace(r, message=value["message"])
22
+ redacted.append(r.revision)
23
+ shown.append(r)
24
+ if redacted:
25
+ warnings.warn(secretscan._REDACTED.format(count=len(redacted)), SecretRedactedWarning, stacklevel=2)
26
+ return shown, redacted
27
+
28
+
29
+ def execute(args: argparse.Namespace) -> output.Result:
30
+ """Run `history` and return its text and JSON result."""
31
+ shown, redacted = redacted_history(Path(args.project))
32
+ data = {"revisions": [{"revision": r.revision, "down_revision": r.down_revision, "message": r.message}
33
+ for r in shown],
34
+ "redacted": redacted}
35
+ text = "".join(f"{r.revision} <- {r.down_revision or 'base'} | {r.message}\n" for r in shown)
36
+ return output.Result("history", data, text)
37
+
38
+
39
+ def run(args: argparse.Namespace) -> None:
40
+ """Run `history` and print its text output."""
41
+ output.emit_result(execute(args), "text", [])
@@ -0,0 +1,43 @@
1
+ """`init`: create the .promptmigrate/ scaffold."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ from pathlib import Path
8
+
9
+ from .. import output, project
10
+ from ..errors import InitializationError
11
+
12
+
13
+ def init(project_dir: Path) -> Path:
14
+ root = project.root_dir(project_dir)
15
+ if root.exists():
16
+ raise InitializationError(f"Already exists: {root}")
17
+ (root / "versions").mkdir(parents=True)
18
+ (root / "drafts").mkdir()
19
+ (root / "states").mkdir()
20
+ (root / ".gitignore").write_text("/states/\n", encoding="utf-8")
21
+ (root / "environments.json").write_text(
22
+ json.dumps({"environments": {"dev": {}, "staging": {}}}, indent=2) + "\n", encoding="utf-8"
23
+ )
24
+ starter = {
25
+ "messages": [{"role": "system", "content": "You are a helpful AI assistant."}],
26
+ "model": "provider/model-id",
27
+ "parameters": {"temperature": 0},
28
+ "tools": [],
29
+ "response_schema": None,
30
+ }
31
+ (root / "drafts" / "assistant.json").write_text(project.pretty(starter), encoding="utf-8")
32
+ return root
33
+
34
+
35
+ def execute(args: argparse.Namespace) -> output.Result:
36
+ """Run `init` and return its text and JSON result."""
37
+ root = init(Path(args.project))
38
+ return output.Result("init", {"path": str(root)}, f"Initialized {root}\n")
39
+
40
+
41
+ def run(args: argparse.Namespace) -> None:
42
+ """Run `init` and print its text output."""
43
+ output.emit_result(execute(args), "text", [])
@@ -0,0 +1,51 @@
1
+ """`plan`: read-only preview of what `upgrade` or `downgrade` would do to an environment."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from pathlib import Path
7
+
8
+ from .. import apply, output, revisions, store
9
+ from .. import plan as planning
10
+ from ..plan import MigrationPlan
11
+
12
+
13
+ def plan(project_dir: Path, env: str, target: str = "head") -> MigrationPlan:
14
+ """Resolve `target` against the environment's verified applied state. Writes nothing."""
15
+ env = store.resolve_environment(project_dir, env)
16
+ revisions_ = revisions.load_revisions(project_dir)
17
+ if target not in ("head", "-1", "base"):
18
+ planning.upgrade_count(revisions_, target) # like `upgrade`, reject an unknown id before reading the env
19
+ with store.connect_readonly(project_dir, env) as db:
20
+ applied = apply._verify(db, revisions_, env) if db is not None else 0
21
+ return planning.build(revisions_, applied, target)
22
+
23
+
24
+ def render(label: str, result: MigrationPlan) -> str:
25
+ """The plan as the text `promptmigrate plan` prints."""
26
+ if result.direction == "none":
27
+ return f"{label}: nothing to do (at {result.start or 'base'})\n"
28
+ verb = "apply" if result.direction == "upgrade" else "revert"
29
+ lines = [f"{label}: would {verb} {len(result.steps)} revision(s) ({result.start or 'base'} -> {result.target or 'base'})"]
30
+ for step in result.steps:
31
+ lines.append(f" {step.revision}")
32
+ lines.extend(f" {name} ({kind})" for name, kind in step.changes)
33
+ return "\n".join(lines) + "\n"
34
+
35
+
36
+ def execute(args: argparse.Namespace) -> output.Result:
37
+ """Run `plan` and return its text and JSON result."""
38
+ project_dir = Path(args.project)
39
+ label = store.display_name(project_dir, args.env)
40
+ result = plan(project_dir, args.env, args.target)
41
+ data = {
42
+ "direction": result.direction, "start": result.start, "target": result.target,
43
+ "steps": [{"revision": step.revision, "changes": [{"name": name, "kind": kind} for name, kind in step.changes]}
44
+ for step in result.steps],
45
+ }
46
+ return output.Result("plan", data, render(label, result), label)
47
+
48
+
49
+ def run(args: argparse.Namespace) -> None:
50
+ """Print the plan for `args.env` and `args.target`."""
51
+ output.emit_result(execute(args), "text", [])