Spaces:
Running

File size: 5,742 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
"""Ops commands.



python -m core.cli sync-tools        # index pack tools for tool search (owner role)

python -m core.cli expire-approvals  # mark overdue approvals expired (owner role)

python -m core.cli check-deploy      # refuse a deploy that would strand waiting runs



Phase 18 (docs/deployment.md):



python -m core.cli seed-demo [--reset]                 # public demo tenant (app + owner roles)

python -m core.cli purge-retention [--tenant ID] [--dry-run]   # audit/messages (owner role)

python -m core.cli verify-audit --tenant ID           # hash chain, retention-anchor aware

python -m core.cli check-config                       # refuse dev defaults in production

"""

from __future__ import annotations

import argparse
import asyncio
import sys
from typing import Any

from sqlalchemy import text

from core.config import get_settings
from core.db.session import Database
from core.packs.loader import discover_packs


async def sync_tools() -> int:
    from core.tools.search import ToolSearch

    db = Database(get_settings().owner_database_url)
    specs = [t.spec for p in discover_packs() for t in p.tools()]
    async with db.session() as s, s.begin():
        n = await ToolSearch().sync_global(s, specs)
    await db.dispose()
    print(f"indexed {n} tools")
    return 0


async def expire_approvals() -> int:
    from core.approvals.service import ApprovalService

    db = Database(get_settings().owner_database_url)
    async with db.session() as s, s.begin():
        expired = await ApprovalService().expire_pending(s)
    await db.dispose()
    print(f"expired {len(expired)} approvals")
    return 0


async def check_deploy() -> int:
    from core.agent.runtime import CORE_NODES, incompatible_waiting_runs

    nodes = sorted([*CORE_NODES, *(i.name for p in discover_packs() for i in p.intents())])
    db = Database(get_settings().owner_database_url)
    async with db.session() as s:
        # Phase 18: the release step runs this BEFORE migrating; a fresh database has no runs.
        if (await s.execute(text("SELECT to_regclass('runs')"))).scalar() is None:
            await db.dispose()
            print("fresh database: no waiting runs to check")
            return 0
        bad = await incompatible_waiting_runs(s, nodes)
    await db.dispose()
    if bad:
        print(f"refusing deploy: {len(bad)} waiting runs need removed nodes: {bad[:10]}")
        return 1
    print("deploy is compatible with waiting runs")
    return 0


async def seed_demo(reset: bool = False) -> int:
    import json

    from core.ops.demo import seed_demo_tenant

    s = get_settings()
    db, owner_db = Database(s.database_url), Database(s.owner_database_url)
    try:
        res = await seed_demo_tenant(db, owner_db, discover_packs(), s, reset=reset)
    finally:
        await db.dispose()
        await owner_db.dispose()
    print(json.dumps(res.as_dict()))
    return 1 if res.missing_seeders else 0


async def purge_retention(tenants: list[str], dry_run: bool = False) -> int:
    import json
    import uuid

    from core.ops.retention import purge_all

    s = get_settings()
    owner_db = Database(s.owner_database_url)
    try:
        ids = [uuid.UUID(t) for t in tenants] if tenants else None
        out = await purge_all(owner_db, s, ids, dry_run=dry_run)
    finally:
        await owner_db.dispose()
    for r in out:
        print(json.dumps({**r.as_dict(), "dry_run": dry_run}))
    return 0


async def verify_audit(tenants: list[str]) -> int:
    import uuid

    from core.ops.retention import verify_chain_anchored

    if not tenants:
        print("verify-audit needs --tenant")
        return 2
    owner_db = Database(get_settings().owner_database_url)
    bad = 0
    try:
        for t in tenants:
            tid = uuid.UUID(t)
            async with owner_db.session(tenant_id=tid) as s:
                rep = await verify_chain_anchored(s, tid)
            print(f"{tid}: ok={rep.ok} checked={rep.checked} broken_at_seq={rep.broken_at_seq}")
            bad += not rep.ok
    finally:
        await owner_db.dispose()
    return 1 if bad else 0


async def check_config() -> int:
    from core.ops.preflight import production_problems

    problems = production_problems(get_settings())
    for p in problems:
        print(f"config problem: {p}")
    if not problems:
        print("configuration ok")
    return 1 if problems else 0


COMMANDS = [
    "sync-tools",
    "expire-approvals",
    "check-deploy",
    "seed-demo",
    "purge-retention",
    "verify-audit",
    "check-config",
]


def main(argv: list[str] | None = None) -> None:
    if sys.platform == "win32":
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    p = argparse.ArgumentParser(prog="workpilot")
    p.add_argument("command", choices=COMMANDS)
    p.add_argument("--reset", action="store_true", help="seed-demo: wipe and re-seed")
    p.add_argument("--tenant", action="append", default=[], help="tenant id (repeatable)")
    p.add_argument("--dry-run", action="store_true", help="purge-retention: roll back")
    a = p.parse_args(argv)
    fn: dict[str, Any] = {
        "sync-tools": sync_tools,
        "expire-approvals": expire_approvals,
        "check-deploy": check_deploy,
        "seed-demo": lambda: seed_demo(a.reset),
        "purge-retention": lambda: purge_retention(a.tenant, a.dry_run),
        "verify-audit": lambda: verify_audit(a.tenant),
        "check-config": check_config,
    }
    raise SystemExit(asyncio.run(fn[a.command]()))


if __name__ == "__main__":
    main()