@collective-intelligence/backlog 0.0.0-stage → 0.2.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.
@@ -0,0 +1,1768 @@
1
+ #!/usr/bin/env python3
2
+ """Azure DevOps helper shared by the Human Backlog skills.
3
+
4
+ Talks to the Human Backlog project named by the Human Backlog Config, using an
5
+ Entra token that the Azure CLI issues for the configured tenant
6
+ (`az login --tenant <tenant>` once). Every command prints JSON on stdout;
7
+ errors go to stderr with exit code 1.
8
+
9
+ Human Backlog Config, resolved per key; the first source with a value wins
10
+ 1. env vars ADO_PROVIDER, ADO_PROJECT_URL, ADO_TENANT, ADO_RATINGS_PIPELINE_URL
11
+ 2. "humanBacklog" in the nearest .devpunks/settings.json above the working directory
12
+ 3. config.json beside this script
13
+ Keys: provider ("azure-devops"), projectUrl (https://dev.azure.com/{org}/{project}),
14
+ tenant, and optional ratingsPipelineUrl.
15
+
16
+ Commands
17
+ whoami who the token belongs to
18
+ get ID [ID ...] [--relations] read work items (HTML fields as plain text)
19
+ backlog [--types ...] [--under ID] ... dump items for matching (all states by default)
20
+ search TEXT [--types ...] keyword search in title and description
21
+ create --type T --json FILE [--parent ID] [--dry-run]
22
+ update ID --json FILE [--expected-rev N] [--dry-run]
23
+ link SOURCE TARGET --type related|parent|child [--comment TEXT] [--dry-run]
24
+ unlink SOURCE TARGET --type related [--expected-rev N] [--dry-run]
25
+ set-state ID STATE --comment TEXT [--expected-rev N] [--dry-run]
26
+ forward-only Human State write (see set-state --help)
27
+ revision-check BR_ID [--touch ID ...] [--shared-approved FEATURE_ID ...]
28
+ planning-context [--team NAME_OR_ID] [--iteration NAME_PATH_OR_ID]
29
+ planning-check PLAN.json read-only capacity and item checks; preview allowed field changes
30
+ hyperlink ID URL [--comment TEXT] add one Hyperlink relation; no write when the URL is linked
31
+ unhyperlink ID URL remove the Hyperlink relation to URL; no write when none links it
32
+ comment ID (--text TEXT | --file FILE) [--dry-run]
33
+ attach ID --file FILE --receipt JSON [--comment TEXT] [--dry-run]
34
+ sync-ratings [FEATURE_ID ... | --all] [--dry-run] recompute ratings from linked BRs
35
+ apply PLAN.json [--dry-run] create a whole backlog plan (see analyze-business-request)
36
+ doctor read-only check of the config and the process: ready or blocked
37
+ eject --out PATH zip the Human Backlog skills with config.json and MANIFEST.json
38
+
39
+ Field JSON uses friendly names (see FIELDS) or raw reference names. Values of
40
+ rich-text fields may be written in a small Markdown subset (headings, bullet
41
+ and numbered lists, **bold**, blank-line paragraphs); they are converted to HTML.
42
+ """
43
+ import argparse
44
+ import contextlib
45
+ from datetime import date, timedelta
46
+ import hashlib
47
+ import html
48
+ import io
49
+ import json
50
+ import math
51
+ import os
52
+ import re
53
+ import subprocess
54
+ import sys
55
+ import tempfile
56
+ import urllib.error
57
+ import urllib.parse
58
+ import urllib.request
59
+ import zipfile
60
+
61
+ CONFIG_ENV = {
62
+ "provider": "ADO_PROVIDER",
63
+ "projectUrl": "ADO_PROJECT_URL",
64
+ "tenant": "ADO_TENANT",
65
+ "ratingsPipelineUrl": "ADO_RATINGS_PIPELINE_URL",
66
+ }
67
+ REQUIRED_CONFIG = ("provider", "projectUrl", "tenant")
68
+ CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
69
+ PROJECT_URL = re.compile(r"^https://dev\.azure\.com/([^/]+)/([^/]+)/?$")
70
+ ADO_RESOURCE = "499b84ac-1321-427f-aa17-267ca6975798"
71
+
72
+ FIELDS = {
73
+ "Title": "System.Title",
74
+ "State": "System.State",
75
+ "AssignedTo": "System.AssignedTo",
76
+ "AreaPath": "System.AreaPath",
77
+ "IterationPath": "System.IterationPath",
78
+ "Tags": "System.Tags",
79
+ "Parent": "System.Parent",
80
+ "CreatedDate": "System.CreatedDate",
81
+ "ChangedDate": "System.ChangedDate",
82
+ "ClosedDate": "Microsoft.VSTS.Common.ClosedDate",
83
+ "Description": "System.Description",
84
+ "Context": "Custom.ContextAndExistingAssets",
85
+ "SuccessCriteria": "Microsoft.VSTS.Common.AcceptanceCriteria",
86
+ "AcceptanceCriteria": "Microsoft.VSTS.Common.AcceptanceCriteria",
87
+ "Requester": "Custom.Requester",
88
+ "RequestDate": "Custom.RequestDate",
89
+ "StartDate": "Microsoft.VSTS.Scheduling.StartDate",
90
+ "TargetDate": "Microsoft.VSTS.Scheduling.TargetDate",
91
+ "Priority": "Microsoft.VSTS.Common.Priority",
92
+ "BusinessValue": "Custom.BusinessValueScore",
93
+ "Urgency": "Custom.Urgency",
94
+ "ValueArea": "Microsoft.VSTS.Common.ValueArea",
95
+ "ReproSteps": "Microsoft.VSTS.TCM.ReproSteps",
96
+ "Severity": "Microsoft.VSTS.Common.Severity",
97
+ "Effort": "Microsoft.VSTS.Scheduling.Effort",
98
+ }
99
+ FRIENDLY = {}
100
+ for _name, _ref in FIELDS.items():
101
+ FRIENDLY.setdefault(_ref, _name)
102
+
103
+ HTML_FIELDS = {
104
+ "System.Description",
105
+ "Custom.ContextAndExistingAssets",
106
+ "Microsoft.VSTS.Common.AcceptanceCriteria",
107
+ "Microsoft.VSTS.TCM.ReproSteps",
108
+ }
109
+
110
+ TYPES = {
111
+ "br": "Business Request",
112
+ "business request": "Business Request",
113
+ "epic": "Epic",
114
+ "feature": "Feature",
115
+ "pbi": "Product Backlog Item",
116
+ "product backlog item": "Product Backlog Item",
117
+ "bug": "Bug",
118
+ }
119
+
120
+ # Allowed parent type for each child type: the backlog hierarchy of the process.
121
+ # Business Request sits at Feature level but never has a parent or children.
122
+ ALLOWED_PARENT = {
123
+ "Epic": set(),
124
+ "Feature": {"Epic"},
125
+ "Business Request": set(),
126
+ "Product Backlog Item": {"Feature"},
127
+ "Bug": {"Feature"},
128
+ }
129
+
130
+ # Process fields the skills read or write on each work-item type, beside the System fields every
131
+ # type has. `doctor` checks them; setup-human-backlog/references/process.md lists them for the team.
132
+ PROCESS_FIELDS = {
133
+ "Epic": (),
134
+ "Feature": ("Microsoft.VSTS.Common.AcceptanceCriteria", "Custom.BusinessValueScore", "Custom.Urgency"),
135
+ "Business Request": ("Microsoft.VSTS.Common.AcceptanceCriteria", "Custom.ContextAndExistingAssets",
136
+ "Custom.Requester", "Custom.RequestDate", "Microsoft.VSTS.Scheduling.TargetDate",
137
+ "Custom.BusinessValueScore", "Custom.Urgency", "Microsoft.VSTS.Common.Priority"),
138
+ "Product Backlog Item": ("Microsoft.VSTS.Common.AcceptanceCriteria",),
139
+ "Bug": ("Microsoft.VSTS.TCM.ReproSteps",),
140
+ }
141
+
142
+ LINK_TYPES = {
143
+ "related": "System.LinkTypes.Related",
144
+ "parent": "System.LinkTypes.Hierarchy-Reverse", # target becomes the parent of source
145
+ "child": "System.LinkTypes.Hierarchy-Forward", # target becomes a child of source
146
+ }
147
+ LINK_NAMES = {v: k for k, v in LINK_TYPES.items()}
148
+
149
+ # A plan produced by analyze-business-request is a backlog, not a schedule: no estimates, no dates.
150
+ PLAN_FORBIDDEN = {
151
+ "Microsoft.VSTS.Scheduling.Effort",
152
+ "Microsoft.VSTS.Scheduling.StoryPoints",
153
+ "Microsoft.VSTS.Scheduling.RemainingWork",
154
+ "Microsoft.VSTS.Scheduling.OriginalEstimate",
155
+ "Microsoft.VSTS.Scheduling.CompletedWork",
156
+ "Microsoft.VSTS.Scheduling.Size",
157
+ "Microsoft.VSTS.Scheduling.StartDate",
158
+ "Microsoft.VSTS.Scheduling.TargetDate",
159
+ "Microsoft.VSTS.Scheduling.FinishDate",
160
+ "Microsoft.VSTS.Common.BusinessValue",
161
+ "Microsoft.VSTS.Common.TimeCriticality",
162
+ }
163
+
164
+ READ_FIELDS = [
165
+ "System.Id", "System.WorkItemType", "System.Title", "System.State", "System.Parent",
166
+ "System.Tags", "System.CreatedDate", "System.ChangedDate", "Microsoft.VSTS.Common.ClosedDate",
167
+ "System.AssignedTo", "System.IterationPath", "System.Description", "Microsoft.VSTS.Common.AcceptanceCriteria",
168
+ "Custom.BusinessValueScore", "Custom.Urgency",
169
+ "Microsoft.VSTS.TCM.ReproSteps", "Microsoft.VSTS.Common.Severity",
170
+ ]
171
+
172
+ MAX_SIMPLE_ATTACHMENT_BYTES = 130_000_000
173
+
174
+ SCORE_FIELDS = ("Custom.BusinessValueScore", "Custom.Urgency")
175
+ EDITABLE_FEATURE_STATES = {"New", "Planned"}
176
+
177
+ # Human States of a Business Request. BR_FLOW is the forward order; Rejected and
178
+ # Withdrawn leave it from any non-final state. `set-state` is the only command that writes them.
179
+ BR_FLOW = ("Received", "In analysis", "Planned", "In progress", "On staging", "Live")
180
+ BR_FINAL = {"Live", "Rejected", "Withdrawn"}
181
+ BR_STATES = (*BR_FLOW, "Rejected", "Withdrawn")
182
+ SET_STATE_HELP = """\
183
+ Move a Business Request to a Human State. This is the only automated way to write its State.
184
+
185
+ Human States: Received, In analysis, Planned, In progress, On staging, Live, Rejected, Withdrawn.
186
+ STATE is not a Human State refused, no write, exit 1
187
+ STATE is the current state no write, exit 0 (status "unchanged")
188
+ current state is Live, Rejected or Withdrawn
189
+ refused, no write, exit 1
190
+ STATE is earlier in Received > In analysis > Planned > In progress > On staging > Live
191
+ refused, no write, exit 1
192
+ STATE is Rejected or Withdrawn written from every non-final state
193
+ otherwise one JSON Patch: test /rev, State, --comment as one comment
194
+ A stale --expected-rev is refused before any write. --dry-run reports the decision and writes nothing."""
195
+
196
+ _token = None
197
+
198
+
199
+ def die(msg):
200
+ print(json.dumps({"error": msg}, ensure_ascii=False), file=sys.stderr)
201
+ sys.exit(1)
202
+
203
+
204
+ def out(obj):
205
+ print(json.dumps(obj, indent=2, ensure_ascii=False))
206
+
207
+
208
+ def json_object(path, key=None):
209
+ """Read a JSON object, or the object under `key`; a missing file or key gives {}."""
210
+ if not os.path.isfile(path):
211
+ return {}
212
+ value = load_json(path)
213
+ if key is not None and isinstance(value, dict):
214
+ value = value.get(key, {})
215
+ if not isinstance(value, dict):
216
+ die(f"{path}: {key or 'the file'} must be a JSON object.")
217
+ return value
218
+
219
+
220
+ def nearest_settings():
221
+ directory = os.getcwd()
222
+ while not os.path.isfile(os.path.join(directory, ".devpunks", "settings.json")):
223
+ parent = os.path.dirname(directory)
224
+ if parent == directory:
225
+ return {}
226
+ directory = parent
227
+ return json_object(os.path.join(directory, ".devpunks", "settings.json"), "humanBacklog")
228
+
229
+
230
+ def load_config():
231
+ """Resolve the Human Backlog Config (see the module help); stop on a missing or invalid key."""
232
+ env = {key: os.environ[name] for key, name in CONFIG_ENV.items() if os.environ.get(name)}
233
+ sources = (env, nearest_settings(), json_object(CONFIG_FILE))
234
+ config = {}
235
+ for key in CONFIG_ENV:
236
+ value = next((source[key] for source in sources if source.get(key)), None)
237
+ if value:
238
+ config[key] = value
239
+ for key in REQUIRED_CONFIG:
240
+ if key not in config:
241
+ die(f"The Human Backlog Config has no {key}. Set {CONFIG_ENV[key]}, humanBacklog.{key} "
242
+ f"in .devpunks/settings.json, or {key} in {CONFIG_FILE}.")
243
+ if config["provider"] != "azure-devops":
244
+ die(f"The Human Backlog Config provider must be azure-devops, not {config['provider']!r}.")
245
+ match = PROJECT_URL.match(config["projectUrl"])
246
+ if not match:
247
+ die(f"The Human Backlog Config projectUrl must be https://dev.azure.com/{{org}}/{{project}}, "
248
+ f"not {config['projectUrl']!r}.")
249
+ config["org"], config["project"] = match.group(1), urllib.parse.unquote(match.group(2))
250
+ return config
251
+
252
+
253
+ def base():
254
+ return f"https://dev.azure.com/{load_config()['org']}"
255
+
256
+
257
+ def pbase():
258
+ config = load_config()
259
+ return f"https://dev.azure.com/{config['org']}/{urllib.parse.quote(config['project'])}"
260
+
261
+
262
+ def token():
263
+ global _token
264
+ if _token:
265
+ return _token
266
+ tenant = load_config()["tenant"]
267
+ try:
268
+ res = subprocess.run(
269
+ ["az", "account", "get-access-token", "--tenant", tenant, "--resource", ADO_RESOURCE,
270
+ "--query", "accessToken", "-o", "tsv"],
271
+ capture_output=True, text=True, check=True)
272
+ except FileNotFoundError:
273
+ die(f"Azure CLI (az) is not installed or not on PATH. Install the Azure CLI, then run: az login --tenant {tenant}")
274
+ except subprocess.CalledProcessError as e:
275
+ die(f"Could not get an Azure DevOps token for tenant {tenant}. "
276
+ f"Run: az login --tenant {tenant}\n{e.stderr.strip()}")
277
+ _token = res.stdout.strip()
278
+ return _token
279
+
280
+
281
+ def call(method, url, body=None, content_type="application/json", timeout=30):
282
+ data = body if isinstance(body, bytes) else json.dumps(body).encode() if body is not None else None
283
+ req = urllib.request.Request(url, data=data, method=method, headers={
284
+ "Authorization": f"Bearer {token()}", "Content-Type": content_type})
285
+ try:
286
+ with urllib.request.urlopen(req, timeout=timeout) as r:
287
+ raw = r.read()
288
+ return json.loads(raw) if raw else {}
289
+ except urllib.error.HTTPError as e:
290
+ detail = e.read().decode(errors="replace")
291
+ try:
292
+ detail = json.loads(detail).get("message", detail)
293
+ except ValueError:
294
+ pass
295
+ die(f"{method} {url} -> HTTP {e.code}: {detail[:500]}")
296
+ except (urllib.error.URLError, OSError) as e:
297
+ die(f"{method} {url} -> transport error: {e}. The operation may have completed; inspect before retrying.")
298
+
299
+
300
+ def wi_url(wid):
301
+ return f"{pbase()}/_workitems/edit/{wid}"
302
+
303
+
304
+ def api_url(wid):
305
+ return f"{base()}/_apis/wit/workItems/{wid}"
306
+
307
+
308
+ def norm_type(t):
309
+ v = TYPES.get(str(t).strip().lower())
310
+ if not v:
311
+ die(f"Unknown work item type '{t}'. Use one of: br, epic, feature, pbi, bug.")
312
+ return v
313
+
314
+
315
+ def article(word):
316
+ return "an" if word[:1].lower() in "aeiou" else "a"
317
+
318
+
319
+ def ref_of(name):
320
+ return FIELDS.get(name, name)
321
+
322
+
323
+ # ---------- text conversion ----------
324
+
325
+ def md_to_html(text):
326
+ """Convert a small Markdown subset to HTML. Text that already looks like HTML is kept."""
327
+ if text is None:
328
+ return None
329
+ s = str(text)
330
+ if s.lstrip().startswith("<"):
331
+ return s
332
+
333
+ def inline(t):
334
+ t = html.escape(t, quote=False)
335
+ t = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", t)
336
+ t = re.sub(r"(?<![\w*])\*(?!\s)([^*]+?)(?<!\s)\*(?![\w*])", r"<i>\1</i>", t)
337
+ t = re.sub(r"`([^`]+)`", r"<code>\1</code>", t)
338
+ return t
339
+
340
+ parts, para, items, rows, list_tag = [], [], [], [], None
341
+
342
+ def flush_table():
343
+ if rows:
344
+ cells = [[c.strip() for c in r.strip().strip("|").split("|")] for r in rows
345
+ if not re.match(r"^\|?[\s:|-]+\|?$", r.strip())]
346
+ if cells:
347
+ head, body = cells[0], cells[1:]
348
+ parts.append("<table><tr>" + "".join(f"<th>{inline(c)}</th>" for c in head) + "</tr>"
349
+ + "".join("<tr>" + "".join(f"<td>{inline(c)}</td>" for c in r) + "</tr>" for r in body)
350
+ + "</table>")
351
+ rows.clear()
352
+
353
+ def flush_para():
354
+ if para:
355
+ parts.append("<p>" + " ".join(inline(p) for p in para) + "</p>")
356
+ para.clear()
357
+
358
+ def flush_list():
359
+ nonlocal list_tag
360
+ if items:
361
+ parts.append(f"<{list_tag}>" + "".join(f"<li>{inline(i)}</li>" for i in items) + f"</{list_tag}>")
362
+ items.clear()
363
+ list_tag = None
364
+
365
+ for line in s.splitlines():
366
+ stripped = line.strip()
367
+ heading = re.match(r"^(#{1,4})\s+(.*)$", stripped)
368
+ bullet = re.match(r"^[-*]\s+(.*)$", stripped)
369
+ number = re.match(r"^\d+[.)]\s+(.*)$", stripped)
370
+ if stripped.startswith("|"):
371
+ flush_para()
372
+ flush_list()
373
+ rows.append(stripped)
374
+ continue
375
+ flush_table()
376
+ if not stripped:
377
+ flush_para()
378
+ flush_list()
379
+ elif heading:
380
+ flush_para()
381
+ flush_list()
382
+ level = min(len(heading.group(1)) + 1, 4)
383
+ parts.append(f"<h{level}>{inline(heading.group(2))}</h{level}>")
384
+ elif bullet or number:
385
+ flush_para()
386
+ tag = "ul" if bullet else "ol"
387
+ if list_tag and list_tag != tag:
388
+ flush_list()
389
+ list_tag = tag
390
+ items.append((bullet or number).group(1))
391
+ else:
392
+ flush_list()
393
+ para.append(stripped)
394
+ flush_para()
395
+ flush_list()
396
+ flush_table()
397
+ return "".join(parts)
398
+
399
+
400
+ def html_to_text(value):
401
+ if not isinstance(value, str):
402
+ return value
403
+ t = re.sub(r"(?i)<li[^>]*>", "\n- ", value)
404
+ t = re.sub(r"(?i)</t[dh]>", " | ", t)
405
+ t = re.sub(r"(?i)<br\s*/?>|</p>|</div>|</h\d>|</li>|</ul>|</ol>|</tr>", "\n", t)
406
+ t = re.sub(r"<[^>]+>", "", t)
407
+ t = html.unescape(t)
408
+ t = re.sub(r"[ \t\xa0]+", " ", t)
409
+ t = re.sub(r"\n\s*\n+", "\n", t)
410
+ return t.strip()
411
+
412
+
413
+ def fmt_value(ref, v):
414
+ if isinstance(v, dict) and "displayName" in v:
415
+ return f"{v.get('displayName')} <{v.get('uniqueName')}>"
416
+ if ref in HTML_FIELDS:
417
+ return html_to_text(v)
418
+ return v
419
+
420
+
421
+ def compact(item, relations=False, chars=None):
422
+ f = item.get("fields", {})
423
+ res = {
424
+ "id": item["id"],
425
+ "rev": item.get("rev"),
426
+ "type": f.get("System.WorkItemType"),
427
+ "title": f.get("System.Title"),
428
+ "state": f.get("System.State"),
429
+ "url": wi_url(item["id"]),
430
+ }
431
+ other = {}
432
+ for ref, v in f.items():
433
+ if ref in ("System.Id", "System.WorkItemType", "System.Title", "System.State"):
434
+ continue
435
+ name = FRIENDLY.get(ref)
436
+ if not name:
437
+ continue
438
+ val = fmt_value(ref, v)
439
+ if chars and isinstance(val, str) and len(val) > chars:
440
+ val = val[:chars].rstrip() + "…"
441
+ other[name] = val
442
+ res["fields"] = other
443
+ if relations:
444
+ rels = []
445
+ attachments = []
446
+ hyperlinks = []
447
+ for r in item.get("relations") or []:
448
+ if r["rel"] == "AttachedFile":
449
+ attributes = r.get("attributes") or {}
450
+ attachments.append({"name": attributes.get("name"), "url": r["url"],
451
+ "comment": attributes.get("comment")})
452
+ continue
453
+ if r["rel"] == "Hyperlink":
454
+ hyperlinks.append({"url": r["url"], "comment": (r.get("attributes") or {}).get("comment")})
455
+ continue
456
+ kind = LINK_NAMES.get(r["rel"])
457
+ if not kind:
458
+ continue
459
+ rels.append({"link": kind, "id": int(r["url"].rsplit("/", 1)[-1]),
460
+ "comment": (r.get("attributes") or {}).get("comment")})
461
+ res["relations"] = rels
462
+ res["attachments"] = attachments
463
+ res["hyperlinks"] = hyperlinks
464
+ return res
465
+
466
+
467
+ # ---------- reading ----------
468
+
469
+ def fetch(ids, fields=None, relations=False):
470
+ items = []
471
+ ids = list(dict.fromkeys(int(i) for i in ids))
472
+ for i in range(0, len(ids), 200):
473
+ chunk = ",".join(str(x) for x in ids[i:i + 200])
474
+ if relations:
475
+ url = f"{base()}/_apis/wit/workitems?ids={chunk}&$expand=relations&errorPolicy=omit&api-version=7.1"
476
+ else:
477
+ fl = ",".join(fields or READ_FIELDS)
478
+ url = f"{base()}/_apis/wit/workitems?ids={chunk}&fields={fl}&errorPolicy=omit&api-version=7.1"
479
+ items += [x for x in call("GET", url).get("value", []) if x]
480
+ return items
481
+
482
+
483
+ def wiql(query):
484
+ res = call("POST", f"{pbase()}/_apis/wit/wiql?api-version=7.1", {"query": query})
485
+ if "workItems" in res:
486
+ return [w["id"] for w in res["workItems"]]
487
+ return [r["target"]["id"] for r in res.get("workItemRelations", []) if r.get("target")]
488
+
489
+
490
+ def type_clause(types):
491
+ names = [norm_type(t) for t in types]
492
+ return "[System.WorkItemType] IN (" + ", ".join(f"'{n}'" for n in names) + ")"
493
+
494
+
495
+ def cmd_whoami(a):
496
+ d = call("GET", f"{base()}/_apis/connectionData")
497
+ u = d.get("authenticatedUser", {})
498
+ config = load_config()
499
+ out({"user": u.get("providerDisplayName"), "id": u.get("id"), "org": config["org"],
500
+ "project": config["project"], "ratingsPipelineUrl": config.get("ratingsPipelineUrl")})
501
+
502
+
503
+ def cmd_get(a):
504
+ items = fetch(a.ids, relations=True)
505
+ out([compact(i, relations=True) for i in items])
506
+
507
+
508
+ def cmd_backlog(a):
509
+ types = a.types.split(",")
510
+ states = "" if a.include_removed else " AND [System.State] NOT IN ('Removed', 'Rejected')"
511
+ if a.under:
512
+ q = ("SELECT [System.Id] FROM WorkItemLinks WHERE "
513
+ f"[Source].[System.Id] = {int(a.under)} "
514
+ "AND [System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward' "
515
+ f"AND [Target].{type_clause(types)} MODE (Recursive)")
516
+ ids = [i for i in wiql(q) if i != int(a.under)]
517
+ else:
518
+ q = ("SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = @project "
519
+ f"AND {type_clause(types)}{states} ORDER BY [System.ChangedDate] DESC")
520
+ ids = wiql(q)
521
+ items = [compact(i, chars=a.chars) for i in fetch(ids)]
522
+ if a.under and not a.include_removed:
523
+ items = [i for i in items if i["state"] not in ("Removed", "Rejected")]
524
+ out({"count": len(items), "items": items})
525
+
526
+
527
+ def cmd_search(a):
528
+ text = a.text.replace("'", "''")
529
+ q = ("SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = @project "
530
+ f"AND {type_clause(a.types.split(','))} "
531
+ f"AND ([System.Title] CONTAINS '{text}' OR [System.Description] CONTAINS WORDS '{text}') "
532
+ "ORDER BY [System.ChangedDate] DESC")
533
+ items = [compact(i, chars=a.chars) for i in fetch(wiql(q))]
534
+ out({"count": len(items), "items": items})
535
+
536
+
537
+ # ---------- writing ----------
538
+
539
+ def load_json(path):
540
+ try:
541
+ if path == "-":
542
+ return json.load(sys.stdin)
543
+ with open(path, encoding="utf-8") as fh:
544
+ return json.load(fh)
545
+ except (OSError, ValueError) as e:
546
+ die(f"Cannot read JSON from {path}: {e}")
547
+
548
+
549
+ def field_ops(fields, op="add"):
550
+ ops = []
551
+ for name, value in fields.items():
552
+ ref = ref_of(name)
553
+ if ref in HTML_FIELDS:
554
+ value = md_to_html(value)
555
+ ops.append({"op": op, "path": f"/fields/{ref}", "value": value})
556
+ return ops
557
+
558
+
559
+ def check_parent(child_type, parent_id):
560
+ parent = fetch([parent_id], fields=["System.WorkItemType", "System.Title"])
561
+ if not parent:
562
+ die(f"Parent #{parent_id} not found.")
563
+ ptype = parent[0]["fields"]["System.WorkItemType"]
564
+ if ptype not in ALLOWED_PARENT.get(child_type, set()):
565
+ die(f"A {child_type} cannot be a child of {ptype} #{parent_id}. "
566
+ f"Allowed parents: {sorted(ALLOWED_PARENT.get(child_type, set())) or 'none'}.")
567
+
568
+
569
+ # ---------- business ratings ----------
570
+
571
+ def validate_scores(fields, required=False):
572
+ values = {ref_of(k): v for k, v in fields.items()}
573
+ if "Microsoft.VSTS.Common.BusinessValue" in values:
574
+ die("Use BusinessValue (Custom.BusinessValueScore), not the legacy Business Value field.")
575
+ for ref in SCORE_FIELDS:
576
+ if ref not in values:
577
+ if required:
578
+ die(f"{FRIENDLY[ref]} is required; ask the business for an integer from 1 to 5.")
579
+ continue
580
+ if type(values[ref]) is not int or not 1 <= values[ref] <= 5:
581
+ die(f"{FRIENDLY[ref]} must be an integer from 1 to 5; do not infer a score.")
582
+
583
+
584
+ def related_ids(item):
585
+ return {int(r["url"].rsplit("/", 1)[-1]) for r in item.get("relations", [])
586
+ if r["rel"] == LINK_TYPES["related"]}
587
+
588
+
589
+ def get_one(wid):
590
+ items = fetch([wid], relations=True)
591
+ if not items:
592
+ die(f"Work item #{wid} not found or inaccessible.")
593
+ return items[0]
594
+
595
+
596
+ def check_expected_revision(item, expected_rev):
597
+ if expected_rev is not None and item.get("rev") != expected_rev:
598
+ die(f"Work item #{item['id']} changed since review: expected revision {expected_rev}, "
599
+ f"found {item.get('rev')}. Reconcile the change before writing.")
600
+
601
+
602
+ def inspect_br_revision(br_id, touched_ids=(), shared_approved=()):
603
+ """Read-only eligibility and sharing checks for a proposed BR revision."""
604
+ cache, blockers = {}, []
605
+
606
+ def read(wid):
607
+ wid = int(wid)
608
+ if wid not in cache:
609
+ cache[wid] = get_one(wid)
610
+ return cache[wid]
611
+
612
+ br = read(br_id)
613
+ if br["fields"]["System.WorkItemType"] != "Business Request":
614
+ die(f"#{br_id} is not a Business Request.")
615
+ linked_features = set()
616
+ for relation in br.get("relations") or []:
617
+ if relation["rel"] not in LINK_NAMES:
618
+ if relation["rel"] not in {"AttachedFile", "Hyperlink", "ArtifactLink"}:
619
+ blockers.append(f"Unsupported relationship type on BR #{br_id}: {relation['rel']}.")
620
+ continue
621
+ other = read(int(relation["url"].rsplit("/", 1)[-1]))
622
+ typ = other["fields"]["System.WorkItemType"]
623
+ if relation["rel"] == LINK_TYPES["related"] and typ == "Feature":
624
+ linked_features.add(other["id"])
625
+ elif relation["rel"] == LINK_TYPES["related"] and typ == "Business Request":
626
+ continue # Cross-references to other requests are not implementation backlog.
627
+ else:
628
+ blockers.append(f"Unsupported backlog relationship from BR #{br_id} to {typ} #{other['id']}.")
629
+ state = br["fields"].get("System.State")
630
+ mode = None
631
+ if state == "Received" and not linked_features and not blockers:
632
+ mode = "free_edit"
633
+ elif state in ("In analysis", "Planned") and not blockers:
634
+ mode = "cascade"
635
+ else:
636
+ blockers.append("Only a Received BR without linked backlog, or an In analysis or Planned BR "
637
+ "with all Features New/Planned, can be revised.")
638
+
639
+ touched = set(int(wid) for wid in touched_ids)
640
+ impacted_features = set()
641
+ if mode == "free_edit" and touched - {int(br_id)}:
642
+ blockers.append("Free edit may change the BR only; it must not generate or revise backlog.")
643
+ for wid in sorted(touched - {int(br_id)}):
644
+ target = read(wid)
645
+ typ = target["fields"]["System.WorkItemType"]
646
+ if typ == "Feature":
647
+ impacted_features.add(wid)
648
+ elif typ == "Product Backlog Item":
649
+ parents = [int(r["url"].rsplit("/", 1)[-1]) for r in target.get("relations") or []
650
+ if r["rel"] == LINK_TYPES["parent"]]
651
+ if len(parents) != 1 or read(parents[0])["fields"]["System.WorkItemType"] != "Feature":
652
+ blockers.append(f"PBI #{wid} does not have exactly one Feature parent.")
653
+ else:
654
+ impacted_features.add(parents[0])
655
+ else:
656
+ blockers.append(f"Revision cannot update {typ} #{wid}; only this BR, Features and PBIs are editable.")
657
+
658
+ shared = []
659
+ for fid in sorted(linked_features | impacted_features):
660
+ feature = read(fid)
661
+ feature_state = feature["fields"].get("System.State")
662
+ if feature_state not in EDITABLE_FEATURE_STATES:
663
+ blockers.append(f"Feature #{fid} is {feature_state}; all linked or affected Features must be New or Planned.")
664
+ others = []
665
+ for rid in sorted(related_ids(feature) - {int(br_id)}):
666
+ request = read(rid)
667
+ if request["fields"]["System.WorkItemType"] == "Business Request":
668
+ others.append({"id": rid, "title": request["fields"].get("System.Title"),
669
+ "state": request["fields"].get("System.State")})
670
+ if others:
671
+ shared.append({"feature": fid, "otherBRs": others, "affected": fid in impacted_features})
672
+ affected_shared = {row["feature"] for row in shared if row["affected"]}
673
+ approved = set(int(fid) for fid in shared_approved)
674
+ for fid in sorted(affected_shared - approved):
675
+ blockers.append(f"Shared Feature #{fid} needs explicit user feedback on the proposed change before any write.")
676
+ if approved - affected_shared:
677
+ blockers.append(f"Shared approvals do not match affected shared Features: {sorted(approved - affected_shared)}.")
678
+ snapshots = [{"id": wid, "rev": value.get("rev"), "type": value["fields"]["System.WorkItemType"],
679
+ "state": value["fields"].get("System.State"), "title": value["fields"].get("System.Title")}
680
+ for wid, value in sorted(cache.items())]
681
+ return {"br": int(br_id), "mode": mode, "eligible": not blockers, "blockers": blockers,
682
+ "linkedFeatures": sorted(linked_features), "affectedFeatures": sorted(impacted_features),
683
+ "sharedFeatures": shared, "snapshots": snapshots}
684
+
685
+
686
+ def cmd_revision_check(a):
687
+ result = inspect_br_revision(a.id, a.touch, a.shared_approved)
688
+ out(result)
689
+ if not result["eligible"]:
690
+ raise SystemExit(1)
691
+
692
+
693
+ def paged_values(url):
694
+ values, seen = [], set()
695
+ for page in range(100):
696
+ query = urllib.parse.urlencode({"api-version": "7.1", "$top": 100, "$skip": page * 100})
697
+ batch = call("GET", f"{url}?{query}").get("value", [])
698
+ if not batch:
699
+ return values
700
+ identifiers = [row.get("id") or row.get("identity", {}).get("id") for row in batch]
701
+ if len(set(identifiers)) != len(identifiers) or any(wid is None or wid in seen for wid in identifiers):
702
+ die("Team/member pagination returned missing or repeated identities; results may be incomplete.")
703
+ seen.update(identifiers)
704
+ values.extend(batch)
705
+ if len(batch) < 100:
706
+ return values
707
+ die("Team/member pagination limit reached; refine the query instead of assuming complete results.")
708
+
709
+
710
+ def planning_context(team=None, iteration=None):
711
+ project = urllib.parse.quote(load_config()["project"], safe="")
712
+ teams_url = f"{base()}/_apis/projects/{project}/teams"
713
+ teams = paged_values(teams_url)
714
+ matches = teams if team is None else [t for t in teams if str(team).casefold() in
715
+ {t["id"].casefold(), t["name"].casefold()}]
716
+ if len(matches) != 1:
717
+ if team is not None:
718
+ die("Team name/ID is missing or ambiguous; select an exact team from planning-context.")
719
+ return {"selectionRequired": True, "teams": [{"id": t["id"], "name": t["name"]} for t in teams]}
720
+ selected = matches[0]
721
+ team_id = urllib.parse.quote(selected["id"], safe="")
722
+ settings_url = f"{pbase()}/{team_id}/_apis/work/teamsettings"
723
+ settings = call("GET", f"{settings_url}?api-version=7.1")
724
+ iterations_response = call("GET", f"{settings_url}/iterations?api-version=7.1")
725
+ iterations = iterations_response.get("value", iterations_response.get("values", []))
726
+ members = [row["identity"] for row in paged_values(f"{teams_url}/{team_id}/members")]
727
+ result = {"selectionRequired": False, "team": {"id": selected["id"], "name": selected["name"]},
728
+ "workingDays": settings.get("workingDays", []),
729
+ "members": [{k: member.get(k) for k in ("id", "displayName", "uniqueName", "isContainer")} for member in members],
730
+ "iterations": iterations}
731
+ if iteration is not None:
732
+ candidates = [i for i in iterations if str(iteration).casefold() in
733
+ {str(i.get(k, "")).casefold() for k in ("id", "name", "path")}]
734
+ if len(candidates) != 1 or not candidates[0].get("path"):
735
+ die("Select one configured team iteration with an explicit path.")
736
+ selected_iteration = candidates[0]
737
+ path = selected_iteration["path"].replace("'", "''")
738
+ ids = wiql("SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = @project "
739
+ f"AND [System.IterationPath] = '{path}' "
740
+ "AND [System.WorkItemType] IN ('Feature', 'Bug') ORDER BY [System.Id]")
741
+ workload = fetch(ids)
742
+ if set(ids) != {i["id"] for i in workload}:
743
+ die("Some iteration work items are inaccessible; do not plan from an incomplete workload.")
744
+ result.update({"iteration": selected_iteration, "workloadScope": "project iteration",
745
+ "workload": [compact(i) for i in workload]})
746
+ return result
747
+
748
+
749
+ def inspect_sprint_plan(plan, context, today=None):
750
+ """Check a temporary planning proposal without persisting estimates or changing work items."""
751
+ today = today or date.today()
752
+ blockers, updates, snapshots = [], [], {}
753
+ iteration = context.get("iteration") or {}
754
+ attrs = iteration.get("attributes") or {}
755
+ try:
756
+ start, finish = (date.fromisoformat(attrs[k][:10]) for k in ("startDate", "finishDate"))
757
+ except (KeyError, TypeError, ValueError):
758
+ die("Sprint start and finish dates must be configured before planning.")
759
+ weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
760
+ working = {str(day).lower() for day in context.get("workingDays", [])}
761
+ if not working or not working <= set(weekdays):
762
+ die("Team working days are missing or invalid; clarify the calendar before planning.")
763
+ span = (finish - start).days + 1
764
+ if not 7 < span <= 14:
765
+ die("The selected iteration does not cover a two-week sprint.")
766
+ dates = [start + timedelta(days=i) for i in range(span)
767
+ if weekdays[(start + timedelta(days=i)).weekday()] in working]
768
+ if len(dates) != 2 * len(working):
769
+ die("The selected iteration does not contain two complete configured working weeks.")
770
+ remaining = [day for day in dates if day >= today]
771
+ if not remaining:
772
+ die("Past iterations cannot be used for normal sprint planning.")
773
+ if not iteration.get("path"):
774
+ die("The selected iteration has no assignable path.")
775
+
776
+ def number(value, label, minimum=0):
777
+ if type(value) not in (int, float) or not math.isfinite(value) or value < minimum:
778
+ die(f"{label} must be a finite number greater than or equal to {minimum}.")
779
+ return value
780
+
781
+ members = {str(m.get("uniqueName", "")).casefold(): m for m in context.get("members", [])
782
+ if m.get("uniqueName") and not m.get("isContainer")}
783
+ developers = {}
784
+ for dev in plan.get("developers", []):
785
+ key = str(dev.get("identity", "")).casefold()
786
+ if key not in members or key in developers:
787
+ die("Each available developer must be a distinct confirmed team-member identity.")
788
+ available = number(dev.get("availableDays"), "availableDays")
789
+ reserved = number(dev.get("reservedDays", 0), "reservedDays")
790
+ if available > len(remaining) or reserved > available:
791
+ die("Developer availability/reserve exceeds the remaining sprint working days.")
792
+ developers[key] = {"identity": members[key]["uniqueName"], "availableDays": available,
793
+ "reservedDays": reserved, "plannedDays": 0, "existingDays": 0, "sequence": []}
794
+ if not developers:
795
+ die("Confirm the available developers before producing a sprint allocation.")
796
+ project_name = load_config()["project"]
797
+
798
+ def read(wid):
799
+ if type(wid) is not int or wid <= 0:
800
+ die("Planning item IDs must be positive integers.")
801
+ if wid not in snapshots:
802
+ snapshots[wid] = get_one(wid)
803
+ project = snapshots[wid]["fields"].get("System.TeamProject")
804
+ if project is not None and project != project_name:
805
+ die(f"Work item #{wid} belongs to another project.")
806
+ return snapshots[wid]
807
+
808
+ def identity_key(value):
809
+ if isinstance(value, dict):
810
+ value = value.get("uniqueName", "")
811
+ value = str(value or "").strip()
812
+ match = re.search(r"<([^<>]+)>$", value)
813
+ return (match.group(1) if match else value).casefold()
814
+
815
+ def owner(item):
816
+ return identity_key(item["fields"].get("System.AssignedTo"))
817
+
818
+ def propose(item, fields):
819
+ changes = {k: v for k, v in fields.items()
820
+ if (owner(item) != str(v).casefold() if k == "AssignedTo" else item["fields"].get(ref_of(k)) != v)}
821
+ if changes:
822
+ updates.append({"id": item["id"], "expectedRev": item["rev"], "fields": changes})
823
+
824
+ terminal = {"Done", "Closed", "Resolved", "Removed", "Rejected"}
825
+ accounted = set()
826
+ for row in plan.get("existingLoad", []):
827
+ current = read(row.get("id"))
828
+ wid = current["id"]
829
+ key = str(row.get("developer", "")).casefold()
830
+ if wid in accounted or key not in developers:
831
+ die("Existing work must be listed once and allocated to an available developer.")
832
+ if current["fields"]["System.WorkItemType"] not in {"Feature", "Bug"} or current["fields"].get("System.State") in terminal:
833
+ die("Existing load must refer to an unfinished Feature or Bug.")
834
+ if owner(current) != key:
835
+ die(f"Existing load #{wid} has another or no owner; do not silently reassign it in a capacity reserve.")
836
+ developers[key]["existingDays"] += number(row.get("days"), "existing load days")
837
+ accounted.add(wid)
838
+ for row in plan.get("items", []):
839
+ current = read(row.get("id"))
840
+ wid = current["id"]
841
+ key = str(row.get("developer", "")).casefold()
842
+ if wid in accounted or key not in developers:
843
+ die("Each selected Feature/Bug must occur once and have exactly one available developer.")
844
+ days = number(row.get("days"), "planning duration", 0.01)
845
+ accounted.add(wid)
846
+ developers[key]["plannedDays"] += days
847
+ developers[key]["sequence"].append(wid)
848
+ typ, state = current["fields"]["System.WorkItemType"], current["fields"].get("System.State")
849
+ if typ == "Feature":
850
+ if state not in EDITABLE_FEATURE_STATES:
851
+ blockers.append(f"Feature #{wid} is {state}; keep committed/started work as existing load, not a normal planning update.")
852
+ continue
853
+ propose(current, {"IterationPath": iteration["path"], "AssignedTo": developers[key]["identity"], "State": "Planned"})
854
+ child_ids = [int(r["url"].rsplit("/", 1)[-1]) for r in current.get("relations", [])
855
+ if r["rel"] == LINK_TYPES["child"]]
856
+ for child_id in child_ids:
857
+ child = read(child_id)
858
+ child_fields = child["fields"]
859
+ if child_fields["System.WorkItemType"] != "Product Backlog Item" or child_fields.get("System.State") == "Removed":
860
+ continue
861
+ child_state = child_fields.get("System.State")
862
+ if child_fields.get("System.IterationPath") != iteration["path"] and child_state not in {"New", "Approved", "Planned"}:
863
+ blockers.append(f"PBI #{child_id} is {child_state} in another iteration; do not rewrite work history to make the Feature fit.")
864
+ else:
865
+ propose(child, {"IterationPath": iteration["path"]})
866
+ elif typ == "Bug":
867
+ if state not in {"New", "Approved", "Planned"}:
868
+ blockers.append(f"Bug #{wid} is {state}; started or finished Bugs require a separate decision.")
869
+ else:
870
+ propose(current, {"IterationPath": iteration["path"], "AssignedTo": developers[key]["identity"]})
871
+ else:
872
+ blockers.append(f"#{wid} is a {typ}; allocate whole Features or individual Bugs, not PBIs, Epics or BRs.")
873
+
874
+ for current in context.get("workload", []):
875
+ if current.get("state") in terminal or current["id"] in accounted:
876
+ continue
877
+ assigned = identity_key(current.get("fields", {}).get("AssignedTo"))
878
+ if not assigned or assigned in developers:
879
+ blockers.append(f"Existing sprint item #{current['id']} is not accounted for; include its remaining load or explicitly replan it.")
880
+ for dev in developers.values():
881
+ dev["totalDays"] = dev["reservedDays"] + dev["existingDays"] + dev["plannedDays"]
882
+ if dev["totalDays"] > dev["availableDays"] + 1e-9:
883
+ blockers.append(f"Developer {dev['identity']} is over capacity: {dev['totalDays']} days for {dev['availableDays']} available.")
884
+ return {"eligible": not blockers, "blockers": blockers, "iteration": iteration,
885
+ "remainingWorkingDates": [day.isoformat() for day in remaining], "capacity": list(developers.values()),
886
+ "updates": updates if not blockers else [],
887
+ "snapshots": [{"id": i["id"], "rev": i["rev"], "state": i["fields"].get("System.State")}
888
+ for i in snapshots.values()],
889
+ "limitations": "Checks numerical budgets and allowed item changes, not actual technical duration, dated dependencies, absences or external approval feasibility."}
890
+
891
+
892
+ def cmd_planning_context(a):
893
+ out(planning_context(a.team, a.iteration))
894
+
895
+
896
+ def cmd_planning_check(a):
897
+ plan = load_json(a.plan)
898
+ if not plan.get("team") or not plan.get("iteration"):
899
+ die("A planning proposal must identify its team and target iteration.")
900
+ result = inspect_sprint_plan(plan, planning_context(plan["team"], plan["iteration"]))
901
+ out(result)
902
+ if not result["eligible"]:
903
+ raise SystemExit(1)
904
+
905
+
906
+ def rating_result(feature, brs):
907
+ """Pure aggregation: evaluate both dimensions separately, never invent missing scores."""
908
+ result = {"id": feature.get("id"), "state": feature["fields"].get("System.State")}
909
+ if result["state"] not in EDITABLE_FEATURE_STATES:
910
+ return {**result, "status": "frozen"}
911
+ if not brs:
912
+ return {**result, "status": "no_linked_brs"}
913
+ missing = []
914
+ for br in brs:
915
+ for ref in SCORE_FIELDS:
916
+ value = br["fields"].get(ref)
917
+ if type(value) is not int or not 1 <= value <= 5:
918
+ missing.append({"br": br["id"], "field": FRIENDLY[ref], "value": value})
919
+ if missing:
920
+ return {**result, "status": "needs_input", "missing": missing}
921
+ fields = {FRIENDLY[ref]: max(br["fields"][ref] for br in brs) for ref in SCORE_FIELDS}
922
+ return {**result, "status": "ready", "brs": sorted(br["id"] for br in brs), "fields": fields}
923
+
924
+
925
+ def collect_feature_ratings(feature, extra_br_ids=()):
926
+ if feature["fields"].get("System.State") not in EDITABLE_FEATURE_STATES:
927
+ return rating_result(feature, [])
928
+ ids = related_ids(feature) | set(extra_br_ids)
929
+ linked = fetch(sorted(ids), relations=True) if ids else []
930
+ missing = ids - {i["id"] for i in linked}
931
+ if missing:
932
+ die(f"Cannot compute Feature ratings: linked work items inaccessible: {sorted(missing)}")
933
+ brs = [i for i in linked if i["fields"]["System.WorkItemType"] == "Business Request"]
934
+ return rating_result(feature, brs)
935
+
936
+
937
+ def feature_rating_changes(feature, extra_br_ids=()):
938
+ """The ratings result for this read of the Feature, and the rating fields it must change."""
939
+ result = collect_feature_ratings(feature, extra_br_ids)
940
+ if result["status"] != "ready":
941
+ return result, {}
942
+ return result, {name: value for name, value in result["fields"].items()
943
+ if feature["fields"].get(ref_of(name)) != value}
944
+
945
+
946
+ def sync_feature_ratings(feature_id, dry_run=False, extra_br_ids=()):
947
+ feature = get_one(feature_id)
948
+ if feature["fields"]["System.WorkItemType"] != "Feature":
949
+ die(f"#{feature_id} is not a Feature.")
950
+ result, changes = feature_rating_changes(feature, extra_br_ids)
951
+ if result["status"] != "ready":
952
+ return result
953
+ if not changes:
954
+ return {**result, "status": "unchanged"}
955
+ if dry_run:
956
+ return {**result, "status": "would_update", "changes": changes}
957
+ # Prevent a stale write if the Feature is committed while we read its BRs.
958
+ ops = [{"op": "test", "path": "/rev", "value": feature["rev"]}] + field_ops(changes)
959
+ call("PATCH", f"{api_url(feature_id)}?api-version=7.1", ops,
960
+ content_type="application/json-patch+json")
961
+ return {**result, "status": "updated", "changes": changes}
962
+
963
+
964
+ def linked_feature_ids(br):
965
+ ids = related_ids(br)
966
+ return sorted(i["id"] for i in (fetch(sorted(ids)) if ids else [])
967
+ if i["fields"]["System.WorkItemType"] == "Feature")
968
+
969
+
970
+ def sync_link_ratings(source, target, dry_run=False):
971
+ items = {i["id"]: i for i in fetch([source, target])}
972
+ if set(items) != {source, target}:
973
+ die("Cannot read both ends of the link.")
974
+ types = {i["fields"]["System.WorkItemType"] for i in items.values()}
975
+ if types == {"Business Request", "Feature"}:
976
+ fid = next(i["id"] for i in items.values() if i["fields"]["System.WorkItemType"] == "Feature")
977
+ if dry_run:
978
+ feature = get_one(fid)
979
+ bid = target if fid == source else source
980
+ return collect_feature_ratings(feature, [bid])
981
+ return sync_feature_ratings(fid)
982
+ return None
983
+
984
+
985
+ def cmd_sync_ratings(a):
986
+ all_features = getattr(a, "all_features", False)
987
+ if bool(a.ids) == all_features:
988
+ die("Use sync-ratings FEATURE_ID [...] or sync-ratings --all.")
989
+ ids = a.ids
990
+ if all_features:
991
+ ids = wiql("SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = @project "
992
+ "AND [System.WorkItemType] = 'Feature' AND [System.State] IN ('New', 'Planned') "
993
+ "ORDER BY [System.Id]")
994
+ report = []
995
+ failed = False
996
+ for fid in ids:
997
+ try:
998
+ report.append(sync_feature_ratings(fid, a.dry_run))
999
+ except SystemExit:
1000
+ failed = True
1001
+ report.append({"id": fid, "status": "error", "message": "Sync failed; see stderr. No retry or bypass of state/revision checks."})
1002
+ out(report)
1003
+ if failed:
1004
+ raise SystemExit(1)
1005
+
1006
+
1007
+ def create_item(wtype, fields, parent=None, dry_run=False):
1008
+ if wtype == "Business Request" and any(ref_of(k) == "System.State" for k in fields):
1009
+ die("A Business Request starts in Received, so create sends no State. Use set-state to move it later.")
1010
+ validate_scores(fields, required=wtype in ("Business Request", "Feature"))
1011
+ if wtype not in ("Business Request", "Feature") and any(ref_of(k) in SCORE_FIELDS for k in fields):
1012
+ die("BusinessValue and Urgency belong only to BRs and Features.")
1013
+ ops = field_ops(fields)
1014
+ if parent:
1015
+ ops.append({"op": "add", "path": "/relations/-",
1016
+ "value": {"rel": LINK_TYPES["parent"], "url": api_url(parent)}})
1017
+ qs = "validateOnly=true&" if dry_run else ""
1018
+ res = call("POST", f"{pbase()}/_apis/wit/workitems/${urllib.parse.quote(wtype)}?{qs}api-version=7.1",
1019
+ ops, content_type="application/json-patch+json")
1020
+ if dry_run:
1021
+ return {"validated": True, "type": wtype, "title": fields.get("Title")}
1022
+ return {"id": res["id"], "type": wtype, "title": res["fields"].get("System.Title"), "url": wi_url(res["id"])}
1023
+
1024
+
1025
+ def cmd_create(a):
1026
+ wtype = norm_type(a.type)
1027
+ fields = load_json(a.json)
1028
+ if wtype == "Feature":
1029
+ die("Create Features with an apply plan containing BR Related links; ratings are derived from those BRs.")
1030
+ if not fields.get("Title") and not fields.get("System.Title"):
1031
+ die("Title is required.")
1032
+ if a.parent:
1033
+ check_parent(wtype, a.parent)
1034
+ out(create_item(wtype, fields, a.parent, a.dry_run))
1035
+
1036
+
1037
+ def cmd_update(a):
1038
+ fields = load_json(a.json)
1039
+ validate_scores(fields)
1040
+ current = get_one(a.id)
1041
+ check_expected_revision(current, getattr(a, "expected_rev", None))
1042
+ typ = current["fields"]["System.WorkItemType"]
1043
+ rating_change = any(ref_of(k) in SCORE_FIELDS for k in fields)
1044
+ if rating_change and typ != "Business Request":
1045
+ die("Ratings are entered on BRs only; use sync-ratings to derive Feature values before Committed.")
1046
+ new_state = next((v for k, v in fields.items() if ref_of(k) == "System.State"), None)
1047
+ if typ == "Business Request" and new_state is not None:
1048
+ die("update does not change a Business Request's Human State; use set-state.")
1049
+ precommit, ops = None, field_ops(fields)
1050
+ if (typ == "Feature" and current["fields"]["System.State"] in EDITABLE_FEATURE_STATES
1051
+ and new_state in {"Committed", "In Progress", "Resolved", "Done"}):
1052
+ # The ratings freeze with the State in one patch on the reviewed revision, so any
1053
+ # other change to the Feature since the review refuses the whole write.
1054
+ precommit, changes = feature_rating_changes(current)
1055
+ if precommit["status"] != "ready":
1056
+ die("Feature ratings cannot be frozen until linked BR ratings are complete: " + json.dumps(precommit))
1057
+ status = "unchanged" if not changes else "would_update" if a.dry_run else "updated"
1058
+ precommit = {**precommit, "status": status, **({"changes": changes} if changes else {})}
1059
+ ops = field_ops(changes) + ops
1060
+ if a.dry_run:
1061
+ out({"dry_run": True, "id": a.id, "ops": ops, "precommit_ratings": precommit})
1062
+ return
1063
+ ops = [{"op": "test", "path": "/rev", "value": current["rev"]}] + ops
1064
+ res = call("PATCH", f"{api_url(a.id)}?api-version=7.1", ops,
1065
+ content_type="application/json-patch+json")
1066
+ report = {"id": res["id"], "rev": res["rev"], "url": wi_url(res["id"])}
1067
+ if rating_change:
1068
+ report["feature_ratings"] = [sync_feature_ratings(fid) for fid in linked_feature_ids(get_one(a.id))]
1069
+ if precommit:
1070
+ report["precommit_ratings"] = precommit
1071
+ out(report)
1072
+
1073
+
1074
+ def existing_links(wid):
1075
+ item = fetch([wid], relations=True)
1076
+ rels = set()
1077
+ for r in (item[0].get("relations") or []) if item else []:
1078
+ if r["rel"] in LINK_NAMES:
1079
+ rels.add((r["rel"], int(r["url"].rsplit("/", 1)[-1])))
1080
+ return rels
1081
+
1082
+
1083
+ def add_link(source, target, kind, comment=None, dry_run=False, sync_scores=True):
1084
+ rel = LINK_TYPES[kind]
1085
+ if (rel, int(target)) in existing_links(source):
1086
+ result = {"skipped": "already linked", "source": source, "target": target, "link": kind}
1087
+ if kind == "related" and sync_scores:
1088
+ result["feature_ratings"] = sync_link_ratings(source, target, dry_run)
1089
+ return result
1090
+ if dry_run:
1091
+ result = {"dry_run": True, "source": source, "target": target, "link": kind, "comment": comment}
1092
+ if kind == "related" and sync_scores:
1093
+ result["feature_ratings"] = sync_link_ratings(source, target, True)
1094
+ return result
1095
+ value = {"rel": rel, "url": api_url(target)}
1096
+ if comment:
1097
+ value["attributes"] = {"comment": comment}
1098
+ call("PATCH", f"{base()}/_apis/wit/workitems/{source}?api-version=7.1",
1099
+ [{"op": "add", "path": "/relations/-", "value": value}],
1100
+ content_type="application/json-patch+json")
1101
+ result = {"linked": True, "source": source, "target": target, "link": kind, "comment": comment}
1102
+ if kind == "related" and sync_scores:
1103
+ result["feature_ratings"] = sync_link_ratings(source, target)
1104
+ return result
1105
+
1106
+
1107
+ def cmd_link(a):
1108
+ if a.type in ("parent", "child"):
1109
+ child, parent = (a.source, a.target) if a.type == "parent" else (a.target, a.source)
1110
+ ctype = fetch([child], fields=["System.WorkItemType"])[0]["fields"]["System.WorkItemType"]
1111
+ check_parent(ctype, parent)
1112
+ out(add_link(a.source, a.target, a.type, a.comment, a.dry_run))
1113
+
1114
+
1115
+ def remove_related_link(source, target, expected_rev=None, dry_run=False):
1116
+ current = get_one(source)
1117
+ other = get_one(target)
1118
+ check_expected_revision(current, expected_rev)
1119
+ indexes = [i for i, r in enumerate(current.get("relations") or [])
1120
+ if r["rel"] == LINK_TYPES["related"] and int(r["url"].rsplit("/", 1)[-1]) == target]
1121
+ ops = [{"op": "test", "path": "/rev", "value": current["rev"]}]
1122
+ ops += [{"op": "remove", "path": f"/relations/{i}"} for i in reversed(indexes)]
1123
+ report = {"source": source, "target": target, "link": "related", "dry_run": dry_run,
1124
+ "status": "would_unlink" if dry_run and indexes else "unlinked" if indexes else "already_unlinked"}
1125
+ if indexes and not dry_run:
1126
+ result = call("PATCH", f"{api_url(source)}?api-version=7.1", ops,
1127
+ content_type="application/json-patch+json")
1128
+ report["rev"] = result.get("rev")
1129
+ if dry_run:
1130
+ report["ops"] = ops if indexes else []
1131
+ types = {current["fields"]["System.WorkItemType"], other["fields"]["System.WorkItemType"]}
1132
+ if types == {"Business Request", "Feature"}:
1133
+ feature = current if current["fields"]["System.WorkItemType"] == "Feature" else other
1134
+ bid = target if feature["id"] == source else source
1135
+ if dry_run:
1136
+ projected = {**feature, "relations": [r for r in feature.get("relations", [])
1137
+ if not (r["rel"] == LINK_TYPES["related"] and int(r["url"].rsplit("/", 1)[-1]) == bid)]}
1138
+ report["feature_ratings"] = collect_feature_ratings(projected)
1139
+ else:
1140
+ report["feature_ratings"] = sync_feature_ratings(feature["id"])
1141
+ return report
1142
+
1143
+
1144
+ def cmd_unlink(a):
1145
+ out(remove_related_link(a.source, a.target, a.expected_rev, a.dry_run))
1146
+
1147
+
1148
+ def add_hyperlink(wid, url, comment=None):
1149
+ """Add a Hyperlink relation to `url`; an item that already has one to the same URL stays unchanged."""
1150
+ current = get_one(wid)
1151
+ if any(r["rel"] == "Hyperlink" and r["url"] == url for r in current.get("relations") or []):
1152
+ return {"id": wid, "url": url, "status": "unchanged"}
1153
+ value = {"rel": "Hyperlink", "url": url}
1154
+ if comment:
1155
+ value["attributes"] = {"comment": comment}
1156
+ ops = [{"op": "test", "path": "/rev", "value": current["rev"]},
1157
+ {"op": "add", "path": "/relations/-", "value": value}]
1158
+ res = call("PATCH", f"{api_url(wid)}?api-version=7.1", ops, content_type="application/json-patch+json")
1159
+ return {"id": wid, "url": url, "comment": comment, "status": "written", "rev": res.get("rev")}
1160
+
1161
+
1162
+ def cmd_hyperlink(a):
1163
+ out(add_hyperlink(a.id, a.url, a.comment))
1164
+
1165
+
1166
+ def remove_hyperlink(wid, url):
1167
+ """Remove the Hyperlink relations to `url`; an item without one stays unchanged."""
1168
+ current = get_one(wid)
1169
+ indexes = [i for i, r in enumerate(current.get("relations") or []) if r["rel"] == "Hyperlink" and r["url"] == url]
1170
+ if not indexes:
1171
+ return {"id": wid, "url": url, "status": "unchanged"}
1172
+ ops = [{"op": "test", "path": "/rev", "value": current["rev"]}]
1173
+ ops += [{"op": "remove", "path": f"/relations/{i}"} for i in reversed(indexes)]
1174
+ res = call("PATCH", f"{api_url(wid)}?api-version=7.1", ops, content_type="application/json-patch+json")
1175
+ return {"id": wid, "url": url, "status": "written", "rev": res.get("rev")}
1176
+
1177
+
1178
+ def cmd_unhyperlink(a):
1179
+ out(remove_hyperlink(a.id, a.url))
1180
+
1181
+
1182
+ def add_comment(wid, text, dry_run=False):
1183
+ body = md_to_html(text)
1184
+ if dry_run:
1185
+ return {"dry_run": True, "id": wid, "comment_html": body}
1186
+ res = call("POST", f"{pbase()}/_apis/wit/workItems/{wid}/comments?api-version=7.1-preview.4", {"text": body})
1187
+ return {"commented": True, "id": wid, "commentId": res.get("id")}
1188
+
1189
+
1190
+ def set_state(wid, target, comment, expected_rev=None, dry_run=False):
1191
+ """Move a Business Request forward to `target`; refuse a backward move or a move out of a final state."""
1192
+ if target not in BR_STATES:
1193
+ die(f"{target!r} is not a Human State. Use one of: {', '.join(BR_STATES)}.")
1194
+ if not comment.strip():
1195
+ die("--comment must say why the Human State changes.")
1196
+ current = get_one(wid)
1197
+ if current["fields"]["System.WorkItemType"] != "Business Request":
1198
+ die(f"#{wid} is not a Business Request.")
1199
+ check_expected_revision(current, expected_rev)
1200
+ state = current["fields"].get("System.State")
1201
+ report = {"id": wid, "from": state, "to": target, "dry_run": dry_run}
1202
+ if state == target:
1203
+ return {**report, "status": "unchanged"}
1204
+ if state in BR_FINAL:
1205
+ die(f"Business Request #{wid} is {state}, a final Human State; set-state does not move it.")
1206
+ if state not in BR_STATES:
1207
+ die(f"Business Request #{wid} is {state!r}, not a Human State; correct it in Azure DevOps first.")
1208
+ if target in BR_FLOW and BR_FLOW.index(target) < BR_FLOW.index(state):
1209
+ die(f"Business Request #{wid} is {state}; set-state does not move it back to {target}.")
1210
+ if dry_run:
1211
+ return {**report, "status": "would_write"}
1212
+ # One atomic write: the revision test, the State and its comment (System.History).
1213
+ ops = [{"op": "test", "path": "/rev", "value": current["rev"]},
1214
+ {"op": "add", "path": "/fields/System.State", "value": target},
1215
+ {"op": "add", "path": "/fields/System.History", "value": md_to_html(comment)}]
1216
+ res = call("PATCH", f"{api_url(wid)}?api-version=7.1", ops, content_type="application/json-patch+json")
1217
+ return {**report, "status": "written", "rev": res.get("rev"), "url": wi_url(wid)}
1218
+
1219
+
1220
+ def cmd_set_state(a):
1221
+ out(set_state(a.id, a.state, a.comment, a.expected_rev, a.dry_run))
1222
+
1223
+
1224
+ def cmd_comment(a):
1225
+ if a.file:
1226
+ with open(a.file, encoding="utf-8") as fh:
1227
+ text = fh.read()
1228
+ else:
1229
+ text = a.text
1230
+ out(add_comment(a.id, text, a.dry_run))
1231
+
1232
+
1233
+ def save_attachment_receipt(path, state):
1234
+ """Checkpoint uploads before linking, so a retry can reuse the same attachment."""
1235
+ temp_path = None
1236
+ try:
1237
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8",
1238
+ dir=os.path.dirname(os.path.abspath(path)),
1239
+ prefix=".ado-attachment-", delete=False) as fh:
1240
+ temp_path = fh.name
1241
+ json.dump(state, fh, indent=2, ensure_ascii=False)
1242
+ fh.flush()
1243
+ os.fsync(fh.fileno())
1244
+ os.replace(temp_path, path)
1245
+ except OSError as e:
1246
+ if temp_path and os.path.exists(temp_path):
1247
+ os.unlink(temp_path)
1248
+ die(f"Cannot save attachment receipt {path}: {e}. "
1249
+ f"Uploaded URL: {state.get('attachmentUrl', 'not available')}. Inspect before retrying.")
1250
+
1251
+
1252
+ def attach_file(wid, path, receipt_path, comment=None, dry_run=False):
1253
+ if os.path.realpath(path) == os.path.realpath(receipt_path):
1254
+ die("The attachment receipt must be a different file from the evidence.")
1255
+ try:
1256
+ if not os.path.isfile(path):
1257
+ die(f"Attachment is not a regular file: {path}")
1258
+ if os.path.getsize(path) > MAX_SIMPLE_ATTACHMENT_BYTES:
1259
+ die("Attachment exceeds the helper's 130 MB simple-upload limit. Use a shorter recording; keep the existing Bug.")
1260
+ with open(path, "rb") as fh:
1261
+ data = fh.read()
1262
+ except OSError as e:
1263
+ die(f"Cannot read attachment {path}: {e}")
1264
+ identity = {"workItemUrl": wi_url(wid), "fileName": os.path.basename(path),
1265
+ "sha256": hashlib.sha256(data).hexdigest()}
1266
+ state = dict(identity)
1267
+ if os.path.exists(receipt_path):
1268
+ state = load_json(receipt_path)
1269
+ if not isinstance(state, dict) or any(state.get(k) != v for k, v in identity.items()):
1270
+ die("Attachment receipt belongs to a different file or work item; do not reuse it.")
1271
+ if not isinstance(state.get("attachmentUrl"), str) or not state["attachmentUrl"]:
1272
+ die("An upload was attempted but no attachment URL was recorded. Its result is uncertain; inspect before retrying, and do not start another upload with a new receipt.")
1273
+ current = get_one(wid)
1274
+ report = {"id": wid, "url": wi_url(wid), "fileName": identity["fileName"],
1275
+ "sizeBytes": len(data), "receipt": receipt_path, "dry_run": dry_run}
1276
+ if dry_run:
1277
+ return {**report, "status": "would_attach", "attachmentUrl": state.get("attachmentUrl")}
1278
+ if not state.get("attachmentUrl"):
1279
+ state["uploadAttempted"] = True
1280
+ save_attachment_receipt(receipt_path, state)
1281
+ query = urllib.parse.urlencode({"fileName": identity["fileName"], "api-version": "7.1"})
1282
+ uploaded = call("POST", f"{pbase()}/_apis/wit/attachments?{query}", data,
1283
+ content_type="application/octet-stream", timeout=60)
1284
+ if not uploaded.get("url"):
1285
+ die("Upload returned no attachment URL. Keep the receipt and inspect before retrying.")
1286
+ state["attachmentUrl"] = uploaded["url"]
1287
+ save_attachment_receipt(receipt_path, state)
1288
+ current = get_one(wid)
1289
+ attachment_url = state["attachmentUrl"]
1290
+ attachment_id = urllib.parse.urlsplit(attachment_url).path.rstrip("/").rsplit("/", 1)[-1]
1291
+ for relation in current.get("relations") or []:
1292
+ if (relation["rel"] == "AttachedFile" and
1293
+ urllib.parse.urlsplit(relation["url"]).path.rstrip("/").rsplit("/", 1)[-1] == attachment_id):
1294
+ return {**report, "status": "already_attached", "attachmentUrl": attachment_url}
1295
+ value = {"rel": "AttachedFile", "url": attachment_url}
1296
+ if comment:
1297
+ value["attributes"] = {"comment": comment}
1298
+ call("PATCH", f"{api_url(wid)}?api-version=7.1",
1299
+ [{"op": "test", "path": "/rev", "value": current["rev"]},
1300
+ {"op": "add", "path": "/relations/-", "value": value}],
1301
+ content_type="application/json-patch+json")
1302
+ return {**report, "status": "attached", "attachmentUrl": attachment_url}
1303
+
1304
+
1305
+ def cmd_attach(a):
1306
+ out(attach_file(a.id, a.file, a.receipt, a.comment, a.dry_run))
1307
+
1308
+
1309
+ # ---------- plan ----------
1310
+
1311
+ def cmd_apply(a):
1312
+ plan = load_json(a.plan)
1313
+ items = plan.get("items", [])
1314
+ br = plan.get("br")
1315
+ keys, errors = {}, []
1316
+
1317
+ def resolve(ref):
1318
+ if isinstance(ref, int) or (isinstance(ref, str) and ref.isdigit()):
1319
+ return int(ref)
1320
+ if ref in keys:
1321
+ return keys[ref].get("id") or f"<{ref}>"
1322
+ return None
1323
+
1324
+ # validation pass: structure, hierarchy, forbidden fields
1325
+ known_types = {}
1326
+ numeric = {int(i["parent"]) for i in items if isinstance(i.get("parent"), int)}
1327
+ numeric |= {int(l[k]) for l in plan.get("links", []) for k in ("from", "to") if isinstance(l.get(k), int)}
1328
+ if br:
1329
+ numeric.add(int(br))
1330
+ for it in fetch(sorted(numeric), fields=["System.WorkItemType", "System.Title", "System.State"]) if numeric else []:
1331
+ known_types[it["id"]] = it["fields"]["System.WorkItemType"]
1332
+ missing = numeric - set(known_types)
1333
+ if missing:
1334
+ errors.append(f"Work items not found: {sorted(missing)}")
1335
+ if br and known_types.get(int(br)) not in (None, "Business Request"):
1336
+ errors.append(f"#{br} is a {known_types[int(br)]}, not a Business Request.")
1337
+
1338
+ for it in items:
1339
+ key = it.get("key")
1340
+ if not key or key in keys:
1341
+ errors.append(f"Each item needs a unique 'key' (problem with {key!r}).")
1342
+ continue
1343
+ it["type"] = norm_type(it.get("type", ""))
1344
+ if it["type"] == "Business Request":
1345
+ errors.append(f"{key}: a plan cannot create Business Requests; use the create-business-request skill.")
1346
+ keys[key] = it
1347
+ known_types[key] = it["type"]
1348
+ f = it.get("fields", {})
1349
+ if not f.get("Title"):
1350
+ errors.append(f"{key}: Title is required.")
1351
+ bad = sorted(n for n in f if ref_of(n) in PLAN_FORBIDDEN)
1352
+ if bad:
1353
+ errors.append(f"{key}: estimates and dates are not allowed in a backlog plan: {bad}")
1354
+ parent = it.get("parent")
1355
+ if parent is not None:
1356
+ ptype = known_types.get(int(parent) if isinstance(parent, int) else parent)
1357
+ if ptype is None:
1358
+ errors.append(f"{key}: parent {parent!r} is unknown or defined after this item.")
1359
+ elif ptype not in ALLOWED_PARENT.get(it["type"], set()):
1360
+ errors.append(f"{key}: a {it['type']} cannot be a child of {article(ptype)} {ptype} ({parent!r}).")
1361
+ elif it["type"] in ("Feature", "Product Backlog Item", "Bug"):
1362
+ errors.append(f"{key}: a {it['type']} needs a parent.")
1363
+
1364
+ for l in plan.get("links", []):
1365
+ if l.get("type", "related") != "related":
1366
+ errors.append(f"Link {l}: only 'related' links are allowed here; hierarchy goes in 'parent'.")
1367
+ for end in ("from", "to"):
1368
+ v = l.get(end)
1369
+ if not (isinstance(v, int) or v in keys):
1370
+ errors.append(f"Link {l}: '{end}' must be a work item id or an item key.")
1371
+
1372
+ if "brParent" in plan:
1373
+ errors.append("brParent is not allowed: a Business Request never has a parent.")
1374
+
1375
+ if errors:
1376
+ die("Plan is not valid:\n- " + "\n- ".join(errors))
1377
+
1378
+ # Scores in the plan are derived, never independently estimated on Features.
1379
+ new_rating_previews = []
1380
+ for it in items:
1381
+ if it["type"] != "Feature":
1382
+ if any(ref_of(k) in SCORE_FIELDS for k in it.get("fields", {})):
1383
+ die(f"{it['key']}: ratings belong only to Features in a backlog plan.")
1384
+ continue
1385
+ if it.get("id"):
1386
+ continue
1387
+ if any(ref_of(k) == "System.State" and v != "New" for k, v in it["fields"].items()):
1388
+ die(f"{it['key']}: new Features must start in New; reconcile before commitment.")
1389
+ extra_brs = set()
1390
+ for link in plan.get("links", []):
1391
+ ends = (link["from"], link["to"])
1392
+ if it["key"] not in ends:
1393
+ continue
1394
+ other = ends[1] if ends[0] == it["key"] else ends[0]
1395
+ if isinstance(other, int) and known_types.get(other) == "Business Request":
1396
+ extra_brs.add(other)
1397
+ result = collect_feature_ratings({"fields": {"System.State": "New"}}, extra_brs)
1398
+ if result["status"] != "ready":
1399
+ die(f"{it['key']}: cannot derive Feature ratings: " + json.dumps(result))
1400
+ for name, value in it["fields"].items():
1401
+ if ref_of(name) in SCORE_FIELDS and value != result["fields"][FRIENDLY[ref_of(name)]]:
1402
+ die(f"{it['key']}: {name} must equal the maximum of linked BRs.")
1403
+ it["fields"] = {k: v for k, v in it["fields"].items() if ref_of(k) not in SCORE_FIELDS}
1404
+ it["fields"].update(result["fields"])
1405
+ new_rating_previews.append({**result, "key": it["key"], "status": "would_create"})
1406
+
1407
+ report = {"dry_run": a.dry_run, "created": [], "skipped": [], "links": [], "comment": None}
1408
+
1409
+ def save():
1410
+ if not a.dry_run and a.plan != "-":
1411
+ with open(a.plan, "w", encoding="utf-8") as fh:
1412
+ json.dump(plan, fh, indent=2, ensure_ascii=False)
1413
+
1414
+ for it in items:
1415
+ if it.get("id"):
1416
+ report["skipped"].append({"key": it["key"], "id": it["id"], "reason": "already created"})
1417
+ continue
1418
+ parent = resolve(it.get("parent")) if it.get("parent") is not None else None
1419
+ if a.dry_run:
1420
+ # parents created in this plan don't exist yet: validate the item on its own
1421
+ res = create_item(it["type"], it["fields"], parent if isinstance(parent, int) else None, dry_run=True)
1422
+ res.update({"key": it["key"], "parent": it.get("parent")})
1423
+ else:
1424
+ res = create_item(it["type"], it["fields"], parent)
1425
+ it["id"] = res["id"]
1426
+ save()
1427
+ res["key"] = it["key"]
1428
+ report["created"].append(res)
1429
+
1430
+ for l in plan.get("links", []):
1431
+ src, tgt = resolve(l["from"]), resolve(l["to"])
1432
+ if a.dry_run and (isinstance(src, str) or isinstance(tgt, str)):
1433
+ report["links"].append({"dry_run": True, "from": l["from"], "to": l["to"], "comment": l.get("comment")})
1434
+ continue
1435
+ report["links"].append(add_link(src, tgt, "related", l.get("comment"), a.dry_run, sync_scores=False))
1436
+
1437
+ affected_features = {int(it["id"]) for it in items if it["type"] == "Feature" and it.get("id")}
1438
+ for link in plan.get("links", []):
1439
+ for end in ("from", "to"):
1440
+ ref = link[end]
1441
+ fid = resolve(ref)
1442
+ if isinstance(fid, int) and known_types.get(ref) == "Feature":
1443
+ affected_features.add(fid)
1444
+ pending_brs = {fid: set() for fid in affected_features}
1445
+ for link in plan.get("links", []):
1446
+ for feature_end, br_end in (("from", "to"), ("to", "from")):
1447
+ feature_ref, br_ref = link[feature_end], link[br_end]
1448
+ fid = resolve(feature_ref)
1449
+ if fid in pending_brs and known_types.get(br_ref) == "Business Request":
1450
+ pending_brs[fid].add(resolve(br_ref))
1451
+ report["feature_ratings"] = [sync_feature_ratings(fid, a.dry_run,
1452
+ extra_br_ids=pending_brs[fid] if a.dry_run else ())
1453
+ for fid in sorted(affected_features)]
1454
+ if a.dry_run:
1455
+ report["feature_ratings"].extend(new_rating_previews)
1456
+
1457
+ if br and plan.get("brComment") and not plan.get("brCommentPosted"):
1458
+ report["comment"] = add_comment(int(br), plan["brComment"], a.dry_run)
1459
+ if not a.dry_run:
1460
+ plan["brCommentPosted"] = True
1461
+ save()
1462
+ out(report)
1463
+
1464
+
1465
+ # ---------- setup: doctor and eject ----------
1466
+
1467
+ DOCTOR_CHECKS = ("config", "az", "project", "types", "fields", "states", "iterations", "create")
1468
+ DOCTOR_HELP = """\
1469
+ Read-only check of the Human Backlog Config and the Azure DevOps process. Writes nothing.
1470
+
1471
+ Checks, in order: config, az (signed in for the tenant), project (reachable), types (the five
1472
+ work-item types), fields (every process field the skills use), states (exactly the eight Human
1473
+ States on Business Request), iterations (the default team has iterations), create (Azure DevOps
1474
+ validates, without saving, one create per type with only the fields the skills always set, so a
1475
+ required field that intake may leave empty is a mismatch). A failing config,
1476
+ az or project check skips the checks after it. JSON status is "ready" when every check passes (exit 0);
1477
+ otherwise "blocked" with every mismatch (exit 1)."""
1478
+
1479
+ PACKAGE = "@collective-intelligence/backlog"
1480
+ # The Human Backlog skills an Eject carries; in an HI repo other skills sit beside them.
1481
+ SKILL_NAMES = ("analyze-business-request", "create-bug", "create-business-request", "human-backlog-ado",
1482
+ "plan-sprint", "setup-human-backlog", "update-business-request")
1483
+ SKILLS_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
1484
+ EJECT_NAME = "human-backlog-skills.zip"
1485
+ # Where an ejected ado.py finds its config: CONFIG_FILE, beside the script.
1486
+ CONFIG_ENTRY = "human-backlog-ado/scripts/config.json"
1487
+ EJECT_SKIP_NAMES = {"tests", "__pycache__", ".DS_Store"}
1488
+ # The team keeps the process reference (Q33); an earlier Eject's config is replaced by CONFIG_ENTRY.
1489
+ EJECT_SKIP_FILES = {"setup-human-backlog/references/process.md", CONFIG_ENTRY}
1490
+ EJECT_HELP = """\
1491
+ Write one zip of the installed Human Backlog skills, without tests, plus
1492
+ human-backlog-ado/scripts/config.json (the resolved Human Backlog Config, where an ejected ado.py reads it)
1493
+ and MANIFEST.json (package, skillTreeSha256, configSha256, date). Makes no network call; run doctor first."""
1494
+
1495
+
1496
+ def attempt(fn, *args):
1497
+ """Run a helper that stops through die(); return (result, None) or (None, its error message)."""
1498
+ stderr = io.StringIO()
1499
+ try:
1500
+ with contextlib.redirect_stderr(stderr):
1501
+ return fn(*args), None
1502
+ except SystemExit:
1503
+ return None, json.loads(stderr.getvalue())["error"]
1504
+
1505
+
1506
+ def process_mismatches(work_item_types):
1507
+ """Compare the project's work-item types with PROCESS_FIELDS and the Human States."""
1508
+ types = {t["name"]: t for t in work_item_types}
1509
+ found = {
1510
+ "types": [f"Work item type {name} is missing." for name in PROCESS_FIELDS if name not in types],
1511
+ "fields": [f"{name} has no field {ref}." for name, refs in PROCESS_FIELDS.items() if name in types
1512
+ for ref in refs if ref not in {f["referenceName"] for f in types[name].get("fields", [])}],
1513
+ }
1514
+ if "Business Request" in types:
1515
+ states = [s["name"] for s in types["Business Request"].get("states", [])]
1516
+ found["states"] = ([f"Business Request has no Human State {s!r}." for s in BR_STATES if s not in states]
1517
+ + [f"Business Request state {s!r} is not a Human State." for s in states if s not in BR_STATES])
1518
+ return found
1519
+
1520
+
1521
+ # The fields the skills always set when they create each work-item type. `doctor` asks Azure DevOps
1522
+ # to validate one such minimal create per type (validateOnly saves nothing), so a process rule the
1523
+ # skills cannot meet is a mismatch before the first real create. That includes a required field
1524
+ # that intake may leave empty, such as Requester, RequestDate or SuccessCriteria.
1525
+ DOCTOR_CREATE = {
1526
+ "Epic": ("Title", "Description"),
1527
+ "Feature": ("Title", "Description", "AcceptanceCriteria", "BusinessValue", "Urgency"),
1528
+ "Business Request": ("Title", "Description", "Context", "TargetDate", "BusinessValue", "Urgency"),
1529
+ "Product Backlog Item": ("Title", "Description"),
1530
+ "Bug": ("Title", "ReproSteps"),
1531
+ }
1532
+
1533
+
1534
+ def create_mismatches(work_item_types):
1535
+ """Validate one create per process type the project has; the types and fields checks report the rest."""
1536
+ sample = {"Title": "Human Backlog doctor check", "Description": "Validated by ado.py doctor; not saved.",
1537
+ "AcceptanceCriteria": "- Validated", "Context": "doctor check",
1538
+ "TargetDate": (date.today() + timedelta(days=30)).isoformat(), "BusinessValue": 3, "Urgency": 3,
1539
+ "ReproSteps": "1. Validated by ado.py doctor"}
1540
+ types = {t["name"]: t for t in work_item_types}
1541
+ found = []
1542
+ for name, names in DOCTOR_CREATE.items():
1543
+ if name not in types:
1544
+ continue
1545
+ known = {f["referenceName"] for f in types[name].get("fields", [])}
1546
+ ops = field_ops({k: sample[k] for k in names if ref_of(k) in known})
1547
+ url = f"{pbase()}/_apis/wit/workitems/${urllib.parse.quote(name)}?validateOnly=true&api-version=7.1"
1548
+ _, error = attempt(call, "POST", url, ops, "application/json-patch+json")
1549
+ if error:
1550
+ found.append(f"Azure DevOps refuses to create {article(name)} {name}: {error}")
1551
+ return found
1552
+
1553
+
1554
+ def read_project():
1555
+ project = urllib.parse.quote(load_config()["project"], safe="")
1556
+ return call("GET", f"{base()}/_apis/projects/{project}?api-version=7.1")
1557
+
1558
+
1559
+ def doctor_findings():
1560
+ """Mismatches per doctor check; a check that could not run is absent."""
1561
+ found = {}
1562
+ for check, read in (("config", load_config), ("az", token), ("project", read_project)):
1563
+ _, error = attempt(read)
1564
+ found[check] = [error] if error else []
1565
+ if error:
1566
+ return found
1567
+ types, error = attempt(call, "GET", f"{pbase()}/_apis/wit/workitemtypes?api-version=7.1")
1568
+ found.update({"types": [error]} if error else process_mismatches(types.get("value", [])))
1569
+ iterations, error = attempt(call, "GET", f"{pbase()}/_apis/work/teamsettings/iterations?api-version=7.1")
1570
+ if error:
1571
+ found["iterations"] = [error]
1572
+ else:
1573
+ found["iterations"] = [] if iterations.get("value") else ["The default team has no iterations; plan-sprint needs them."]
1574
+ if types and "value" in types:
1575
+ found["create"] = create_mismatches(types["value"])
1576
+ return found
1577
+
1578
+
1579
+ def cmd_doctor(a):
1580
+ found = doctor_findings()
1581
+ checks = [{"check": c, "status": "skipped" if c not in found else "fail" if found[c] else "pass"}
1582
+ for c in DOCTOR_CHECKS]
1583
+ ready = all(check["status"] == "pass" for check in checks)
1584
+ out({"status": "ready" if ready else "blocked", "checks": checks,
1585
+ "mismatches": [f"{c}: {m}" for c in DOCTOR_CHECKS for m in found.get(c, [])]})
1586
+ if not ready:
1587
+ raise SystemExit(1)
1588
+
1589
+
1590
+ def skill_files():
1591
+ """Sorted (zip path, bytes) of every file of the installed Human Backlog skills that an Eject carries."""
1592
+ files = []
1593
+ for name in SKILL_NAMES:
1594
+ folder = os.path.join(SKILLS_DIR, name)
1595
+ if not os.path.isdir(folder):
1596
+ die(f"The Human Backlog skill {name} is not installed in {SKILLS_DIR}. Reinstall the skills, then eject.")
1597
+ for directory, dirs, names in os.walk(folder):
1598
+ dirs[:] = [d for d in dirs if d not in EJECT_SKIP_NAMES]
1599
+ for file_name in names:
1600
+ path = os.path.join(directory, file_name)
1601
+ rel = os.path.relpath(path, SKILLS_DIR).replace(os.sep, "/")
1602
+ if file_name not in EJECT_SKIP_NAMES and rel not in EJECT_SKIP_FILES:
1603
+ with open(path, "rb") as fh:
1604
+ files.append((rel, fh.read()))
1605
+ return sorted(files)
1606
+
1607
+
1608
+ def tree_sha256(files):
1609
+ """sha256 over each file's path, a NUL byte and the sha256 of its bytes, in path order."""
1610
+ digest = hashlib.sha256()
1611
+ for rel, data in files:
1612
+ digest.update(rel.encode() + b"\0" + hashlib.sha256(data).digest())
1613
+ return digest.hexdigest()
1614
+
1615
+
1616
+ def cmd_eject(a):
1617
+ config = load_config()
1618
+ config_bytes = (json.dumps({k: config[k] for k in CONFIG_ENV if k in config}, indent=2) + "\n").encode()
1619
+ files = skill_files()
1620
+ manifest = {"package": PACKAGE, "skillTreeSha256": tree_sha256(files),
1621
+ "configSha256": hashlib.sha256(config_bytes).hexdigest(), "date": date.today().isoformat()}
1622
+ entries = sorted([*files, (CONFIG_ENTRY, config_bytes),
1623
+ ("MANIFEST.json", (json.dumps(manifest, indent=2) + "\n").encode())])
1624
+ path = os.path.join(a.out, EJECT_NAME) if os.path.isdir(a.out) else a.out
1625
+ try:
1626
+ with zipfile.ZipFile(path, "w") as zf:
1627
+ for name, data in entries:
1628
+ info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
1629
+ info.external_attr = 0o644 << 16
1630
+ zf.writestr(info, data, zipfile.ZIP_DEFLATED)
1631
+ except OSError as e:
1632
+ die(f"Cannot write the Eject zip {path}: {e}")
1633
+ out({"zip": os.path.abspath(path), **manifest})
1634
+
1635
+
1636
+ def main():
1637
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
1638
+ sub = p.add_subparsers(dest="cmd", required=True)
1639
+
1640
+ sub.add_parser("whoami").set_defaults(fn=cmd_whoami)
1641
+
1642
+ s = sub.add_parser("get")
1643
+ s.add_argument("ids", nargs="+", type=int)
1644
+ s.add_argument("--relations", action="store_true", help="kept for readability; relations are always included")
1645
+ s.set_defaults(fn=cmd_get)
1646
+
1647
+ s = sub.add_parser("backlog")
1648
+ s.add_argument("--types", default="epic,feature,br")
1649
+ s.add_argument("--under", type=int, help="only descendants of this Epic/Feature")
1650
+ s.add_argument("--include-removed", action="store_true", help="also Removed / Rejected items")
1651
+ s.add_argument("--chars", type=int, default=600, help="truncate long text fields (0 = no limit)")
1652
+ s.set_defaults(fn=cmd_backlog)
1653
+
1654
+ s = sub.add_parser("search")
1655
+ s.add_argument("text")
1656
+ s.add_argument("--types", default="epic,feature,br,pbi")
1657
+ s.add_argument("--chars", type=int, default=400)
1658
+ s.set_defaults(fn=cmd_search)
1659
+
1660
+ s = sub.add_parser("create")
1661
+ s.add_argument("--type", required=True)
1662
+ s.add_argument("--json", required=True, help="file with {field: value}, or - for stdin")
1663
+ s.add_argument("--parent", type=int)
1664
+ s.add_argument("--dry-run", action="store_true", help="validate with Azure DevOps without saving")
1665
+ s.set_defaults(fn=cmd_create)
1666
+
1667
+ s = sub.add_parser("update")
1668
+ s.add_argument("id", type=int)
1669
+ s.add_argument("--json", required=True)
1670
+ s.add_argument("--expected-rev", type=int, help="reject if the item changed since the reviewed revision")
1671
+ s.add_argument("--dry-run", action="store_true")
1672
+ s.set_defaults(fn=cmd_update)
1673
+
1674
+ s = sub.add_parser("link")
1675
+ s.add_argument("source", type=int)
1676
+ s.add_argument("target", type=int)
1677
+ s.add_argument("--type", required=True, choices=sorted(LINK_TYPES))
1678
+ s.add_argument("--comment")
1679
+ s.add_argument("--dry-run", action="store_true")
1680
+ s.set_defaults(fn=cmd_link)
1681
+
1682
+ s = sub.add_parser("unlink")
1683
+ s.add_argument("source", type=int)
1684
+ s.add_argument("target", type=int)
1685
+ s.add_argument("--type", required=True, choices=["related"])
1686
+ s.add_argument("--expected-rev", type=int)
1687
+ s.add_argument("--dry-run", action="store_true")
1688
+ s.set_defaults(fn=cmd_unlink)
1689
+
1690
+ s = sub.add_parser("revision-check")
1691
+ s.add_argument("id", type=int, help="Business Request to revise")
1692
+ s.add_argument("--touch", nargs="*", type=int, default=[], help="existing Features/PBIs affected, including parents of new PBIs and changed links or ratings")
1693
+ s.add_argument("--shared-approved", nargs="*", type=int, default=[], help="shared Feature IDs with explicit user feedback for this exact proposed change")
1694
+ s.set_defaults(fn=cmd_revision_check)
1695
+
1696
+ s = sub.add_parser("planning-context")
1697
+ s.add_argument("--team", help="exact team name or ID; optional when only one team exists")
1698
+ s.add_argument("--iteration", help="exact configured iteration ID, path or unique name")
1699
+ s.set_defaults(fn=cmd_planning_context)
1700
+
1701
+ s = sub.add_parser("planning-check")
1702
+ s.add_argument("plan", help="temporary sprint proposal JSON; estimates are never written to Azure")
1703
+ s.set_defaults(fn=cmd_planning_check)
1704
+
1705
+ s = sub.add_parser("set-state", description=SET_STATE_HELP, formatter_class=argparse.RawDescriptionHelpFormatter)
1706
+ s.add_argument("id", type=int, metavar="ID", help="Business Request ID")
1707
+ s.add_argument("state", metavar="STATE", help="target Human State, for example \"In analysis\"")
1708
+ s.add_argument("--comment", required=True, help="why the state changes, in the request's language; saved as one comment")
1709
+ s.add_argument("--expected-rev", type=int, help="refuse if the request changed since this revision")
1710
+ s.add_argument("--dry-run", action="store_true", help="report the decision without writing")
1711
+ s.set_defaults(fn=cmd_set_state)
1712
+
1713
+ s = sub.add_parser("hyperlink", description="Add one Hyperlink relation to URL in one revision-tested patch. "
1714
+ "No write and status \"unchanged\" when the item already links URL; `get` lists it in hyperlinks.")
1715
+ s.add_argument("id", type=int, metavar="ID", help="work item ID")
1716
+ s.add_argument("url", metavar="URL", help="link target, for example the Fog page of a Business Request")
1717
+ s.add_argument("--comment", metavar="TEXT", help="link comment shown in Azure DevOps")
1718
+ s.set_defaults(fn=cmd_hyperlink)
1719
+
1720
+ s = sub.add_parser("unhyperlink", description="Remove the Hyperlink relation to URL in one revision-tested patch. "
1721
+ "No write and status \"unchanged\" when no Hyperlink links URL.")
1722
+ s.add_argument("id", type=int, metavar="ID", help="work item ID")
1723
+ s.add_argument("url", metavar="URL", help="exact URL of the Hyperlink to remove, for example a Superseded Fog")
1724
+ s.set_defaults(fn=cmd_unhyperlink)
1725
+
1726
+ s = sub.add_parser("comment")
1727
+ s.add_argument("id", type=int)
1728
+ g = s.add_mutually_exclusive_group(required=True)
1729
+ g.add_argument("--text")
1730
+ g.add_argument("--file")
1731
+ s.add_argument("--dry-run", action="store_true")
1732
+ s.set_defaults(fn=cmd_comment)
1733
+
1734
+ s = sub.add_parser("attach")
1735
+ s.add_argument("id", type=int)
1736
+ s.add_argument("--file", required=True, help="local evidence file")
1737
+ s.add_argument("--receipt", required=True, help="persistent local JSON receipt; reuse the same path when retrying")
1738
+ s.add_argument("--comment")
1739
+ s.add_argument("--dry-run", action="store_true", help="inspect local file and target without uploading or linking")
1740
+ s.set_defaults(fn=cmd_attach)
1741
+
1742
+ s = sub.add_parser("sync-ratings")
1743
+ s.add_argument("ids", nargs="*", type=int)
1744
+ s.add_argument("--all", dest="all_features", action="store_true", help="scan every Feature in New or Planned")
1745
+ s.add_argument("--dry-run", action="store_true")
1746
+ s.set_defaults(fn=cmd_sync_ratings)
1747
+
1748
+ s = sub.add_parser("apply")
1749
+ s.add_argument("plan")
1750
+ s.add_argument("--dry-run", action="store_true")
1751
+ s.set_defaults(fn=cmd_apply)
1752
+
1753
+ s = sub.add_parser("doctor", description=DOCTOR_HELP, formatter_class=argparse.RawDescriptionHelpFormatter)
1754
+ s.set_defaults(fn=cmd_doctor)
1755
+
1756
+ s = sub.add_parser("eject", description=EJECT_HELP, formatter_class=argparse.RawDescriptionHelpFormatter)
1757
+ s.add_argument("--out", required=True, metavar="PATH",
1758
+ help=f"zip file to write, or an existing directory to write {EJECT_NAME} in")
1759
+ s.set_defaults(fn=cmd_eject)
1760
+
1761
+ a = p.parse_args()
1762
+ if getattr(a, "chars", None) == 0:
1763
+ a.chars = None
1764
+ a.fn(a)
1765
+
1766
+
1767
+ if __name__ == "__main__":
1768
+ main()