dev-loops 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/.claude/.claude-plugin/plugin.json +1 -1
  2. package/.claude/agents/dev-loop.md +1 -1
  3. package/.claude/agents/refiner.md +1 -0
  4. package/.claude/skills/dev-loop/SKILL.md +16 -6
  5. package/.claude/skills/dev-loop/templates/slides-story-review.md +54 -0
  6. package/.claude/skills/docs/artifact-authority-contract.md +86 -31
  7. package/.claude/skills/docs/local-planning-flow.md +63 -0
  8. package/.claude/skills/docs/local-planning-worked-example.md +139 -0
  9. package/.claude/skills/docs/merge-preconditions.md +35 -0
  10. package/.claude/skills/docs/plan-file-contract.md +37 -0
  11. package/.claude/skills/docs/retrospective-checkpoint-contract.md +55 -7
  12. package/.claude/skills/docs/spike-mode-contract.md +237 -0
  13. package/CHANGELOG.md +43 -0
  14. package/README.md +1 -0
  15. package/agents/refiner.agent.md +1 -0
  16. package/package.json +5 -3
  17. package/scripts/github/capture-review-threads.mjs +20 -2
  18. package/scripts/github/probe-copilot-review.mjs +69 -3
  19. package/scripts/github/upsert-checkpoint-verdict.mjs +18 -3
  20. package/scripts/lib/jq-output.mjs +297 -0
  21. package/scripts/loop/check-retro-tooling.mjs +246 -0
  22. package/scripts/loop/copilot-pr-handoff.mjs +21 -3
  23. package/scripts/loop/detect-pr-gate-coordination-state.mjs +35 -2
  24. package/scripts/loop/docs-grill-contract.mjs +70 -0
  25. package/scripts/loop/info.mjs +21 -2
  26. package/scripts/loop/pr-runner-coordination.mjs +20 -4
  27. package/scripts/loop/resolve-dev-loop-startup.mjs +176 -5
  28. package/scripts/loop/resolve-pr-conflicts.mjs +357 -0
  29. package/scripts/loop/run-watch-cycle.mjs +77 -3
  30. package/scripts/loop/slides-story-review-contract.mjs +123 -0
  31. package/scripts/pages/build-site.mjs +136 -0
  32. package/scripts/projects/add-queue-item.mjs +12 -2
  33. package/scripts/projects/list-queue-items.mjs +12 -2
  34. package/scripts/projects/move-queue-item.mjs +12 -2
  35. package/scripts/refine/_refine-helpers.mjs +20 -0
  36. package/scripts/refine/exit-spike.mjs +186 -0
  37. package/scripts/refine/promote-plan.mjs +387 -0
  38. package/scripts/refine/refine-plan-file.mjs +165 -0
  39. package/scripts/refine/validate-plan-file.mjs +64 -0
  40. package/scripts/refine/validate-spike-file.mjs +87 -0
  41. package/skills/dev-loop/SKILL.md +11 -1
  42. package/skills/dev-loop/templates/slides-story-review.md +54 -0
  43. package/skills/docs/artifact-authority-contract.md +86 -31
  44. package/skills/docs/local-planning-flow.md +63 -0
  45. package/skills/docs/local-planning-worked-example.md +139 -0
  46. package/skills/docs/merge-preconditions.md +35 -0
  47. package/skills/docs/plan-file-contract.md +37 -0
  48. package/skills/docs/retrospective-checkpoint-contract.md +55 -7
  49. package/skills/docs/spike-mode-contract.md +237 -0
