File size: 10,102 Bytes
c14ceee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
"""harness/workspace.py β€” the unified WORKSPACE object model (owner directive 2026-07-12:
"every single time we create a module or analytics from the AIOS, it should be modular β€” a
workspace").

Every artifact AIOS creates β€” a view, a dashboard, an alert, a scheduled report β€” is a MODULAR,
self-contained workspace object: it carries everything needed to re-run itself (the governed
query / metric reference), renders through the house primitives, composes into bigger objects
(views β†’ dashboards β†’ schedules), and exports as a TENANT-AGNOSTIC template (queries reference
topic/metric KEYS; scope lives in the model, so a template stamps onto any tenant whose model
has those keys β€” the same principle that made model/ itself the template library).

This module is the facade: one uniform envelope + one listing/manage/export surface over the
underlying stores (views.json, routines.json). It does not replace them β€” it makes them one
workspace.
"""
import json
import time
from pathlib import Path

import harness.views as V
import harness.routines as R
import harness.semantic as SEM

TEMPLATES_DIR = Path(__file__).resolve().parents[1] / "model" / "templates"

# query keys that are tenant/context-specific and must NOT travel in a template
_STRIP = ("team_id", "filters", "date_from", "date_to")


def items():
    """Every workspace object, uniform envelope: {kind, name, detail, created_at}."""
    out = []
    vs, ds = V.views(), V.dashboards()
    dash_members = {vn for d in ds.values() for vn in d.get("views", [])}
    for name, v in vs.items():
        spec = v.get("chart") or {}
        q = spec.get("query") or {}
        out.append({"kind": "view", "name": name,
                    "detail": f"{q.get('topic', '?')} Β· {', '.join(q.get('measures') or [])}"
                              + (" Β· in a dashboard" if name in dash_members else ""),
                    "created_at": v.get("saved_at", "")})
    for name, d in ds.items():
        out.append({"kind": "dashboard", "name": name,
                    "detail": f"{len(d.get('views', []))} view(s): "
                              + ", ".join(d.get("views", [])[:4]),
                    "created_at": d.get("created_at", "")})
    rt = R.load()
    for key, a in rt.get("alerts", {}).items():
        out.append({"kind": "alert", "name": key,
                    "detail": f"{a.get('metric')} Β· {a.get('mode')}"
                              + (f" Β· team {a['team_id']}" if a.get("team_id") else ""),
                    "created_at": a.get("created_at", "")})
    for key, r in rt.get("reports", {}).items():
        out.append({"kind": "report", "name": key,
                    "detail": f"{r.get('cadence')} Β· {r.get('channel')}",
                    "created_at": r.get("created_at", "")})
    for key, i in (rt.get("insights") or {}).items():
        out.append({"kind": "insight", "name": key,
                    "detail": f"{i.get('cadence')} Β· \"{(i.get('prompt') or '')[:60]}\"",
                    "created_at": i.get("created_at", "")})
    return sorted(out, key=lambda x: x.get("created_at") or "", reverse=True)


def delete(kind, name):
    if kind == "view":
        V.delete_view(name)
    elif kind == "dashboard":
        V.delete_dashboard(name)
    elif kind == "alert":
        R.delete_alert(name)
    elif kind == "report":
        R.delete_report(name)
    elif kind == "insight":
        R.delete_insight(name)
    else:
        raise SEM.ModelError(f"unknown workspace kind {kind!r}")


# ------------------------------------------------------------------ templates (tenant-agnostic)

def _templatize_view(name):
    v = V.views().get(name)
    if not v:
        raise SEM.ModelError(f"unknown view {name!r}")
    spec = dict(v.get("chart") or {})
    q = dict(spec.get("query") or {})
    if not q:
        raise SEM.ModelError(f"view {name!r} carries no query β€” cannot templatize")
    stripped = {k: q.pop(k) for k in _STRIP if k in q}
    stripped = {k: v for k, v in stripped.items() if v}      # record only real tenant baggage
    q["window"] = "ytd"                      # instantiation default; tenant picks at stamp time
    spec["query"] = q
    return {"name": name, "spec": spec,
            "stripped": sorted(stripped)}    # honest record of what was tenant-specific


def export_template(kind, name):
    """Export a view or dashboard as a tenant-agnostic template JSON in model/templates/.
    Dashboards embed their views' templates β€” one self-contained modular unit."""
    if kind == "view":
        tpl = {"template": "view", "exported_at": time.strftime("%Y-%m-%d %H:%M"),
               **_templatize_view(name)}
    elif kind == "dashboard":
        d = V.dashboards().get(name)
        if d is None:
            raise SEM.ModelError(f"unknown dashboard {name!r}")
        tpl = {"template": "dashboard", "name": name,
               "exported_at": time.strftime("%Y-%m-%d %H:%M"),
               "views": [_templatize_view(vn) for vn in d.get("views", [])]}
    else:
        raise SEM.ModelError("only views and dashboards templatize (alerts/reports are one-liners "
                             "β€” recreate from the metric key)")
    TEMPLATES_DIR.mkdir(parents=True, exist_ok=True)
    safe = "".join(c if c.isalnum() or c in "-_ " else "_" for c in name).strip().replace(" ", "-")
    path = TEMPLATES_DIR / f"{kind}-{safe}.json"
    path.write_text(json.dumps(tpl, indent=1), encoding="utf-8")
    return str(path)


