ui-director-skill 2.0.0 → 3.0.0
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.
- package/CHANGELOG.md +25 -0
- package/INSTALL.md +47 -18
- package/README.md +34 -31
- package/SKILL.md +14 -9
- package/assets/bundle-profiles.json +178 -0
- package/assets/capabilities.json +259 -0
- package/assets/install-manifest.json +27 -0
- package/assets/project-profile.example.json +23 -0
- package/assets/routing-rules.json +24 -0
- package/assets/upstreams.json +100 -0
- package/benchmark/README.md +54 -0
- package/benchmark/blind.mjs +141 -0
- package/benchmark/cases.json +66 -0
- package/benchmark/fixtures/reference.html +39 -0
- package/bin/ui.mjs +53 -10
- package/examples/usage.md +19 -50
- package/install.py +304 -0
- package/lib/core.mjs +8 -3
- package/lib/workflows.mjs +151 -29
- package/package.json +8 -3
- package/references/delivery-contract.md +5 -0
- package/references/design-intelligence.md +2 -0
- package/references/integrations/security-policy.md +2 -0
- package/references/integrations/skill-manager.md +5 -0
- package/references/integrations/upstream-adapters.md +25 -0
- package/references/integrations.md +2 -0
- package/references/motion-interaction.md +2 -0
- package/references/orchestration/context-management.md +14 -0
- package/references/orchestration/iteration-loop.md +9 -0
- package/references/orchestration/routing.md +13 -0
- package/references/platforms/desktop.md +3 -0
- package/references/platforms/hmi.md +5 -0
- package/references/platforms/mobile.md +3 -0
- package/references/platforms/web.md +3 -0
- package/references/quality-assurance.md +2 -0
- package/references/routing.md +2 -27
- package/references/stages/design-research.md +2 -0
- package/references/stages/design-system.md +7 -0
- package/references/stages/deslop.md +3 -0
- package/references/stages/motion-interaction.md +31 -0
- package/references/stages/prototyping.md +2 -0
- package/references/stages/ux-strategy.md +10 -0
- package/references/stages/visual-direction.md +13 -0
- package/references/stages/visual-validation.md +25 -0
- package/references/visual-direction.md +2 -0
- package/skill_manager.py +657 -0
- package/templates/DECISIONS.md +2 -3
- package/templates/DESIGN.md +9 -10
- package/templates/PRODUCT.md +5 -4
- package/templates/REVIEW.md +13 -10
- package/config/optional-skills.json +0 -16
- package/config/quality-rubric.json +0 -13
- package/config/workflows.json +0 -15
- package/references/design-workflows.md +0 -21
- package/references/platforms.md +0 -17
- package/references/project-inspection.md +0 -11
- package/references/quality-gates.md +0 -16
- package/references/specialists.md +0 -9
package/skill_manager.py
ADDED
|
@@ -0,0 +1,657 @@
|
|
|
1
|
+
"""Explicit, git-based companion manager. No upstream scripts are run by this module."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import re
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
import tempfile
|
|
10
|
+
from contextlib import contextmanager, ExitStack
|
|
11
|
+
from datetime import datetime, timedelta, timezone
|
|
12
|
+
|
|
13
|
+
BASE = Path(__file__).resolve().parent
|
|
14
|
+
REGISTRY = json.loads((BASE/'assets/bundle-profiles.json').read_text(encoding='utf-8'))
|
|
15
|
+
PROVIDERS = REGISTRY['providers']
|
|
16
|
+
HEX = re.compile(r'[0-9a-f]{40}')
|
|
17
|
+
NAME = re.compile(r'[a-z0-9][a-z0-9-]*')
|
|
18
|
+
|
|
19
|
+
def git(*args, cwd=None):
|
|
20
|
+
env = dict(os.environ, GIT_TERMINAL_PROMPT='0', GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL=os.devnull)
|
|
21
|
+
p = subprocess.run(['git','-c','core.hooksPath='+os.devnull,'-c','protocol.file.allow=never',*args], cwd=cwd, env=env, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=180)
|
|
22
|
+
if p.returncode: raise ValueError('git failed: '+p.stderr.strip()[-1000:])
|
|
23
|
+
return p.stdout.strip()
|
|
24
|
+
|
|
25
|
+
def url(provider):
|
|
26
|
+
return 'https://github.com/'+PROVIDERS[provider]['repo']+'.git'
|
|
27
|
+
|
|
28
|
+
def remote_head(provider):
|
|
29
|
+
s=git('ls-remote',url(provider),'HEAD').split()
|
|
30
|
+
if not s or not HEX.fullmatch(s[0]): raise ValueError('Unable to resolve HEAD: '+provider)
|
|
31
|
+
return s[0]
|
|
32
|
+
|
|
33
|
+
def checkout(provider, commit, path):
|
|
34
|
+
if not HEX.fullmatch(commit): raise ValueError('Invalid commit')
|
|
35
|
+
path.mkdir(); git('init','-q',cwd=path)
|
|
36
|
+
git('fetch','--depth=1','--no-tags',url(provider),commit,cwd=path)
|
|
37
|
+
git('checkout','--detach','FETCH_HEAD',cwd=path)
|
|
38
|
+
if git('rev-parse','HEAD',cwd=path)!=commit: raise ValueError('Commit mismatch')
|
|
39
|
+
|
|
40
|
+
def skill_name(path):
|
|
41
|
+
try:
|
|
42
|
+
t=(path/'SKILL.md').read_text(encoding='utf-8-sig')
|
|
43
|
+
if not t.startswith('---\n'): return None
|
|
44
|
+
m=re.search(r'^name:\s*[\"\']?([a-z0-9-]+)[\"\']?\s*$',t.split('---',2)[1],re.M)
|
|
45
|
+
return m.group(1) if m else None
|
|
46
|
+
except (OSError,UnicodeError,IndexError): return None
|
|
47
|
+
|
|
48
|
+
CACHE_FILE = re.compile(r'.+\.pyc(?:\.[0-9]+)?')
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def is_python_cache(path):
|
|
52
|
+
return path.parent.name == '__pycache__' and CACHE_FILE.fullmatch(path.name)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def ignore_python_cache(directory, names):
|
|
56
|
+
directory = Path(directory)
|
|
57
|
+
return {name for name in names if is_python_cache(directory/name)
|
|
58
|
+
and not (directory/name).is_symlink() and not (directory/name).is_dir()}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def file_hashes(path, *, include_cache=False, digest_version=2):
|
|
62
|
+
if path.is_symlink() or not path.is_dir():
|
|
63
|
+
raise ValueError('Unsafe or missing skill directory: '+str(path))
|
|
64
|
+
files = {}
|
|
65
|
+
for entry in sorted(path.rglob('*')):
|
|
66
|
+
if entry.is_symlink():
|
|
67
|
+
raise ValueError('Unsupported link or special file: '+str(entry))
|
|
68
|
+
if entry.is_dir():
|
|
69
|
+
continue
|
|
70
|
+
if not include_cache and is_python_cache(entry):
|
|
71
|
+
continue
|
|
72
|
+
if not entry.is_file():
|
|
73
|
+
raise ValueError('Unsupported link or special file: '+str(entry))
|
|
74
|
+
value = hashlib.sha256(entry.read_bytes()).digest()
|
|
75
|
+
if digest_version == 2:
|
|
76
|
+
value += bytes([entry.stat().st_mode & 0o111])
|
|
77
|
+
files[entry.relative_to(path).as_posix()] = value
|
|
78
|
+
return files
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def digest_files(files):
|
|
82
|
+
fingerprint = hashlib.sha256()
|
|
83
|
+
for name, value in files.items():
|
|
84
|
+
fingerprint.update(name.encode()+b'\0'+value)
|
|
85
|
+
return fingerprint.hexdigest()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def digest(path, *, include_cache=False, digest_version=2):
|
|
89
|
+
return digest_files(file_hashes(path, include_cache=include_cache, digest_version=digest_version))
|
|
90
|
+
|
|
91
|
+
def source_skill(repo, spec, root):
|
|
92
|
+
paths=list(spec['paths'])
|
|
93
|
+
# Prefer upstream's host-specific generated variant when present in the allowlist.
|
|
94
|
+
agent_dir=root.parent.name
|
|
95
|
+
paths.sort(key=lambda p:not p.startswith(agent_dir+'/'))
|
|
96
|
+
for rel in paths:
|
|
97
|
+
p=repo/rel
|
|
98
|
+
if p.is_dir() and skill_name(p)==spec['name'] and all((p/r).exists() for r in spec['required']):
|
|
99
|
+
if p.resolve()!=p or any(x.is_symlink() for x in p.parents if x!=repo.parent): raise ValueError('Symlink source path: '+rel)
|
|
100
|
+
digest(p)
|
|
101
|
+
return p,rel
|
|
102
|
+
raise ValueError('No complete allowlisted skill '+spec['name']+' in '+str(repo.name)+'; check upstream layout; nothing silently substituted')
|
|
103
|
+
|
|
104
|
+
def state_dir(root): return root.parent/'ui-director-managed'/root.name
|
|
105
|
+
|
|
106
|
+
def validate_record(name,r):
|
|
107
|
+
if not isinstance(name, str) or not NAME.fullmatch(name) or not isinstance(r, dict):
|
|
108
|
+
raise ValueError(f'Invalid lock record: {name}')
|
|
109
|
+
provider, commit, checksum = r.get('provider'), r.get('commit'), r.get('sha256')
|
|
110
|
+
if (not isinstance(provider, str) or provider not in PROVIDERS
|
|
111
|
+
or not isinstance(commit, str) or not HEX.fullmatch(commit)
|
|
112
|
+
or not isinstance(checksum, str) or not re.fullmatch('[0-9a-f]{64}', checksum)
|
|
113
|
+
or r.get('digest_version', 1) not in (1, 2)):
|
|
114
|
+
raise ValueError('Invalid lock record: '+name)
|
|
115
|
+
if name not in [s['name'] for s in PROVIDERS[r['provider']]['skills']]: raise ValueError('Unknown skill in lock: '+name)
|
|
116
|
+
|
|
117
|
+
def validate_records(records):
|
|
118
|
+
if not isinstance(records, dict):
|
|
119
|
+
raise ValueError('Invalid lock records')
|
|
120
|
+
for name, record in records.items():
|
|
121
|
+
validate_record(name, record)
|
|
122
|
+
|
|
123
|
+
def read_lock(state):
|
|
124
|
+
f=state/'lock.json'
|
|
125
|
+
if not f.exists(): return {}
|
|
126
|
+
data=json.loads(f.read_text(encoding='utf-8'))
|
|
127
|
+
if not isinstance(data, dict) or data.get('schema') != 1:
|
|
128
|
+
raise ValueError('Unsupported lock schema')
|
|
129
|
+
validate_records(data.get('skills'))
|
|
130
|
+
return data['skills']
|
|
131
|
+
|
|
132
|
+
def atomic_json(path,data):
|
|
133
|
+
with tempfile.NamedTemporaryFile(mode='w',encoding='utf-8',dir=path.parent,delete=False) as f:
|
|
134
|
+
tmp=Path(f.name);json.dump(data,f,indent=2);f.write('\n')
|
|
135
|
+
try: os.replace(tmp,path)
|
|
136
|
+
finally: tmp.unlink(missing_ok=True)
|
|
137
|
+
|
|
138
|
+
def write_lock(state,records): atomic_json(state/'lock.json',{'schema':1,'skills':records})
|
|
139
|
+
|
|
140
|
+
def status(root):
|
|
141
|
+
lock=read_lock(state_dir(root));result=[]
|
|
142
|
+
for provider,entry in PROVIDERS.items():
|
|
143
|
+
for spec in entry['skills']:
|
|
144
|
+
n=spec['name'];p=root/n;r=lock.get(n)
|
|
145
|
+
if r:
|
|
146
|
+
try: s='MANAGED' if matches(p,r) else 'MODIFIED'
|
|
147
|
+
except (OSError,ValueError): s='MISSING OR UNSAFE'
|
|
148
|
+
elif p.exists() or p.is_symlink(): s='EXTERNAL' if skill_name(p)==n else 'CONFLICT'
|
|
149
|
+
else: s='MISSING'
|
|
150
|
+
result.append(dict(provider=provider,skill=n,status=s,commit=r['commit'] if r else None))
|
|
151
|
+
return result
|
|
152
|
+
|
|
153
|
+
@contextmanager
|
|
154
|
+
def process_lock(lockfile):
|
|
155
|
+
if lockfile.is_symlink() or (lockfile.exists() and not lockfile.is_file()):
|
|
156
|
+
raise ValueError('Unsafe manager lock: '+str(lockfile))
|
|
157
|
+
with lockfile.open('a+b') as lock:
|
|
158
|
+
try:
|
|
159
|
+
if os.name == 'nt':
|
|
160
|
+
import msvcrt
|
|
161
|
+
lock.seek(0)
|
|
162
|
+
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
|
|
163
|
+
else:
|
|
164
|
+
import fcntl
|
|
165
|
+
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
166
|
+
except OSError as exc:
|
|
167
|
+
raise ValueError('Another operation holds the lock: '+str(lockfile)) from exc
|
|
168
|
+
yield
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@contextmanager
|
|
172
|
+
def guard(root, *, recovery=False, legacy_stale_lock=False):
|
|
173
|
+
state = state_dir(root)
|
|
174
|
+
if root.resolve() != root or state.resolve() != state:
|
|
175
|
+
raise ValueError('Refusing symlinked install or state root: '+str(root))
|
|
176
|
+
state.mkdir(parents=True, exist_ok=True)
|
|
177
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
178
|
+
with process_lock(state/'manager.lock'):
|
|
179
|
+
# Keep older writers out of the newer history and digest formats.
|
|
180
|
+
# New writers synchronize via the process lock, including after a crash.
|
|
181
|
+
busy = state/'busy'
|
|
182
|
+
marker = busy/'manager-v2'
|
|
183
|
+
try:
|
|
184
|
+
busy.mkdir()
|
|
185
|
+
except FileExistsError:
|
|
186
|
+
if busy.is_symlink() or not busy.is_dir() or marker.is_symlink():
|
|
187
|
+
raise ValueError('Unsafe manager lock: '+str(busy))
|
|
188
|
+
if not marker.is_file():
|
|
189
|
+
if not (recovery and legacy_stale_lock and not any(busy.iterdir())):
|
|
190
|
+
raise ValueError('Legacy manager lock exists. Stop the old process before running '
|
|
191
|
+
'ui companions recover --legacy-stale-lock.')
|
|
192
|
+
marker.touch()
|
|
193
|
+
if (state/'pending.json').exists() and not recovery:
|
|
194
|
+
raise ValueError('Interrupted transaction. Run ui companions recover for '+str(root))
|
|
195
|
+
yield state
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def matches(path, record):
|
|
199
|
+
if record is None:
|
|
200
|
+
return not path.exists() and not path.is_symlink()
|
|
201
|
+
expected = record['sha256']
|
|
202
|
+
version = record.get('digest_version', 1)
|
|
203
|
+
if digest(path, digest_version=version) == expected:
|
|
204
|
+
return True
|
|
205
|
+
# Older lock files may include Python cache files in the saved digest.
|
|
206
|
+
return version == 1 and digest(path, include_cache=True, digest_version=1) == expected
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def copy_recorded_payload(source, destination, record):
|
|
210
|
+
version = record.get('digest_version', 1)
|
|
211
|
+
omit_cache = version == 2 or digest(source, digest_version=1) == record['sha256']
|
|
212
|
+
shutil.copytree(source, destination, ignore=ignore_python_cache if omit_cache else None)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def verify_current(root, records, names):
|
|
216
|
+
for name in names:
|
|
217
|
+
if not matches(root/name, records.get(name)):
|
|
218
|
+
reason = 'Local changes' if name in records else 'Unmanaged destination'
|
|
219
|
+
raise ValueError(f'{reason}: {root/name}')
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
STAMP = re.compile(r'[0-9]{8}T[0-9]{12}Z')
|
|
223
|
+
STAMP_FORMAT = '%Y%m%dT%H%M%S%fZ'
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def transaction_path(state, stamp):
|
|
227
|
+
if not isinstance(stamp, str) or not STAMP.fullmatch(stamp):
|
|
228
|
+
raise ValueError('Invalid transaction identifier')
|
|
229
|
+
path = state/'history'/stamp
|
|
230
|
+
if path.resolve() != path:
|
|
231
|
+
raise ValueError('Unsafe history path: '+str(path))
|
|
232
|
+
return path
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def next_transaction_stamp(state):
|
|
236
|
+
history = state/'history'
|
|
237
|
+
if history.resolve() != history:
|
|
238
|
+
raise ValueError('Unsafe history directory: '+str(history))
|
|
239
|
+
now = datetime.now(timezone.utc)
|
|
240
|
+
stamp = now.strftime(STAMP_FORMAT)
|
|
241
|
+
if not history.exists():
|
|
242
|
+
return stamp
|
|
243
|
+
latest = max((entry.name for entry in history.iterdir() if STAMP.fullmatch(entry.name)), default='')
|
|
244
|
+
if latest and latest >= stamp:
|
|
245
|
+
stamp = (datetime.strptime(latest, STAMP_FORMAT) + timedelta(microseconds=1)).strftime(STAMP_FORMAT)
|
|
246
|
+
return stamp
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def read_transaction(txn):
|
|
250
|
+
data = json.loads((txn/'transaction.json').read_text(encoding='utf-8'))
|
|
251
|
+
if not isinstance(data, dict) or data.get('schema', 1) not in (1, 2):
|
|
252
|
+
raise ValueError('Unknown transaction format: '+str(txn))
|
|
253
|
+
before, after, names = data.get('before'), data.get('after'), data.get('names')
|
|
254
|
+
validate_records(before)
|
|
255
|
+
validate_records(after)
|
|
256
|
+
changed = {name for name in set(before) | set(after) if before.get(name) != after.get(name)}
|
|
257
|
+
if not isinstance(names, list) or any(not isinstance(name, str) for name in names):
|
|
258
|
+
raise ValueError('Invalid history change list: '+str(txn))
|
|
259
|
+
recorded_names = set(names)
|
|
260
|
+
if (len(names) != len(recorded_names) or not changed <= recorded_names <= set(before) | set(after)
|
|
261
|
+
or (data.get('schema') == 2 and recorded_names != changed)):
|
|
262
|
+
raise ValueError('Invalid history change list: '+str(txn))
|
|
263
|
+
if data.get('reversal_of') is not None:
|
|
264
|
+
transaction_path(txn.parent.parent, data['reversal_of'])
|
|
265
|
+
return data
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def restore_before(root, txn, meta, *, quarantine_legacy_partial=False):
|
|
269
|
+
before, after = meta['before'], meta['after']
|
|
270
|
+
legacy = meta.get('schema') != 2
|
|
271
|
+
cancelled = txn/'cancelled'
|
|
272
|
+
if cancelled.resolve() != cancelled:
|
|
273
|
+
raise ValueError('Unsafe recovery path: '+str(cancelled))
|
|
274
|
+
cancelled.mkdir(exist_ok=True)
|
|
275
|
+
for name in meta['names']:
|
|
276
|
+
path = root/name
|
|
277
|
+
old, new = before.get(name), after.get(name)
|
|
278
|
+
present = path.exists() or path.is_symlink()
|
|
279
|
+
backup = txn/('displaced' if legacy else 'before')/name
|
|
280
|
+
if legacy:
|
|
281
|
+
if (present and old and not backup.exists() and matches(path, old)) or (not present and not old):
|
|
282
|
+
continue
|
|
283
|
+
elif old:
|
|
284
|
+
# The backup is the original directory moved out of the live root.
|
|
285
|
+
# If it was never moved, or has already been restored, leave live files alone.
|
|
286
|
+
if not backup.exists() and not backup.is_symlink():
|
|
287
|
+
continue
|
|
288
|
+
elif not present or (txn/'incoming'/name).exists():
|
|
289
|
+
continue
|
|
290
|
+
|
|
291
|
+
if old and not backup.exists() and legacy:
|
|
292
|
+
legacy_backup = txn/'before'/name
|
|
293
|
+
if legacy_backup.resolve() != legacy_backup or not matches(legacy_backup, old):
|
|
294
|
+
raise ValueError('Invalid legacy backup: '+str(legacy_backup))
|
|
295
|
+
# Copy the legacy backup fully before exposing it to the host.
|
|
296
|
+
with tempfile.TemporaryDirectory(dir=txn) as temp:
|
|
297
|
+
staged = Path(temp)/name
|
|
298
|
+
copy_recorded_payload(legacy_backup, staged, old)
|
|
299
|
+
backup.parent.mkdir(exist_ok=True)
|
|
300
|
+
if backup.resolve() != backup:
|
|
301
|
+
raise ValueError('Unsafe recovery path: '+str(backup))
|
|
302
|
+
staged.rename(backup)
|
|
303
|
+
if old and (backup.resolve() != backup or not matches(backup, old)):
|
|
304
|
+
raise ValueError('Backup hash mismatch: '+str(backup))
|
|
305
|
+
if present:
|
|
306
|
+
can_quarantine = legacy and quarantine_legacy_partial
|
|
307
|
+
quarantined = cancelled/name
|
|
308
|
+
if quarantined.exists() or quarantined.is_symlink():
|
|
309
|
+
raise ValueError('Unexpected files during recovery. Preserved: '+str(path))
|
|
310
|
+
if not can_quarantine and (not new or not matches(path, new)):
|
|
311
|
+
raise ValueError('Unexpected files during recovery. Preserved: '+str(path))
|
|
312
|
+
path.rename(quarantined)
|
|
313
|
+
if can_quarantine:
|
|
314
|
+
print('PRESERVED', quarantined)
|
|
315
|
+
if old:
|
|
316
|
+
backup.rename(path)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def finish_recovery(root, state, *, quarantine_legacy_partial=False):
|
|
320
|
+
pending = state/'pending.json'
|
|
321
|
+
journal = json.loads(pending.read_text(encoding='utf-8'))
|
|
322
|
+
if not isinstance(journal, dict):
|
|
323
|
+
raise ValueError('Invalid recovery journal: '+str(pending))
|
|
324
|
+
stamp = journal.get('transaction')
|
|
325
|
+
txn = transaction_path(state, stamp)
|
|
326
|
+
meta = read_transaction(txn)
|
|
327
|
+
current = read_lock(state)
|
|
328
|
+
if (txn/'committed.json').is_file():
|
|
329
|
+
if current != meta['after']:
|
|
330
|
+
raise ValueError('Committed transaction and lockfile disagree: '+str(txn))
|
|
331
|
+
verify_current(root, meta['after'], meta['names'])
|
|
332
|
+
else:
|
|
333
|
+
if current not in (meta['before'], meta['after']):
|
|
334
|
+
raise ValueError('Interrupted transaction and lockfile disagree: '+str(txn))
|
|
335
|
+
restore_before(root, txn, meta, quarantine_legacy_partial=quarantine_legacy_partial)
|
|
336
|
+
write_lock(state, meta['before'])
|
|
337
|
+
atomic_json(txn/'aborted.json', {'aborted': True})
|
|
338
|
+
pending.unlink()
|
|
339
|
+
return stamp
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def recover(root, legacy_stale_lock=False, quarantine_legacy_partial=False):
|
|
343
|
+
with guard(root, recovery=True, legacy_stale_lock=legacy_stale_lock) as state:
|
|
344
|
+
if (state/'pending.json').is_file():
|
|
345
|
+
stamp = finish_recovery(root, state, quarantine_legacy_partial=quarantine_legacy_partial)
|
|
346
|
+
print('RECOVERED', stamp, root)
|
|
347
|
+
else:
|
|
348
|
+
print('NO PENDING TRANSACTION', root)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def transaction(root, state, before, after, staged, *, reversal_of=None, expected_digests=None):
|
|
352
|
+
names = sorted(staged)
|
|
353
|
+
verify_current(root, before, names)
|
|
354
|
+
if not names:
|
|
355
|
+
return None
|
|
356
|
+
stamp = next_transaction_stamp(state)
|
|
357
|
+
txn = transaction_path(state, stamp)
|
|
358
|
+
txn.mkdir(parents=True)
|
|
359
|
+
backup, incoming = txn/'before', txn/'incoming'
|
|
360
|
+
backup.mkdir()
|
|
361
|
+
incoming.mkdir()
|
|
362
|
+
for name, source in staged.items():
|
|
363
|
+
if source is not None:
|
|
364
|
+
copy_recorded_payload(source, incoming/name, after[name])
|
|
365
|
+
verify_current(incoming, after, [name])
|
|
366
|
+
meta = {'schema': 2, 'before': before, 'after': after, 'names': names, 'reversal_of': reversal_of}
|
|
367
|
+
atomic_json(txn/'transaction.json', meta)
|
|
368
|
+
pending = state/'pending.json'
|
|
369
|
+
atomic_json(pending, {'transaction': stamp})
|
|
370
|
+
try:
|
|
371
|
+
for name in names:
|
|
372
|
+
path = root/name
|
|
373
|
+
verify_current(root, before, [name])
|
|
374
|
+
if expected_digests and name in expected_digests and digest(path) != expected_digests[name]:
|
|
375
|
+
raise ValueError(f'Local files changed after preview: {path}. Generate a new preview.')
|
|
376
|
+
if name in before:
|
|
377
|
+
path.rename(backup/name)
|
|
378
|
+
if name in after:
|
|
379
|
+
(incoming/name).rename(path)
|
|
380
|
+
write_lock(state, after)
|
|
381
|
+
atomic_json(txn/'committed.json', {'committed': True})
|
|
382
|
+
except BaseException:
|
|
383
|
+
finish_recovery(root, state)
|
|
384
|
+
raise
|
|
385
|
+
pending.unlink()
|
|
386
|
+
return stamp
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def file_changes(before, after):
|
|
390
|
+
return {
|
|
391
|
+
'added': sorted(after.keys() - before.keys()),
|
|
392
|
+
'removed': sorted(before.keys() - after.keys()),
|
|
393
|
+
'changed': sorted(name for name in before.keys() & after.keys() if before[name] != after[name]),
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def stage_changes(root, selected, update, temp, approved_commits=None):
|
|
398
|
+
before = read_lock(state_dir(root))
|
|
399
|
+
after = dict(before)
|
|
400
|
+
staged, commits, changes, skipped = {}, {}, {}, {}
|
|
401
|
+
for provider in selected:
|
|
402
|
+
specs = PROVIDERS[provider]['skills']
|
|
403
|
+
existing = {name: record for name, record in before.items() if record['provider'] == provider}
|
|
404
|
+
if update and not existing:
|
|
405
|
+
continue
|
|
406
|
+
pins = {record['commit'] for record in existing.values()}
|
|
407
|
+
if len(pins) > 1 and not update:
|
|
408
|
+
raise ValueError(f'Mixed pins for {provider}. Preview an update first.')
|
|
409
|
+
|
|
410
|
+
wanted = []
|
|
411
|
+
for spec in specs:
|
|
412
|
+
name = spec['name']
|
|
413
|
+
destination = root/name
|
|
414
|
+
if name in before:
|
|
415
|
+
verify_current(root, before, [name])
|
|
416
|
+
if before[name]['provider'] != provider:
|
|
417
|
+
raise ValueError('Provider conflict: '+name)
|
|
418
|
+
if update:
|
|
419
|
+
wanted.append(spec)
|
|
420
|
+
elif not update:
|
|
421
|
+
if destination.exists() or destination.is_symlink():
|
|
422
|
+
if skill_name(destination) != name:
|
|
423
|
+
raise ValueError('Unmanaged collision: '+str(destination))
|
|
424
|
+
skipped[name] = str(destination)
|
|
425
|
+
continue
|
|
426
|
+
duplicate = next((path.parent for path in sorted(root.glob('*/SKILL.md'))
|
|
427
|
+
if skill_name(path.parent) == name), None)
|
|
428
|
+
if duplicate:
|
|
429
|
+
skipped[name] = str(duplicate)
|
|
430
|
+
continue
|
|
431
|
+
wanted.append(spec)
|
|
432
|
+
if not wanted:
|
|
433
|
+
continue
|
|
434
|
+
|
|
435
|
+
if approved_commits is not None:
|
|
436
|
+
commit = approved_commits.get(provider)
|
|
437
|
+
if not isinstance(commit, str) or not HEX.fullmatch(commit):
|
|
438
|
+
raise ValueError(f'Reviewed plan lacks a valid commit for {provider}')
|
|
439
|
+
if not update and pins and pins != {commit}:
|
|
440
|
+
raise ValueError(f'The existing pin for {provider} changed. Preview again.')
|
|
441
|
+
else:
|
|
442
|
+
commit = remote_head(provider) if update or not pins else next(iter(pins))
|
|
443
|
+
commits[provider] = commit
|
|
444
|
+
if update and pins == {commit}:
|
|
445
|
+
continue
|
|
446
|
+
|
|
447
|
+
repo = temp/provider
|
|
448
|
+
checkout(provider, commit, repo)
|
|
449
|
+
for spec in wanted:
|
|
450
|
+
name = spec['name']
|
|
451
|
+
source, relative_source = source_skill(repo, spec, root)
|
|
452
|
+
dest = temp/'payload'/name
|
|
453
|
+
dest.parent.mkdir(exist_ok=True)
|
|
454
|
+
shutil.copytree(source, dest)
|
|
455
|
+
for license_name in ('LICENSE', 'LICENSE.md', 'LICENSE.txt', 'COPYING'):
|
|
456
|
+
license_file = repo/license_name
|
|
457
|
+
if license_file.is_file() and not license_file.is_symlink() and not (dest/license_name).exists():
|
|
458
|
+
shutil.copy2(license_file, dest/license_name)
|
|
459
|
+
record = {
|
|
460
|
+
'provider': provider, 'commit': commit, 'source_path': relative_source, 'sha256': digest(dest),
|
|
461
|
+
'digest_version': 2,
|
|
462
|
+
}
|
|
463
|
+
if record == before.get(name):
|
|
464
|
+
continue
|
|
465
|
+
after[name] = record
|
|
466
|
+
staged[name] = dest
|
|
467
|
+
old_files = file_hashes(root/name) if name in before else {}
|
|
468
|
+
changes[name] = {
|
|
469
|
+
'repository': url(provider),
|
|
470
|
+
'from_commit': before[name]['commit'] if name in before else None,
|
|
471
|
+
'from_sha256': digest_files(old_files) if name in before else None,
|
|
472
|
+
'to_commit': commit,
|
|
473
|
+
**file_changes(old_files, file_hashes(dest)),
|
|
474
|
+
}
|
|
475
|
+
entry = {
|
|
476
|
+
'root': str(root), 'commits': commits, 'before': before, 'after': after,
|
|
477
|
+
'changes': changes, 'external': skipped,
|
|
478
|
+
}
|
|
479
|
+
return entry, staged
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def read_plan(path, roots, operation):
|
|
483
|
+
plan = json.loads(path.read_text(encoding='utf-8'))
|
|
484
|
+
if not isinstance(plan, dict) or plan.get('schema') != 1 or plan.get('operation') != operation:
|
|
485
|
+
raise ValueError('Plan format or operation differs. Generate a new preview.')
|
|
486
|
+
selected = plan.get('providers')
|
|
487
|
+
if not isinstance(selected, list) or not selected or any(
|
|
488
|
+
not isinstance(provider, str) or provider not in PROVIDERS for provider in selected
|
|
489
|
+
) or len(set(selected)) != len(selected):
|
|
490
|
+
raise ValueError('Invalid provider selection in plan')
|
|
491
|
+
destinations = plan.get('destinations')
|
|
492
|
+
if not isinstance(destinations, list) or not all(
|
|
493
|
+
isinstance(entry, dict) and isinstance(entry.get('commits'), dict) for entry in destinations
|
|
494
|
+
) or [entry.get('root') for entry in destinations] != [str(root) for root in roots]:
|
|
495
|
+
raise ValueError('Plan destinations differ. Use the same agent, scope, and path as the preview.')
|
|
496
|
+
return selected, destinations
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def apply_plan(roots, selected, operation, args):
|
|
500
|
+
update = operation == 'update'
|
|
501
|
+
if args.offline:
|
|
502
|
+
if not args.dry_run or args.plan:
|
|
503
|
+
raise ValueError('--offline requires --dry-run without --plan')
|
|
504
|
+
print(json.dumps({
|
|
505
|
+
'operation': operation, 'providers': selected,
|
|
506
|
+
'destinations': [{'root': str(root), 'status': status(root)} for root in roots],
|
|
507
|
+
'note': 'Local status only. Run --dry-run without --offline to create a plan.',
|
|
508
|
+
}, indent=2))
|
|
509
|
+
return
|
|
510
|
+
|
|
511
|
+
if args.dry_run:
|
|
512
|
+
if args.plan:
|
|
513
|
+
raise ValueError('Use --dry-run to create a preview or --plan to apply it')
|
|
514
|
+
destinations = []
|
|
515
|
+
for root in roots:
|
|
516
|
+
with tempfile.TemporaryDirectory(prefix='ui-director-preview-') as temporary:
|
|
517
|
+
entry, _ = stage_changes(root, selected, update, Path(temporary).resolve())
|
|
518
|
+
destinations.append(entry)
|
|
519
|
+
print(json.dumps({'schema': 1, 'operation': operation, 'providers': selected,
|
|
520
|
+
'destinations': destinations}, indent=2))
|
|
521
|
+
return
|
|
522
|
+
|
|
523
|
+
if not args.plan:
|
|
524
|
+
raise ValueError('Generate and review a preview with --dry-run, then apply it with --plan FILE.')
|
|
525
|
+
approved, destinations = read_plan(args.plan, roots, operation)
|
|
526
|
+
if (args.provider or getattr(args, 'profile', None)) and approved != selected:
|
|
527
|
+
raise ValueError('Requested providers differ from the plan. Generate a new preview.')
|
|
528
|
+
with ExitStack() as stack:
|
|
529
|
+
prepared = []
|
|
530
|
+
for root, reviewed in zip(roots, destinations):
|
|
531
|
+
state = stack.enter_context(guard(root))
|
|
532
|
+
if read_lock(state) != reviewed.get('before'):
|
|
533
|
+
raise ValueError(f'Local lock changed after preview: {root}. Generate a new preview.')
|
|
534
|
+
temp = stack.enter_context(tempfile.TemporaryDirectory(prefix='stage-', dir=state))
|
|
535
|
+
entry, staged = stage_changes(root, approved, update, Path(temp), reviewed['commits'])
|
|
536
|
+
if entry != reviewed:
|
|
537
|
+
raise ValueError(f'Preview no longer matches {root}. Generate a new preview.')
|
|
538
|
+
prepared.append((root, state, entry, staged))
|
|
539
|
+
for root, state, entry, staged in prepared:
|
|
540
|
+
expected_digests = {name: change['from_sha256'] for name, change in entry['changes'].items()
|
|
541
|
+
if change['from_sha256'] is not None}
|
|
542
|
+
stamp = transaction(root, state, entry['before'], entry['after'], staged,
|
|
543
|
+
expected_digests=expected_digests)
|
|
544
|
+
print('COMMITTED '+stamp if stamp else 'NO CHANGES', root)
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def history_records(state):
|
|
548
|
+
history = state/'history'
|
|
549
|
+
if not history.is_dir():
|
|
550
|
+
return
|
|
551
|
+
for entry in sorted(history.iterdir(), reverse=True):
|
|
552
|
+
if not STAMP.fullmatch(entry.name):
|
|
553
|
+
continue
|
|
554
|
+
txn = transaction_path(state, entry.name)
|
|
555
|
+
if (txn/'aborted.json').exists() or (txn/'rolled-back.json').exists():
|
|
556
|
+
continue
|
|
557
|
+
metadata = txn/'transaction.json'
|
|
558
|
+
if not metadata.is_file():
|
|
559
|
+
continue
|
|
560
|
+
meta = read_transaction(txn)
|
|
561
|
+
if meta.get('schema') == 2 and not (txn/'committed.json').is_file():
|
|
562
|
+
continue
|
|
563
|
+
yield txn, meta
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def latest_transaction(state, current, requested=None):
|
|
567
|
+
records = iter(history_records(state))
|
|
568
|
+
reversed_transactions = set()
|
|
569
|
+
for txn, meta in records:
|
|
570
|
+
if meta.get('schema') == 2:
|
|
571
|
+
if meta.get('reversal_of'):
|
|
572
|
+
reversed_transactions.add(meta['reversal_of'])
|
|
573
|
+
continue
|
|
574
|
+
if txn.name in reversed_transactions or (requested and txn.name != requested):
|
|
575
|
+
continue
|
|
576
|
+
if current != meta['after']:
|
|
577
|
+
if requested or meta.get('schema') == 2:
|
|
578
|
+
raise ValueError('Committed history and lockfile disagree: '+str(txn))
|
|
579
|
+
# Older versions could leave an uncommitted transaction in history.
|
|
580
|
+
continue
|
|
581
|
+
if not requested and meta.get('schema') != 2:
|
|
582
|
+
previous = next(records, None)
|
|
583
|
+
if previous:
|
|
584
|
+
_, earlier = previous
|
|
585
|
+
if (meta['after'] == earlier['before'] and meta['before'] == earlier['after']
|
|
586
|
+
and set(meta['names']) == set(earlier['names'])):
|
|
587
|
+
raise ValueError(f'Legacy transaction {txn.name} may be an unmarked rollback. '
|
|
588
|
+
'Inspect history and select a transaction with --transaction ID.')
|
|
589
|
+
return txn, meta
|
|
590
|
+
if requested:
|
|
591
|
+
raise ValueError('Transaction is unavailable or already rolled back: '+requested)
|
|
592
|
+
return None
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def rollback(root, dry=False, requested=None):
|
|
596
|
+
if requested:
|
|
597
|
+
transaction_path(state_dir(root), requested)
|
|
598
|
+
if dry:
|
|
599
|
+
latest = latest_transaction(state_dir(root), read_lock(state_dir(root)), requested)
|
|
600
|
+
print('WOULD ROLL BACK '+latest[0].name if latest else 'NO HISTORY', root)
|
|
601
|
+
return
|
|
602
|
+
with guard(root) as state:
|
|
603
|
+
current = read_lock(state)
|
|
604
|
+
latest = latest_transaction(state, current, requested)
|
|
605
|
+
if latest is None:
|
|
606
|
+
print('NO HISTORY', root)
|
|
607
|
+
return
|
|
608
|
+
txn, meta = latest
|
|
609
|
+
before, names = meta['before'], meta['names']
|
|
610
|
+
verify_current(root, current, names)
|
|
611
|
+
staged = {}
|
|
612
|
+
for name in names:
|
|
613
|
+
if current.get(name) == before.get(name):
|
|
614
|
+
continue
|
|
615
|
+
backup = txn/'before'/name
|
|
616
|
+
if name in before:
|
|
617
|
+
if backup.resolve() != backup or not matches(backup, before[name]):
|
|
618
|
+
raise ValueError('Backup hash mismatch: '+name)
|
|
619
|
+
staged[name] = backup
|
|
620
|
+
else:
|
|
621
|
+
staged[name] = None
|
|
622
|
+
transaction(root, state, current, before, staged, reversal_of=txn.name)
|
|
623
|
+
print('ROLLED BACK', txn.name, root)
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def run(args, roots):
|
|
627
|
+
if args.cmd in ('bundle', 'update-upstreams'):
|
|
628
|
+
update = args.cmd == 'update-upstreams'
|
|
629
|
+
profile = getattr(args, 'profile', None)
|
|
630
|
+
if not any((update, profile, args.provider, args.plan, args.offline)):
|
|
631
|
+
raise ValueError('Bundle requires --provider, --profile, or an existing --plan.')
|
|
632
|
+
default_providers = list(PROVIDERS) if update else REGISTRY['profiles'].get(profile, [])
|
|
633
|
+
selected = list(dict.fromkeys(args.provider or default_providers))
|
|
634
|
+
apply_plan(roots, selected, 'update' if update else 'install', args)
|
|
635
|
+
return 0
|
|
636
|
+
for root in roots:
|
|
637
|
+
if args.cmd == 'status':
|
|
638
|
+
state = state_dir(root)
|
|
639
|
+
print(json.dumps({
|
|
640
|
+
'root': str(root), 'lock': str(state/'lock.json'), 'skills': status(root),
|
|
641
|
+
'manual_only': REGISTRY['manual_only'], 'recovery_needed': (state/'pending.json').exists(),
|
|
642
|
+
'note': 'file verification only; runtime not verified',
|
|
643
|
+
}, indent=2))
|
|
644
|
+
elif args.cmd == 'check-updates':
|
|
645
|
+
lock = read_lock(state_dir(root))
|
|
646
|
+
providers = sorted({record['provider'] for record in lock.values()})
|
|
647
|
+
heads = {provider: remote_head(provider) for provider in providers}
|
|
648
|
+
print(json.dumps({'root': str(root), 'updates': [
|
|
649
|
+
{'skill': name, 'provider': record['provider'], 'current': record['commit'],
|
|
650
|
+
'remote': heads[record['provider']], 'update_available': record['commit'] != heads[record['provider']]}
|
|
651
|
+
for name, record in lock.items()
|
|
652
|
+
]}, indent=2))
|
|
653
|
+
elif args.cmd == 'rollback-upstreams':
|
|
654
|
+
rollback(root, args.dry_run, args.transaction)
|
|
655
|
+
elif args.cmd == 'recover-upstreams':
|
|
656
|
+
recover(root, args.legacy_stale_lock, args.quarantine_legacy_partial)
|
|
657
|
+
return 0
|
package/templates/DECISIONS.md
CHANGED