Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,12 @@ lore work rank CAR-3 --top --reason "report is due Friday"
lore work list --all
lore status # what's outstanding: the fold's summary + the live open work (what lore_status returns)
lore work label CAR-2 CAR-5 --add "stripe integration" --reason "group the Stripe work"
lore work archive --origin linear --reason "starting fresh" --dry-run # every open ticket mirrored from Linear; drop --dry-run to do it
lore work unarchive CAR-2 --reason "still wanted" # back to the status it had before
lore work claim CAR-2 --holder enso:athena --ref WEB-12 --stage build --status in_progress --json # take a ticket for a run; exit 3 if someone holds it
lore work claim CAR-2 --holder enso:athena --ref WEB-12 --stage review --status review # same holder + ref: hand it to the next stage
lore work renew --holder enso:athena # heartbeat: confirm every claim this holder has
lore work release CAR-2 --holder enso:athena --ref WEB-12 --status done --reason "deployed"
lore work list --label "stripe integration" # one theme's open tickets (recall --label: open and closed)
lore work show CAR-2 # the ticket with its full history
```
Expand Down
68 changes: 68 additions & 0 deletions integrations/enso/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# lore ↔ enso

Run lore tickets through an [enso](https://github.com/nerdburn/enso) project:
one enso task per ticket, each stage change written back to the ticket, and
never two runs of the same ticket at once.

`lore_bridge.py` has no model in it. It needs the `lore` and `enso` CLIs on
the machine that runs enso, lore ≥ the release with `lore work claim`, and
enso ≥ the release with `enso task add --unique-ref`.

## How a ticket flows

1. Someone (a person on the board, or the PM agent) assigns a `todo` ticket
to the agent's name (`LORE_ASSIGNEE`).
2. `dispatch` claims it in lore, creates the enso task with
`--unique-ref lore:<KEY>`, and records the task ref and stage on the claim.
3. enso runs its stages. After every move the `transition` hook updates the
ticket's stage and status; a block also leaves the reason as a comment.
4. `done` releases the claim and closes the ticket; `cancelled` releases it.

Each `dispatch` run also renews the runner's claims (its heartbeat — lore
emails the account lead about a claim that has been silent for six hours),
repairs anything a missed hook left behind, and drops the enso task of a
ticket a person closed in lore.

## Setup

Settings live in one small file beside the script (`lore-bridge.env.sh`):

```sh
export LORE_PROJECT=acme
export LORE_HOLDER=enso:athena
export LORE_ASSIGNEE=athena
export ENSO_PROJECT=WEB
```

A command job that runs the dispatcher (`jobs/lore-dispatch/JOB.md`):

```markdown
---
name: Lore dispatch
schedule: "*/3 * * * *"
enabled: true
command: bash -c '. /path/to/lore-bridge.env.sh && python3 /path/to/lore_bridge.py dispatch'
timeout: 240
---
Start lore tickets assigned to the agent and keep claims in step with enso.
```

The project hook (`PROJECT.md`):

```yaml
hooks:
after_transition: bash -c '. /path/to/lore-bridge.env.sh && python3 /path/to/lore_bridge.py transition'
```

See the docstring in `lore_bridge.py` for every setting, including
`LORE_STATUS_MAP` when the project's stage names differ from
build / review / qa / merge / deploy.

## What refuses a duplicate

- `lore work claim` exits 3 when another holder — or the same holder under a
different task ref — has the ticket. Nothing is written.
- `enso task add --unique-ref` creates nothing when an unfinished task
already carries `lore:<KEY>`; the dispatcher adopts that task instead.
- A claim never expires by itself. Freeing a ticket whose runner is gone is
a person's call: `lore work release <KEY> --force --reason "…"`.
Binary file not shown.
198 changes: 198 additions & 0 deletions integrations/enso/lore_bridge.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
#!/usr/bin/env python3
"""Run lore tickets through an enso project, one enso task per ticket.

Two entry points, both model-free:

lore_bridge.py dispatch scheduled (an enso command job): heartbeat, start
tickets assigned to the agent, reconcile the rest
lore_bridge.py transition enso project hook `after_transition`: write each
stage change back to the ticket

A ticket is never run twice at once. Two guards, either of which is enough:
lore gives a ticket one claim (`lore work claim` exits 3 when it is held), and
enso refuses a second unfinished task for the ticket
(`enso task add --unique-ref lore:<KEY>`).

Configuration (environment):
LORE_PROJECT lore project name (`lore -p`) required
LORE_HOLDER the name this runner claims under, e.g. enso:athena required
LORE_ASSIGNEE tickets assigned to this name are started dispatch
ENSO_PROJECT enso project key new tasks go to dispatch
ENSO_WORKSPACE enso workspace (enso sets it for jobs and hooks) required
LORE_MAX_NEW most tickets to start per run (default 3)
LORE_STATUS_MAP JSON {"<enso stage>": "<lore status>"} overriding the defaults
LORE_BIN / ENSO_BIN executables (default: lore / enso)

Standard library only; python3 3.9+.
"""
from __future__ import annotations

import json
import os
import subprocess
import sys

FINISHED = ("done", "cancelled")
STATUS = {"backlog": "todo", "blocked": "blocked", "build": "in_progress", "review": "review", "qa": "review", "merge": "review", "deploy": "review"}
HELD = 3 # `lore work claim` / `release`: someone else holds the ticket


def env(name: str, default: str | None = None) -> str:
value = os.environ.get(name, default)
if not value:
sys.exit(f"lore_bridge: set {name}")
return value


def run(cmd: list[str], stdin: str | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run(cmd, input=stdin, capture_output=True, text=True)


def last_json(text: str):
for line in reversed(text.strip().splitlines()):
try:
return json.loads(line)
except ValueError:
continue
try:
return json.loads(text)
except ValueError:
return None


def lore(*args: str, ok: tuple[int, ...] = (0,)) -> tuple[int, object]:
proc = run([os.environ.get("LORE_BIN", "lore"), *args, "-p", env("LORE_PROJECT")])
if proc.returncode not in ok:
raise RuntimeError(f"lore {' '.join(args[:3])}: {proc.stderr.strip() or proc.stdout.strip()}")
return proc.returncode, last_json(proc.stdout)


def enso(*args: str, stdin: str | None = None) -> tuple[int, object, str]:
proc = run([os.environ.get("ENSO_BIN", "enso"), *args, "--workspace", env("ENSO_WORKSPACE"), "--json"], stdin)
return proc.returncode, last_json(proc.stdout), proc.stderr.strip() or proc.stdout.strip()


def status_for(stage: str) -> str:
table = {**STATUS, **json.loads(os.environ.get("LORE_STATUS_MAP", "{}"))}
return table.get(stage, "in_progress")


def lore_key(task: dict) -> str | None:
for ref in task.get("refs") or []:
if ref.get("kind") == "lore":
return str(ref.get("value"))
return None


def claim(key: str, **fields: str | None) -> bool:
"""Take or confirm the claim; False when someone else holds the ticket."""
args = ["work", "claim", key, "--holder", env("LORE_HOLDER"), "--json"]
for flag, value in fields.items():
if value:
args += [f"--{flag}", value]
code, _ = lore(*args, ok=(0, HELD))
return code == 0


def release(key: str, reason: str, ref: str | None = None, status: str | None = None) -> None:
args = ["work", "release", key, "--holder", env("LORE_HOLDER"), "--reason", reason, "--json"]
if ref:
args += ["--ref", ref]
if status:
args += ["--status", status]
lore(*args, ok=(0, HELD))


def start(ticket: dict) -> str:
"""Claim the ticket, then create its enso task. Returns a line for the log."""
key = ticket["key"].upper()
if not claim(key, stage="queued"):
return f"{key}: held by someone else, skipped"
body = "\n\n".join(filter(None, [
(ticket.get("description") or "").strip(),
f"Lore ticket: {key}" + (f" (priority {ticket['priority']})" if ticket.get("priority") else ""),
"Sources:\n" + "\n".join(f"- {s}" for s in ticket["sources"]) if ticket.get("sources") else "",
]))
code, out, err = enso("task", "add", f"{key}: {ticket['title']}", "--project", env("ENSO_PROJECT"), "--body-file", "-", "--unique-ref", f"lore:{key}", stdin=body)
task = out if code == 0 else (out or {}).get("existing") if isinstance(out, dict) else None
if not isinstance(task, dict) or not task.get("ref"):
release(key, f"could not create the enso task: {err[:300]}")
return f"{key}: enso refused the task ({err[:120]}); claim released"
stage = str(task.get("stage") or "")
claim(key, ref=task["ref"], stage=stage, status=status_for(stage))
return f"{key}: {'started as' if code == 0 else 'already running as'} {task['ref']} ({stage})"


def reconcile(ticket: dict) -> str | None:
"""Bring one of our claims back in line with its enso task, in case a hook was missed."""
key, held = ticket["key"].upper(), ticket["claim"]
ref = held.get("ref")
if not ref:
return start(ticket) # a run that died between the claim and the task
code, task, err = enso("task", "show", ref)
if code != 0 or not isinstance(task, dict):
return f"{key}: cannot read enso task {ref} ({err[:120]}); claim left as is"
stage = str(task.get("stage") or "")
if stage == "done":
release(key, f"{ref} finished", ref=ref, status="done")
return f"{key}: {ref} done; released"
if stage == "cancelled":
release(key, f"{ref} was cancelled", ref=ref)
return f"{key}: {ref} cancelled; released"
if ticket.get("state") == "closed":
# A person closed the ticket while it was running: stop the work, then let go.
message = f"{key} was closed in lore"
enso("task", "stop", ref, "--message", message)
code, _, err = enso("task", "drop", ref, "--message", message)
if code != 0:
return f"{key}: closed in lore but {ref} is still running ({err[:120]}); will retry"
release(key, f"{ref} dropped: the ticket was closed", ref=ref)
return f"{key}: closed in lore; {ref} dropped and released"
if stage != held.get("stage"):
claim(key, ref=ref, stage=stage, status=status_for(stage))
return f"{key}: caught up to {ref} ({stage})"
return None


def dispatch() -> None:
holder, assignee = env("LORE_HOLDER"), env("LORE_ASSIGNEE").lower()
lore("work", "renew", "--holder", holder, "--json")
_, tickets = lore("work", "list", "--all", "--json")
lines: list[str] = []
for t in tickets or []:
if (t.get("claim") or {}).get("holder") == holder:
line = reconcile(t)
if line:
lines.append(line)
fresh = [t for t in tickets or [] if not t.get("claim") and t.get("status") == "todo" and str(t.get("assignee") or "").lower() == assignee]
for t in fresh[: int(os.environ.get("LORE_MAX_NEW", "3"))]:
lines.append(start(t))
print("\n".join(lines) if lines else "nothing to do")


def transition() -> None:
ref, stage = env("ENSO_TASK"), env("ENSO_TO_STAGE")
code, task, err = enso("task", "show", ref)
if code != 0 or not isinstance(task, dict):
sys.exit(f"lore_bridge: cannot read {ref}: {err}")
key = lore_key(task)
if not key:
return # not a lore ticket
message = os.environ.get("ENSO_MESSAGE", "").strip()
if stage == "done":
release(key, message[:500] or f"{ref} finished", ref=ref, status="done")
elif stage == "cancelled":
release(key, message[:500] or f"{ref} was cancelled", ref=ref)
else:
if not claim(key, ref=ref, stage=stage, status=status_for(stage), reason=message[:500] or None):
sys.exit(f"lore_bridge: {key} is held by someone else; {ref} should not be running")
if stage == "blocked" and message:
lore("work", "comment", key, f"Blocked at {os.environ.get('ENSO_FROM_STAGE', '?')} ({ref}): {message}", "--by", env("LORE_HOLDER"))
print(f"{key}: {ref} → {stage}")


if __name__ == "__main__":
commands = {"dispatch": dispatch, "transition": transition}
if len(sys.argv) != 2 or sys.argv[1] not in commands:
sys.exit("usage: lore_bridge.py dispatch | transition")
commands[sys.argv[1]]()
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"web/dist",
"manifests",
"docs/PLAYBOOK.md",
"docs/GITHUB_PROJECTS_SOURCE.md"
"docs/GITHUB_PROJECTS_SOURCE.md",
"integrations"
],
"scripts": {
"build": "tsc",
Expand Down
8 changes: 5 additions & 3 deletions src/board/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { gitShow } from '../bare.js'
import { blobStoreFromEnv, MAX_ATTACHMENT_BYTES, TooLarge, writeHashed, type BlobStore } from '../blobs.js'
import { addComment, ticketThread } from '../comments.js'
import { workAdd, workMove, workSet } from '../commands/project.js'
import { workRank, type WorkWriteOptions } from '../commands/work.js'
import { statusBeforeArchive, workRank, type WorkWriteOptions } from '../commands/work.js'
import { serializeFor } from '../queue.js'
import { findItem, labelCounts, summarizeForRecall, WORK_PRIORITIES, WORK_STATUSES, type LoreWorkItem, type RankTarget } from '../work.js'
import { assigneeResolver, assigneeOptions, bareProject, bareProjects, bareWorkItems, boardRole, type BoardRole } from './access.js'
Expand Down Expand Up @@ -395,13 +395,15 @@ export function createBoardHandler(opts: BoardOptions): BoardHandler {
return send(res, 200, { item }), true
}
if (key && action === 'move' && method === 'POST') {
const status = str(body.status)
const current = bareWorkItems(opts.repos, project).items.find((i) => i.key.toUpperCase() === key.toUpperCase())
// "Unarchive": back to the status the ticket held before it was archived.
const status = body.restore === true && current?.status === 'archived' ? statusBeforeArchive(current) : str(body.status)
const target = rankTarget(body, bareWorkItems(opts.repos, project).items, key)
const item = await write(async () => {
let item: LoreWorkItem | undefined
if (status) {
try {
item = await workMove(cwd, key, status, { reason: reason ?? `moved to ${status} on the board` }, w)
item = await workMove(cwd, key, status, { reason: reason ?? (body.restore === true ? 'unarchived on the board' : `moved to ${status} on the board`) }, w)
} catch (err) {
if (!target || !/is already/.test(String(err))) throw err
}
Expand Down
52 changes: 52 additions & 0 deletions src/claim-alert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { createSendMail, emailConfigFromEnv, type MailMessage, type SendMail } from './board/email.js'
import type { LoreConfig } from './config.js'
import { CLAIM_STALE_HOURS, describeClaim, readWorkItems, staleClaims, workPrefix, writeWorkItems, type LoreWorkItem } from './work.js'

const esc = (s: string) => s.replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]!)

/**
* A claim never lapses on its own, so a holder that has stopped (a crashed
* runner, a machine that is down) would hold its tickets forever in silence.
* Each sync reports tickets whose holder has not confirmed its claim for
* CLAIM_STALE_HOURS — once per silence; the next renewal clears the mark.
* Recipient: LORE_ALERT_NOTIFY, else the project's account lead.
*/
export async function alertStaleClaims(
root: string,
config: Pick<LoreConfig, 'project' | 'client' | 'work'>,
opts: { send?: SendMail; now?: number } = {},
): Promise<string[]> {
const now = opts.now ?? Date.now()
const prefix = workPrefix(config)
const items = readWorkItems(root, prefix)
const stale = staleClaims(items, now).filter((i) => !i.claim!.stale_notified)
if (stale.length === 0) return []
const to = process.env.LORE_ALERT_NOTIFY || config.client?.owner
const cfg = emailConfigFromEnv()
if (!to || (!opts.send && (!cfg.from || !cfg.api))) {
console.warn(`⚠ ${stale.length} stale claim${stale.length === 1 ? '' : 's'} (${stale.map((i) => i.key).join(', ')}) not emailed: set LORE_ALERT_NOTIFY or client.owner, and the board email settings`)
return []
}
await (opts.send ?? createSendMail(cfg, console.log))(staleClaimEmail(to, config.project, stale, now))
const at = new Date(now).toISOString()
for (const i of stale) i.claim!.stale_notified = at
writeWorkItems(root, prefix, items)
return stale.map((i) => i.key)
}

export function staleClaimEmail(to: string, project: string, stale: LoreWorkItem[], now = Date.now()): MailMessage {
const lines = stale.map((i) => {
const hours = Math.round((now - Date.parse(i.claim!.renewed)) / 3_600_000)
return `${i.key} — ${i.title}\n held by ${describeClaim(i.claim)}, silent for ${hours}h`
})
const text =
`${stale.length} ticket${stale.length === 1 ? ' is' : 's are'} claimed in ${project} by a holder that has not confirmed its claim for over ${CLAIM_STALE_HOURS} hours.\n\n` +
`${lines.join('\n\n')}\n\n` +
`Nothing else will pick these up while the claim stands. Check the holder is running; if it is gone, free a ticket with:\nlore work release <KEY> --force --reason "<why>" -p ${project}\n`
return {
to,
subject: `Lore: ${stale.length} claimed ticket${stale.length === 1 ? '' : 's'} in ${project} gone quiet`,
text,
html: `<div style="font:16px/1.5 system-ui,sans-serif;color:#1f1d1a;max-width:560px">${text.split('\n\n').map((p) => `<p>${esc(p).replace(/\n/g, '<br>')}</p>`).join('')}</div>`,
}
}
Loading
Loading