PROPOSALS_DIR = Path(__file__).resolve().parents[1] / "model" / "proposals"


def promote(kind, name, note=""):
    """Nominate a workspace object for PROMOTION into the governed model (principle 3: model
    just-in-time, promote what's proven). v0: writes a reviewable proposal file under
    model/proposals/ β€” the next Claude session is the Modeler: it reviews the proposal, lands
    the actual model diff (a metric, a skill recipe, or a curated template), and deletes the
    proposal. Git is the branch mode; nothing merges without that review."""
    if kind == "view":
        v = V.views().get(name)
        if not v:
            raise SEM.ModelError(f"unknown view {name!r}")
        spec = v.get("chart") or {}
        payload = {"kind": "view", "name": name, "spec": spec}
        q = spec.get("query") or {}
        hint = (f"candidate: a named metric or skill recipe on topic {q.get('topic')!r} "
                f"(measures {q.get('measures')}, group_by {q.get('group_by')})")
    elif kind == "dashboard":
        d = V.dashboards().get(name)
        if d is None:
            raise SEM.ModelError(f"unknown dashboard {name!r}")
        payload = {"kind": "dashboard", "name": name, "views": d.get("views", []),
                   "view_specs": {vn: (V.views().get(vn) or {}).get("chart")
                                  for vn in d.get("views", [])}}
        hint = "candidate: a curated template in model/templates/ or a skill recipe"
    else:
        raise SEM.ModelError("only views and dashboards can be nominated")
    try:
        import harness.telemetry as TEL
        usage = TEL.summary()
    except Exception:
        usage = {}
    PROPOSALS_DIR.mkdir(parents=True, exist_ok=True)
    safe = "".join(c if c.isalnum() or c in "-_ " else "_" for c in name).strip().replace(" ", "-")
    path = PROPOSALS_DIR / f"{time.strftime('%Y%m%d-%H%M')}-{kind}-{safe}.json"
    path.write_text(json.dumps({
        "proposed_at": time.strftime("%Y-%m-%d %H:%M"),
        "note": note, "suggested": hint, "usage_at_nomination": usage, **payload,
        "reviewer_instructions": (
            "MODELER REVIEW (next Claude session): decide metric / skill-recipe / template / "
            "reject; land the model diff in model/*.yml with a validate contract where "
            "applicable; re-run the eval gate; DELETE this proposal file; log the decision."),
    }, indent=1), encoding="utf-8")
    return str(path)


def proposals():
    if not PROPOSALS_DIR.exists():
        return []
    return sorted(p.name for p in PROPOSALS_DIR.glob("*.json"))


def templates():
    if not TEMPLATES_DIR.exists():
        return []
    return sorted(p.name for p in TEMPLATES_DIR.glob("*.json"))


def _ytd():
    from datetime import date
    t = date.today()
    return t.replace(month=1, day=1).isoformat(), t.isoformat()


def instantiate_template(filename, new_name=None):
    """Stamp a template into THIS tenant's workspace: window resolves to YTD now; tenant scope
    comes from the model (topics/tenant.yml), so no per-tenant edits are needed."""
    path = TEMPLATES_DIR / filename
    if not path.exists():
        raise SEM.ModelError(f"unknown template {filename!r}")
    tpl = json.loads(path.read_text(encoding="utf-8"))
    df, dt_ = _ytd()

    def _stamp_view(vtpl, vname):
        spec = dict(vtpl["spec"])
        q = dict(spec.get("query") or {})
        q.pop("window", None)
        q["date_from"], q["date_to"] = df, dt_
        spec["query"] = q
        spec["title"] = vname
        import harness.tools as T
        T.save_view(vname, {"chart": spec})
        return vname

    def _fresh(name):
        """Never clobber an existing object β€” suffix until free."""
        vs, ds = V.views(), V.dashboards()
        cand, i = name, 2
        while cand in vs or cand in ds:
            cand = f"{name} ({i})"
            i += 1
        return cand

    if tpl.get("template") == "view":
        vname = _fresh(new_name or tpl["name"])
        return {"created": "view", "name": _stamp_view(tpl, vname)}
    if tpl.get("template") == "dashboard":
        dname = _fresh(new_name or tpl["name"])
        # namespace member views under the new dashboard so instantiation NEVER overwrites
        # existing views (modularity means copies, not aliasing)
        vnames = [_stamp_view(vt, _fresh(f"{dname} Β· {vt['name']}"))
                  for vt in tpl.get("views", [])]
        import harness.tools as T
        T.compose_dashboard(dname, vnames)
        return {"created": "dashboard", "name": dname, "views": vnames}
    raise SEM.ModelError(f"bad template file {filename!r}")