diff --git a/CHANGELOG.md b/CHANGELOG.md index ae56000..0b5e8a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## 0.12.0 — 2026-11-04 + +Comments can be fixed and removed, and any change can be undone. + +- `ado_comment edit=` replaces a comment's text (markdown and `@[name]` mentions as when adding); + `edit=last` takes your own latest comment on the item - fixing what was just written without looking for its id. + The old text goes into the audit log, so `ado_undo` puts it back (unless someone changed the comment since). +- `ado_comment delete=`: a preview first (author, date, start of the text), then `confirm=`; + `ado_undo` adds the text back as a new comment (Azure DevOps gives it a new id and today's date). Only the author can + change or delete a comment in Azure DevOps; the error says so. +- `ado_work_item include=comments` shows each comment's id (`[comment 123]`). +- `ado_undo item=` reverts change n of the numbered `list=true`, `id=` the latest change on that item; + the preview names later changes on the same items. A confirm token always reverts what its preview showed. +- Fixed: a DELETE answered with an empty body (204) was reported as a failure ("The input does not contain any JSON + tokens") although it had worked - e.g. `ado_undo` of a comment. Every empty answer is now a success. +- CLI: `adolens comment --edit |last`, `--delete --confirm `; `adolens undo --item --id `. + ## 0.11.5 — 2026-10-27 - Fixed: the Environments tab of the settings window showed every row twice (two loads at once: choosing the diff --git a/README.md b/README.md index 6450bcd..8ad9ad5 100644 --- a/README.md +++ b/README.md @@ -225,7 +225,7 @@ What each MCP tool answers, when Claude should reach for it, and the CLI command | `ado_query` | items found by WIQL (with `@Me`, `@CurrentIteration`…) or a saved query, one line each | lists, filters, "open bugs of the sprint" | `adolens query --wiql "SELECT …"`, `adolens query --query "Shared Queries/Open bugs"` | | `ado_create` | creates an item from markdown; required fields, allowed values and people are checked first; `template` fills what is not given from a team template; soft length notes | writing stories, bugs, tasks | `adolens create --type Bug --title "…" --description "…" --field "Severity=2 - High"` | | `ado_update` | changes one or many items (ids or WIQL): fields, state along the transitions, people, tags `+a; -b`, iteration `current`, a comment; many items → preview + `confirm` token | closing, moving to a sprint, mass changes | `adolens update 123 --state Done --comment "…"`, `adolens update --wiql "…" --tags "+reviewed"` | -| `ado_comment` | markdown comment; `@[name]` mentions notify the person | asking, deciding, reporting | `adolens comment 123 "@[Anna] please confirm"` | +| `ado_comment` | markdown comment; `@[name]` mentions notify the person; `edit=` or `edit=last` (your latest) replaces a comment's text, `delete=` removes one after a preview; comment ids are in `ado_work_item include=comments` | asking, deciding, reporting | `adolens comment 123 "@[Anna] please confirm"` | | `ado_link` | parent, child, related, predecessor, successor, duplicate, duplicate-of, tested-by, tests; `remove` unlinks | structuring the backlog | `adolens link 123 456 --type child` | | `ado_sprint` | a team's sprint (`current`, `next`, `previous` or by name): dates and working day, items by state, estimates, remaining work against the capacity left, items needing attention (no change for days, blocked, no estimate, no criteria, unassigned), task progress per item; says plainly when the sprint has ended | stand-up, sprint review, "will we make it" | `adolens sprint`, `adolens sprint next --team "Demo Team" --detail summary` | | `ado_board` | a team's board: columns with WIP limits (over-limit flagged) and their cards; `move` + `column` moves a card — the state follows the column's mapping for the item's type | "what is in progress", moving cards | `adolens board`, `adolens board --move 123 --column "In Progress"` | @@ -250,7 +250,7 @@ What each MCP tool answers, when Claude should reach for it, and the CLI command | `ado_file` | a file by TFVC path, Git path + repo, or just its name (found through Code Search); X++ objects as their list of methods (tables, extensions, views also as fields, indexes and relations), `part` shows one method; without `version` it names the branch read; `history=true`: who changed it, when, through which pull request and for which work items | "what does this object do", "why is it like this" | `adolens file CreditCheck.xml --part validate`, `adolens file CreditCheck.xml --history` | | `ado_health` | backlog hygiene of a team's open items (newest first): no acceptance criteria, description, estimate or parent, no change for 14+ days while in progress, left in a finished sprint, look-alike titles (series like "Sprint 202 / 203" excluded); items done in the last 30 days without any linked code | refinement, keeping the backlog clean | `adolens health --team "Demo Team"` | | `ado_release_notes` | markdown release notes: requirements and bugs finished in a sprint or between dates, requirements grouped under their feature | sprint review, a release page on the wiki | `adolens release-notes previous`, `adolens release-notes --since 14d` | -| `ado_undo` | reverts the last change ADO Lens made: field values back (fields someone changed since are left and named), comment deleted, link removed or added back, a created item set to its removed state; always a preview first; `list=true` shows recent changes | "undo that", a mistaken mass change | `adolens undo --list`, `adolens undo` | +| `ado_undo` | reverts a change ADO Lens made - the last one, `item=` from the numbered `list=true`, or `id=` for the latest on that item (later changes on the same item are named in the preview): field values back (fields someone changed since are left and named), comment deleted, link removed or added back, a created item set to its removed state; always a preview first; `list=true` shows recent changes | "undo that", a mistaken mass change | `adolens undo --list`, `adolens undo` | | `ado_recipe` | saved repeatable changes: steps with a WIQL query (or ids) and what to do with each item - fields, state, iteration `next`, tags, a comment, a child item from a template (`{title}`, `{id}`); `{parameters}`; every run previewed, then confirmed | "close the sprint", "set up a new customer" | `adolens recipe run close-sprint --param sprint="Demo\Sprint 6"`, `--yes` for Task Scheduler | ### Ready commands (prompts) and skills diff --git a/README.pl.md b/README.pl.md index 6e8a379..1f4b610 100644 --- a/README.pl.md +++ b/README.pl.md @@ -226,7 +226,7 @@ Na co odpowiada każde narzędzie MCP, kiedy Claude powinien po nie sięgnąć i | `ado_query` | elementy z WIQL (z `@Me`, `@CurrentIteration`…) albo z zapisanego zapytania, po jednej linii | listy, filtry, „otwarte bugi sprintu” | `adolens query --wiql "SELECT …"`, `adolens query --query "Shared Queries/Open bugs"` | | `ado_create` | tworzy element z markdownu; najpierw sprawdza pola wymagane, dozwolone wartości i osoby; `template` uzupełnia brakujące wartości z szablonu zespołu; miękkie uwagi o długości | pisanie historii, bugów, zadań | `adolens create --type Bug --title "…" --description "…" --field "Severity=2 - High"` | | `ado_update` | zmienia jeden lub wiele elementów (id albo WIQL): pola, stan zgodnie z przejściami, osoby, tagi `+a; -b`, iteracja `current`, komentarz; wiele elementów → podgląd + token `confirm` | zamykanie, przenoszenie do sprintu, zmiany masowe | `adolens update 123 --state Done --comment "…"`, `adolens update --wiql "…" --tags "+reviewed"` | -| `ado_comment` | komentarz w markdownie; `@[imię]` oznacza osobę i wysyła jej powiadomienie | pytania, decyzje, raporty | `adolens comment 123 "@[Anna] potwierdź proszę"` | +| `ado_comment` | komentarz w markdownie; `@[imię]` oznacza osobę i wysyła jej powiadomienie; `edit=` albo `edit=last` (twój ostatni) podmienia treść komentarza, `delete=` usuwa go po podglądzie; id komentarzy widać w `ado_work_item include=comments` | pytania, decyzje, raporty | `adolens comment 123 "@[Anna] potwierdź proszę"` | | `ado_link` | rodzic, dziecko, powiązany, poprzednik, następnik, duplikat, duplikat-czego, testowany-przez, testuje; `remove` usuwa | porządkowanie backlogu | `adolens link 123 456 --type child` | | `ado_sprint` | sprint zespołu (`current`, `next`, `previous` albo po nazwie): daty i dzień roboczy, elementy według stanu, szacunki, pozostała praca wobec pozostałej pojemności, elementy do uwagi (bez zmian od kilku dni, zablokowane, bez szacunku, bez kryteriów, bez osoby), postęp zadań per element; mówi wprost, gdy sprint się skończył | daily, przegląd sprintu, „czy zdążymy” | `adolens sprint`, `adolens sprint next --team "Demo Team" --detail summary` | | `ado_board` | tablica zespołu: kolumny z limitami WIP (przekroczenia oznaczone) i ich karty; `move` + `column` przesuwa kartę — stan wynika z mapowania kolumny dla typu elementu | „co jest w toku”, przesuwanie kart | `adolens board`, `adolens board --move 123 --column "In Progress"` | @@ -251,7 +251,7 @@ Na co odpowiada każde narzędzie MCP, kiedy Claude powinien po nie sięgnąć i | `ado_file` | plik po ścieżce TFVC, ścieżce Git + repo albo samej nazwie (szukanej przez Code Search); obiekty X++ jako lista metod (tabele, rozszerzenia, widoki także jako pola, indeksy i relacje), `part` pokazuje jedną metodę; bez `version` podaje, z której gałęzi czyta; `history=true`: kto zmieniał, kiedy, w którym pull requeście i dla jakich work itemów | „co robi ten obiekt”, „dlaczego tak działa” | `adolens file CreditCheck.xml --part validate`, `adolens file CreditCheck.xml --history` | | `ado_health` | higiena otwartych elementów zespołu (od najnowszych): brak kryteriów akceptacji, opisu, szacunku albo rodzica, w toku bez zmian od 14+ dni, zostawione w zakończonym sprincie, podobne tytuły (serie typu „Sprint 202 / 203” pominięte); elementy zakończone w ostatnich 30 dniach bez powiązanego kodu | refinement, porządek w backlogu | `adolens health --team "Demo Team"` | | `ado_release_notes` | notatki wydania w markdownie: wymagania i błędy zakończone w sprincie albo między datami, wymagania pogrupowane pod feature'ami | przegląd sprintu, strona wydania na wiki | `adolens release-notes previous`, `adolens release-notes --since 14d` | -| `ado_undo` | cofa ostatnią zmianę zrobioną przez ADO Lens: przywraca wartości pól (pola zmienione w międzyczasie przez innych zostają i są wymienione), usuwa komentarz, usuwa lub przywraca link, utworzony element przestawia w stan usunięty; zawsze najpierw podgląd; `list=true` pokazuje ostatnie zmiany | „cofnij to”, pomyłka przy zmianie wsadowej | `adolens undo --list`, `adolens undo` | +| `ado_undo` | cofa zmianę zrobioną przez ADO Lens - ostatnią, `item=` z ponumerowanej listy `list=true` albo `id=` dla ostatniej zmiany w tym elemencie (późniejsze zmiany w tym samym elemencie są wymienione w podglądzie): przywraca wartości pól (pola zmienione w międzyczasie przez innych zostają i są wymienione), usuwa komentarz, usuwa lub przywraca link, utworzony element przestawia w stan usunięty; zawsze najpierw podgląd; `list=true` pokazuje ostatnie zmiany | „cofnij to”, pomyłka przy zmianie wsadowej | `adolens undo --list`, `adolens undo` | | `ado_recipe` | zapisane powtarzalne zmiany: kroki z zapytaniem WIQL (albo id) i tym, co zrobić z każdym elementem - pola, stan, iteracja `next`, tagi, komentarz, element podrzędny z szablonu (`{title}`, `{id}`); `{parametry}`; każde uruchomienie najpierw podgląd, potem potwierdzenie | „zamknij sprint”, „nowy klient” | `adolens recipe run close-sprint --param sprint="Demo\Sprint 6"`, `--yes` dla Harmonogramu zadań | ### Gotowe polecenia (prompty) i skille diff --git a/src/AdoLens/AdoClient.cs b/src/AdoLens/AdoClient.cs index a30e853..9003f80 100644 --- a/src/AdoLens/AdoClient.cs +++ b/src/AdoLens/AdoClient.cs @@ -187,8 +187,16 @@ public async Task SendAsync(HttpMethod method, string url, object? } await EnsureSuccessAsync(res, ct); var etag = res.Headers.ETag?.Tag ?? (res.Headers.TryGetValues("ETag", out var tags) ? tags.FirstOrDefault() : null); + // No content (204, or an empty body without a length - a DELETE): done, nothing to read. + if (res.StatusCode == HttpStatusCode.NoContent || res.Content.Headers.ContentLength == 0) return (default, etag); + if (res.Content.Headers.ContentLength is null) + { + var bytes = await res.Content.ReadAsByteArrayAsync(ct); + if (bytes.AsSpan().Trim(" \r\n\t"u8).Length == 0) return (default, etag); + using var small = JsonDocument.Parse(bytes); + return (small.RootElement.Clone(), etag); + } await using var stream = await res.Content.ReadAsStreamAsync(ct); - if (res.Content.Headers.ContentLength == 0) return (default, etag); using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: ct); return (doc.RootElement.Clone(), etag); } diff --git a/src/AdoLens/AdoLens.csproj b/src/AdoLens/AdoLens.csproj index 1de9ba8..f1a7600 100644 --- a/src/AdoLens/AdoLens.csproj +++ b/src/AdoLens/AdoLens.csproj @@ -25,7 +25,7 @@ ADO Lens for Azure DevOps Azure DevOps (work items, boards, wiki, Git and TFVC, pipelines) served to AI assistants over MCP Copyright © 2026 WillowDev - 0.11.5 + 0.12.0 diff --git a/src/AdoLens/Audit.cs b/src/AdoLens/Audit.cs index fbec3f8..d4b3e50 100644 --- a/src/AdoLens/Audit.cs +++ b/src/AdoLens/Audit.cs @@ -13,7 +13,7 @@ public sealed record AuditEntry { public string Batch { get; init; } = ""; public DateTime Utc { get; init; } - /// update | create | comment | link-add | link-remove | undone (Batch: the batch reverted). + /// update | create | comment | comment-edit | comment-delete | link-add | link-remove | undone (Batch: the batch reverted). public string Kind { get; init; } = ""; public int Id { get; init; } public string? Project { get; init; } @@ -22,6 +22,9 @@ public sealed record AuditEntry public Dictionary? Before { get; init; } public Dictionary? After { get; init; } public int? CommentId { get; init; } + /// A comment's text (HTML) before and after an edit; before a delete. + public string? BeforeText { get; init; } + public string? AfterText { get; init; } public string? Rel { get; init; } public int? Target { get; init; } public string? Tool { get; init; } @@ -108,7 +111,7 @@ public static List FromOps(string batch, string tool, JsonElement be public static int? TargetOf(string? url) => url is not null && int.TryParse(url[(url.LastIndexOf('/') + 1)..], out var t) ? t : null; - static string Token(string batch) => + internal static string Token(string batch) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes("undo:" + batch)))[..8].ToLowerInvariant(); static string Describe(AuditEntry e) => e.Kind switch @@ -117,6 +120,8 @@ static string Token(string batch) => $"{kv.Key.Split('.')[^1]} {Formatting.Collapse(e.After!.GetValueOrDefault(kv.Key) ?? "-", 30)} -> {Formatting.Collapse(kv.Value ?? "-", 30)}")), "create" => $"#{e.Id} {e.Title}: created -> set to a removed state", "comment" => $"#{e.Id} {e.Title}: comment {e.CommentId} deleted", + "comment-edit" => $"#{e.Id}: comment {e.CommentId} back to \"{Formatting.Collapse(Html.ToMarkdown(e.BeforeText), 60)}\"", + "comment-delete" => $"#{e.Id}: deleted comment added back (as a new comment): \"{Formatting.Collapse(Html.ToMarkdown(e.BeforeText), 60)}\"", "link-add" => $"#{e.Id}: link {Short(e.Rel)} #{e.Target} removed", "link-remove" => $"#{e.Id}: link {Short(e.Rel)} #{e.Target} added back", _ => e.Kind, @@ -124,15 +129,23 @@ static string Token(string batch) => static string Short(string? rel) => rel?.Split('.')[^1] ?? "?"; - /// The last changes ADO Lens made (latest first), which ado_undo would revert. - public static string List(Lens lens, string? connection, int top) + /// The last changes ADO Lens made (latest first), numbered for ado_undo item=; with a work item id only its changes. + public static string List(Lens lens, string? connection, int top, int? workItem = null) { var cfg = lens.For(connection).Config; var batches = Open(Read(lens, cfg.Connection)); if (batches.Count == 0) return "no changes by ADO Lens to undo on this connection"; - var sb = new StringBuilder($"changes by ADO Lens on {cfg.Connection}, latest first (undo reverts the first):\n"); - foreach (var batch in batches.Take(Math.Clamp(top, 1, 20))) - sb.AppendLine($"- {batch[0].Utc.ToLocalTime():yyyy-MM-dd HH:mm} {batch[0].Tool}: {string.Join(" | ", batch.Take(5).Select(Describe))}{(batch.Count > 5 ? $" | … {batch.Count - 5} more" : "")}"); + var sb = new StringBuilder($"changes by ADO Lens on {cfg.Connection}{(workItem is { } w ? $" touching #{w}" : "")}, latest first " + + "(ado_undo reverts the first; item= another, id= the latest on that item):\n"); + var shown = 0; + for (var i = 0; i < batches.Count && shown < Math.Clamp(top, 1, 20); i++) + { + var batch = batches[i]; + if (workItem is { } only && !batch.Any(e => e.Id == only)) continue; + shown++; + sb.AppendLine($"{i + 1}. {batch[0].Utc.ToLocalTime():yyyy-MM-dd HH:mm} {batch[0].Tool}: {string.Join(" | ", batch.Take(5).Select(Describe))}{(batch.Count > 5 ? $" | … {batch.Count - 5} more" : "")}"); + } + if (shown == 0) sb.AppendLine($"- none touching #{workItem}"); return sb.ToString().TrimEnd(); } @@ -148,17 +161,32 @@ static List> Open(List all) /// Reverts the last batch: always a preview first, written with its token. Fields someone changed after ADO Lens /// are left as they are and reported. /// - public static async Task UndoAsync(Lens lens, string? connection, string? confirm, CancellationToken ct = default) + public static async Task UndoAsync(Lens lens, string? connection, string? confirm, CancellationToken ct = default, int? item = null, int? workItem = null) { var session = lens.For(connection); var batches = Open(Read(lens, session.Config.Connection)); if (batches.Count == 0) return "nothing to undo: no changes by ADO Lens on this connection"; - var batch = batches[0]; + // The token names its batch: a confirm reverts what its preview showed, whichever it was. + var confirmed = confirm is { Length: > 0 } c ? batches.FirstOrDefault(b => string.Equals(Token(b[0].Batch), c.Trim(), StringComparison.OrdinalIgnoreCase)) : null; + var index = confirmed is not null ? batches.IndexOf(confirmed) + : item is { } nth ? nth - 1 + : workItem is { } w ? batches.FindIndex(b => b.Any(e => e.Id == w)) + : 0; + if (index < 0 || index >= batches.Count) + return item is not null ? $"no change {item} to undo (ado_undo list=true shows them)" : $"no change by ADO Lens on #{workItem} to undo"; + var batch = batches[index]; var token = Token(batch[0].Batch); - if (!string.Equals(confirm?.Trim(), token, StringComparison.OrdinalIgnoreCase)) - return $"UNDO PREVIEW - nothing written yet. The last change ({batch[0].Tool}, {batch[0].Utc.ToLocalTime():yyyy-MM-dd HH:mm}) would be reverted:\n" + + if (confirmed is null) + { + // An older change: say what came after it on the same items, so nothing newer is overwritten unseen. + var touched = batch.Select(e => e.Id).ToHashSet(); + var later = batches.Take(index).Where(b => b.Any(e => touched.Contains(e.Id))).ToList(); + return $"UNDO PREVIEW - nothing written yet. {(index == 0 ? "The last change" : $"Change {index + 1}")} ({batch[0].Tool}, {batch[0].Utc.ToLocalTime():yyyy-MM-dd HH:mm}) would be reverted:\n" + string.Join('\n', batch.Select(e => "- " + Describe(e))) + + (later.Count > 0 ? $"\nnote: {later.Count} later change(s) by ADO Lens touch the same item(s): " + + string.Join(" | ", later.Select(b => $"{b[0].Utc.ToLocalTime():MM-dd HH:mm} {b[0].Tool}")) + " - fields changed since are left as they are" : "") + $"\nShow this to the user. To revert it, call again with confirm={token}."; + } var work = session.Work; var ids = batch.Select(e => e.Id).Distinct().ToList(); @@ -194,6 +222,20 @@ await session.Client.SendAsync(HttpMethod.Delete, $"{AdoClient.Scope(e.Project!)}_apis/wit/workItems/{e.Id}/comments/{e.CommentId}?api-version=7.1-preview.4", null, null, ct); results.Add($"deleted the comment on #{e.Id}"); break; + case "comment-edit": + { + // Only when the comment still has the text ADO Lens wrote; an edit by someone since is kept. + var now = await work.CommentAsync(e.Project!, e.Id, e.CommentId!.Value, ct); + if (!Same(Html.ToMarkdown(Json.Str(now, "text")), Html.ToMarkdown(e.AfterText))) + { results.Add($"#{e.Id}: comment {e.CommentId} was changed since - left as it is"); break; } + await work.UpdateCommentAsync(e.Project!, e.Id, e.CommentId.Value, e.BeforeText ?? "", ct); + results.Add($"#{e.Id}: comment {e.CommentId} has its old text again"); + break; + } + case "comment-delete": + var back = await work.AddCommentAsync(e.Project!, e.Id, e.BeforeText ?? "", ct); + results.Add($"#{e.Id}: the deleted comment is back as comment {(back.TryGetProperty("id", out var bid) ? bid.ToString() : "?")} (today's date)"); + break; case "create": var s = (await session.Meta.GetAsync(e.Project!, ct)).Snapshot; var type = s.FindType(WorkItems.Field(wi, "System.WorkItemType") ?? ""); diff --git a/src/AdoLens/Cli.cs b/src/AdoLens/Cli.cs index 307ccc3..e7fceb2 100644 --- a/src/AdoLens/Cli.cs +++ b/src/AdoLens/Cli.cs @@ -45,7 +45,7 @@ refresh fetch the work item structure of a project now --connection create --type --title [--description ] [--criteria ] [--assign ] [--parent ] [--iteration ] [--area ] [--tags "a; b"] [--state ] [--field "Name=Value"]… update or --wiql ""; same options as create, plus --reason, --comment , --confirm - comment + comment --edit |last (replace) --delete --confirm link --type parent|child|related|predecessor|successor|duplicate|duplicate-of|tested-by|tests [--remove] sprint [current|next|previous|] --team --detail summary|normal|full board [] --team --move --column --detail summary|normal|full @@ -72,7 +72,7 @@ wiki [] --search --depth 2 --detail full --wiki label "" a D365 message as seen (values for %1 are fine) or @File:Id: label, languages, where used health backlog hygiene of the team --team release-notes [current|previous|] or --since 14d [--until yyyy-MM-dd] markdown for the wiki - undo revert the last change made by ADO Lens (preview, then --confirm ) --list + undo revert a change made by ADO Lens (preview, then --confirm ) --list --item --id recipe list | show | save --file | delete run [--param k=v]… [--confirm | --yes (no preview: Task Scheduler)] api raw JSON of a GET request (development) @@ -530,8 +530,13 @@ public async Task UpdateAsync() public async Task CommentAsync() { - if (cl.Positional.Count < 2 || !int.TryParse(cl.Positional[0], out var id)) { Console.Error.WriteLine("usage: adolens comment "); return 2; } - Print(await WorkQueries.CommentAsync(NewLens(), cl.Opt("connection"), id, string.Join(' ', cl.Positional.Skip(1)))); + var delete = cl.Opt("delete") is { } d && int.TryParse(d, out var dn) ? dn : (int?)null; + if (cl.Positional.Count < 1 || !int.TryParse(cl.Positional[0], out var id) || (cl.Positional.Count < 2 && delete is null)) + { + Console.Error.WriteLine("usage: adolens comment [--edit |last] | adolens comment --delete [--confirm ]"); + return 2; + } + Print(await WorkQueries.CommentAsync(NewLens(), cl.Opt("connection"), id, string.Join(' ', cl.Positional.Skip(1)), cl.Opt("edit"), delete, cl.Opt("confirm"))); return 0; } @@ -1032,7 +1037,9 @@ public async Task ReleaseNotesAsync() public async Task UndoAsync() { var lens = NewLens(); - Print(cl.Flag("list") ? Audit.List(lens, cl.Opt("connection"), 20) : await Audit.UndoAsync(lens, cl.Opt("connection"), cl.Opt("confirm"))); + var item = cl.Opt("item") is { } it && int.TryParse(it, out var itn) ? itn : (int?)null; + var wid = cl.Opt("id") is { } wi && int.TryParse(wi, out var win) ? win : (int?)null; + Print(cl.Flag("list") ? Audit.List(lens, cl.Opt("connection"), 20, wid) : await Audit.UndoAsync(lens, cl.Opt("connection"), cl.Opt("confirm"), default, item, wid)); return 0; } diff --git a/src/AdoLens/CommandLine.cs b/src/AdoLens/CommandLine.cs index 38f08dd..2650adb 100644 --- a/src/AdoLens/CommandLine.cs +++ b/src/AdoLens/CommandLine.cs @@ -28,7 +28,7 @@ public sealed partial class CommandLine ["query"] = ["connection=", "project=", "wiql=", "query=", "top="], ["create"] = ["connection=", "project=", "type=", "title=", "description=", "criteria=", "assign=", "parent=", "iteration=", "area=", "tags=", "state=", "field=", "template="], ["update"] = ["connection=", "ids=", "wiql=", "state=", "reason=", "title=", "description=", "criteria=", "assign=", "iteration=", "area=", "tags=", "field=", "comment=", "confirm="], - ["comment"] = ["connection="], + ["comment"] = ["connection=", "edit=", "delete=", "confirm="], ["sprint"] = ["connection=", "project=", "team=", "detail="], ["board"] = ["connection=", "project=", "team=", "detail=", "move=", "column="], ["backlog"] = ["connection=", "project=", "team=", "level=", "top=", "move=", "above=", "below="], @@ -52,7 +52,7 @@ public sealed partial class CommandLine ["metrics"] = ["connection=", "project=", "team=", "sprints="], ["health"] =["connection=", "project=", "team="], ["release-notes"] = ["connection=", "project=", "team=", "since=", "until="], - ["undo"] = ["connection=", "confirm=", "list"], + ["undo"] = ["connection=", "confirm=", "list", "item=", "id="], ["recipe"] = ["connection=", "file=", "param=", "confirm=", "yes"], }; diff --git a/src/AdoLens/McpTools.cs b/src/AdoLens/McpTools.cs index 2ee8efc..4c1742d 100644 --- a/src/AdoLens/McpTools.cs +++ b/src/AdoLens/McpTools.cs @@ -555,9 +555,13 @@ public static Task Update(Lens lens, }, comment, confirm, lens.Settings.ConfirmBulkAbove, ct)); [McpServerTool(Name = "ado_comment")] - [Description("Adds a markdown comment to a work item; @[name or e-mail] mentions and notifies a person.")] - public static Task Comment(Lens lens, int id, string text, string? connection = null, CancellationToken ct = default) - => McpTools.Run("ado_comment", new { id, connection }, () => WorkQueries.CommentAsync(lens, connection, id, text, ct)); + [Description("Adds a markdown comment to a work item; @[name or e-mail] mentions and notifies a person. edit=|last replaces a comment's text (last: your latest); delete= removes one after a preview (confirm). Comment ids: ado_work_item include=comments.")] + public static Task Comment(Lens lens, int id, string? text = null, + [Description("Comment id, or 'last' for your latest comment.")] string? edit = null, + int? delete = null, + [Description("Token from the delete preview.")] string? confirm = null, + string? connection = null, CancellationToken ct = default) + => McpTools.Run("ado_comment", new { id, edit, delete, confirm, connection }, () => WorkQueries.CommentAsync(lens, connection, id, text, edit, delete, confirm, ct)); [McpServerTool(Name = "ado_link")] [Description("Links a work item to others: parent, child, related, predecessor, successor, duplicate, duplicate-of, tested-by, tests; remove=true unlinks.")] @@ -620,10 +624,13 @@ public static Task Search(Lens lens, string text, => McpTools.Run("ado_search", new { text, scope, top, project, connection }, () => Knowledge.SearchAsync(lens, connection, project, text, scope, top, ct)); [McpServerTool(Name = "ado_undo")] - [Description("Reverts the last change ADO Lens made (fields, comment, link, created item): preview, then confirm=; list=true shows recent changes.")] - public static Task Undo(Lens lens, string? confirm = null, bool list = false, string? connection = null, CancellationToken ct = default) - => McpTools.Run("ado_undo", new { confirm, list, connection }, - () => list ? Task.FromResult(Audit.List(lens, connection, 10)) : Audit.UndoAsync(lens, connection, confirm, ct)); + [Description("Reverts a change ADO Lens made (fields, comment added, edited or deleted, link, created item): preview, then confirm=. The last one by default; item= from list=true, or id= for the latest on that item.")] + public static Task Undo(Lens lens, string? confirm = null, bool list = false, + [Description("Number of a change in list=true.")] int? item = null, + [Description("Work item: its latest change (with list=true: only its changes).")] int? id = null, + string? connection = null, CancellationToken ct = default) + => McpTools.Run("ado_undo", new { confirm, list, item, id, connection }, + () => list ? Task.FromResult(Audit.List(lens, connection, 10, id)) : Audit.UndoAsync(lens, connection, confirm, ct, item, id)); } [McpServerToolType, Toolset(Toolsets.Tests)] diff --git a/src/AdoLens/WorkItemFormat.cs b/src/AdoLens/WorkItemFormat.cs index 719da07..e265512 100644 --- a/src/AdoLens/WorkItemFormat.cs +++ b/src/AdoLens/WorkItemFormat.cs @@ -254,7 +254,9 @@ public static string Comments(List comments, int total) var who = Json.Str(Json.Obj(c, "createdBy"), "displayName"); var when = Date(Json.Str(c, "createdDate")); var text = Html.ToMarkdown(Json.Str(c, "text")); - sb.AppendLine($"- {when} {who}: {Formatting.Collapse(text, 800)}"); + // The id is what ado_comment edit= and delete= take. + var id = c.TryGetProperty("id", out var cid) ? $" [comment {cid}]" : ""; + sb.AppendLine($"- {when} {who}{id}: {Formatting.Collapse(text, 800)}"); } return sb.ToString().TrimEnd(); } diff --git a/src/AdoLens/WorkItems.cs b/src/AdoLens/WorkItems.cs index d28f2c4..4d0d630 100644 --- a/src/AdoLens/WorkItems.cs +++ b/src/AdoLens/WorkItems.cs @@ -156,6 +156,15 @@ public Task PatchAsync(int id, List ops, CancellationToken public Task AddCommentAsync(string project, int id, string html, CancellationToken ct = default) => client.PostAsync($"{AdoClient.Scope(project)}_apis/wit/workItems/{id}/comments?{CommentsApi}", new { text = html }, ct); + public Task CommentAsync(string project, int id, int commentId, CancellationToken ct = default) => + client.GetAsync($"{AdoClient.Scope(project)}_apis/wit/workItems/{id}/comments/{commentId}?{CommentsApi}", ct); + + public Task UpdateCommentAsync(string project, int id, int commentId, string html, CancellationToken ct = default) => + client.SendAsync(HttpMethod.Patch, $"{AdoClient.Scope(project)}_apis/wit/workItems/{id}/comments/{commentId}?{CommentsApi}", new { text = html }, "application/json", ct); + + public Task DeleteCommentAsync(string project, int id, int commentId, CancellationToken ct = default) => + client.SendAsync(HttpMethod.Delete, $"{AdoClient.Scope(project)}_apis/wit/workItems/{id}/comments/{commentId}?{CommentsApi}", null, null, ct); + // ---- writing --------------------------------------------------------------------------------------------------- /// diff --git a/src/AdoLens/WorkQueries.cs b/src/AdoLens/WorkQueries.cs index 981d07b..84d573a 100644 --- a/src/AdoLens/WorkQueries.cs +++ b/src/AdoLens/WorkQueries.cs @@ -265,14 +265,22 @@ public static async Task CommentHtmlAsync(Identities people, string mark CommentId = comment.ValueKind == JsonValueKind.Object && comment.TryGetProperty("id", out var cid) && cid.TryGetInt32(out var n) ? n : null, }; - public static async Task CommentAsync(Lens lens, string? connection, int id, string text, CancellationToken ct = default) + /// + /// Adds a comment; with (a comment id, or "last" for the user's own latest one) replaces a + /// comment's text; with removes a comment after a preview (confirm=token). Edits and + /// deletes are in the audit log, so ado_undo puts the old text back. + /// + public static async Task CommentAsync(Lens lens, string? connection, int id, string? text, string? edit = null, int? delete = null, + string? confirm = null, CancellationToken ct = default) { - if (string.IsNullOrWhiteSpace(text)) throw new ArgumentException("text is required"); var session = lens.For(connection); var items = await session.Work.GetAsync([id], relations: false, ["System.Id", "System.TeamProject", "System.WorkItemType", "System.State", "System.Title"], ct); if (items.Count == 0) return $"no work item #{id} visible with this PAT"; var project = WorkItems.Field(items[0], "System.TeamProject")!; + if (delete is { } gone) return await DeleteCommentAsync(lens, session, items[0], project, gone, confirm, ct); + if (string.IsNullOrWhiteSpace(text)) throw new ArgumentException("text is required"); var html = await CommentHtmlAsync(session.People, text, ct); + if (!string.IsNullOrWhiteSpace(edit)) return await EditCommentAsync(lens, session, items[0], project, edit.Trim(), html, ct); var added = await session.Work.AddCommentAsync(project, id, html, ct); Audit.Write(lens, session.Config.Connection, [CommentEntry(Audit.NewBatch(), "ado_comment", items[0], project, added)]); var mentions = Mention().Matches(text).Count; @@ -280,6 +288,57 @@ public static async Task CommentAsync(Lens lens, string? connection, int return $"commented on {WorkItemFormat.Header(items[0])}{(mentions > 0 ? $" ({mentions} mention(s) notified)" : "")}{note}"; } + static string Excerpt(JsonElement comment) => + $"{Json.Str(Json.Obj(comment, "createdBy"), "displayName")} {Json.Str(comment, "createdDate")?[..Math.Min(10, Json.Str(comment, "createdDate")!.Length)]}: " + + $"\"{Formatting.Collapse(Html.ToMarkdown(Json.Str(comment, "text")), 120)}\""; + + static string? ForbiddenHint(AdoApiException ex) => + ex.Status is System.Net.HttpStatusCode.Forbidden or System.Net.HttpStatusCode.Unauthorized or System.Net.HttpStatusCode.BadRequest + ? " - Azure DevOps lets only the author change or delete a comment" : null; + + static async Task EditCommentAsync(Lens lens, Session session, JsonElement wi, string project, string which, string html, CancellationToken ct) + { + JsonElement old; + if (which.Equals("last", StringComparison.OrdinalIgnoreCase)) + { + // The user's own latest comment: what was written a moment ago and needs fixing. + var (me, _) = await new Boards(session).MeAsync(ct); + var mine = (await session.Work.CommentsAsync(project, WorkItems.Id(wi), 200, ct)) + .LastOrDefault(c => string.Equals(Json.Str(Json.Obj(c, "createdBy"), "id"), me, StringComparison.OrdinalIgnoreCase)); + if (mine.ValueKind != JsonValueKind.Object) return $"{WorkItemFormat.Header(wi)}: no comment of yours to replace"; + old = mine; + } + else if (int.TryParse(which, out var cid)) old = await session.Work.CommentAsync(project, WorkItems.Id(wi), cid, ct); + else throw new ArgumentException("edit takes a comment id (ado_work_item include=comments shows them) or 'last'"); + var commentId = old.GetProperty("id").GetInt32(); + JsonElement now; + try { now = await session.Work.UpdateCommentAsync(project, WorkItems.Id(wi), commentId, html, ct); } + catch (AdoApiException ex) when (ForbiddenHint(ex) is { } hint) { throw new InvalidOperationException(ex.Message + hint); } + Audit.Write(lens, session.Config.Connection, [new AuditEntry + { + Batch = Audit.NewBatch(), Tool = "ado_comment", Kind = "comment-edit", Id = WorkItems.Id(wi), Project = project, Title = WorkItems.Field(wi, "System.Title"), + CommentId = commentId, BeforeText = Json.Str(old, "text"), AfterText = Json.Str(now, "text") ?? html, + }]); + return $"replaced comment {commentId} on {WorkItemFormat.Header(wi)} (was {Excerpt(old)}); ado_undo puts the old text back"; + } + + static async Task DeleteCommentAsync(Lens lens, Session session, JsonElement wi, string project, int commentId, string? confirm, CancellationToken ct) + { + var old = await session.Work.CommentAsync(project, WorkItems.Id(wi), commentId, ct); + var token = Audit.Token($"delete-comment:{session.Config.Connection}:{WorkItems.Id(wi)}:{commentId}"); + if (!string.Equals(confirm?.Trim(), token, StringComparison.OrdinalIgnoreCase)) + return $"DELETE PREVIEW - nothing deleted yet. Comment {commentId} on {WorkItemFormat.Header(wi)}:\n- {Excerpt(old)}\n" + + $"Show this to the user. To delete it, call again with confirm={token}. (ado_undo can add the text back later, as a new comment with today's date.)"; + try { await session.Work.DeleteCommentAsync(project, WorkItems.Id(wi), commentId, ct); } + catch (AdoApiException ex) when (ForbiddenHint(ex) is { } hint) { throw new InvalidOperationException(ex.Message + hint); } + Audit.Write(lens, session.Config.Connection, [new AuditEntry + { + Batch = Audit.NewBatch(), Tool = "ado_comment", Kind = "comment-delete", Id = WorkItems.Id(wi), Project = project, Title = WorkItems.Field(wi, "System.Title"), + CommentId = commentId, BeforeText = Json.Str(old, "text"), + }]); + return $"deleted comment {commentId} on {WorkItemFormat.Header(wi)} ({Excerpt(old)})"; + } + static readonly Dictionary LinkTypes = new(StringComparer.OrdinalIgnoreCase) { ["parent"] = "System.LinkTypes.Hierarchy-Reverse", diff --git a/tests/AdoLens.Tests/WorkItemTests.cs b/tests/AdoLens.Tests/WorkItemTests.cs index 92a99a8..d617c17 100644 --- a/tests/AdoLens.Tests/WorkItemTests.cs +++ b/tests/AdoLens.Tests/WorkItemTests.cs @@ -30,6 +30,9 @@ sealed class DemoItems public readonly List<(int Id, string Body)> Patches = []; public readonly List Created = []; public readonly List Comments = []; + /// PATCH bodies (comment id, body) and deleted comment ids. + public readonly List<(string Id, string Body)> CommentEdits = []; + public readonly List CommentDeletes = []; static JsonObject Item(int id, string type, string state, string title, string fields, string relations) => (JsonObject)JsonNode.Parse($$""" @@ -75,11 +78,26 @@ public FakeAdo Routes(FakeAdo ado) => ado }) .On("/contoso/Demo/_apis/wit/workItems/1/comments", r => { - if (r.Method == HttpMethod.Post) { Comments.Add(Body(r)); return Json("""{"id":1}"""); } + // One comment: /comments/ (GET, PATCH, DELETE with an empty 204 answer, as Azure DevOps does). + var last = r.RequestUri!.AbsolutePath.Split('/')[^1]; + if (int.TryParse(last, out _)) + { + if (r.Method == HttpMethod.Delete) { lock (CommentDeletes) CommentDeletes.Add(last); return new HttpResponseMessage(HttpStatusCode.NoContent); } + if (r.Method == HttpMethod.Patch) + { + var body = Body(r); + lock (CommentEdits) CommentEdits.Add((last, body)); + return Json(new JsonObject { ["id"] = int.Parse(last), ["text"] = JsonNode.Parse(body)!["text"]!.DeepClone() }.ToJsonString()); + } + return Json(last == "12" + ? """{"id":12,"text":"
Second
","createdBy":{"id":"p-ben","displayName":"Ben Kowalski"},"createdDate":"2026-10-02T10:00:00Z"}""" + : """{"id":11,"text":"
First idea
","createdBy":{"id":"p-anna","displayName":"Anna Nowak"},"createdDate":"2026-10-01T10:00:00Z"}"""); + } + if (r.Method == HttpMethod.Post) { Comments.Add(Body(r)); return Json("""{"id":13}"""); } return Json(""" {"comments":[ - {"text":"
Second
","createdBy":{"displayName":"Ben Kowalski"},"createdDate":"2026-10-02T10:00:00Z"}, - {"text":"
First idea
","createdBy":{"displayName":"Anna Nowak"},"createdDate":"2026-10-01T10:00:00Z"}]} + {"id":12,"text":"
Second
","createdBy":{"id":"p-ben","displayName":"Ben Kowalski"},"createdDate":"2026-10-02T10:00:00Z"}, + {"id":11,"text":"
First idea
","createdBy":{"id":"p-anna","displayName":"Anna Nowak"},"createdDate":"2026-10-01T10:00:00Z"}]} """); }) .On("/contoso/_apis/identities", r => Json(r.RequestUri!.Query.Contains("anna", StringComparison.OrdinalIgnoreCase) @@ -99,7 +117,8 @@ public class WorkItemTests : IDisposable public WorkItemTests() { - var ado = items.Routes(demo.Routes(new FakeAdo())); + var ado = items.Routes(demo.Routes(new FakeAdo())) + .On("/contoso/_apis/connectionData", """{"authenticatedUser":{"id":"p-anna","providerDisplayName":"Anna Nowak"}}"""); var s = new Settings { DefaultConnection = "contoso" }; s.Connections["contoso"] = new Connection { Organization = "contoso", Project = "Demo" }; lens = new Lens(s, "0.0.0", dir, _ => null, _ => "pat", _ => ado.Client()); @@ -147,8 +166,42 @@ public async Task Token_footer_ends_the_answer_when_switched_on() public async Task Comments_come_oldest_first_as_markdown() { var text = await WorkQueries.ItemAsync(lens, null, "1", "comments", "summary"); - var first = text.IndexOf("Anna Nowak: First **idea**", StringComparison.Ordinal); - Assert.True(first > 0 && first < text.IndexOf("Ben Kowalski: Second", StringComparison.Ordinal), text); + var first = text.IndexOf("Anna Nowak [comment 11]: First **idea**", StringComparison.Ordinal); + Assert.True(first > 0 && first < text.IndexOf("Ben Kowalski [comment 12]: Second", StringComparison.Ordinal), text); + } + + [Fact] + public async Task A_comment_is_replaced_deleted_after_a_preview_and_both_undone() + { + // edit=last: the user's own latest comment (Anna's 11, not Ben's newer 12). + var replaced = await WorkQueries.CommentAsync(lens, null, 1, "Better **idea**", edit: "last"); + Assert.StartsWith("replaced comment 11 on #1", replaced); + Assert.Contains("idea", items.CommentEdits.Single().Body.Replace("\\u003C", "<").Replace("\\u003E", ">")); + + // delete: a preview first, then the token. + var preview = await WorkQueries.CommentAsync(lens, null, 1, null, delete: 12); + Assert.StartsWith("DELETE PREVIEW - nothing deleted yet. Comment 12 on #1", preview); + Assert.Empty(items.CommentDeletes); + var token = System.Text.RegularExpressions.Regex.Match(preview, "confirm=([0-9a-f]+)").Groups[1].Value; + Assert.StartsWith("deleted comment 12 on #1", await WorkQueries.CommentAsync(lens, null, 1, null, delete: 12, confirm: token)); + Assert.Equal(["12"], items.CommentDeletes); // an empty 204 answer is a success + + // The list numbers the changes; item=2 is the edit (the delete is the latest), id=1 the latest on #1. + var list = Audit.List(lens, null, 10); + Assert.Contains("1. ", list); + Assert.Contains("2. ", list); + var undoEdit = await Audit.UndoAsync(lens, null, null, default, item: 2); + Assert.StartsWith("UNDO PREVIEW - nothing written yet. Change 2 (ado_comment", undoEdit); + Assert.Contains("1 later change(s) by ADO Lens touch the same item(s)", undoEdit); + var editToken = System.Text.RegularExpressions.Regex.Match(undoEdit, "confirm=([0-9a-f]+)").Groups[1].Value; + // The comment still has another text in this fake, so the old one is not forced back. + Assert.Contains("was changed since - left as it is", await Audit.UndoAsync(lens, null, editToken)); + + var undoDelete = await Audit.UndoAsync(lens, null, null, default, workItem: 1); + Assert.Contains("deleted comment added back", undoDelete); + var deleteToken = System.Text.RegularExpressions.Regex.Match(undoDelete, "confirm=([0-9a-f]+)").Groups[1].Value; + Assert.Contains("the deleted comment is back as comment 13", await Audit.UndoAsync(lens, null, deleteToken)); + Assert.Contains("Second", items.Comments.Last()); } [Fact]