From 06e3d82af8036530ef1d548dd424f918a586c35e Mon Sep 17 00:00:00 2001 From: Bakhomious Basta Date: Wed, 4 Nov 2026 20:35:16 +0100 Subject: [PATCH] feat(adf): render Jira's document format as Markdown internal/adf turns the Atlassian Document Format, the JSON of a Jira ticket's description and comments, into Markdown for the orchestrator and the user to read: the walk over a document's nodes, and the inline text with its marks, mentions, emoji, dates, cards and attachments. A node without a rule of its own shows its content, or the text that stands in for it, so the blocks that adf-blocks adds already come through as plain text. Decision 57 and fact 39 in docs/plan.md; the Jira row becomes adf, adf-blocks and jira. --- docs/plan.md | 8 ++- internal/adf/adf.go | 84 ++++++++++++++++++++++ internal/adf/adf_test.go | 80 +++++++++++++++++++++ internal/adf/block.go | 15 ++++ internal/adf/inline.go | 112 ++++++++++++++++++++++++++++++ internal/adf/testdata/blocks.json | 71 +++++++++++++++++++ internal/adf/testdata/blocks.md | 23 ++++++ internal/adf/testdata/inline.json | 38 ++++++++++ internal/adf/testdata/inline.md | 2 + internal/adf/testdata/text.json | 54 ++++++++++++++ internal/adf/testdata/text.md | 8 +++ 11 files changed, 493 insertions(+), 2 deletions(-) create mode 100644 internal/adf/adf.go create mode 100644 internal/adf/adf_test.go create mode 100644 internal/adf/block.go create mode 100644 internal/adf/inline.go create mode 100644 internal/adf/testdata/blocks.json create mode 100644 internal/adf/testdata/blocks.md create mode 100644 internal/adf/testdata/inline.json create mode 100644 internal/adf/testdata/inline.md create mode 100644 internal/adf/testdata/text.json create mode 100644 internal/adf/testdata/text.md diff --git a/docs/plan.md b/docs/plan.md index 6c1c7a1..32b949f 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -58,7 +58,9 @@ The first milestone is a walking skeleton (`skeleton`): one feature on a throwaw | `plugin-check` | `baton pane` checks the files of the plugin folder that it finds in its cache before each `copilot` starts, a role's after its wait too, and writes the plugin under the next name beside a changed folder; `baton hook guard` denies a role's `create` and `edit` in baton's cache, so that a role can't turn the guard off for the panes that start after it (decisions 36, 52 and 53, risk 12) | Done (#35) | | `guard-orchestrator` | In the orchestrator's pane, `baton hook guard` asks the user before each outward action, and before each `baton feature start` while `planApproval`, a new setting, is on; it lets baton's commands for the orchestrator run, denies the other commands that it watches, and denies `edit` and `create` outside the session's folder; the orchestrator runs with `--allow-all` (decisions 8, 19, 45 and 54; fact 37) | Done (#36) | | `belt` | Risk 2's second belt, in a role's pane: settings in the environment of the role's `copilot`, which each command and script there inherits, so that git's pushes out of the machine fail, sent by `pushInsteadOf` rules to a remote helper that doesn't exist, with a rule for each remote's URL and the remotes' push URLs cleared, and `gh` fails, its config folder under `/dev/null`; the pane goes without the GitHub tokens of the user's environment, and `copilot` gets `GH_TOKEN`'s or `GITHUB_TOKEN`'s as `COPILOT_GITHUB_TOKEN`, for its own login (decision 55, fact 38, risk 2) | Done (#37) | -| `gates` | The repo's gate, a new setting: the user's command that checks the repo's code, which the engineer's handover, QA's approval and the lead's final report run in the feature's worktree, and which refuses the handover while it fails; `baton start` and `baton feature start` refuse a repo without one, and the guard denies a role's `create` and `edit` in baton's config folder (decision 56, risk 13) | In review (#38) | +| `gates` | The repo's gate, a new setting: the user's command that checks the repo's code, which the engineer's handover, QA's approval and the lead's final report run in the feature's worktree, and which refuses the handover while it fails; `baton start` and `baton feature start` refuse a repo without one, and the guard denies a role's `create` and `edit` in baton's config folder (decision 56, risk 13) | Done (#38) | +| `adf` | `internal/adf`: the Atlassian Document Format, the JSON of a Jira ticket's description and comments, as Markdown to read: the walk over a document's nodes, and the inline text, with its marks, mentions, emoji, dates, cards and attachments; a node without a rule of its own shows its content, or the text that stands in for it (decision 57, fact 39) | In review (#39) | +| `adf-blocks` | `internal/adf`'s blocks: headings, lists and task lists, code blocks, quotes and panels, rules, tables and expands (decision 57) | Todo | | `jira` | `baton jira `: the ticket as text, from Jira's REST API with a read-only token in the Keychain (decision 6) | Todo | | `deliver-github` | `baton deliver` for GitHub: push the branch and open the pull request with `gh`, the lead's final report as its body | Todo | | `close` | `baton feature close `: ends the feature's session; keeps its branch and, unless asked, its worktree | Todo | @@ -134,6 +136,7 @@ Checked on 2026-10-31 with Copilot CLI 1.0.105 and tmux 3.8, unless a fact says 36. **The tools' arguments in a `preToolUse` hook** (Copilot CLI 1.0.105, on 2026-11-03, checked live). The hook's input names the tool in `toolName` and gives its arguments in `toolArgs`, which the hooks reference types as `unknown`, as a JSON object: for `bash`, `command` and `description`, with `mode` and, for an async call, `initial_wait` and `shellId` (the agent-wake spike's hook log); for `create`, `path` and `file_text`; for `edit`, `path`, `old_str` and `new_str`, the paths absolute, as the CLI's tool schemas ask. The input also has `sessionId`, `timestamp` and `cwd`. The answer `{"permissionDecision":"deny","permissionDecisionReason":…}` stops the tool, under `--allow-all` too, and the agent gets `Denied by preToolUse hook: ` with the reason, which a denial needs. The live check ran `copilot -p` with Claude Haiku 5.5, `--allow-all`, the plugin of `guard-hook` and a throwaway `COPILOT_HOME`, in a throwaway repo, for 0.21 AI credits: `baton hook guard` denied `tmux -V` and a `create` in baton's folder, and said nothing to a `create` and an `edit` of a file in the repo, which ran. Of a role's tools (decision 10), `bash`, `create` and `edit` write; `view`, `grep`, `glob` and `web_fetch` read; and `read_bash`, `stop_bash` and `list_bash` look after the shells that `bash` starts. 37. **The user's answer to a `preToolUse` hook's `ask`** (Copilot CLI 1.0.105, on 2026-11-03, checked live). In an interactive session under `--allow-all`, the answer `{"permissionDecision":"ask","permissionDecisionReason":…}` holds the tool and shows the "Hook permission request" of fact 4 in the pane: the reason, the tool's name and its arguments as JSON, and "Do you want to allow this tool call?". Yes runs the tool; No is a field for what the agent should do instead, which does nothing while it's empty. After a No, the agent gets `Denied by user via preToolUse hook prompt: ` with the reason, and `The user provided the following feedback: ` with the text; copilot puts a full stop after the reason, so a reason that ends in one shows two. The input's `sessionId` is the name of the session's folder in `$COPILOT_HOME/session-state/`. Without `COPILOT_ALLOW_ALL`, the folder-trust question still shows under `--allow-all` (fact 9), and the footer shows `Allow All`, where fact 27's showed `Manual Approval`. The live check ran the orchestrator's pane with Claude Haiku 5.5, the plugin of `guard-orchestrator` and a throwaway `COPILOT_HOME`, in a throwaway repo without a remote, on a tmux server of its own, for 0.32 AI credits: the guard asked about `git push --dry-run`, which the check declined with feedback, and about `baton feature start`, which it allowed, and whose script ran but failed with `baton: command not found`, since baton wasn't on the live pane's `PATH`; a `create` in the session's `files/` folder ran, and one in the repo was denied. 38. **What makes git's pushes and gh fail** (git 2.56.0, gh 2.103.2 and Copilot CLI 1.0.105, on 2026-11-04, in throwaway folders, against `.invalid` hosts and local paths). git reads the settings that `GIT_CONFIG_COUNT` counts in `GIT_CONFIG_KEY_` and `GIT_CONFIG_VALUE_` after its config files, and those of `git -c` after them; it reads the count as C's `strtoul` does, so it takes ` 1` and `+1`, and fails with 128 on `x`, and on `-1` (`too many entries`). A push to a remote's URL takes the `url..pushInsteadOf` rule whose prefix matches the most of the URL, and of equal ones the rule whose base git read first, or else an `insteadOf` rule; a remote's push URL (`remote..pushurl`) skips the `pushInsteadOf` rules, but not the `insteadOf` ones. Since git 2.46 (its release notes), an empty `pushurl` clears the remote's push URLs that git read before it, so its pushes go to its URL; an older git takes it for one more push URL, and still pushes to the others. git takes a URL for a path on the machine when it has no colon, or a slash before its first colon, or starts with `file://`; `https://…`, `ssh://…`, `git@host:repo`, `host:repo` and `[::1]:repo` leave the machine. A push to `::`, whose remote helper `git-remote-` isn't there, fails with 128 and `git: 'remote-' is not a git command`, before any network. `git send-pack` takes its URL as it is, with no rule: it went on to look the host up. `git config --get-regexp` exits with 1 when no setting matches. Copilot's `bash` tool adds three settings of its own after those that it inherits, `safe.bareRepository=explicit`, `credential.interactive=never` and `core.fsmonitor=false`, and raises `GIT_CONFIG_COUNT` to match; it keeps `GIT_CONFIG_PARAMETERS`, and reads `BASH_ENV` only with its `bashEnv` setting, off by default, which `--bash-env` saves in the user's config (`copilot help config`). With `GH_CONFIG_DIR` under a file, such as `/dev/null/x`, every `gh` command, `--version` and `auth` too, fails before it starts, with 1 and `failed to create root command: failed to read configuration: open /dev/null/x/config.yml: not a directory`, and writes nothing; with an empty folder, gh still takes the user's login from the Keychain (gh's source). Copilot CLI takes its GitHub token from `COPILOT_GITHUB_TOKEN`, then `GH_TOKEN`, then `GITHUB_TOKEN`, then its own login, which `copilot login` keeps in the Keychain, and last from `gh auth token` (`copilot help environment`, and GitHub's docs on its authentication). The belt (decision 55) was checked with `baton feature start` on a tmux server of its own, with a stand-in `copilot`, and once with the real one, offline (`COPILOT_OFFLINE`) with a stand-in model on 127.0.0.1, for 0 AI credits. In the lead's pane, pushes to `origin`, whose push URL the belt had cleared, and to typed `https` and scp-like URLs failed, pushes to a local remote and to a typed path went through, `gh --version` failed, and copilot's `bash` added its three settings after the belt's; the orchestrator's pane kept `GH_TOKEN`. +39. **The Atlassian Document Format** (Atlassian's docs, and its `@atlaskit/adf-schema` and `@atlaskit/editor-common` packages on npm, on 2026-11-04). Jira's REST API v3 gives a ticket's description and comments as ADF: a JSON tree of nodes, each with a `type`, and as the type needs, `content`, `attrs`, `text` and `marks`. ADF's JSON schema lists ten inline nodes, which flow in a line of text: `text`, `date`, `emoji`, `hardBreak`, `inlineCard`, `mention`, `placeholder`, `status`, `inlineExtension` and `mediaInline`; the rest are blocks. A task item, a decision item and a media's caption hold inline nodes as they are, not in a paragraph, and a task list holds task items, block task items and task lists. A `date`'s `timestamp` is a string of milliseconds since the epoch, which Atlassian's own renderer shows as the day in UTC (`timestampToIsoFormat`), though the docs' example, `1582152559`, reads as seconds. A `mention`, a `status` and an extension carry their text in `attrs.text`, an `emoji` in `attrs.text` or `attrs.shortName`, a card its address in `attrs.url`, and a `media` its alternative text in `attrs.alt`, and an external one its address in `attrs.url`. ## 3. Design @@ -213,7 +216,7 @@ Every change takes an exclusive lock on the feature (`flock` on its `lock` file, } ``` -**Jira** (decision 6). `baton jira DEMO-1` prints the ticket's summary, type, status, description (Atlassian Document Format turned into Markdown), subtasks, links and comments. It reads the token from the Keychain with `/usr/bin/security`, and the site's `cloudId` from the site. +**Jira** (decisions 6 and 57). `baton jira DEMO-1` prints the ticket's summary, type, status, description (the Atlassian Document Format turned into Markdown by `internal/adf`), subtasks, links and comments. It reads the token from the Keychain with `/usr/bin/security`, and the site's `cloudId` from the site. **Delivery.** `baton deliver ` pushes the branch and opens the pull request against the base branch, titled from the brief, with the lead's final report as its body: on GitHub with `gh pr create`, on Bitbucket Cloud with its REST API and a token from the Keychain. It never merges. @@ -279,6 +282,7 @@ Decisions marked **lead's call** are the lead's, for the user's end review. The 54. **`baton hook guard` asks the user in the orchestrator's pane** (lead's call, flagged; decisions 8, 17, 19, 45, 48, 49 and 52, facts 4, 28 and 37, risks 2 and 3). The orchestrator's `copilot` runs with `--allow-all`, so its tools run unasked, and the guard answers `ask` where the user should decide, which copilot shows in the pane with the reason and the call, for the user to allow, or to decline with a word for the orchestrator (fact 37); the orchestrator's prompt tells it to ask the user what they want instead. For `bash`, the guard reads the script's commands (decision 51). Baton's commands for the orchestrator run unasked: `baton wait`, `baton answer`, `baton handover`, `baton status` and baton's help. `baton feature start` asks while plan approval is on (decision 8), so the user checks the plan first, and runs unasked once `planApproval` is `false` (decision 49); the guard reads the config file only for a script that starts a feature, for the repo of the hook's folder, and a mistake in the file, or a folder outside a repo, fails the hook, so `copilot` denies the script (fact 4). An outward command asks, so the user approves each push and each pull request, until `baton deliver` comes (decision 17). The guard denies, with a reason for the orchestrator, `tmux` and `osascript`, another agent's CLI, baton's other commands, such as `baton ask` or `baton pane`, and, as in a role's pane (decision 52), a program that only the run decides and a script that it can't read. A script runs whole or not at all: a command that the guard denies denies the script, and otherwise the first command that asks names the question, so the user's yes runs the whole script. The guard names baton's `feature` and `hook` commands by two words (decision 52), so that `baton feature start` asks and a later `baton feature close` can differ. For `create` and `edit`, it denies a path outside the session's folder, `session-state/` in copilot's home folder, which `COPILOT_HOME` names in the pane, or else `~/.copilot`, with the walk of decision 52; the input's `sessionId` names the session (fact 37). A session ID that isn't one folder's name fails the hook, and a session's folder that isn't there holds nothing. The orchestrator keeps `ask_user` and copilot's folder-trust question (decision 45). The guard misses what it misses in a role's pane (decision 52): the orchestrator can write any file with `bash`, and run local commands, such as `rm`, unasked (risk 3), and `web_fetch` can send data in a URL. Its extra tools, such as nudge's, run unasked, and send what they send. The guard reads the plan approval of the hook's folder's repo, not of a repo that the script `cd`s into, and `baton feature start -h` asks too. Rejected: denying outward commands in this pane until `baton deliver` comes, which would leave the user no way to push from it; asking about every command, as copilot did before (decision 45), which buries the questions that matter among the rest; and copilot's `--deny-tool` rules, which only deny (fact 28). 55. **A role's pane runs with a second belt** (the user's call, 2026-11-04, for the git and `gh` parts; lead's call, flagged, for the rest; decisions 9, 17, 52 and 54, facts 28 and 38, risk 2). The guard sees only what a command shows (risk 2), so `baton pane` gives a role's `copilot` settings in its environment, which each command and script that the role runs inherits, whatever runs it, and which make git's pushes out of the machine and `gh` fail. For git, after the settings that `GIT_CONFIG_COUNT` counts in baton's own environment, which it keeps, it adds a `pushInsteadOf` rule for each character that starts a URL that leaves the machine, a letter, a digit or `[`, which sends the push to `baton-blocks-push::`, a remote helper that doesn't exist, so that git fails before any network and names baton's belt; a rule that keeps `file://` URLs as they are; and, for the remotes in git's config for the repo, the user's own config included, as the pane finds them when it starts, a rule for each remote's URL that leaves, which beats the user's own rules for a shorter prefix, and an empty `pushurl` for each remote with a push URL that leaves, which clears its push URLs, so that its pushes go to its URL. A git before 2.46, which can't clear them, gets an `insteadOf` rule for each such push URL instead, which also blocks fetches from the URLs that start with it (fact 38). Pushes to a path on the machine, `file://` URLs among them, still work, and fetches, pulls and clones don't change. For `gh`, `GH_CONFIG_DIR` names a folder under `/dev/null`, so that every `gh` command fails before it starts and never reaches the user's login in the Keychain, as it would with an empty folder (fact 38). The pane goes without `GH_TOKEN`, `GITHUB_TOKEN`, `GH_ENTERPRISE_TOKEN` and `GITHUB_ENTERPRISE_TOKEN`, which other tools would use; but `copilot` takes its own login from `GH_TOKEN` or `GITHUB_TOKEN`, or, after its own login, from `gh` (fact 38), so it gets the first of the two that is set as `COPILOT_GITHUB_TOKEN`, unless that is set already, and a user whose `copilot` logs in only through `gh` runs `copilot login` once (README). `baton pane` makes the belt before it waits, and fails when it can't: when git can't read the repo's config or its own version, or when `GIT_CONFIG_COUNT` is a count that git reads but Go doesn't, such as ` 1`, since baton can't tell then where to put its settings. The orchestrator's pane goes without the belt, since the user approves its outward actions there (decision 54). The costs: a push to a relative path that starts with a letter or a digit, such as `git push backup.git`, fails too, as does one to a git server on the machine by its URL, such as `http://localhost/…`; and the roles lose `gh`'s reads, which their prompts don't ask for. Like the guard, the belt stops a role's mistakes, and what the guard can't see, not a role that sets out to get past it (risk 2). Rejected: an empty `GH_CONFIG_DIR` folder, which leaves `gh` the user's login in the Keychain; `BASH_ENV`, which `copilot` reads only with a setting of the user's (fact 38); `copilot`'s deny rules, which match the command that the bash tool runs, as the guard does, not what it runs in turn (fact 28); and `copilot`'s command sandbox, whose policy, such as whether commands reach the network, lives in the user's settings, which each of their `copilot` sessions shares (risk 2). 56. **A repo's gate checks the code before each handover that vouches for it** (lead's call, flagged; the user's call, 2026-11-04, for its `//nolint:gosec`; decisions 13, 34, 49 and 52, fact 16, risk 13). The config file's `gate`, a setting like the others (decision 49), is the user's command that checks the repo's code, such as `mise run check`. The engineer's handover, QA's approval and the lead's final report run it, since each of these roles vouches for the code that it hands on; the rejections, the reviewer's approval, which follows QA's on the same code, the lead's brief and the orchestrator's moves don't. baton reads the gate at each of these handovers, for the repo of the role's folder, and runs it with `/bin/sh -c` in the feature's worktree, wherever in the repo the role runs baton, with baton's environment, the belt's in a role's pane (decision 55), nothing on its input, and its output and its errors on baton's output, in order, after a line that names the gate and the folder, so the role reads what failed. It runs once baton has checked the move and the role's open question on the feature as it stands, so a move that baton refuses runs no gate, and without the feature's lock, so that the other roles' `baton wait` and `baton status` don't wait for it; baton checks the move again under the lock when it writes the handover. A gate that fails refuses the handover, which changes nothing: the role fixes what failed, or, for QA, rejects with the failures. The journal logs the gate that a handover ran, with the handover. The gate has no time limit, since a check can take minutes; Ctrl-C or a hangup stops it, as it stops baton (decision 42): baton kills the gate's shell, and Ctrl-C reaches the commands that the shell started too, but a signal to baton alone leaves them to run to their end. Every repo needs a gate, so that none is forgotten: `baton start`, when it makes the orchestrator's session, and `baton feature start` refuse a repo without one, and say where to set it; `"gate": "true"` checks nothing, for a repo that has no checks. A gated handover refuses too, if the user takes the gate out while a feature runs; the others still go. The config file refuses a gate that is only spaces, and one that starts with `-`, which `sh -c` reads as its own options (bash, dash and zsh all do). The gate is a command line by design, the user's own, from the config file, which only the user writes, so its one place to run carries `//nolint:gosec` for G204, with its reason; decision 34's reason, arguments that no shell reads, doesn't fit it. The guard denies a role's `create` and `edit` in baton's config folder (decision 52), so a role's file tools can't change the gate, and a config folder that isn't there holds nothing, as no feature runs without the file; a role's `bash` still can, and a role can weaken the checks that the gate runs from inside the repo, such as its `mise.toml` (risk 13). Rejected: running the gate in the role's working folder, which may be any folder of the repo; a time limit, which would fail a slow but sound check; a repo without a gate, which would make the gate easy to forget; and gating QA's rejection, which reports a failure rather than vouching for the code. +57. **A ticket's text as Markdown, through `internal/adf`** (lead's call, flagged; decision 6, fact 39). `internal/adf` renders a ticket's ADF as Markdown for the orchestrator and the user to read, which takes far fewer tokens than the JSON, and which nobody needs to render: so the text stays as Jira has it, with no escapes, but for a `|` in a table's cell. Strong, em, strike, code and links show as Markdown's marks, code innermost and a link outermost, and the other marks, such as underline and colours, leave the text plain; code that holds backticks gets a longer fence. A mention, an emoji, a status, a card and an extension show their text or their address, a date its day in UTC, as Jira shows it, and a file or an image `[attachment]`, with its alternative text or its address, since text can't show it (fact 39). A node without a rule of its own, such as one that a later ADF adds, shows its content, or the text that stands in for it, so that each of a ticket's words reaches the orchestrator; a run of inline nodes in a block makes a paragraph. The converter came to about 240 lines, so it came in two steps, `adf`, the walk and the inline text, and `adf-blocks`, the blocks' structure, ahead of `jira`, so that each stays near 150 lines. Rejected: handing the orchestrator the ADF itself, which costs it many more tokens to read. ## 5. Risks diff --git a/internal/adf/adf.go b/internal/adf/adf.go new file mode 100644 index 0000000..610f649 --- /dev/null +++ b/internal/adf/adf.go @@ -0,0 +1,84 @@ +// Package adf renders the Atlassian Document Format, the JSON in which Jira's REST API gives a +// ticket's description and comments, as Markdown to read (decision 57). +package adf + +import ( + "cmp" + "slices" + "strings" +) + +// Node is a node of a document: a block, such as a paragraph or a table, or an inline node, such +// as a run of text or a mention. +type Node struct { + Type string `json:"type"` + Text string `json:"text"` + Attrs map[string]any `json:"attrs"` + Marks []Mark `json:"marks"` + Content []Node `json:"content"` +} + +// Mark styles a run of text, such as strong or a link. +type Mark struct { + Type string `json:"type"` + Attrs map[string]any `json:"attrs"` +} + +// Markdown renders a node, most often a whole document, as Markdown. The Markdown is for reading, +// so the text stays as Jira has it, and a node that text can't show, such as an image, leaves a +// word in its place. A node of an unknown type shows its content, or the text that stands in for +// it. +func Markdown(node Node) string { + return blocks([]Node{node}) +} + +// blocks renders nodes one after the other, with a blank line between them. A run of inline +// nodes makes one block, and an empty block makes none. +func blocks(nodes []Node) string { + parts := make([]string, 0, len(nodes)) + for len(nodes) > 0 { + var part string + if run := inlineRun(nodes); run > 0 { + part, nodes = inline(nodes[:run]), nodes[run:] + } else { + part, nodes = block(nodes[0]), nodes[1:] + } + + if part != "" { + parts = append(parts, part) + } + } + + return strings.Join(parts, "\n\n") +} + +// inlineRun returns how many of the nodes, from the first on, are inline nodes. +func inlineRun(nodes []Node) int { + end := slices.IndexFunc(nodes, func(node Node) bool { return !isInline(node.Type) }) + if end < 0 { + return len(nodes) + } + + return end +} + +// isInline tells the nodes that flow in a line of text from the blocks. +func isInline(kind string) bool { + return slices.Contains([]string{ + "text", "hardBreak", "mention", "emoji", "date", "status", "inlineCard", + "inlineExtension", "placeholder", "mediaInline", + }, kind) +} + +// standIn returns the text that stands in for a node without content: a mention's name, an +// emoji, a status, a card's address or an extension's text. +func standIn(node Node) string { + return cmp.Or(attr(node.Attrs, "text"), attr(node.Attrs, "shortName"), attr(node.Attrs, "url")) +} + +// attr returns the text of the attribute, or "" if there is none. +func attr(attrs map[string]any, key string) string { + text, _ := attrs[key].(string) + + return text +} diff --git a/internal/adf/adf_test.go b/internal/adf/adf_test.go new file mode 100644 index 0000000..fba1191 --- /dev/null +++ b/internal/adf/adf_test.go @@ -0,0 +1,80 @@ +package adf_test + +import ( + "encoding/json/v2" + "io/fs" + "os" + "strings" + "testing" + "time" + + "github.com/codedogapp/baton/internal/adf" +) + +// TestMain puts the tests in a zone east of UTC, so that a date shown in the machine's zone, not +// in UTC, fails them, wherever they run. +func TestMain(m *testing.M) { + time.Local = time.FixedZone("UTC+2", int((2 * time.Hour).Seconds())) + + m.Run() +} + +// TestMarkdown renders each document in testdata and compares it with the Markdown beside it. +func TestMarkdown(t *testing.T) { + testdata := os.DirFS("testdata") + + docs, err := fs.Glob(testdata, "*.json") + if err != nil || len(docs) == 0 { + t.Fatalf("no documents in testdata: %v", err) + } + + for _, doc := range docs { + name := strings.TrimSuffix(doc, ".json") + t.Run(name, func(t *testing.T) { + var node adf.Node + if err := json.Unmarshal(read(t, testdata, doc), &node); err != nil { + t.Fatal(err) + } + + want := strings.TrimSuffix(string(read(t, testdata, name+".md")), "\n") + if got := adf.Markdown(node); got != want { + t.Errorf("Markdown() =\n%s\nwant:\n%s", got, want) + } + }) + } +} + +func TestMarkdownOfOneNode(t *testing.T) { + tests := []struct { + name string + node adf.Node + want string + }{ + {"nothing", adf.Node{}, ""}, + {"an inline node", adf.Node{Type: "text", Text: "plain"}, "plain"}, + { + "an unknown node", + adf.Node{Type: "future", Content: []adf.Node{{Type: "media"}}}, + "[attachment]", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := adf.Markdown(tt.node); got != tt.want { + t.Errorf("Markdown() = %q, want %q", got, tt.want) + } + }) + } +} + +func read(t *testing.T, files fs.FS, path string) []byte { + t.Helper() + + data, err := fs.ReadFile(files, path) + if err != nil { + t.Fatal(err) + } + + return data +} diff --git a/internal/adf/block.go b/internal/adf/block.go new file mode 100644 index 0000000..88197d8 --- /dev/null +++ b/internal/adf/block.go @@ -0,0 +1,15 @@ +package adf + +import "cmp" + +// block renders a block node. +func block(node Node) string { + switch node.Type { + case "paragraph": + return inline(node.Content) + case "media": + return attachment(node) + default: + return cmp.Or(blocks(node.Content), standIn(node)) + } +} diff --git a/internal/adf/inline.go b/internal/adf/inline.go new file mode 100644 index 0000000..2b8c287 --- /dev/null +++ b/internal/adf/inline.go @@ -0,0 +1,112 @@ +package adf + +import ( + "cmp" + "slices" + "strconv" + "strings" + "time" +) + +// inline renders inline nodes as one run of text. +func inline(nodes []Node) string { + var text strings.Builder + for _, node := range nodes { + text.WriteString(span(node)) + } + + return text.String() +} + +// span renders an inline node. +func span(node Node) string { + switch node.Type { + case "text": + return styled(node) + case "hardBreak": + return "\n" + case "date": + return date(attr(node.Attrs, "timestamp")) + case "mediaInline": + return attachment(node) + default: + return cmp.Or(inline(node.Content), standIn(node)) + } +} + +// styled renders a run of text with its marks: code innermost, since code shows its text as it +// is, and a link outermost. Other marks, such as a colour, leave the text plain. +func styled(node Node) string { + text := node.Text + if _, ok := find(node.Marks, "code"); ok { + text = code(text) + } + + for _, style := range []struct{ mark, delim string }{{"em", "*"}, {"strong", "**"}, {"strike", "~~"}} { + if _, ok := find(node.Marks, style.mark); ok { + text = style.delim + text + style.delim + } + } + + if link, ok := find(node.Marks, "link"); ok { + text = "[" + text + "](" + attr(link.Attrs, "href") + ")" + } + + return text +} + +// find returns the mark of the type, if the marks hold one. +func find(marks []Mark, kind string) (Mark, bool) { + i := slices.IndexFunc(marks, func(mark Mark) bool { return mark.Type == kind }) + if i < 0 { + return Mark{}, false + } + + return marks[i], true +} + +// code renders text as a code span. A backtick at either end of the text would join the fence, so +// a space stands between them, which Markdown drops. +func code(text string) string { + pad := "" + if strings.HasPrefix(text, "`") || strings.HasSuffix(text, "`") { + pad = " " + } + + ticks := fence(text) + + return ticks + pad + text + pad + ticks +} + +// fence returns the shortest run of backticks that the code doesn't hold, so that the code can't +// end its own fence. +func fence(code string) string { + ticks := "`" + for strings.Contains(code, ticks) { + ticks += "`" + } + + return ticks +} + +// date renders a date's timestamp, milliseconds since the epoch, as its day in UTC, as Jira does. +// A timestamp that isn't a number shows as it is. +func date(timestamp string) string { + millis, err := strconv.ParseInt(timestamp, 10, 64) + if err != nil { + return timestamp + } + + return time.UnixMilli(millis).UTC().Format(time.DateOnly) +} + +// attachment stands in for a file or an image, which text can't show, with its name, or its +// address if it has no name. +func attachment(node Node) string { + name := cmp.Or(attr(node.Attrs, "alt"), attr(node.Attrs, "url")) + if name == "" { + return "[attachment]" + } + + return "[attachment: " + name + "]" +} diff --git a/internal/adf/testdata/blocks.json b/internal/adf/testdata/blocks.json new file mode 100644 index 0000000..f237ae7 --- /dev/null +++ b/internal/adf/testdata/blocks.json @@ -0,0 +1,71 @@ +{ + "version": 1, + "type": "doc", + "content": [ + {"type": "paragraph", "content": [{"type": "text", "text": "A paragraph."}]}, + { + "type": "mediaSingle", + "attrs": {"layout": "center"}, + "content": [ + { + "type": "media", + "attrs": {"type": "file", "id": "1", "collection": "c", "alt": "screen.png", "width": 640, "height": 480} + }, + { + "type": "caption", + "content": [ + {"type": "text", "text": "The "}, + {"type": "text", "text": "login", "marks": [{"type": "em"}]}, + {"type": "text", "text": " screen"} + ] + } + ] + }, + { + "type": "mediaGroup", + "content": [ + {"type": "media", "attrs": {"type": "external", "url": "https://example.com/a.png"}}, + {"type": "media", "attrs": {"type": "external", "url": "https://example.com/b.png", "alt": "A diagram"}}, + {"type": "media", "attrs": {"type": "file", "id": "2", "collection": "c"}} + ] + }, + {"type": "blockCard", "attrs": {"url": "https://example.com/DEMO-3"}}, + {"type": "extension", "attrs": {"extensionType": "demo", "extensionKey": "k", "text": "A macro's text"}}, + { + "type": "bodiedExtension", + "attrs": {"extensionType": "demo", "extensionKey": "k", "text": "Text for a missing macro"}, + "content": [{"type": "paragraph", "content": [{"type": "text", "text": "The macro's body"}]}] + }, + { + "type": "layoutSection", + "content": [ + { + "type": "layoutColumn", + "attrs": {"width": 50}, + "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Left"}]}] + }, + { + "type": "layoutColumn", + "attrs": {"width": 50}, + "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Right"}]}] + } + ] + }, + { + "type": "futureBlock", + "content": [ + { + "type": "paragraph", + "content": [ + {"type": "text", "text": "Unknown, "}, + { + "type": "futureInline", + "attrs": {"text": "stand-in"}, + "content": [{"type": "text", "text": "with known text"}] + } + ] + } + ] + } + ] +} diff --git a/internal/adf/testdata/blocks.md b/internal/adf/testdata/blocks.md new file mode 100644 index 0000000..f9df551 --- /dev/null +++ b/internal/adf/testdata/blocks.md @@ -0,0 +1,23 @@ +A paragraph. + +[attachment: screen.png] + +The *login* screen + +[attachment: https://example.com/a.png] + +[attachment: A diagram] + +[attachment] + +https://example.com/DEMO-3 + +A macro's text + +The macro's body + +Left + +Right + +Unknown, with known text diff --git a/internal/adf/testdata/inline.json b/internal/adf/testdata/inline.json new file mode 100644 index 0000000..b88703b --- /dev/null +++ b/internal/adf/testdata/inline.json @@ -0,0 +1,38 @@ +{ + "version": 1, + "type": "doc", + "content": [ + { + "type": "taskList", + "attrs": {"localId": "a"}, + "content": [ + { + "type": "taskItem", + "attrs": {"localId": "b", "state": "TODO"}, + "content": [ + {"type": "text", "text": "Ask "}, + {"type": "mention", "attrs": {"id": "0", "text": "@Demo User", "accessLevel": ""}}, + {"type": "text", "text": " "}, + {"type": "emoji", "attrs": {"shortName": ":smile:", "id": "1f604", "text": "😄"}}, + {"type": "emoji", "attrs": {"shortName": ":demo:", "id": "1"}}, + {"type": "text", "text": " by "}, + {"type": "date", "attrs": {"timestamp": "1767223800000"}}, + {"type": "text", "text": " or "}, + {"type": "date", "attrs": {"timestamp": "soon"}}, + {"type": "text", "text": ","}, + {"type": "hardBreak"}, + {"type": "status", "attrs": {"text": "IN PROGRESS", "color": "blue", "localId": "c"}}, + {"type": "text", "text": ", "}, + {"type": "inlineCard", "attrs": {"url": "https://example.com/DEMO-2"}}, + {"type": "text", "text": ", "}, + {"type": "mediaInline", "attrs": {"type": "file", "id": "d", "collection": "e", "alt": "log.txt"}}, + {"type": "text", "text": ", "}, + {"type": "placeholder", "attrs": {"text": "a placeholder"}}, + {"type": "text", "text": " and "}, + {"type": "inlineExtension", "attrs": {"extensionType": "demo", "extensionKey": "f", "text": "an extension"}} + ] + } + ] + } + ] +} diff --git a/internal/adf/testdata/inline.md b/internal/adf/testdata/inline.md new file mode 100644 index 0000000..7396353 --- /dev/null +++ b/internal/adf/testdata/inline.md @@ -0,0 +1,2 @@ +Ask @Demo User 😄:demo: by 2025-12-31 or soon, +IN PROGRESS, https://example.com/DEMO-2, [attachment: log.txt], a placeholder and an extension diff --git a/internal/adf/testdata/text.json b/internal/adf/testdata/text.json new file mode 100644 index 0000000..0ceb63f --- /dev/null +++ b/internal/adf/testdata/text.json @@ -0,0 +1,54 @@ +{ + "version": 1, + "type": "doc", + "content": [ + { + "type": "paragraph", + "content": [ + {"type": "text", "text": "Plain, "}, + {"type": "text", "text": "strong", "marks": [{"type": "strong"}]}, + {"type": "text", "text": ", "}, + {"type": "text", "text": "em", "marks": [{"type": "em"}]}, + {"type": "text", "text": ", "}, + {"type": "text", "text": "struck", "marks": [{"type": "strike"}]}, + {"type": "text", "text": ", "}, + { + "type": "text", + "text": "underlined", + "marks": [{"type": "underline"}, {"type": "textColor", "attrs": {"color": "#ff0000"}}] + }, + {"type": "text", "text": ", "}, + {"type": "text", "text": "bold code", "marks": [{"type": "strong"}, {"type": "code"}]}, + {"type": "text", "text": " and "}, + {"type": "text", "text": "make check", "marks": [{"type": "code"}]}, + {"type": "text", "text": "."} + ] + }, + { + "type": "paragraph", + "content": [ + {"type": "text", "text": "See "}, + { + "type": "text", + "text": "the docs", + "marks": [{"type": "link", "attrs": {"href": "https://example.com/docs"}}, {"type": "strong"}] + }, + {"type": "text", "text": ", then run "}, + {"type": "text", "text": "a``b", "marks": [{"type": "code"}]}, + {"type": "hardBreak"}, + {"type": "text", "text": "on a new line."} + ] + }, + { + "type": "paragraph", + "content": [ + {"type": "text", "text": "Ticks: "}, + {"type": "text", "text": "`x", "marks": [{"type": "code"}]}, + {"type": "text", "text": " and "}, + {"type": "text", "text": "y`", "marks": [{"type": "code"}]} + ] + }, + {"type": "paragraph", "content": []}, + {"type": "paragraph", "content": [{"type": "text", "text": "Last."}]} + ] +} diff --git a/internal/adf/testdata/text.md b/internal/adf/testdata/text.md new file mode 100644 index 0000000..419dad4 --- /dev/null +++ b/internal/adf/testdata/text.md @@ -0,0 +1,8 @@ +Plain, **strong**, *em*, ~~struck~~, underlined, **`bold code`** and `make check`. + +See [**the docs**](https://example.com/docs), then run ```a``b``` +on a new line. + +Ticks: `` `x `` and `` y` `` + +Last.