@@ -0,0 +1,165 @@
1
+ #!/usr/bin/env node
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { parseArgs } from "node:util";
5
+
6
+ import { buildParseError, formatCliError, parseJsonText } from "../_core-helpers.mjs";
7
+ import { requireTokenValue } from "../_cli-primitives.mjs";
8
+ import { validatePlanFile } from "./validate-plan-file.mjs";
9
+ import { extractSection, isDirectCliRun } from "./_refine-helpers.mjs";
10
+ import {
11
+ refinePlanFileInPlace,
12
+ PLAN_FILE_REFINE_STOP,
13
+ } from "@dev-loops/core/loop/plan-file-refine-contract";
14
+ import { PLAN_FILE_REFINEMENT_SECTIONS } from "@dev-loops/core/loop/plan-file-intake-contract";
15
+ import { classifyDocsGrillFinding } from "../loop/docs-grill-contract.mjs";
16
+
17
+ const USAGE = `Usage:
18
+ refine-plan-file.mjs --plan-file <path> --payload <path> [--json]
19
+ Refine a local plan file in place: write the refiner-produced Acceptance
20
+ criteria, Definition of done, coverage matrix, and recorded docs-grill
21
+ findings into the plan file, advance the intake state to
22
+ plan_refined_ready_for_promotion, and stop at a local human-review
23
+ checkpoint. Read-only against the tracker: no GitHub calls, no issue/PR/
24
+ comment, no promotion.
25
+
26
+ Required:
27
+ --plan-file <path> Path to the phase-doc-format plan file to refine in place
28
+ --payload <path> Path to a JSON file with the refiner output
29
+ ({ acceptanceCriteria, definitionOfDone, coverageMatrix,
30
+ grillFindings? })
31
+ Optional:
32
+ --json Machine-readable JSON output
33
+ --help Show this help
34
+ Exit codes:
35
+ 0 Refinement succeeded; plan written in place; stop for local human review
36
+ 1 Argument error, or fail-closed refine/grill/ambiguous state (no write)`.trim();
37
+
38
+ const parseError = buildParseError(USAGE);
39
+
40
+ export function parseRefinePlanFileCliArgs(argv) {
41
+ const { tokens } = parseArgs({
42
+ args: [...argv],
43
+ options: {
44
+ help: { type: "boolean", short: "h" },
45
+ "plan-file": { type: "string" },
46
+ payload: { type: "string" },
47
+ json: { type: "boolean" },
48
+ },
49
+ allowPositionals: true,
50
+ strict: false,
51
+ tokens: true,
52
+ });
53
+ const options = { help: false, planFile: undefined, payload: undefined, json: false };
54
+ for (const token of tokens) {
55
+ if (token.kind === "positional") {
56
+ throw parseError(`Unknown argument: ${token.value}`);
57
+ }
58
+ if (token.kind !== "option") continue;
59
+ if (token.name === "help") {
60
+ options.help = true;
61
+ return options;
62
+ }
63
+ if (token.name === "plan-file") {
64
+ options.planFile = requireTokenValue(token, parseError, { flagPattern: /^-/u });
65
+ continue;
66
+ }
67
+ if (token.name === "payload") {
68
+ options.payload = requireTokenValue(token, parseError, { flagPattern: /^-/u });
69
+ continue;
70
+ }
71
+ if (token.name === "json") {
72
+ options.json = true;
73
+ continue;
74
+ }
75
+ throw parseError(`Unknown argument: ${token.rawName}`);
76
+ }
77
+ if (typeof options.planFile !== "string" || options.planFile.trim().length === 0) {
78
+ throw parseError("refine-plan-file requires --plan-file <path>");
79
+ }
80
+ if (typeof options.payload !== "string" || options.payload.trim().length === 0) {
81
+ throw parseError("refine-plan-file requires --payload <path>");
82
+ }
83
+ return options;
84
+ }
85
+
86
+ export async function runCli(argv = process.argv.slice(2), { stdout = process.stdout } = {}) {
87
+ const options = parseRefinePlanFileCliArgs(argv);
88
+ if (options.help) {
89
+ stdout.write(`${USAGE}\n`);
90
+ return { ok: true, help: true };
91
+ }
92
+
93
+ const planPath = path.resolve(options.planFile);
94
+ const markdownText = await readFile(planPath, "utf8");
95
+ const payload = parseJsonText(await readFile(path.resolve(options.payload), "utf8"));
96
+
97
+ // Read the section-presence facts with the P1 surfaces, then hand them to the
98
+ // pure refine contract. The contract owns the state-machine gate and the
99
+ // in-place rewrite; this script owns I/O only.
100
+ // The docs-grill runs as a step of refinement. Classify each finding here (this
101
+ // script owns the scripts/ boundary) with #948's classifier and pass the
102
+ // dispositions to the pure core contract; an invalid finding yields a null
103
+ // disposition, which the contract fails closed on (docs_grill_failed).
104
+ const rawFindings = Array.isArray(payload?.grillFindings) ? payload.grillFindings : [];
105
+ const grillDispositions = rawFindings.map((finding) => {
106
+ const classified = classifyDocsGrillFinding(finding);
107
+ return {
108
+ kind: finding?.kind,
109
+ summary: typeof finding?.summary === "string" ? finding.summary : "",
110
+ disposition: classified.ok ? classified.disposition : null,
111
+ };
112
+ });
113
+
114
+ const [acHeading, dodHeading] = PLAN_FILE_REFINEMENT_SECTIONS;
115
+ const result = refinePlanFileInPlace({
116
+ markdownText,
117
+ baseSectionsValid: validatePlanFile(markdownText).ok,
118
+ hasAcceptanceCriteria: extractSection(markdownText, acHeading) ? true : false,
119
+ hasDefinitionOfDone: extractSection(markdownText, dodHeading) ? true : false,
120
+ payload: { ...payload, grillDispositions },
121
+ });
122
+
123
+ if (!result.ok) {
124
+ // Fail closed: surface the reason, do not write, do not advance, do not promote.
125
+ if (options.json) {
126
+ stdout.write(`${JSON.stringify({ ok: false, reason: result.reason, planFileIntakeState: result.planFileIntakeState ?? null })}\n`);
127
+ } else {
128
+ stdout.write(`refine-plan-file: FAIL (${result.reason})\n`);
129
+ }
130
+ process.exitCode = 1;
131
+ return result;
132
+ }
133
+
134
+ // Write the refined plan back in place — the single canonical artifact.
135
+ await writeFile(planPath, result.refinedMarkdown, "utf8");
136
+
137
+ const summary = {
138
+ ok: true,
139
+ planFile: planPath,
140
+ planFileIntakeState: result.planFileIntakeState,
141
+ stop: result.stop,
142
+ grillDispositions: result.grillDispositions,
143
+ };
144
+ if (options.json) {
145
+ stdout.write(`${JSON.stringify(summary)}\n`);
146
+ } else {
147
+ stdout.write(
148
+ [
149
+ "refine-plan-file: PASS",
150
+ ` plan: ${planPath}`,
151
+ ` state: ${result.planFileIntakeState}`,
152
+ ` stop: ${result.stop.kind} (${PLAN_FILE_REFINE_STOP.LOCAL_HUMAN_REVIEW === result.stop.kind ? "stop for local human review; no tracker artifact created" : result.stop.kind})`,
153
+ ` grill findings recorded: ${result.grillDispositions.length}`,
154
+ ].join("\n") + "\n",
155
+ );
156
+ }
157
+ return summary;
158
+ }
159
+
160
+ if (isDirectCliRun(import.meta.url)) {
161
+ runCli().catch((error) => {
162
+ process.stderr.write(`${formatCliError(error)}\n`);
163
+ process.exitCode = 1;
164
+ });
165
+ }
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from "node:fs/promises";
3
+
4
+ import { formatCliError } from "../_core-helpers.mjs";
5
+ import {
6
+ DEFAULT_USAGE_SUFFIX,
7
+ checkBaseSections,
8
+ parseCheckerCliArgs,
9
+ writeCheckerOutput,
10
+ isDirectCliRun,
11
+ } from "./_refine-helpers.mjs";
12
+
13
+ const USAGE = `Usage:
14
+ validate-plan-file.mjs --input <path> [--json]
15
+ Validate the base authoring sections of a phase-doc-format plan file: Status, Objective, In scope, Explicit non-goals.${"\n"}${DEFAULT_USAGE_SUFFIX}`;
16
+
17
+ /**
18
+ * Base authoring sections a phase doc carries before refinement adds AC/DoD.
19
+ * Heading → distinct missing_* error code. Single source of truth: the section
20
+ * list is derived from these keys so the validator and the exported list cannot
21
+ * drift.
22
+ */
23
+ const SECTION_CODES = {
24
+ Status: "missing_status",
25
+ Objective: "missing_objective",
26
+ "In scope": "missing_in_scope",
27
+ "Explicit non-goals": "missing_explicit_non_goals",
28
+ };
29
+
30
+ /** Base authoring section headings, in order (derived from SECTION_CODES). */
31
+ export const PLAN_FILE_BASE_SECTIONS = Object.keys(SECTION_CODES);
32
+
33
+ /**
34
+ * Pure validator. Reports whether a plan file (phase-doc format) carries every
35
+ * base authoring section with a non-empty body. An absent or empty-body section
36
+ * is reported under that section's distinct missing_* code. No side effects.
37
+ *
38
+ * @param {string} markdownText
39
+ * @returns {{ checker: "validate-plan-file", ok: boolean, errors: { code: string, message: string }[] }}
40
+ */
41
+ export function validatePlanFile(markdownText) {
42
+ // checkBaseSections reports each absent/empty section under its distinct
43
+ // missing_* code; an empty-body section is malformed here too.
44
+ return checkBaseSections(markdownText, "validate-plan-file", SECTION_CODES);
45
+ }
46
+
47
+ export async function runCli(argv = process.argv.slice(2), { stdout = process.stdout } = {}) {
48
+ const options = parseCheckerCliArgs(argv, USAGE, "validate-plan-file");
49
+ if (options.help) {
50
+ stdout.write(`${USAGE}\n`);
51
+ return { ok: true, help: true };
52
+ }
53
+ const markdownText = await readFile(options.input, "utf8");
54
+ const result = validatePlanFile(markdownText);
55
+ writeCheckerOutput(result, { stdout, json: options.json });
56
+ return result;
57
+ }
58
+
59
+ if (isDirectCliRun(import.meta.url)) {
60
+ runCli().catch((error) => {
61
+ process.stderr.write(`${formatCliError(error)}\n`);
62
+ process.exitCode = 1;
63
+ });
64
+ }
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from "node:fs/promises";
3
+
4
+ import { formatCliError } from "../_core-helpers.mjs";
5
+ import {
6
+ DEFAULT_USAGE_SUFFIX,
7
+ checkBaseSections,
8
+ parseCheckerCliArgs,
9
+ writeCheckerOutput,
10
+ isDirectCliRun,
11
+ } from "./_refine-helpers.mjs";
12
+
13
+ const USAGE = `Usage:
14
+ validate-spike-file.mjs --input <path> [--json]
15
+ Validate the base authoring sections of a spike artifact: Question, Approach, Findings, Recommendation.${"\n"}${DEFAULT_USAGE_SUFFIX}`;
16
+
17
+ /**
18
+ * Base authoring sections a spike artifact carries.
19
+ * Heading → distinct missing_* error code.
20
+ */
21
+ const SECTION_CODES = {
22
+ Question: "missing_question",
23
+ Approach: "missing_approach",
24
+ Findings: "missing_findings",
25
+ Recommendation: "missing_recommendation",
26
+ };
27
+
28
+ export const SPIKE_FILE_BASE_SECTIONS = Object.keys(SECTION_CODES);
29
+
30
+ /**
31
+ * Recommendation is the exit-marker section: present + non-empty means the
32
+ * spike has reached a recommendation and is ready for a discard/graduate exit
33
+ * decision. The exploration scaffold (Question/Approach/Findings) is what an
34
+ * in-progress spike must carry for `--spike` entry. (Mirrors the plan-file
35
+ * base-vs-refinement-section split.)
36
+ */
37
+ export const SPIKE_FILE_EXIT_MARKER_SECTION = "Recommendation";
38
+ export const SPIKE_FILE_EXPLORATION_SECTIONS = SPIKE_FILE_BASE_SECTIONS.filter(
39
+ (h) => h !== SPIKE_FILE_EXIT_MARKER_SECTION,
40
+ );
41
+
42
+ const EXPLORATION_SECTION_CODES = Object.fromEntries(
43
+ SPIKE_FILE_EXPLORATION_SECTIONS.map((h) => [h, SECTION_CODES[h]]),
44
+ );
45
+
46
+ /**
47
+ * Pure validator. Reports whether a spike artifact carries every base authoring
48
+ * section with a non-empty body. An absent or empty-body section is reported
49
+ * under that section's distinct missing_* code. No side effects.
50
+ *
51
+ * @param {string} markdownText
52
+ * @returns {{ checker: "validate-spike-file", ok: boolean, errors: { code: string, message: string }[] }}
53
+ */
54
+ export function validateSpikeFile(markdownText) {
55
+ return checkBaseSections(markdownText, "validate-spike-file", SECTION_CODES);
56
+ }
57
+
58
+ /**
59
+ * Entry-gate validator for `--spike`: a spike is startable as soon as it carries
60
+ * the exploration scaffold (Question/Approach/Findings) with non-empty bodies;
61
+ * the Recommendation is filled in DURING the spike, not required to begin one.
62
+ *
63
+ * @param {string} markdownText
64
+ * @returns {{ checker: "validate-spike-file", ok: boolean, errors: { code: string, message: string }[] }}
65
+ */
66
+ export function validateSpikeExplorationSections(markdownText) {
67
+ return checkBaseSections(markdownText, "validate-spike-file", EXPLORATION_SECTION_CODES);
68
+ }
69
+
70
+ export async function runCli(argv = process.argv.slice(2), { stdout = process.stdout } = {}) {
71
+ const options = parseCheckerCliArgs(argv, USAGE, "validate-spike-file");
72
+ if (options.help) {
73
+ stdout.write(`${USAGE}\n`);
74
+ return { ok: true, help: true };
75
+ }
76
+ const markdownText = await readFile(options.input, "utf8");
77
+ const result = validateSpikeFile(markdownText);
78
+ writeCheckerOutput(result, { stdout, json: options.json });
79
+ return result;
80
+ }
81
+
82
+ if (isDirectCliRun(import.meta.url)) {
83
+ runCli().catch((error) => {
84
+ process.stderr.write(`${formatCliError(error)}\n`);
85
+ process.exitCode = 1;
86
+ });
87
+ }
@@ -118,6 +118,16 @@ Info/handoff requests can be served directly via `node <dev-loops-package-root>/
118
118
  - `node <dev-loops-package-root>/cli/index.mjs loop info --pr <n>` — human-readable PR state summary (branch, CI, threads, rounds, action)
119
119
  - `node <dev-loops-package-root>/cli/index.mjs loop info --issue <n> --json` — machine-readable JSON output
120
120
 
121
+ ## Reading tool output (token-economical convention)
122
+
123
+ When you need a fact from a dev-loops JSON-emitting script, climb this ladder and stop at the first rung that answers the question — never read more output than you need:
124
+
125
+ 1. **Prefer the dev-loops subcommand / concise mode.** Use `loop info` or a script's `--concise`/`--summary` mode (e.g. `run-watch-cycle.mjs --concise`, `probe-copilot-review.mjs --concise`) for a human-readable digest. The concise modes surface loop state, Copilot round count, unresolved/actionable thread counts, round-cap-clean eligibility, CI status, next action, and the current round's new Copilot comment bodies.
126
+ 2. **`--silent` / `-s` for a yes/no check.** Reads ZERO output: `… --jq '<predicate>' --silent; echo $?` exits `0` for true / `1` for false. Without `--jq`, `--silent` maps the script's success (`ok:true`) to exit `0`, failure to `1`. Example: `probe-copilot-review.mjs --repo o/r --pr N --jq '.status=="idle"' -s`.
127
+ 3. **`--jq <filter>` to extract a single field.** The `--jq`-wired scripts (`probe-copilot-review.mjs`, `capture-review-threads.mjs`, `upsert-checkpoint-verdict.mjs`, the `scripts/projects/*` queue scripts) accept a gh-style `--jq` filter (jq subset: field access, `.[]`/`.[N]`, `|`, `select(...)`, `==`/`!=`/`<`/`<=`/`>`/`>=`, `length`, `keys`). It prints only the filtered value. An invalid filter fails closed (stderr + exit `2`), distinct from a clean predicate-false (silent exit `1`).
128
+ 4. **`gh … --jq` on a raw `gh` call** when no dev-loops script covers it.
129
+ 5. **NEVER `| python3` or `node -e`** to parse tool JSON. If a field you need is missing from a script's output, add it to the script (or its concise mode), not an inline parser.
130
+
121
131
  ## Guard rules
122
132
 
123
133
  **Handoff envelope precedence:** The dev-loop builds the envelope immediately after authoritative-state resolution and treats it as the first handoff artifact. Read it first, load only `requiredReads`, execute `nextAction`. See [Resolve authoritative state](#resolve-authoritative-state). Derivation contract: [Workflow Handoff Contract](../docs/workflow-handoff-contract.md).
@@ -128,7 +138,7 @@ Info/handoff requests can be served directly via `node <dev-loops-package-root>/
128
138
 
129
139
  **Bounded async task contract:** Break work into discrete tasks with clear inputs, explicit outputs, bounded scope. No shell polling — use `run-watch-cycle.mjs` or `gh run watch`.
130
140
 
131
- **Round-cap budget check (enforced):** After every watch cycle, fix pass, or reply-resolve, check whether completed Copilot review rounds have reached the maximum (default: 5). Stop re-requesting Copilot review when the limit is reached — never re-request after the cap.
141
+ **Round-cap budget check (enforced):** After every watch cycle, fix pass, or reply-resolve, check whether completed Copilot review rounds have reached the maximum (default: 5). Stop re-requesting Copilot review when the limit is reached — never re-request after the cap. Read these gate-cadence facts via the token-economical convention above (`run-watch-cycle.mjs --concise`, or `--jq`/`--silent` for a single field/predicate) — never `| python3` or `node -e`.
132
142
 
133
143
  ## Shorthand issue-based auto trigger contract
134
144
 
@@ -0,0 +1,54 @@
1
+ # Slides content & storytelling review prompt template
2
+
3
+ Use this template when running the bounded slides-story reviewer mode behind `dev-loop`.
4
+
5
+ You are a public-audience storytelling reviewer judging a deck's **narrative**, not its pixels. The visual designer/vision loop owns layout, spacing, and contrast; you own arc, message, sequencing, and audience fit.
6
+
7
+ ## Inputs
8
+
9
+ - `acceptanceCriteria`: required list of slice-level acceptance criteria the review is judging
10
+ - `storytellingBrief`: required short focus brief (audience, intended takeaway, what to watch for)
11
+ - `deckBundle.deckSourcePath`: required path to the deck source (e.g. the Slidev `.md`)
12
+ - `deckBundle.slideScreenshots[]`: optional captured slides from the UI smoke harness
13
+ - `slideId`
14
+ - `screenshotPath`
15
+
16
+ ## Review lens (public audience)
17
+
18
+ 1. **Arc**: hook → tension → resolution. Does slide 1 make a stranger care?
19
+ 2. **One message per slide**: each slide has a single takeaway; titles state the claim, not the topic.
20
+ 3. **Sequencing**: order builds understanding; no forward references; jargon introduced before it is used.
21
+ 4. **Audience calibration**: a public/non-insider reader can follow it — internal enum names, state-machine identifiers, and pills are translated or earn their keep, not dumped raw.
22
+ 5. **Cut / merge / reorder**: explicit recommendations — which slides to drop, combine, or move.
23
+ 6. **Close**: a memorable takeaway, not a feature list.
24
+
25
+ ## Review policy
26
+
27
+ 1. Fail closed on any missing, ambiguous, or unreadable required input — do not guess the narrative.
28
+ 2. Ground every finding in a specific `slideId` (and a `screenshotPath` when available).
29
+ 3. Return only deterministic findings tied to the brief and acceptance criteria; do not invent content.
30
+
31
+ ## Required output format
32
+
33
+ Allowed enum values:
34
+ - `outcome`: `"story_review_satisfied"` | `"needs_iteration"`
35
+ - `severity`: `"high"` | `"medium"` | `"low"`
36
+
37
+ Return strict JSON with this shape (example uses concrete values):
38
+
39
+ ```json
40
+ {
41
+ "outcome": "needs_iteration",
42
+ "summary": "short overall verdict on whether the deck lands",
43
+ "findings": [
44
+ {
45
+ "severity": "high",
46
+ "slideId": "hero",
47
+ "problem": "what is wrong with the narrative on this slide and why it fails the public audience",
48
+ "correctiveAction": "what to change next (cut/merge/reorder/reword)"
49
+ }
50
+ ]
51
+ }
52
+ ```
53
+
54
+ When `outcome` is `"needs_iteration"`, `findings` must be non-empty.
@@ -1,6 +1,6 @@
1
1
  # Artifact authority contract
2
2
 
3
- This document is the canonical authority for the artifact-selection model: when work originates from a GitHub issue (tracker-first) vs a persisted markdown plan file (local-planning).
3
+ This document is the canonical authority for the artifact-selection model: whether a work item originates from a GitHub issue (tracker-first) or from a persisted markdown plan file (local-planning).
4
4
 
5
5
  This canonical owner lives in the shipped `skills/docs/` surface because installed skill/runtime consumers reliably own the skills subtree. In installed layouts, read the same contract via [Artifact Authority Contract](../docs/artifact-authority-contract.md) from the installed skill directory.
6
6
 
@@ -8,9 +8,11 @@ Other repo docs may summarize or link this contract, but they should not redefin
8
8
 
9
9
  ## Two-tier model
10
10
 
11
- dev-loops supports two mutually exclusive artifact authority modes. Every work item must originate from exactly one authoritative artifact a GitHub issue or a persisted markdown plan file. No work may originate from a PR or direct local change unless explicitly requested.
11
+ dev-loops supports two mutually exclusive artifact authority modes. Every work item originates from exactly one authoritative artifact: a GitHub issue or a persisted markdown plan file. Work originates from a PR or a direct local change only when explicitly requested.
12
12
 
13
- ### Tracker-first (default)
13
+ The shipped extension default selects local-planning; see [Shipped default posture](#shipped-default-posture) below. The mode names that follow describe the two tiers; "default" in their headings refers to the github-first code-level fallback in `BUILT_IN_DEFAULTS`, which the shipped extension layer overrides to local-first.
14
+
15
+ ### Tracker-first
14
16
 
15
17
  **GitHub issues are the authoritative artifact store.** Work originates from a GitHub issue. A linked PR is the execution artifact. GitHub is the canonical source of truth for issue identity, acceptance criteria, scope, and lifecycle state.
16
18
 
@@ -25,12 +27,12 @@ Key contract:
25
27
  - When an open linked PR exists, reuse it rather than opening another
26
28
  - Implementation may proceed through either the GitHub-first routed path or the local implementation strategy (see [Public Dev Loop Contract](public-dev-loop-contract.md) `targetPreference`)
27
29
 
28
- ### Local-planning (opt-out)
30
+ ### Local-planning
29
31
 
30
- **Persisted markdown plan files are the authoritative artifact store.** Work originates from a markdown plan file committed to the repository. No GitHub issue is required. GitHub PRs are still used for review and merge, but the plan file is the canonical spec.
32
+ **Persisted markdown plan files are the authoritative artifact store.** Work originates from a local markdown plan file in the repo working tree, and no GitHub issue is required. The plan file stays uncommitted through authoring, refinement, and local review; promotion is the step that commits it (the helper sequence commits it as part of opening the PR). GitHub PRs carry review and merge while the plan file stays the canonical spec.
31
33
 
32
34
  Artifacts:
33
- - **Planning artifact:** Persisted markdown plan file (e.g., `docs/phases/phase-<n>.md`)
35
+ - **Planning artifact:** Persisted markdown plan file (e.g., `docs/phases/phase-<n>.md`); its format and required base sections are defined in the [Plan-file Contract](plan-file-contract.md)
34
36
  - **Execution artifact:** Local branch and associated GitHub PR (created during implementation)
35
37
  - **No GitHub issue:** The plan file replaces the issue as the canonical spec
36
38
 
@@ -41,10 +43,10 @@ Key contract:
41
43
 
42
44
  ### Mode selection table
43
45
 
44
- | Mode | Canonical artifact | GitHub issue required | Settings values |
46
+ | Mode | Canonical artifact | GitHub issue required | Settings value |
45
47
  |---|---|---|---|
46
- | Tracker-first (default) | GitHub issue | Yes | `strategy.default: github-first` |
47
- | Local-planning (opt-out) | Markdown plan file | No | `strategy.default: local-first` |
48
+ | Tracker-first | GitHub issue | Yes | `strategy.default: github-first` |
49
+ | Local-planning (shipped default) | Markdown plan file | No | `strategy.default: local-first` |
48
50
 
49
51
  `inputSource.default` further disambiguates local-first startup:
50
52
  | inputSource | Meaning |
@@ -54,62 +56,115 @@ Key contract:
54
56
 
55
57
  ## Settings mechanism
56
58
 
57
- Artifact authority mode is controlled by `.devloops` at repo root:
59
+ The repo's default artifact-authority posture is declared by `strategy.default`, set in `.devloops` at repo root and resolved against the layered config defaults:
58
60
 
59
61
  ```yaml
60
62
  # .devloops
61
63
  strategy:
62
- default: github-first # tracker-first (GitHub issue required)
63
- # default: local-first # local-planning (markdown plan file)
64
+ default: local-first # local-planning (markdown plan file)
65
+ # default: github-first # tracker-first (GitHub issue required)
64
66
  inputSource:
65
67
  default: tracker # spec source for local-first: tracker (issue body) or phase-docs
66
68
  ```
67
69
 
68
- The `strategy.default` key serves dual purpose:
69
- 1. It selects the artifact authority mode (tracker-first vs local-planning)
70
- 2. It sets the default routing preference for `targetPreference` in dev-loop startup
70
+ The `strategy.default` key carries two jobs:
71
+ 1. It declares the repo's default artifact-authority posture (local-planning under `local-first`, tracker-first under `github-first`).
72
+ 2. It sets the routing preference (`targetPreference`) in dev-loop startup — `prefer_local` under `local-first`, `prefer_github_first` under `github-first`.
73
+
74
+ The authoritative artifact for a given run is selected by the explicit startup input. `scripts/loop/resolve-dev-loop-startup.mjs` takes `--issue` / `--pr` / `--input` / `--plan-file` (mutually exclusive), and `strategy.default` supplies the default routing preference; it does not force the artifact per invocation.
71
75
 
72
76
  The `inputSource.default` key disambiguates local-first startup:
73
- - `tracker` (default): local agent implements from the GitHub issue body; the issue is canonical spec
74
- - `phase-docs`: local agent implements from persisted phase docs; no tracker issue required
77
+ - `tracker` (default): the local agent implements from the GitHub issue body; the issue is the canonical spec
78
+ - `phase-docs`: the local agent implements from persisted phase docs; no tracker issue required
79
+
80
+ ### Shipped default posture
75
81
 
76
- These keys are already defined in `.pi/dev-loop/defaults.yaml` (shipped with dev-loops) and may be overridden in `.devloops` (per-repo).
82
+ The effective default for a consumer comes from the config-merge layering in `packages/core/src/config/config.mjs`. Precedence, low to high:
77
83
 
78
- ### Defaults resolution
84
+ 1. `BUILT_IN_DEFAULTS` (frozen in `config.mjs`) — `strategy.default: github-first`. This is the code-level fallback when no other layer sets the key.
85
+ 2. Extension-packaged defaults (`packages/core/src/config/extension-defaults.yaml`, loaded as the `extensionDefaults` layer) — `strategy.default: local-first`. This is the opinion the package ships and the layer that wins over the built-in fallback.
86
+ 3. Repo-local `.pi/dev-loop/defaults.*` (legacy) — applied when present.
87
+ 4. Repo `.devloops` at repo root — the per-repo override, highest precedence. When `.devloops` is absent, the legacy `.pi/dev-loop/settings.*` / `overrides.*` apply at this position instead.
79
88
 
80
- 1. `.pi/dev-loop/defaults.yaml` shipped default (`github-first`)
81
- 2. `.devloops` — per-repo override (takes precedence)
89
+ With nothing but the shipped package in place, the extension layer resolves `strategy.default` to `local-first`, so the shipped default posture is local-planning (epic #947, decision #7). A repo opts back into tracker-first by setting `strategy.default: github-first` in its own `.devloops`.
90
+
91
+ Two legacy repo-local layers also exist under `.pi/dev-loop/` (the package no longer ships a `.pi/dev-loop/defaults.yaml`). They differ in how they load: `.pi/dev-loop/defaults.*` is always applied when present, between the extension defaults and `.devloops`; `.pi/dev-loop/settings.*` (and the older `overrides.*`) load only when no `.devloops` is present — when `.devloops` exists it is authoritative and those files are ignored (with a deprecation warning). The full precedence, low to high, is: `BUILT_IN_DEFAULTS` < extension defaults < `.pi/dev-loop/defaults.*` < repo `.devloops` (or, when `.devloops` is absent, `.pi/dev-loop/settings.*` / `overrides.*`).
82
92
 
83
93
  ### Explicit non-knobs
84
94
 
85
95
  These are not valid artifact authority mode selectors:
86
- - `strategy.default: copilot` — not a valid mode; must be `github-first` or `local-first`
96
+ - `strategy.default: copilot` — not a valid mode; the enum accepts only `github-first` or `local-first` (`packages/core/src/config/config.mjs`)
87
97
  - Free-form string values — fail closed
88
- - Omitting `strategy.default` entirelydefaults to `github-first` from the shipped defaults
98
+ - Omitting `strategy.default` from every layer resolves to `github-first` from `BUILT_IN_DEFAULTS`; with the shipped extension layer present it resolves to `local-first`
99
+
100
+ ## Local-first plan-file flow end to end
101
+
102
+ Under local-planning, one plan file moves through four stages. Each stage has a shipped helper script; the start, refine, and promote stages also expose their pure logic as an `@dev-loops/core` contract, while the validate stage's `validatePlanFile` lives in its helper script (`scripts/refine/validate-plan-file.mjs`). The [Local-Planning Flow](local-planning-flow.md) skill doc walks the same sequence as operator steps, and the [Local-Planning Worked Example](local-planning-worked-example.md) shows one plan file evolving through every stage.
103
+
104
+ ### P1 — Plan-file artifact + config (#949)
105
+
106
+ The plan file is a phase-doc-format markdown document. Its directory is `localPlanning.plansDir`, which defaults to `docs/phases/` (built-in default in `config.mjs`, mirrored in `extension-defaults.yaml`; `resolvePlansDir(config)` resolves it). Its required base authoring sections — `## Status`, `## Objective`, `## In scope`, `## Explicit non-goals` — and the validator `scripts/refine/validate-plan-file.mjs` (`validatePlanFile`, distinct `missing_*` codes per absent or empty section) are defined in the [Plan-file Contract](plan-file-contract.md).
107
+
108
+ ### P2 — Intake (#950)
109
+
110
+ `scripts/loop/resolve-dev-loop-startup.mjs` accepts `--plan-file <path>` (mutually exclusive with `--issue`, `--pr`, `--input`). It validates the plan and threads an intake state onto its output. The pure contract `@dev-loops/core/loop/plan-file-intake-contract` (`packages/core/src/loop/plan-file-intake-contract.mjs`) defines `evaluatePlanFileIntakeState` and the three `PLAN_FILE_INTAKE_STATE` values:
111
+
112
+ | State | Meaning |
113
+ |---|---|
114
+ | `new_plan_needs_refinement` | Base sections valid; the refinement sections are not yet present |
115
+ | `plan_refined_ready_for_promotion` | Base sections valid and both `PLAN_FILE_REFINEMENT_SECTIONS` (`Acceptance criteria`, `Definition of done`) present |
116
+ | `ambiguous_fail_closed` | Base sections invalid, or only one refinement section present — the resolver does not route the plan forward |
117
+
118
+ In the CLI, a base-valid plan carrying only one refinement section is reported as `ambiguous_fail_closed` with exit 0 (the operator completes the missing section before refine/promote); a missing/unreadable plan, or one that fails the base-section validator, makes startup exit 1 with no readiness bundle.
119
+
120
+ ### P3 — Local refine + review checkpoint (#951)
121
+
122
+ `scripts/refine/refine-plan-file.mjs` drives the refine step; the pure contract `@dev-loops/core/loop/plan-file-refine-contract` (`packages/core/src/loop/plan-file-refine-contract.mjs`) exports `refinePlanFileInPlace`, which writes the refiner payload back into the single canonical plan file in place — the `Acceptance criteria` and `Definition of done` sections, a `Coverage matrix` section (`COVERAGE_MATRIX_HEADING`), and a `Docs-grill findings` section (`DOCS_GRILL_FINDINGS_HEADING`) — then stops at the `local_human_review` checkpoint (`PLAN_FILE_REFINE_STOP.LOCAL_HUMAN_REVIEW`) with the intake state advanced to `plan_refined_ready_for_promotion`. The module performs no GitHub mutation, no network calls, and no filesystem I/O; the caller reads and writes the plan file. The docs-grill runs as a step within refinement: the CLI classifies each finding with `classifyDocsGrillFinding` (`scripts/loop/docs-grill-contract.mjs`) and the contract records the dispositions. See the [Docs-Grill Step](../../docs/docs-grill-step.md).
123
+
124
+ ### P4 — Promotion + authority transfer (#952)
125
+
126
+ `scripts/refine/promote-plan.mjs` promotes a refined plan; the pure contract `@dev-loops/core/loop/plan-file-promote-contract` (`packages/core/src/loop/plan-file-promote-contract.mjs`) exports `evaluatePromoteEligibility` and `buildPromotionPrBody`. Promotion is PR-first: it commits the plan doc and opens exactly one draft PR via the canonical PR wrapper, and mints no GitHub issue. The plan↔PR link is bidirectional — the PR body carries the committed plan-doc path (the spec-of-record) and the plan front-matter carries `prNumber:` (`PLAN_FILE_PR_FRONT_MATTER_KEY`). Promotion is idempotent: a plan that already carries `prNumber` resolves to `already_promoted` (`PLAN_FILE_PROMOTE_ACTION.ALREADY_PROMOTED`) and opens nothing. The optional `prNumber` front-matter and its parser/serializer are described in the [Plan-file Contract](plan-file-contract.md).
127
+
128
+ ### P5 — Local-first noise profile (#953)
129
+
130
+ The shipped extension layer pairs local-first with a low-noise posture, in `packages/core/src/config/extension-defaults.yaml`:
131
+
132
+ | Key | Shipped value | Why |
133
+ |---|---|---|
134
+ | `strategy.default` | `local-first` | The shipped default posture (decision #7) |
135
+ | `autonomy.humanMergeOnly` | `true` | Local-first never auto-merges; a human always merges |
136
+ | `queue.maxAutoFiledIssues` | `1` | Local-first is PR-first, so auto-filing issues is near-zero; a low cap keeps tracker noise minimal |
137
+ | `gates.postFindingsComments` | `true` | Gate findings live on the PR (the spec-of-record and human-review surface) as evidence |
138
+
139
+ These values come from the existing config-merge layering, so no new resolver is involved: `BUILT_IN_DEFAULTS` keeps the github-first posture (`humanMergeOnly: false`, `maxAutoFiledIssues: 10`), and the extension layer sets the local-first values above. A repo `.devloops` can override any of them.
89
140
 
90
141
  ## dev-loops own mode
91
142
 
92
- dev-loops is **tracker-first (opted in, GitHub backend).**
143
+ dev-loops runs **local-planning**, set in its repo-root `.devloops`.
93
144
 
94
- - **Mode:** Tracker-first
95
- - **Settings:** `.pi/dev-loop/defaults.yaml` sets `strategy.default: github-first`
96
- - **Artifact authority:** GitHub issues are the canonical spec for all work in this repository
97
- - **No local-planning override:** This repo does not opt out to local-planning mode
98
- - **Why tracker-first:** All work in this repo originates from GitHub issues. The public dev-loop contract, Copilot follow-up state machines, and gate pipeline all assume issues are the primary artifact. Self-improvement work on dev-loops itself follows the same tracker-first contract.
145
+ - **Mode:** Local-planning
146
+ - **Settings:** repo-root `.devloops` sets `strategy.default: local-first` and `inputSource.default: tracker`
147
+ - **Artifact authority:** the canonical spec for a work item is its plan artifact; the repo dogfoods the same local-first posture the package ships as default
148
+ - **Per-run input:** with `inputSource.default: tracker`, a local-first session can still implement from a GitHub issue body when one is supplied (the issue is the spec source for that run); `phase-docs` switches the source to a committed plan file
149
+ - **Why local-planning:** the repo runs the local-first plan-file flow (plan-file refine review promote) on its own work so the shipped default posture is exercised end to end.
99
150
 
100
151
  ## Relationship to other docs
101
152
 
102
153
  | Doc | Relationship |
103
154
  |---|---|
104
155
  | [Public Dev Loop Contract](public-dev-loop-contract.md) | This contract is the canonical entrypoint; artifact authority contract defines the artifact model it assumes |
105
- | [Tracker-First Loop State](tracker-first-loop-state.md) | That doc defines the PR-level state machine for tracker-first PR workflows it is about execution state, not artifact authority |
156
+ | [Plan-file Contract](plan-file-contract.md) | Defines the plan-file format (phase-doc format) and its required base sections for local-planning mode |
157
+ | [Local-Planning Flow](local-planning-flow.md) | Operator sequence for the local-first flow: validate → start → refine → promote, naming the shipped helper scripts |
158
+ | [Local-Planning Worked Example](local-planning-worked-example.md) | One plan file shown through every stage, with the file content evolving |
159
+ | [Spike-mode Contract](spike-mode-contract.md) | Time-boxed exploratory runs; a graduated spike emits a plan file that enters this local-planning tier |
160
+ | [Tracker-First Loop State](tracker-first-loop-state.md) | Defines the PR-level state machine for tracker-first PR workflows; that is execution state, separate from artifact authority |
106
161
  | [Main Agent Contract](main-agent-contract.md) | Defines the delegation boundary; artifact authority defines which artifacts govern work |
107
162
  | AGENTS.md | Repo constitution; cites the work-origin rule and points to this contract |
108
163
  | [Dev Loop Skill](../dev-loop/SKILL.md) | Public entrypoint skill; cites the work-origin rule and points to this contract |
109
164
 
110
165
  ### Distinction: artifact authority vs tracker-first PR workflow
111
166
 
112
- `tracker-first-loop-state.md` defines a state machine for PR lifecycle management when a tracker item (e.g., Shortcut story) drives a GitHub PR. That is a **PR-level workflow contract**, not the artifact authority model. The term "tracker-first" in that doc refers to tracker-driven PR state transitions it does not redefine the artifact authority contract defined here.
167
+ `tracker-first-loop-state.md` defines a state machine for PR lifecycle management when a tracker item (e.g., Shortcut story) drives a GitHub PR. It is a **PR-level workflow contract**. The term "tracker-first" there refers to tracker-driven PR state transitions, a separate concern from the artifact authority model this doc defines.
113
168
 
114
169
  ## Non-goals
115
170