ex-workflow 1.3.0 → 1.4.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.
- package/CHANGELOG.md +21 -0
- package/README.md +6 -4
- package/dist/{chunk-PFHVB2WT.mjs → chunk-3QUIRAXO.mjs} +2 -2
- package/dist/{chunk-PFHVB2WT.mjs.map → chunk-3QUIRAXO.mjs.map} +1 -1
- package/dist/chunk-3RJ4RNPG.cjs +2 -0
- package/dist/chunk-3RJ4RNPG.cjs.map +1 -0
- package/dist/chunk-66BO7JFR.cjs +2 -0
- package/dist/chunk-66BO7JFR.cjs.map +1 -0
- package/dist/{chunk-UMG3WOD7.cjs → chunk-76ITDJDM.cjs} +2 -2
- package/dist/{chunk-UMG3WOD7.cjs.map → chunk-76ITDJDM.cjs.map} +1 -1
- package/dist/chunk-AWFR3Q4M.mjs +2 -0
- package/dist/{chunk-5ZGNEY2I.mjs.map → chunk-AWFR3Q4M.mjs.map} +1 -1
- package/dist/chunk-BGKXIRGS.mjs +2 -0
- package/dist/chunk-BGKXIRGS.mjs.map +1 -0
- package/dist/chunk-BNKKOAMP.mjs +2 -0
- package/dist/{chunk-ILDXZWEL.mjs.map → chunk-BNKKOAMP.mjs.map} +1 -1
- package/dist/{chunk-YGCNLXPJ.cjs → chunk-CPM2SPDX.cjs} +2 -2
- package/dist/{chunk-YGCNLXPJ.cjs.map → chunk-CPM2SPDX.cjs.map} +1 -1
- package/dist/{chunk-EQXYFHHD.cjs → chunk-G6QELJRL.cjs} +2 -2
- package/dist/{chunk-EQXYFHHD.cjs.map → chunk-G6QELJRL.cjs.map} +1 -1
- package/dist/{chunk-UT7QV6CE.mjs → chunk-HXEJP6KF.mjs} +2 -2
- package/dist/{chunk-UT7QV6CE.mjs.map → chunk-HXEJP6KF.mjs.map} +1 -1
- package/dist/chunk-ILNSTPPV.mjs +2 -0
- package/dist/chunk-ILNSTPPV.mjs.map +1 -0
- package/dist/chunk-LQJPLXFR.cjs +2 -0
- package/dist/{chunk-RGHM3JJM.cjs.map → chunk-LQJPLXFR.cjs.map} +1 -1
- package/dist/chunk-MUQ4FKVH.mjs +2 -0
- package/dist/chunk-MUQ4FKVH.mjs.map +1 -0
- package/dist/chunk-N2NANHRW.mjs +2 -0
- package/dist/{chunk-5DCOXGRW.mjs.map → chunk-N2NANHRW.mjs.map} +1 -1
- package/dist/chunk-NNQ3RHDP.mjs +2 -0
- package/dist/chunk-NNQ3RHDP.mjs.map +1 -0
- package/dist/chunk-OAJ4KV4F.mjs +2 -0
- package/dist/{chunk-3S7F5QXK.mjs.map → chunk-OAJ4KV4F.mjs.map} +1 -1
- package/dist/chunk-OFFQTZEY.cjs +2 -0
- package/dist/chunk-OFFQTZEY.cjs.map +1 -0
- package/dist/chunk-QKW26EV2.mjs +2 -0
- package/dist/chunk-QKW26EV2.mjs.map +1 -0
- package/dist/{chunk-BANKVCYY.cjs → chunk-RMXEQ5HN.cjs} +2 -2
- package/dist/{chunk-BANKVCYY.cjs.map → chunk-RMXEQ5HN.cjs.map} +1 -1
- package/dist/chunk-TBLIZIWH.cjs +2 -0
- package/dist/chunk-TBLIZIWH.cjs.map +1 -0
- package/dist/{chunk-4F5HZLKD.cjs → chunk-U23IRPFF.cjs} +2 -2
- package/dist/{chunk-4F5HZLKD.cjs.map → chunk-U23IRPFF.cjs.map} +1 -1
- package/dist/chunk-WM3JM3H7.mjs +2 -0
- package/dist/chunk-WM3JM3H7.mjs.map +1 -0
- package/dist/chunk-YNYIHJOC.mjs +2 -0
- package/dist/{chunk-5GXB6GMX.mjs.map → chunk-YNYIHJOC.mjs.map} +1 -1
- package/dist/chunk-YRXFEM3F.cjs +2 -0
- package/dist/chunk-YRXFEM3F.cjs.map +1 -0
- package/dist/{chunk-3ZUBCA7Q.cjs → chunk-ZDT2BZGU.cjs} +2 -2
- package/dist/{chunk-3ZUBCA7Q.cjs.map → chunk-ZDT2BZGU.cjs.map} +1 -1
- package/dist/{chunk-H26KXQ3I.cjs → chunk-ZK3V66NC.cjs} +2 -2
- package/dist/{chunk-H26KXQ3I.cjs.map → chunk-ZK3V66NC.cjs.map} +1 -1
- package/dist/cli/bin.cjs +1 -1
- package/dist/cli/bin.cjs.map +1 -1
- package/dist/cli/bin.mjs +1 -1
- package/dist/cli/bin.mjs.map +1 -1
- package/dist/cli/index.cjs +1 -1
- package/dist/cli/index.mjs +1 -1
- package/dist/experimentation/index.cjs +1 -1
- package/dist/experimentation/index.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -8
- package/dist/index.d.ts +9 -8
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/investigation/index.cjs +1 -1
- package/dist/investigation/index.mjs +1 -1
- package/dist/kanban/index.cjs +1 -1
- package/dist/kanban/index.mjs +1 -1
- package/dist/policies/index.cjs +1 -1
- package/dist/policies/index.cjs.map +1 -1
- package/dist/policies/index.d.cts +4 -1
- package/dist/policies/index.d.ts +4 -1
- package/dist/policies/index.mjs +1 -1
- package/dist/policies/index.mjs.map +1 -1
- package/dist/registry/index.cjs +1 -1
- package/dist/registry/index.mjs +1 -1
- package/dist/scrum/index.cjs +1 -1
- package/dist/scrum/index.mjs +1 -1
- package/dist/waterfall/index.cjs +1 -1
- package/dist/waterfall/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-2FBA7RBS.cjs +0 -2
- package/dist/chunk-2FBA7RBS.cjs.map +0 -1
- package/dist/chunk-3S7F5QXK.mjs +0 -2
- package/dist/chunk-5DCOXGRW.mjs +0 -2
- package/dist/chunk-5GXB6GMX.mjs +0 -2
- package/dist/chunk-5ZGNEY2I.mjs +0 -2
- package/dist/chunk-COPYGMHE.mjs +0 -2
- package/dist/chunk-COPYGMHE.mjs.map +0 -1
- package/dist/chunk-CVGEIXW6.cjs +0 -2
- package/dist/chunk-CVGEIXW6.cjs.map +0 -1
- package/dist/chunk-CX2E7ZTQ.mjs +0 -2
- package/dist/chunk-CX2E7ZTQ.mjs.map +0 -1
- package/dist/chunk-ILDXZWEL.mjs +0 -2
- package/dist/chunk-LG23WXAP.mjs +0 -2
- package/dist/chunk-LG23WXAP.mjs.map +0 -1
- package/dist/chunk-MU26QW32.cjs +0 -2
- package/dist/chunk-MU26QW32.cjs.map +0 -1
- package/dist/chunk-OEHVWRJG.mjs +0 -2
- package/dist/chunk-OEHVWRJG.mjs.map +0 -1
- package/dist/chunk-RGHM3JJM.cjs +0 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.4.0 (2026-11-09)
|
|
4
|
+
|
|
5
|
+
Owner follow-ups of 1.3.0: three independence holes closed, each failing closed (a check that passed in 1.3 may refuse in 1.4, never the reverse): a worker self-attesting `context-grounded` (#47), a gate approved by an earlier author (#48), and a later snapshot dropping a required claim (#49). The decisions, the reproductions and the release-gate rows are in the design spec, section 28. The owner chose a minor release for these tightenings; the migration for each is below.
|
|
6
|
+
|
|
7
|
+
- Reserved policy `context-grounded` (#47): `evaluatePolicies` no longer accepts evidence `policy:context-grounded` for it. When no `customPolicy` hook answers it, the policy fails `policy:custom:context-grounded`, and the fix names `withContextGrounding` and `recordContextSnapshot`. A worker can therefore no longer attest the policy through `handoff.produced`. Every other custom policy keeps the 1.2 evidence check.
|
|
8
|
+
- CLI and context grounding (#47): every `exwf` command runs the registry methodology with the grounding hooks added (internal `withGroundingHooks`, which `withContextGrounding` now builds on). `exwf next`, `complete` and `brief` judge a `context-grounded` stage by the snapshots an SDK host recorded. No command or flag changes.
|
|
9
|
+
- Ceremonies (#47, gate): `withContextGrounding` refuses, with `invalid-input`, a stage whose policies a built-in ceremony checks without the hook: the Kanban first column's exit (`replenishment`), the Scrum `backlog` exit (Sprint Planning) and the Experimentation `building` entry. A policy there could never pass.
|
|
10
|
+
- Conflict of interest (#48): `checkGate`, `decide` and the Waterfall rule `approver-not-author` refuse an approval by any author of the item, not only the last one. The authors are every role dispatched from a stage before the gated one since the last rework, plus earlier work the rework did not send back, plus `authorOf`. A dispatch from a stage not in `state.stages` counts. A reviewer dispatched into the gated stage is still not an author. The fix names only non-authors, or says to register one.
|
|
11
|
+
- Planner (#48): a review goes to a reviewer that did none of the work when one exists, else to the first reviewer (whom the gate then refuses until a non-author approver is registered). One item can no longer fail the whole `next`.
|
|
12
|
+
- Context snapshots (#49): `contextOf` carries the `required` claims of every other valid fresh snapshot of the item (earlier or later), whoever recorded it. A carried claim the latest snapshot lacks is reported unverified, so `context-grounded` fails. Only an `item.rework` clears carried claims.
|
|
13
|
+
- Internal: `authorOf` and `lastDispatchBefore` move from `src/core/gates.ts` to `src/core/authors.ts` (still exported from the root entry), and the event index moves from `src/common` to `src/core`.
|
|
14
|
+
- Size: owner approved 2026-11-09 (spec 28), measured. `core+scrum` 61884 → 63954 B; every `core+<methodology>` and `core+registry` grows about +2070 B. `core+policies` 56597 → 58726 B, `dist/index.mjs` 1364 → 1398 B, `dist/{waterfall,registry}/index.mjs` +30 B each. `dist/policies/index.mjs` ratchets down 19820 → 9115 B. The version bump changed no size.
|
|
15
|
+
|
|
16
|
+
**Behaviour changes and migration.**
|
|
17
|
+
|
|
18
|
+
- **`context-grounded`:** without the hook, an item that passed on `policy:context-grounded` evidence is now skipped by `next` (reason `entry-policy`) and refused by `complete` (`policy-unmet`). Plan and complete through `withContextGrounding(m, { entry })` (or `exwf`), and record a qualifying snapshot with `recordContextSnapshot` (by `human` or a registered role that did not work on the item). If one of your own custom policies is named `context-grounded`, rename it.
|
|
19
|
+
- **Conflict of interest:** a role that worked on an item in any earlier stage (for example the developer or the tester before a `code-review` gate) may no longer approve its gate. Register another role with the gate's capability and `canApprove`, or decide as `human`.
|
|
20
|
+
- **Snapshots:** a later snapshot that drops a required claim no longer grounds the item. Repeat the claim with a source, or rework the item.
|
|
21
|
+
|
|
22
|
+
Compatibility: `state.json` unchanged (no new field), and a `.workflow/state.json` written by any earlier release loads unchanged (`test/compat.test.ts` replays the fixtures through 1.3.0). Schema documents: unchanged (ten). Event kinds: unchanged (71). Exports: unchanged (`test/api-surface.json` has no diff; `authorOf` and `lastDispatchBefore` keep their root export). CLI: unchanged (`USAGE`, commands, flags). Error codes: unchanged. Runtime dependencies: unchanged (`ex-flow`, `exsorted`). The deliberate behaviour changes are the three above; there is none for a run where no author approves its own item, no `context-grounded` policy rests on evidence, and snapshots repeat their required claims. `VERSION` is `"1.4.0"`.
|
|
23
|
+
|
|
3
24
|
## 1.3.0 (2026-11-06)
|
|
4
25
|
|
|
5
26
|
Composable policies: three opt-in policies a host adds to any methodology by wrapping it, risk-adaptive gates (#35), context-grounded entry (#36) and run comparison (#34), shipped from the new entry `ex-workflow/policies`; core gains only optional hooks that do nothing when unused. The decisions are in the design spec, section 27. Every change is additive.
|
package/README.md
CHANGED
|
@@ -246,7 +246,7 @@ Investigation and Experimentation store their record under `ext.investigation` /
|
|
|
246
246
|
|
|
247
247
|
## Composable policies
|
|
248
248
|
|
|
249
|
-
`ex-workflow/policies` holds policies you opt into per run by wrapping a methodology. A wrapped methodology keeps every other member, its `name` included, so it runs on the same core and its state persists through the file adapter like the plain one's. The policies are SDK-only: `exwf` runs the
|
|
249
|
+
`ex-workflow/policies` holds policies you opt into per run by wrapping a methodology. A wrapped methodology keeps every other member, its `name` included, so it runs on the same core and its state persists through the file adapter like the plain one's. The policies are SDK-only: `exwf` runs the built-in factory with only the context-grounding hooks added, so it judges a `context-grounded` stage by the snapshots an SDK host recorded (see [Known limitations](#known-limitations)).
|
|
250
250
|
|
|
251
251
|
### Risk-adaptive gates
|
|
252
252
|
|
|
@@ -583,10 +583,12 @@ Deliberate, documented, and stable within 1.x.
|
|
|
583
583
|
- **A custom methodology's state cannot go through the file adapter or the CLI.** The state schema accepts only the five built-in names in `methodology`, so `saveState`, `loadState` and every `exwf` command refuse it. Keep such a state through the SDK and persist it yourself.
|
|
584
584
|
- **No downgrade for Investigation and Experimentation.** 1.1.x cannot load a state that 1.2 wrote for those two methodologies: the 1.1 state schema rejects the `ext` field, and the legacy mirrors do not change that. Keep a run on 1.2 once 1.2 has saved it.
|
|
585
585
|
- **No downgrade for a state with evidence `data`.** 1.2.x cannot load a state carrying `Evidence.data` (a risk assessment or context snapshot recorded by `ex-workflow/policies`): its schema closes `Evidence`. Keep such a run on 1.3.
|
|
586
|
-
- **Policies are SDK-only.** `exwf` runs the
|
|
587
|
-
-
|
|
586
|
+
- **Policies are SDK-only.** `exwf` runs the built-in methodology with only the context-grounding hooks added (no risk gate), so `exwf complete` checks a gate's static requirements only. `exwf decide` does honour an escalation the SDK recorded (`gate.resolved`). Run completions of a risk-gated run through the SDK. There is no CLI command for snapshots or repository changes.
|
|
587
|
+
- **`context-grounded` is a reserved custom policy id.** Since 1.4 only the context-grounding hook answers it: `withContextGrounding` in the SDK, and every `exwf` command, which judges it by the snapshots an SDK host recorded with `recordContextSnapshot` (the CLI records none). An SDK call with the plain methodology fails closed: `next` skips the item with reason `entry-policy` and `complete` refuses `policy-unmet`; evidence `policy:context-grounded` never satisfies it, so a worker cannot attest it through `handoff.produced`. If one of your own custom policies is called `context-grounded`, rename it.
|
|
588
|
+
- **Ceremonies do not consult the grounding hook.** A built-in ceremony that checks stage policies (Kanban `replenishment` on the first column's exit, Scrum Sprint Planning on `backlog`'s exit, Experimentation on `building`'s entry) uses the plain methodology, so a `context-grounded` policy there could never pass; `withContextGrounding` refuses those stages with `invalid-input`. Ground a later stage, such as Kanban `dev`.
|
|
589
|
+
- **Ground a stage the engine evaluates.** The policy is checked where the engine reads stage policies: the planner on the entry of the stage it dispatches into, `complete()` on the exit of the item's stage. A policy on a stage neither reaches is never checked, for example Kanban `exit: ["ready"]` (Kanban copies the commitment column's exit into `dev`'s entry when the board is built, before the wrapper adds the policy) or Scrum `sprint`. Ground Kanban `dev` (`entry: ["dev"]`) or Scrum `in_progress`.
|
|
588
590
|
- **Context grounding on an existing state, and Kanban policy changes.** `withContextGrounding` adds its policy through `defaultStages`, so it reaches a state at `init`; for a state created before wrapping, add `{ kind: "custom", id: "context-grounded", description }` to the stage's `entryPolicy` yourself. A Kanban `operations-review` that changes the commitment column's policies rewrites the next column's entry policies and drops it; add it back the same way.
|
|
589
|
-
- **Independence at entry needs a known worker.** The policy compares the snapshot's recorder with the roles that worked on the item. A `todo` item never dispatched and without a `role` has no worker yet (the planner picks one after the entry check), so a snapshot by the role the planner then picks passes the entry check. Once that role is dispatched its snapshot stops counting: `contextOf` falls back to the latest earlier qualifying snapshot, which may be stale (the brief carries it with its `stale` paths, and an `exit` policy fails on it), or, with none, the brief has no `context` and an `exit` policy fails.
|
|
591
|
+
- **Independence at entry needs a known worker.** The policy compares the snapshot's recorder with the roles that worked on the item. A `todo` item never dispatched and without a `role` has no worker yet (the planner picks one after the entry check), so a snapshot by the role the planner then picks passes the entry check. Once that role is dispatched its snapshot stops counting: `contextOf` falls back to the latest earlier qualifying snapshot, which may be stale (the brief carries it with its `stale` paths, and an `exit` policy fails on it), or, with none, the brief has no `context` and an `exit` policy fails. Since 1.4 a later snapshot keeps the `required` claims of the snapshots it supersedes (one it omits is reported unverified), so that future worker cannot drop them; only a rework clears them. Set `role` on the item, or also pass `exit`, to have the check apply before the work.
|
|
590
592
|
- **`checkGate` alone sees the static gate.** The risk escalation is applied by `complete()` and `decide()`; a host calling `checkGate` directly gets the 1.2 answer.
|
|
591
593
|
|
|
592
594
|
- **Stale lock takeover** narrows the race to the gap between the stat and the unlink; no portable call closes it. On file systems without inodes (FAT, exFAT, some shares) only the mtime is compared. If a stale lock cannot be unlinked (read-only directory, EPERM), the command gives up after its retries with `invalid-input` naming the lock file; delete it by hand.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {c}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {c}from'./chunk-NNQ3RHDP.mjs';import {b}from'./chunk-YS6CXERQ.mjs';var l=r=>r.agreements.length===0?"(none)":r.agreements.map(e=>`"${e}"`).join(", ");function a(r,e,n){return b("invalid-input",`no working agreement ${JSON.stringify(e)} to ${n}`,`current agreements: ${l(r)}; name one of them exactly`)}function m(r,e,n,s){if(e.replaces===e.text)return r;let t=r;return e.replaces!==void 0&&((typeof e.replaces!="string"||!t.agreements.includes(e.replaces))&&a(t,e.replaces,"replace"),t={...t,agreements:t.agreements.filter(i=>i!==e.replaces)},t=c(t,"agreement.retired",n,{text:e.replaces,replacedBy:e.text},s)),t.agreements.includes(e.text)||(t={...t,agreements:[...t.agreements,e.text]}),t}function w(r,e,n,s){(typeof e!="string"||!r.agreements.includes(e))&&a(r,e,"retire");let t={...r,agreements:r.agreements.filter(i=>i!==e)};return c(t,"agreement.retired",n,{text:e,replacedBy:null},s)}export{m as a,w as b};//# sourceMappingURL=chunk-3QUIRAXO.mjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-3QUIRAXO.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/agreements.ts"],"names":["listed","s","a","absent","text","what","fail","applyAgreement","state","change","by","now","appendEvent","retireAgreement"],"mappings":"0EAIA,IAAMA,EAAUC,CAAAA,EACdA,CAAAA,CAAE,WAAW,MAAA,GAAW,CAAA,CAAI,SAAWA,CAAAA,CAAE,UAAA,CAAW,GAAA,CAAKC,CAAAA,EAAM,IAAIA,CAAC,CAAA,CAAA,CAAG,EAAE,IAAA,CAAK,IAAI,EAEpF,SAASC,CAAAA,CAAOF,CAAAA,CAA0BG,CAAAA,CAAeC,EAAqB,CAC5E,OAAOC,EACL,eAAA,CACA,CAAA,qBAAA,EAAwB,KAAK,SAAA,CAAUF,CAAI,CAAC,CAAA,IAAA,EAAOC,CAAI,GACvD,CAAA,oBAAA,EAAuBL,CAAAA,CAAOC,CAAC,CAAC,CAAA,0BAAA,CAClC,CACF,CAeO,SAASM,CAAAA,CACdC,CAAAA,CACAC,EACAC,CAAAA,CACAC,CAAAA,CACkB,CAClB,GAAIF,CAAAA,CAAO,WAAaA,CAAAA,CAAO,IAAA,CAA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|
+
{"version":3,"sources":["../src/core/agreements.ts"],"names":["listed","s","a","absent","text","what","fail","applyAgreement","state","change","by","now","appendEvent","retireAgreement"],"mappings":"0EAIA,IAAMA,EAAUC,CAAAA,EACdA,CAAAA,CAAE,WAAW,MAAA,GAAW,CAAA,CAAI,SAAWA,CAAAA,CAAE,UAAA,CAAW,GAAA,CAAKC,CAAAA,EAAM,IAAIA,CAAC,CAAA,CAAA,CAAG,EAAE,IAAA,CAAK,IAAI,EAEpF,SAASC,CAAAA,CAAOF,CAAAA,CAA0BG,CAAAA,CAAeC,EAAqB,CAC5E,OAAOC,EACL,eAAA,CACA,CAAA,qBAAA,EAAwB,KAAK,SAAA,CAAUF,CAAI,CAAC,CAAA,IAAA,EAAOC,CAAI,GACvD,CAAA,oBAAA,EAAuBL,CAAAA,CAAOC,CAAC,CAAC,CAAA,0BAAA,CAClC,CACF,CAeO,SAASM,CAAAA,CACdC,CAAAA,CACAC,EACAC,CAAAA,CACAC,CAAAA,CACkB,CAClB,GAAIF,CAAAA,CAAO,WAAaA,CAAAA,CAAO,IAAA,CAAM,OAAOD,CAAAA,CAC5C,IAAIP,CAAAA,CAAIO,CAAAA,CACR,OAAIC,CAAAA,CAAO,QAAA,GAAa,UAClB,OAAOA,CAAAA,CAAO,QAAA,EAAa,QAAA,EAAY,CAACR,CAAAA,CAAE,UAAA,CAAW,SAASQ,CAAAA,CAAO,QAAQ,IAC/EN,CAAAA,CAAOF,CAAAA,CAAGQ,EAAO,QAAA,CAAU,SAAS,EACtCR,CAAAA,CAAI,CAAE,GAAGA,CAAAA,CAAG,UAAA,CAAYA,EAAE,UAAA,CAAW,MAAA,CAAQC,CAAAA,EAAMA,CAAAA,GAAMO,EAAO,QAAQ,CAAE,EAC1ER,CAAAA,CAAIW,CAAAA,CACFX,EACA,mBAAA,CACAS,CAAAA,CACA,CAAE,IAAA,CAAMD,EAAO,QAAA,CAAU,UAAA,CAAYA,EAAO,IAAK,CAAA,CACjDE,CACF,CAAA,CAAA,CAEGV,CAAAA,CAAE,UAAA,CAAW,QAAA,CAASQ,EAAO,IAAI,CAAA,GAAGR,EAAI,CAAE,GAAGA,EAAG,UAAA,CAAY,CAAC,GAAGA,CAAAA,CAAE,UAAA,CAAYQ,EAAO,IAAI,CAAE,GACzFR,CACT,CAeO,SAASY,CAAAA,CACdL,CAAAA,CACAJ,CAAAA,CACAM,CAAAA,CACAC,EACkB,CAAA,CACd,OAAOP,GAAS,QAAA,EAAY,CAACI,EAAM,UAAA,CAAW,QAAA,CAASJ,CAAI,CAAA,GAAGD,CAAAA,CAAOK,EAAOJ,CAAAA,CAAM,QAAQ,EAC9F,IAAMH,CAAAA,CAAI,CAAE,GAAGO,CAAAA,CAAO,UAAA,CAAYA,CAAAA,CAAM,WAAW,MAAA,CAAQN,CAAAA,EAAMA,IAAME,CAAI,CAAE,EAC7E,OAAOQ,CAAAA,CAAYX,EAAG,mBAAA,CAAqBS,CAAAA,CAAI,CAAE,IAAA,CAAAN,CAAAA,CAAM,WAAY,IAAK,CAAA,CAAGO,CAAG,CAChF","file":"chunk-3QUIRAXO.mjs","sourcesContent":["import { fail } from \"./errors.ts\";\nimport { appendEvent } from \"./state.ts\";\nimport type { WorkflowState } from \"./types.ts\";\n\nconst listed = (s: WorkflowState<string>) =>\n s.agreements.length === 0 ? \"(none)\" : s.agreements.map((a) => `\"${a}\"`).join(\", \");\n\nfunction absent(s: WorkflowState<string>, text: unknown, what: string): never {\n return fail(\n \"invalid-input\",\n `no working agreement ${JSON.stringify(text)} to ${what}`,\n `current agreements: ${listed(s)}; name one of them exactly`,\n );\n}\n\n/** Adds an agreement (idempotent); with `replaces`, retires that one in the same step. */\nexport function applyAgreement<N extends string>(\n state: WorkflowState<N>,\n change: { text: string; replaces?: string },\n by: string,\n now: string,\n): WorkflowState<N>;\nexport function applyAgreement(\n state: WorkflowState,\n change: { text: string; replaces?: string },\n by: string,\n now: string,\n): WorkflowState;\nexport function applyAgreement<N extends string>(\n state: WorkflowState<N>,\n change: { text: string; replaces?: string },\n by: string,\n now: string,\n): WorkflowState<N> {\n if (change.replaces === change.text) return state;\n let s = state;\n if (change.replaces !== undefined) {\n if (typeof change.replaces !== \"string\" || !s.agreements.includes(change.replaces))\n absent(s, change.replaces, \"replace\");\n s = { ...s, agreements: s.agreements.filter((a) => a !== change.replaces) };\n s = appendEvent(\n s,\n \"agreement.retired\",\n by,\n { text: change.replaces, replacedBy: change.text },\n now,\n );\n }\n if (!s.agreements.includes(change.text)) s = { ...s, agreements: [...s.agreements, change.text] };\n return s;\n}\n\n/** Removes an agreement and records why it left (replacedBy null). */\nexport function retireAgreement<N extends string>(\n state: WorkflowState<N>,\n text: string,\n by: string,\n now: string,\n): WorkflowState<N>;\nexport function retireAgreement(\n state: WorkflowState,\n text: string,\n by: string,\n now: string,\n): WorkflowState;\nexport function retireAgreement<N extends string>(\n state: WorkflowState<N>,\n text: string,\n by: string,\n now: string,\n): WorkflowState<N> {\n if (typeof text !== \"string\" || !state.agreements.includes(text)) absent(state, text, \"retire\");\n const s = { ...state, agreements: state.agreements.filter((a) => a !== text) };\n return appendEvent(s, \"agreement.retired\", by, { text, replacedBy: null }, now);\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkG6QELJRL_cjs=require('./chunk-G6QELJRL.cjs'),chunk66BO7JFR_cjs=require('./chunk-66BO7JFR.cjs'),chunkKA6DVHO5_cjs=require('./chunk-KA6DVHO5.cjs'),chunkLQJPLXFR_cjs=require('./chunk-LQJPLXFR.cjs'),chunkYRXFEM3F_cjs=require('./chunk-YRXFEM3F.cjs'),chunkTBLIZIWH_cjs=require('./chunk-TBLIZIWH.cjs'),chunkDVFTTBCT_cjs=require('./chunk-DVFTTBCT.cjs'),chunkOSHBJIYD_cjs=require('./chunk-OSHBJIYD.cjs'),promises=require('fs/promises'),y=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var y__default=/*#__PURE__*/_interopDefault(y);var et=r=>r!==void 0&&chunkG6QELJRL_cjs.c().includes(r)?chunkG6QELJRL_cjs.b(r):void 0,h=["exwf init <scrum|kanban|waterfall|investigation|experimentation> --config <file> [--roles <file>]","exwf add <item.json> [--by who] exwf edit <id> <patch.json> [--by who]","exwf next [--max n] [--fallback-tokens-per-weight n]","exwf complete <id> <handoff.json> --tokens-in n --tokens-out n --duration-ms n --model m [--estimate] [--role r]","exwf account <item> [--line n] [--tokens-in n] [--tokens-out n] [--duration-ms n] [--model m] [--by who]","exwf ceremony <name> [input.json] [--by who]","exwf decide <pendingId> approve|reject [--by who] [--note text]","exwf config set <patch.json> [--by who] exwf unblock <item> [--blocker id] [--note text] [--by who]","exwf status | board | metrics | pending | lessons","exwf validate <action.json> exwf role add <manifest.json> | role list"],at=new Set(["estimate"]);function ot(r){let t=[],u={};for(let a=0;a<r.length;a++){let S=r[a];if(S.startsWith("--")){let n=S.slice(2);if(at.has(n)){u[n]="true";continue}let f=r[a+1];(f===void 0||f.startsWith("--"))&&chunkOSHBJIYD_cjs.b("invalid-input",`--${n} needs a value`,`pass --${n} <text>`),u[n]=f,a++;}else t.push(S);}return {positional:t,flags:u}}async function x(r){try{return JSON.parse(await promises.readFile(r,"utf8"))}catch(t){return chunkOSHBJIYD_cjs.b("invalid-input",`cannot read JSON from ${r}: ${t.message}`,"check the path and that the file is valid JSON")}}function w(r){let t=et(r.methodology);return t||chunkOSHBJIYD_cjs.b("config-invalid",`methodology "${r.methodology}" is not available in this build`,`available: ${chunkG6QELJRL_cjs.c().join(", ")}`),chunk66BO7JFR_cjs.k(t())}function b(r,t){let u=Number(r[t]);return Number.isFinite(u)||chunkOSHBJIYD_cjs.b("invalid-input",`--${t} must be a number (got ${JSON.stringify(r[t])})`,`pass --${t} <n>`),u}var rt=new Set(["init","add","edit","next","complete","account","ceremony","decide","unblock"]);async function $t(r,t){try{let[u,a]=ot(r).positional;return u!==void 0&&(rt.has(u)||u==="role"&&a==="add"||u==="config"&&a==="set")?await chunkKA6DVHO5_cjs.c(t,()=>tt(r,t)):await tt(r,t)}catch(u){if(u instanceof chunkOSHBJIYD_cjs.a)return {exit:1,out:{ok:false,error:u.toJSON()}};throw u}}async function tt(r,t){let{positional:u,flags:a}=ot(r),[S,...n]=u,f=a.by??"human",d=new Date().toISOString();switch(S){case "init":{let[o]=n,e=et(o);if(!e||!a.config)return {exit:2,out:{ok:false,usage:h}};try{await promises.stat(chunkKA6DVHO5_cjs.b(t)),chunkOSHBJIYD_cjs.b("invalid-input",`${chunkKA6DVHO5_cjs.b(t)} already exists`,"delete .workflow/state.json to start over");}catch(c){if(c instanceof chunkOSHBJIYD_cjs.a||c.code!=="ENOENT")throw c}let i=await x(y__default.default.resolve(t,a.config)),s=a.roles?await x(y__default.default.resolve(t,a.roles)):void 0;if(s!==void 0){Array.isArray(s)||chunkOSHBJIYD_cjs.b("invalid-input",`roles file ${a.roles} must contain an array of role manifests`,"wrap the manifests in [ ... ]");for(let c of s)chunkDVFTTBCT_cjs.b(chunkDVFTTBCT_cjs.e,c,`roles file ${a.roles}`);}let l=chunkTBLIZIWH_cjs.W(s?{methodology:e(),config:i,roles:s,by:f,now:d}:{methodology:e(),config:i,by:f,now:d});return await chunkKA6DVHO5_cjs.d(t,l.state),{exit:0,out:{ok:true,warnings:l.warnings,state:{methodology:l.state.methodology,stages:l.state.stages.map(c=>c.id),roles:Object.keys(l.state.roles)}}}}case "add":{if(!n[0])return {exit:2,out:{ok:false,usage:h}};let o=await chunkKA6DVHO5_cjs.e(t),e=await x(y__default.default.resolve(t,n[0]));chunkDVFTTBCT_cjs.b(chunkDVFTTBCT_cjs.f,e,`item file ${n[0]}`);let i=chunkTBLIZIWH_cjs.V(o,w(o),{type:"item.add",by:f,payload:{item:e}},s=>chunkTBLIZIWH_cjs.t(s,e,f,d));return await chunkKA6DVHO5_cjs.d(t,i.state),{exit:0,out:{ok:true,warnings:i.warnings,item:chunkTBLIZIWH_cjs.s(i.state,e.id)}}}case "edit":{if(!n[0]||!n[1])return {exit:2,out:{ok:false,usage:h}};let o=await chunkKA6DVHO5_cjs.e(t),e=n[0],i=await x(y__default.default.resolve(t,n[1]));chunkDVFTTBCT_cjs.b(chunkDVFTTBCT_cjs.g,i,`patch file ${n[1]}`);let s=chunkTBLIZIWH_cjs.V(o,w(o),{type:"item.edit",by:f,payload:{id:e,patch:i}},l=>chunkTBLIZIWH_cjs.u(l,e,i,f,d));return await chunkKA6DVHO5_cjs.d(t,s.state),{exit:0,out:{ok:true,warnings:s.warnings,item:chunkTBLIZIWH_cjs.s(s.state,e)}}}case "next":{let o=await chunkKA6DVHO5_cjs.e(t),e={now:d};a.max&&(e.max=b(a,"max")),a["fallback-tokens-per-weight"]&&(e.fallbackTokensPerWeight=b(a,"fallback-tokens-per-weight"));let i=chunkLQJPLXFR_cjs.e(o,w(o),e);await chunkKA6DVHO5_cjs.f(t,i.briefs.map(s=>s.item.id));for(let s of i.briefs)await chunkKA6DVHO5_cjs.g(t,s);return await chunkKA6DVHO5_cjs.d(t,i.state),{exit:0,out:{ok:true,reason:i.reason??null,skipped:i.skipped,briefs:i.briefs}}}case "complete":{if(!n[0]||!n[1])return {exit:2,out:{ok:false,usage:h}};let o=await chunkKA6DVHO5_cjs.e(t),e=await x(y__default.default.resolve(t,n[1]));chunkDVFTTBCT_cjs.b(chunkDVFTTBCT_cjs.h,e,`handoff file ${n[1]}`),e.item!==n[0]&&chunkOSHBJIYD_cjs.b("handoff-invalid",`handoff.item "${e.item}" differs from the command's item "${n[0]}"`,"make them match");let i=a.role??e.role,s=b(a,"duration-ms"),l=Date.parse(d)-s;(!Number.isFinite(s)||Number.isNaN(new Date(l).getTime()))&&chunkOSHBJIYD_cjs.b("invalid-input",`--duration-ms must be a number of milliseconds that dates the start (got ${a["duration-ms"]})`,"pass the measured wall-clock time in ms, e.g. --duration-ms 42000");let c={item:n[0],role:i,model:a.model??"",tokensIn:b(a,"tokens-in"),tokensOut:b(a,"tokens-out"),durationMs:s,startedAt:new Date(l).toISOString(),endedAt:d};a.estimate==="true"&&(c.estimate=true);let k=chunkLQJPLXFR_cjs.f(o,w(o),{...e,role:i},c,d);return await chunkKA6DVHO5_cjs.h(t,e,k.state.events.length),await chunkKA6DVHO5_cjs.d(t,k.state),{exit:0,out:{ok:true,warnings:k.warnings,item:chunkTBLIZIWH_cjs.s(k.state,n[0])}}}case "account":{if(!n[0])return {exit:2,out:{ok:false,usage:h}};let o=await chunkKA6DVHO5_cjs.e(t),e={};a["tokens-in"]!==void 0&&(e.tokensIn=b(a,"tokens-in")),a["tokens-out"]!==void 0&&(e.tokensOut=b(a,"tokens-out")),a["duration-ms"]!==void 0&&(e.durationMs=b(a,"duration-ms")),a.model!==void 0&&(e.model=a.model);let i=a.line!==void 0?b(a,"line"):void 0,s=chunkLQJPLXFR_cjs.g(o,n[0],e,a.by??"human",d,i);await chunkKA6DVHO5_cjs.d(t,s);let l=chunkTBLIZIWH_cjs.d(s),c=l.payload.line;return {exit:0,out:{ok:true,line:s.accounting.filter(A=>A.item===n[0])[c-1],event:l}}}case "ceremony":{if(!n[0])return {exit:2,out:{ok:false,usage:h}};let o=await chunkKA6DVHO5_cjs.e(t),e=w(o),i=Object.hasOwn(e.ceremonies,n[0])?e.ceremonies[n[0]]:void 0;i||chunkOSHBJIYD_cjs.b("unknown-ceremony",`"${n[0]}" is not a ${e.name} ceremony`,`available: ${Object.keys(e.ceremonies).join(", ")}`);let s=n[1]?await x(y__default.default.resolve(t,n[1])):{},l=i(o,{...s,by:f,now:d});return await chunkKA6DVHO5_cjs.d(t,l.state),{exit:0,out:{ok:true,warnings:l.warnings,lastEvent:chunkTBLIZIWH_cjs.d(l.state)}}}case "config":{if(n[0]!=="set"||!n[1])return {exit:2,out:{ok:false,usage:h}};let o=await chunkKA6DVHO5_cjs.e(t),e=await x(y__default.default.resolve(t,n[1])),i=chunkTBLIZIWH_cjs.X(o,w(o),e,f,d);return await chunkKA6DVHO5_cjs.d(t,i.state),{exit:0,out:{ok:true,warnings:i.warnings,changed:chunkTBLIZIWH_cjs.d(i.state).payload.changed,config:i.state.config}}}case "unblock":{if(!n[0])return {exit:2,out:{ok:false,usage:h}};let o=n[0],e=await chunkKA6DVHO5_cjs.e(t),i=chunkTBLIZIWH_cjs.s(e,o).blockers.filter(k=>!k.clearedAt).map(k=>k.id);i.length===0&&chunkOSHBJIYD_cjs.b("invalid-input",`item ${o} has no open blocker`,"nothing to clear; check exwf board");let s=a.blocker!==void 0?[a.blocker]:i,l=a.note,c=chunkTBLIZIWH_cjs.V(e,w(e),{type:"blocker.clear",by:f,payload:{id:o,blockers:s,note:l??null}},k=>s.reduce((A,nt)=>chunkYRXFEM3F_cjs.b(A,o,nt,f,d,l),k));return await chunkKA6DVHO5_cjs.d(t,c.state),{exit:0,out:{ok:true,warnings:c.warnings,item:chunkTBLIZIWH_cjs.s(c.state,o)}}}case "decide":{if(!n[0]||n[1]!=="approve"&&n[1]!=="reject")return {exit:2,out:{ok:false,usage:h}};let o=await chunkKA6DVHO5_cjs.e(t),e=o.pending.find(s=>s.id===n[0]),i=chunkYRXFEM3F_cjs.f(o,n[0],n[1],f,a.note??"",d,w(o));return await chunkKA6DVHO5_cjs.d(t,i),{exit:0,out:{ok:true,item:e?.item?chunkTBLIZIWH_cjs.s(i,e.item):null}}}case "status":{let o=await chunkKA6DVHO5_cjs.e(t),e=w(o),i={todo:0,in_progress:0,blocked:0,review:0,awaiting_human:0,done:0,dropped:0};for(let s of Object.values(o.items))i[s.status]+=1;return {exit:0,out:{ok:true,methodology:o.methodology,openIteration:chunkTBLIZIWH_cjs.O(o)??null,counts:i,pending:o.pending,openQuestions:chunkLQJPLXFR_cjs.d(o),lastEvent:chunkTBLIZIWH_cjs.d(o),report:e.report?e.report(o):null}}}case "board":{let o=await chunkKA6DVHO5_cjs.e(t);return {exit:0,out:{ok:true,columns:o.stages.map(i=>({stage:i.id,wipLimit:i.wipLimit??null,items:Object.values(o.items).filter(s=>s.stage===i.id&&s.status!=="dropped").map(s=>({id:s.id,title:s.title,status:s.status,role:s.role??null,age:s.transitions.length?Date.parse(d)-Date.parse(s.transitions[s.transitions.length-1].at):null}))}))}}}case "metrics":{let o=await chunkKA6DVHO5_cjs.e(t);return {exit:0,out:{ok:true,metrics:w(o).metrics(o)}}}case "pending":return {exit:0,out:{ok:true,pending:(await chunkKA6DVHO5_cjs.e(t)).pending}};case "lessons":return {exit:0,out:{ok:true,lessons:(await chunkKA6DVHO5_cjs.e(t)).lessons}};case "validate":{if(!n[0])return {exit:2,out:{ok:false,usage:h}};let o=await chunkKA6DVHO5_cjs.e(t),e=await x(y__default.default.resolve(t,n[0]));return (typeof e!="object"||e===null||Array.isArray(e)||typeof e.type!="string")&&chunkOSHBJIYD_cjs.b("invalid-input",`action file ${n[0]} must hold an object with a string "type"`,'write the action as { "type": "...", "by": "<role>", "payload": { ... } }'),{exit:0,out:{ok:true,violations:chunkTBLIZIWH_cjs.U(o,w(o),e)}}}case "role":{let o=await chunkKA6DVHO5_cjs.e(t);if(n[0]==="list")return {exit:0,out:{ok:true,roles:Object.keys(o.roles),detail:o.roles}};if(n[0]==="add"&&n[1]){let e=await x(y__default.default.resolve(t,n[1]));chunkDVFTTBCT_cjs.b(chunkDVFTTBCT_cjs.e,e,`role manifest ${n[1]}`);let i=chunkLQJPLXFR_cjs.a(o,e,f,d);return await chunkKA6DVHO5_cjs.d(t,i),{exit:0,out:{ok:true,roles:Object.keys(i.roles)}}}return {exit:2,out:{ok:false,usage:h}}}default:return {exit:2,out:{ok:false,usage:h}}}}exports.a=h;exports.b=ot;exports.c=$t;//# sourceMappingURL=chunk-3RJ4RNPG.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-3RJ4RNPG.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/commands.ts"],"names":["factoryOf","name","registeredMethodologies","methodologyFactory","USAGE","BOOLEAN_FLAGS","parseArgs","argv","positional","flags","i","a","key","val","fail","readJson","file","readFile","e","methodologyOf","state","f","withGroundingHooks","num","v","WRITERS","runCommand","cwd","cmd","sub","withStateLock","execute","WorkflowError","rest","by","now","stat","statePath","config","path","roles","r","assertValid","roleSchema","res","init","saveState","s","loadState","item","newItemSchema","applyAction","addItem","getItem","id","patch","itemPatchSchema","editItem","opts","next","checkBriefNames","b","saveBrief","handoff","handoffSchema","role","durationMs","startedAt","acc","complete","saveHandoff","line","s2","correctAccounting","ev","lastEvent","idx","m","c","input","changeConfig","open","blockers","note","clearBlocker","entry","p","decide","counts","openIteration","openQuestions","st","action","validateAction","manifest","registerRole"],"mappings":"mkBA4CA,IAAMA,EAAAA,CAAaC,CAAAA,EACjBA,CAAAA,GAAS,MAAA,EAAaC,mBAAAA,EAAwB,CAAE,QAAA,CAASD,CAAI,CAAA,CACxDE,mBAAAA,CAAmBF,CAAI,CAAA,CACxB,MAAA,CAEOG,CAAAA,CAAQ,CACnB,mGAAA,CACA,6EAAA,CACA,sDAAA,CACA,kHAAA,CACA,0GAAA,CACA,+CACA,iEAAA,CACA,2GAAA,CACA,mDAAA,CACA,gFACF,CAAA,CAOMC,EAAAA,CAAgB,IAAI,GAAA,CAAI,CAAC,UAAU,CAAC,EAEnC,SAASC,EAAAA,CAAUC,CAAAA,CAAwB,CAChD,IAAMC,CAAAA,CAAuB,EAAC,CACxBC,CAAAA,CAAgC,EAAC,CACvC,IAAA,IAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIH,CAAAA,CAAK,MAAA,CAAQG,CAAAA,EAAAA,CAAK,CACpC,IAAMC,CAAAA,CAAIJ,CAAAA,CAAKG,CAAC,CAAA,CAChB,GAAIC,CAAAA,CAAE,UAAA,CAAW,IAAI,CAAA,CAAG,CACtB,IAAMC,CAAAA,CAAMD,CAAAA,CAAE,KAAA,CAAM,CAAC,CAAA,CACrB,GAAIN,EAAAA,CAAc,GAAA,CAAIO,CAAG,CAAA,CAAG,CAC1BH,CAAAA,CAAMG,CAAG,CAAA,CAAI,MAAA,CACb,QACF,CACA,IAAMC,CAAAA,CAAMN,CAAAA,CAAKG,CAA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cjs","sourcesContent":["import { readFile, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n checkBriefNames,\n loadState,\n saveBrief,\n saveHandoff,\n saveState,\n statePath,\n withStateLock,\n} from \"../adapters/file.ts\";\nimport { next as planNext, openQuestions } from \"../core/brief.ts\";\nimport { complete } from \"../core/complete.ts\";\nimport { correctAccounting, type AccountingPatch } from \"../core/accounting.ts\";\nimport { WorkflowError, fail } from \"../core/errors.ts\";\nimport { decide } from \"../core/gates.ts\";\nimport { addItem, editItem, getItem } from \"../core/items/record.ts\";\nimport { clearBlocker } from \"../core/items/blockers.ts\";\nimport type { ItemPatch } from \"../core/types.ts\";\nimport { applyAction, changeConfig, init, validateAction } from \"../core/methodology.ts\";\nimport { openIteration, type PlanOptions } from \"../core/planner.ts\";\nimport { registerRole } from \"../core/roles/registry.ts\";\nimport {\n assertValid,\n handoffSchema,\n itemPatchSchema,\n newItemSchema,\n roleSchema,\n} from \"../schema/index.ts\";\nimport { lastEvent } from \"../core/state.ts\";\nimport { withGroundingHooks } from \"../interface/policies.ts\";\nimport { methodologyFactory, registeredMethodologies } from \"../registry.ts\";\nimport type {\n Accounting,\n Action,\n Handoff,\n ItemStatus,\n Methodology,\n NewItem,\n Role,\n WorkflowState,\n} from \"../core/types.ts\";\n\n/** The factory `name` resolves to in the methodology registry (built-ins pre-registered), if any. */\nconst factoryOf = (name: string | undefined): (() => Methodology) | undefined =>\n name !== undefined && registeredMethodologies().includes(name)\n ? (methodologyFactory(name) as () => Methodology)\n : undefined;\n\nexport const USAGE = [\n \"exwf init <scrum|kanban|waterfall|investigation|experimentation> --config <file> [--roles <file>]\",\n \"exwf add <item.json> [--by who] exwf edit <id> <patch.json> [--by who]\",\n \"exwf next [--max n] [--fallback-tokens-per-weight n]\",\n \"exwf complete <id> <handoff.json> --tokens-in n --tokens-out n --duration-ms n --model m [--estimate] [--role r]\",\n \"exwf account <item> [--line n] [--tokens-in n] [--tokens-out n] [--duration-ms n] [--model m] [--by who]\",\n \"exwf ceremony <name> [input.json] [--by who]\",\n \"exwf decide <pendingId> approve|reject [--by who] [--note text]\",\n \"exwf config set <patch.json> [--by who] exwf unblock <item> [--blocker id] [--note text] [--by who]\",\n \"exwf status | board | metrics | pending | lessons\",\n \"exwf validate <action.json> exwf role add <manifest.json> | role list\",\n];\n\nexport interface Parsed {\n positional: string[];\n flags: Record<string, string>;\n}\n/** Flags that take no value; every other flag needs one. */\nconst BOOLEAN_FLAGS = new Set([\"estimate\"]);\n\nexport function parseArgs(argv: string[]): Parsed {\n const positional: string[] = [];\n const flags: Record<string, string> = {};\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]!;\n if (a.startsWith(\"--\")) {\n const key = a.slice(2);\n if (BOOLEAN_FLAGS.has(key)) {\n flags[key] = \"true\";\n continue;\n }\n const val = argv[i + 1];\n if (val === undefined || val.startsWith(\"--\"))\n fail(\"invalid-input\", `--${key} needs a value`, `pass --${key} <text>`);\n flags[key] = val;\n i++;\n } else positional.push(a);\n }\n return { positional, flags };\n}\n\nasync function readJson<T>(file: string): Promise<T> {\n try {\n return JSON.parse(await readFile(file, \"utf8\")) as T;\n } catch (e) {\n return fail(\n \"invalid-input\",\n `cannot read JSON from ${file}: ${(e as Error).message}`,\n \"check the path and that the file is valid JSON\",\n );\n }\n}\n\nfunction methodologyOf(state: WorkflowState): Methodology {\n const f = factoryOf(state.methodology);\n if (!f)\n fail(\n \"config-invalid\",\n `methodology \"${state.methodology}\" is not available in this build`,\n `available: ${registeredMethodologies().join(\", \")}`,\n );\n // the reserved context-grounded policy is judged by the SDK's snapshots here too (spec 28, #47)\n return withGroundingHooks(f());\n}\n\nfunction num(flags: Record<string, string>, key: string): number {\n const v = Number(flags[key]);\n if (!Number.isFinite(v))\n fail(\n \"invalid-input\",\n `--${key} must be a number (got ${JSON.stringify(flags[key])})`,\n `pass --${key} <n>`,\n );\n return v;\n}\n\nexport interface CommandResult {\n exit: 0 | 1 | 2;\n out: unknown;\n}\n\n/** Commands that load, change and save the state: they run under .workflow/state.lock. */\nconst WRITERS = new Set([\n \"init\",\n \"add\",\n \"edit\",\n \"next\",\n \"complete\",\n \"account\",\n \"ceremony\",\n \"decide\",\n \"unblock\",\n]);\n\nexport async function runCommand(argv: string[], cwd: string): Promise<CommandResult> {\n try {\n const [cmd, sub] = parseArgs(argv).positional;\n const writes =\n cmd !== undefined &&\n (WRITERS.has(cmd) ||\n (cmd === \"role\" && sub === \"add\") ||\n (cmd === \"config\" && sub === \"set\"));\n return writes ? await withStateLock(cwd, () => execute(argv, cwd)) : await execute(argv, cwd);\n } catch (e) {\n if (e instanceof WorkflowError) return { exit: 1, out: { ok: false, error: e.toJSON() } };\n throw e;\n }\n}\n\nasync function execute(argv: string[], cwd: string): Promise<CommandResult> {\n const { positional, flags } = parseArgs(argv);\n const [cmd, ...rest] = positional;\n const by = flags[\"by\"] ?? \"human\";\n const now = new Date().toISOString();\n switch (cmd) {\n case \"init\": {\n const [name] = rest;\n const f = factoryOf(name);\n if (!f || !flags[\"config\"]) return { exit: 2, out: { ok: false, usage: USAGE } };\n try {\n await stat(statePath(cwd));\n fail(\n \"invalid-input\",\n `${statePath(cwd)} already exists`,\n \"delete .workflow/state.json to start over\",\n );\n } catch (e) {\n if (e instanceof WorkflowError) throw e;\n if ((e as NodeJS.ErrnoException).code !== \"ENOENT\") throw e;\n }\n const config = await readJson<unknown>(path.resolve(cwd, flags[\"config\"]));\n const roles = flags[\"roles\"]\n ? await readJson<Role[]>(path.resolve(cwd, flags[\"roles\"]))\n : undefined;\n if (roles !== undefined) {\n if (!Array.isArray(roles))\n fail(\n \"invalid-input\",\n `roles file ${flags[\"roles\"]} must contain an array of role manifests`,\n \"wrap the manifests in [ ... ]\",\n );\n for (const r of roles) assertValid(roleSchema, r, `roles file ${flags[\"roles\"]}`);\n }\n const res = init(\n roles\n ? { methodology: f(), config, roles, by, now }\n : { methodology: f(), config, by, now },\n );\n await saveState(cwd, res.state);\n return {\n exit: 0,\n out: {\n ok: true,\n warnings: res.warnings,\n state: {\n methodology: res.state.methodology,\n stages: res.state.stages.map((s) => s.id),\n roles: Object.keys(res.state.roles),\n },\n },\n };\n }\n case \"add\": {\n if (!rest[0]) return { exit: 2, out: { ok: false, usage: USAGE } };\n const state = await loadState(cwd);\n const item = await readJson<NewItem>(path.resolve(cwd, rest[0]));\n assertValid(newItemSchema, item, `item file ${rest[0]}`);\n const res = applyAction(\n state,\n methodologyOf(state),\n { type: \"item.add\", by, payload: { item } },\n (s) => addItem(s, item, by, now),\n );\n await saveState(cwd, res.state);\n return {\n exit: 0,\n out: {\n ok: true,\n warnings: res.warnings,\n item: getItem(res.state, item.id),\n },\n };\n }\n case \"edit\": {\n if (!rest[0] || !rest[1]) return { exit: 2, out: { ok: false, usage: USAGE } };\n const state = await loadState(cwd);\n const id = rest[0];\n const patch = await readJson<ItemPatch>(path.resolve(cwd, rest[1]));\n assertValid(itemPatchSchema, patch, `patch file ${rest[1]}`);\n const res = applyAction(\n state,\n methodologyOf(state),\n { type: \"item.edit\", by, payload: { id, patch } },\n (s) => editItem(s, id, patch, by, now),\n );\n await saveState(cwd, res.state);\n return {\n exit: 0,\n out: { ok: true, warnings: res.warnings, item: getItem(res.state, id) },\n };\n }\n case \"next\": {\n const state = await loadState(cwd);\n const opts: PlanOptions = { now };\n if (flags[\"max\"]) opts.max = num(flags, \"max\");\n if (flags[\"fallback-tokens-per-weight\"])\n opts.fallbackTokensPerWeight = num(flags, \"fallback-tokens-per-weight\");\n const res = planNext(state, methodologyOf(state), opts);\n // every brief name is checked first, so a refusal writes none of the batch\n await checkBriefNames(\n cwd,\n res.briefs.map((b) => b.item.id),\n );\n // briefs first: a crash then leaves an orphan brief (overwritten next dispatch), never a dispatched item without one\n for (const b of res.briefs) await saveBrief(cwd, b);\n await saveState(cwd, res.state);\n return {\n exit: 0,\n out: {\n ok: true,\n reason: res.reason ?? null,\n skipped: res.skipped,\n briefs: res.briefs,\n },\n };\n }\n case \"complete\": {\n if (!rest[0] || !rest[1]) return { exit: 2, out: { ok: false, usage: USAGE } };\n const state = await loadState(cwd);\n const handoff = await readJson<Handoff>(path.resolve(cwd, rest[1]));\n assertValid(handoffSchema, handoff, `handoff file ${rest[1]}`);\n if (handoff.item !== rest[0])\n fail(\n \"handoff-invalid\",\n `handoff.item \"${handoff.item}\" differs from the command's item \"${rest[0]}\"`,\n \"make them match\",\n );\n const role = flags[\"role\"] ?? handoff.role;\n const durationMs = num(flags, \"duration-ms\");\n const startedAt = Date.parse(now) - durationMs;\n // a negative duration stays accounting-invalid (complete) and a fraction is accepted, as in\n // 1.1; only refuse what Date cannot hold\n if (!Number.isFinite(durationMs) || Number.isNaN(new Date(startedAt).getTime()))\n fail(\n \"invalid-input\",\n `--duration-ms must be a number of milliseconds that dates the start (got ${flags[\"duration-ms\"]})`,\n \"pass the measured wall-clock time in ms, e.g. --duration-ms 42000\",\n );\n const acc: Accounting = {\n item: rest[0],\n role,\n model: flags[\"model\"] ?? \"\",\n tokensIn: num(flags, \"tokens-in\"),\n tokensOut: num(flags, \"tokens-out\"),\n durationMs,\n startedAt: new Date(startedAt).toISOString(),\n endedAt: now,\n };\n if (flags[\"estimate\"] === \"true\") acc.estimate = true;\n const res = complete(state, methodologyOf(state), { ...handoff, role }, acc, now);\n // handoff first: a retry of the same command reproduces the same seq and overwrites an orphan\n await saveHandoff(cwd, handoff, res.state.events.length);\n await saveState(cwd, res.state);\n return {\n exit: 0,\n out: {\n ok: true,\n warnings: res.warnings,\n item: getItem(res.state, rest[0]),\n },\n };\n }\n case \"account\": {\n if (!rest[0]) return { exit: 2, out: { ok: false, usage: USAGE } };\n const state = await loadState(cwd);\n const patch: AccountingPatch = {};\n if (flags[\"tokens-in\"] !== undefined) patch.tokensIn = num(flags, \"tokens-in\");\n if (flags[\"tokens-out\"] !== undefined) patch.tokensOut = num(flags, \"tokens-out\");\n if (flags[\"duration-ms\"] !== undefined) patch.durationMs = num(flags, \"duration-ms\");\n if (flags[\"model\"] !== undefined) patch.model = flags[\"model\"];\n const line = flags[\"line\"] !== undefined ? num(flags, \"line\") : undefined;\n const s2 = correctAccounting(state, rest[0], patch, flags[\"by\"] ?? \"human\", now, line);\n await saveState(cwd, s2);\n const ev = lastEvent(s2)!;\n const idx = (ev.payload as { line: number }).line;\n const mine = s2.accounting.filter((a) => a.item === rest[0]);\n return { exit: 0, out: { ok: true, line: mine[idx - 1], event: ev } };\n }\n case \"ceremony\": {\n if (!rest[0]) return { exit: 2, out: { ok: false, usage: USAGE } };\n const state = await loadState(cwd);\n const m = methodologyOf(state);\n const c = Object.hasOwn(m.ceremonies, rest[0]) ? m.ceremonies[rest[0]] : undefined;\n if (!c)\n fail(\n \"unknown-ceremony\",\n `\"${rest[0]}\" is not a ${m.name} ceremony`,\n `available: ${Object.keys(m.ceremonies).join(\", \")}`,\n );\n const input = rest[1]\n ? await readJson<Record<string, unknown>>(path.resolve(cwd, rest[1]))\n : {};\n const res = c(state, { ...input, by, now });\n await saveState(cwd, res.state);\n return {\n exit: 0,\n out: {\n ok: true,\n warnings: res.warnings,\n lastEvent: lastEvent(res.state),\n },\n };\n }\n case \"config\": {\n if (rest[0] !== \"set\" || !rest[1]) return { exit: 2, out: { ok: false, usage: USAGE } };\n const state = await loadState(cwd);\n const patch = await readJson<Record<string, unknown>>(path.resolve(cwd, rest[1]));\n const res = changeConfig(state, methodologyOf(state), patch, by, now);\n await saveState(cwd, res.state);\n return {\n exit: 0,\n out: {\n ok: true,\n warnings: res.warnings,\n changed: (lastEvent(res.state)!.payload as { changed: string[] }).changed,\n config: res.state.config,\n },\n };\n }\n case \"unblock\": {\n if (!rest[0]) return { exit: 2, out: { ok: false, usage: USAGE } };\n const id = rest[0];\n const state = await loadState(cwd);\n const open = getItem(state, id)\n .blockers.filter((b) => !b.clearedAt)\n .map((b) => b.id);\n if (open.length === 0)\n fail(\n \"invalid-input\",\n `item ${id} has no open blocker`,\n \"nothing to clear; check exwf board\",\n );\n const blockers = flags[\"blocker\"] !== undefined ? [flags[\"blocker\"]] : open;\n const note = flags[\"note\"];\n const res = applyAction(\n state,\n methodologyOf(state),\n { type: \"blocker.clear\", by, payload: { id, blockers, note: note ?? null } },\n (s) => blockers.reduce((acc, b) => clearBlocker(acc, id, b, by, now, note), s),\n );\n await saveState(cwd, res.state);\n return { exit: 0, out: { ok: true, warnings: res.warnings, item: getItem(res.state, id) } };\n }\n case \"decide\": {\n if (!rest[0] || (rest[1] !== \"approve\" && rest[1] !== \"reject\"))\n return { exit: 2, out: { ok: false, usage: USAGE } };\n const state = await loadState(cwd);\n const entry = state.pending.find((p) => p.id === rest[0]);\n const s2 = decide(\n state,\n rest[0],\n rest[1],\n by,\n flags[\"note\"] ?? \"\",\n now,\n methodologyOf(state),\n );\n await saveState(cwd, s2);\n return {\n exit: 0,\n out: { ok: true, item: entry?.item ? getItem(s2, entry.item) : null },\n };\n }\n case \"status\": {\n const state = await loadState(cwd);\n const m = methodologyOf(state);\n const counts: Record<ItemStatus, number> = {\n todo: 0,\n in_progress: 0,\n blocked: 0,\n review: 0,\n awaiting_human: 0,\n done: 0,\n dropped: 0,\n };\n for (const i of Object.values(state.items)) counts[i.status] += 1;\n return {\n exit: 0,\n out: {\n ok: true,\n methodology: state.methodology,\n openIteration: openIteration(state) ?? null,\n counts,\n pending: state.pending,\n openQuestions: openQuestions(state),\n lastEvent: lastEvent(state),\n report: m.report ? m.report(state) : null,\n },\n };\n }\n case \"board\": {\n const state = await loadState(cwd);\n const columns = state.stages.map((st) => ({\n stage: st.id,\n wipLimit: st.wipLimit ?? null,\n items: Object.values(state.items)\n .filter((i) => i.stage === st.id && i.status !== \"dropped\")\n .map((i) => ({\n id: i.id,\n title: i.title,\n status: i.status,\n role: i.role ?? null,\n age: i.transitions.length\n ? Date.parse(now) - Date.parse(i.transitions[i.transitions.length - 1]!.at)\n : null,\n })),\n }));\n return { exit: 0, out: { ok: true, columns } };\n }\n case \"metrics\": {\n const state = await loadState(cwd);\n return {\n exit: 0,\n out: { ok: true, metrics: methodologyOf(state).metrics(state) },\n };\n }\n case \"pending\":\n return {\n exit: 0,\n out: { ok: true, pending: (await loadState(cwd)).pending },\n };\n case \"lessons\":\n return {\n exit: 0,\n out: { ok: true, lessons: (await loadState(cwd)).lessons },\n };\n case \"validate\": {\n if (!rest[0]) return { exit: 2, out: { ok: false, usage: USAGE } };\n const state = await loadState(cwd);\n const action = await readJson<Action>(path.resolve(cwd, rest[0]));\n if (\n typeof action !== \"object\" ||\n action === null ||\n Array.isArray(action) ||\n typeof action.type !== \"string\"\n )\n fail(\n \"invalid-input\",\n `action file ${rest[0]} must hold an object with a string \"type\"`,\n 'write the action as { \"type\": \"...\", \"by\": \"<role>\", \"payload\": { ... } }',\n );\n return {\n exit: 0,\n out: {\n ok: true,\n violations: validateAction(state, methodologyOf(state), action),\n },\n };\n }\n case \"role\": {\n const state = await loadState(cwd);\n if (rest[0] === \"list\")\n return {\n exit: 0,\n out: {\n ok: true,\n roles: Object.keys(state.roles),\n detail: state.roles,\n },\n };\n if (rest[0] === \"add\" && rest[1]) {\n const manifest = await readJson<Role>(path.resolve(cwd, rest[1]));\n assertValid(roleSchema, manifest, `role manifest ${rest[1]}`);\n const s2 = registerRole(state, manifest, by, now);\n await saveState(cwd, s2);\n return { exit: 0, out: { ok: true, roles: Object.keys(s2.roles) } };\n }\n return { exit: 2, out: { ok: false, usage: USAGE } };\n }\n default:\n return { exit: 2, out: { ok: false, usage: USAGE } };\n }\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkGKN5M4B7_cjs=require('./chunk-GKN5M4B7.cjs'),chunk6PFJYRM7_cjs=require('./chunk-6PFJYRM7.cjs'),chunkTBLIZIWH_cjs=require('./chunk-TBLIZIWH.cjs'),chunkOSHBJIYD_cjs=require('./chunk-OSHBJIYD.cjs');function $(e,n){let i=chunkTBLIZIWH_cjs.D(e),o=i.transitions.get(n.id)??[],t=n.transitions,c=chunkTBLIZIWH_cjs.F(i,n.id,o),d=c===void 0||o.length!==t.length?t:t.slice(t.length-c),r=new Set;for(let s of d)s.to.status==="in_progress"&&r.add(s.by);for(let s of [n.role,chunkTBLIZIWH_cjs.H(e,n)])s!==void 0&&r.add(s);return [...r]}var v=chunkGKN5M4B7_cjs.a(["low","medium","high","critical"]),G=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),R=(e,n)=>Object.hasOwn(e,n)?e[n]:void 0,Y=new WeakSet;function I(e,n){if(typeof e=="object"&&e!==null&&Y.has(e))return e;let i=(a,p)=>chunkOSHBJIYD_cjs.b("invalid-input",`${n} options: ${a}`,p),o=(a,p,m)=>{for(let y of Object.keys(a))p.includes(y)||i(`unknown key "${y}" in ${m}`,`use only: ${p.join(", ")}`);},t=(a,p)=>{if(a==="human")return a;let m=G(a)?R(a,"capability"):void 0;return (typeof m!="string"||m.trim()===""||Object.keys(a).length!==1)&&i(`${p} must be "human" or { capability: <name> }`,'e.g. ["human"] or [{ "capability": "review" }]'),{capability:m}};G(e)||i("must be an object",'pass { "gates": ["code-review"] }');let c=e;o(c,["gates","table"],"options");let d=R(c,"gates");Array.isArray(d)||i("gates must be an array of gate ids",'e.g. "gates": ["code-review"]');let r=d.map(a=>(chunkOSHBJIYD_cjs.c(a,"risk gate id"),a)),s=R(c,"table"),u;if(s!==void 0){G(s)||i("table must be an object keyed by risk level",`levels: ${v.join(", ")}`);let a=s;o(a,v,"table"),u={};let p=[];for(let m of v){let y=R(a,m);G(y)||i(`table is missing level "${m}"`,`give every level a row, e.g. "${m}": { "requires": [] }`);let h=y;o(h,["requires","evidence"],`table.${m}`);let l=R(h,"requires");Array.isArray(l)||i(`table.${m}.requires must be an array`,'e.g. "requires": ["human"]');let g=R(h,"evidence");g!==void 0&&(!Array.isArray(g)||!g.every(k=>typeof k=="string"&&k.trim()!==""))&&i(`table.${m}.evidence must be an array of evidence kinds`,'e.g. "evidence": ["sbom"]');let w=l.map((k,oe)=>t(k,`table.${m}.requires[${oe}]`)),O=g===void 0?void 0:[...g],V=[...w.map(k=>JSON.stringify(k)),...(O??[]).map(k=>`evidence ${JSON.stringify(k)}`)],J=p.filter(k=>!V.includes(k));J.length&&i(`table.${m} must include everything the level below it adds (missing ${J.join(", ")})`,"a stricter level only adds: copy the lower level's requires and evidence into it"),p=V,u[m]={requires:w,...O===void 0?{}:{evidence:O}};}}let f=chunkGKN5M4B7_cjs.a(u?{gates:r,table:u}:{gates:r});return Y.add(f),f}var re=chunkGKN5M4B7_cjs.a({low:{requires:[]},medium:{requires:[]},high:{requires:["human"]},critical:{requires:["human"]}}),se=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ae(e){return se(e)&&v.includes(e.level)&&Array.isArray(e.factors)&&e.factors.every(n=>typeof n=="string")&&(e.subject===void 0||typeof e.subject=="string")}function ce(e,n,i,o=$(e,n)){return chunkTBLIZIWH_cjs.l(e,i,"verify")?chunk6PFJYRM7_cjs.a(i,o).length?"not-independent":void 0:"invalid"}function Z(e,n,i,o){let t=I(o,"riskEscalation");if(!t.gates.includes(i.id))return;let c,d="missing",r,s;for(let a of chunkTBLIZIWH_cjs.z(e,n)){if(a.kind!=="risk-assessment")continue;let p=ae(a.data)?ce(e,n,a.by,s??=$(e,n)):"invalid";if(p){c||(d=p,r=a);continue}let m=a.data.level;(!c||v.indexOf(m)>=v.indexOf(c))&&(c=m,d="assessed",r=a);}let u=c??"critical",f=(t.table??re)[u];return {requires:f.requires.map(a=>a==="human"?a:{capability:a.capability}),evidence:[...f.evidence??[]],reason:{level:u,why:d,assessment:r?.ref??null,by:r?.by??null}}}var N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),C=e=>typeof e=="string"&&e.trim()!=="",W=(e,n)=>Object.keys(e).find(i=>!n.includes(i));function ue(e){return e<32||e>=127&&e<=159||e===1564||e===8206||e===8207||e>=8234&&e<=8238||e>=8294&&e<=8297}function de(e){let n=typeof e!="string"?"not a string":e.length>4096?"longer than 4096 characters":[...e].some(o=>ue(o.codePointAt(0)))?"has a control or bidirectional formatting character":e!==e.trim()?"has leading or trailing whitespace":e!==e.normalize("NFC")?"is not Unicode NFC":e.includes("\\")||/^[A-Za-z]:/.test(e)||!e.split("/").every(o=>o!==""&&o!=="."&&o!=="..")?"is not relative with / separators and no empty, . or .. segment":void 0;return n?`${JSON.stringify(typeof e=="string"&&e.length>80?`${e.slice(0,80)}\u2026`:e)} is not a repository-relative POSIX path (${n})`:void 0}function L(e){if(!N(e))return "data must be an object";let n=W(e,["revision","assumptions"]);if(n)return `unknown key "${n}"`;if(!C(e.revision))return "revision must be a non-empty string";let i=e.assumptions;if(!Array.isArray(i))return "assumptions must be an array";for(let[o,t]of i.entries()){let c=`assumptions[${o}]`;if(!N(t))return `${c} must be an object`;let d=W(t,["claim","required","source"]);if(d)return `unknown key "${d}" in ${c}`;if(!C(t.claim))return `${c}.claim must be a non-empty string`;if(t.required!==void 0&&typeof t.required!="boolean")return `${c}.required must be a boolean`;let r=t.source;if(r===void 0)continue;if(!N(r))return `${c}.source must be an object`;let s=W(r,["path","lines","hash"]);if(s)return `unknown key "${s}" in ${c}.source`;let u=de(r.path);if(u)return `${c}.source.path ${u}`;if(!C(r.hash))return `${c}.source.hash must be a non-empty string`;let f=r.lines;if(f!==void 0&&!(Array.isArray(f)&&f.length===2&&Number.isInteger(f[0])&&Number.isInteger(f[1])&&1<=f[0]&&f[0]<=f[1]))return `${c}.source.lines must be two integers [from, to] with 1 <= from <= to`}}function ee(e,n,i){return typeof n!="string"||n!=="human"&&!Object.hasOwn(e.roles,n)?`${JSON.stringify(n)} is neither human nor a registered role`:i.includes(n)?`"${n}" worked on the item`:void 0}var ne=e=>e.assumptions.some(n=>n.source),Q=({source:e,...n})=>e?{...n,source:{...e,...e.lines?{lines:[...e.lines]}:{}}}:n;function E(e,n){let i=chunkTBLIZIWH_cjs.D(e),o=i.evidence.get(n.id)??[],t=n.evidence,c=chunkTBLIZIWH_cjs.F(i,n.id,o),d=c===void 0?t.length:Math.min(c,t.length),r,s=u=>{let f=t[u];if(f.kind!=="context-snapshot"||L(f.data)!==void 0)return;let a=f.data;return !ne(a)||ee(e,f.by,r??=$(e,n))?void 0:a};for(let u=t.length-1;u>=t.length-d;u--){let f=t[u],a=s(u);if(!a)continue;let p=new Set;for(let l=t.length-1;l>=t.length-d;l--){let g=t[l];if(l!==u&&g.kind==="context-snapshot"&&L(g.data)===void 0)for(let w of g.data.assumptions)w.required&&p.add(w.claim);}let m=a.assumptions.map(l=>p.has(l.claim)?{...Q(l),required:true}:Q(l));for(let l of p)a.assumptions.some(g=>g.claim===l)||m.push({claim:l,required:true});let y=o[u+o.length-t.length]??-1,h=[];for(let l of new Set(a.assumptions.map(g=>g.source?.path))){let g=l===void 0?void 0:i.changed.get(l),w=g?chunkTBLIZIWH_cjs.E(g,y,O=>O[0]):0;g&&w<g.length&&h.push([g[w][0],g[w][1],l]);}return h.sort((l,g)=>l[0]-g[0]||l[1]-g[1]),{revision:a.revision,assumptions:m,snapshot:f.ref,by:f.by,stale:h.map(l=>l[2]),unverified:m.filter(l=>!l.source).map(l=>l.claim)}}}var D=["item","revision","assumptions","ref","by","now"],b=(e,n)=>chunkOSHBJIYD_cjs.b("invalid-input",`context snapshot: ${e}`,n);function Ee(e,n,i){N(i)||b("input must be an object",`pass { ${D.join(", ")} }`);let o=W(i,D);o&&b(`unknown key "${o}"`,`use only: ${D.join(", ")}`);let{item:t,revision:c,assumptions:d,ref:r,by:s,now:u}=i;typeof t!="string"&&b("item must be an item id",'e.g. "item": "CART-12"');let f=chunkTBLIZIWH_cjs.s(e,t),a={revision:c,assumptions:d},p=L(a);p&&b(p,'e.g. { "revision": "4f2c1e0", "assumptions": [{ "claim": "totals are cents", "source": { "path": "src/cart.ts", "hash": "\u2026" } }] }'),C(r)||b("ref must be a non-empty string",'name the snapshot artifact, e.g. "ctx/CART-12.json"'),C(s)||b("by must name who recorded it",'e.g. "by": "scout"');let m=ee(e,s,$(e,f));m&&b(`${m} and may not record its context`,"record as human or a registered role that did not work on the item"),ne(a)||b("a snapshot needs at least one assumption with a source (nothing was verified)",'cite what was checked, e.g. "source": { "path": "src/cart.ts", "hash": "\u2026" }'),u!==void 0&&typeof u!="string"&&b("now must be an ISO timestamp string","omit now to use the clock");let y=JSON.parse(JSON.stringify(a));return chunkTBLIZIWH_cjs.V(e,n,{type:"context.snapshot",by:s,payload:{item:t,ref:r,...y}},h=>chunkTBLIZIWH_cjs.A(h,t,{kind:"context-snapshot",ref:r,by:s,data:y},u))}var fe="policy:custom:context-grounded",P="record a fresh one with recordContextSnapshot";function te(e,n){let i=[],o=(s,u)=>i.push({rule:fe,severity:"error",item:n.id,message:s,fix:u}),t=E(e,n);if(!t)return o(`item "${n.id}" has no qualifying context snapshot (none since its last rework is valid, cites a source and was recorded by human or a registered role that did not work on it)`,`have an independent role or a human verify the context and ${P}`),i;let c=`context snapshot "${t.snapshot}" of "${n.id}"`;t.stale.length&&o(`${c} is stale: ${t.stale.join(", ")} changed since`,`re-verify the claims and ${P}`);let r=t.assumptions.filter(s=>s.required).filter(s=>!s.source).map(s=>s.claim);return r.length&&o(`${c} has unverified required assumption(s): ${r.join(" | ")}`,`cite a source { path, hash } for each and ${P}`),i}var le=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function _e(e,n){let i=I(n,"withRiskGate"),o=e.escalateGate;return {...e,escalateGate(t,c,d){let r=Z(t,c,d,i),s=o?.call(e,t,c,d);return !s||!r?s??r:{requires:[...s.requires,...r.requires],evidence:[...s.evidence,...r.evidence],reason:{...s.reason,...r.reason}}}}}var T="context-grounded",me={kind:"custom",id:T,description:"grounded in a fresh, verified context snapshot"},M=(e,n)=>chunkOSHBJIYD_cjs.b("invalid-input",`withContextGrounding options: ${e}`,n);function ie(e,n){let i=e[n];return i===void 0&&n==="exit"?[]:(Array.isArray(i)||M(`${n} must be an array of stage ids`,`e.g. "${n}": ["dev"]`),i.map(o=>(chunkOSHBJIYD_cjs.c(o,`context-grounded ${n} stage id`),o)))}function ze(e,n){le(n)||M("must be an object",'pass { "entry": ["dev"] }');let i=n;for(let d of Object.keys(i))d!=="entry"&&d!=="exit"&&M(`unknown key "${d}"`,"use only: entry, exit");let o=ie(i,"entry"),t=ie(i,"exit"),c=(d,r)=>r&&!d.some(s=>s.kind==="custom"&&s.id===T)?[...d,me]:d;return {...ge(e),defaultStages(d){let r=e.defaultStages(d);for(let u of [...o,...t])r.some(f=>f.id===u)||chunkOSHBJIYD_cjs.b("invalid-input",`withContextGrounding: unknown stage "${u}"`,`stages: ${r.map(f=>f.id).join(", ")}`);let s=pe(e.name,r);for(let[u,f]of [["entry",o],["exit",t]])for(let a of f)s[u].includes(a)&&chunkOSHBJIYD_cjs.b("invalid-input",`withContextGrounding: the ${e.name} ceremony that moves items ${u==="entry"?"into":"out of"} "${a}" checks its ${u} policies without the grounding hook`,`ground a later stage instead, e.g. ${u} ["${r.find(p=>!s.entry.includes(p.id)&&!s.exit.includes(p.id)&&p.id!==r[0].id)?.id??"dev"}"]`);return r.map(u=>({...u,entryPolicy:c(u.entryPolicy,o.includes(u.id)),exitPolicy:c(u.exitPolicy,t.includes(u.id))}))}}}function pe(e,n){return e==="kanban"?{entry:[],exit:n[0]?[n[0].id]:[]}:e==="scrum"?{entry:[],exit:["backlog"]}:e==="experimentation"?{entry:["building"],exit:[]}:{entry:[],exit:[]}}function ge(e){let{customPolicy:n,briefContext:i}=e;return {...e,customPolicy(o,t,c){return c.id===T?te(o,t):n?.call(e,o,t,c)},briefContext(o,t){return E(o,t)??i?.call(e,o,t)}}}exports.a=v;exports.b=re;exports.c=ce;exports.d=Z;exports.e=de;exports.f=E;exports.g=Ee;exports.h=te;exports.i=_e;exports.j=ze;exports.k=ge;//# sourceMappingURL=chunk-66BO7JFR.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-66BO7JFR.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/common/workers.ts","../src/common/risk/options.ts","../src/common/risk/escalation.ts","../src/common/context/snapshot.ts","../src/common/context/policy.ts","../src/interface/policies.ts"],"names":["workersOf","state","item","index","eventIndex","at","all","after","sinceRework","ts","out","t","w","authorOf","RISK_LEVELS","deepFreeze","isObj","x","own","o","k","validated","riskOptions","options","who","bad","what","fix","fail","closed","keys","requirement","q","c","gs","gates","g","assertId","raw","table","below","level","row","rw","rq","ev","requires","i","evidence","here","missing","DEFAULT_RISK_TABLE","isRiskData","data","f","assessorIssue","by","workers","canDo","independenceConflicts","riskEscalation","gate","opts","why","pick","e","freshEvidence","issue","l","resolved","nonEmpty","extra","hidden","repoPathIssue","path","ch","seg","snapshotIssue","list","a","ka","src","ks","pathIssue","recorderIssue","sourced","d","copyOf","source","rest","contextOf","fresh","qualifying","carried","j","assumptions","claim","pos","hits","firstAfter","b","h","KEYS","recordContextSnapshot","methodology","input","id","revision","ref","now","getItem","copy","applyAction","s","addEvidence","RULE","RECORD","contextGroundedViolations","v","message","ctx","of","unverified","withRiskGate","inner","prior","GROUNDED","groundedPolicy","badGrounding","stageIds","key","ids","withContextGrounding","entry","exit","add","on","p","withGroundingHooks","config","stages","st","checked","ceremonyChecked","name","customPolicy","briefContext","policy"],"mappings":"yNAeO,SAASA,CAAAA,CAAUC,CAAAA,CAA8BC,CAAAA,CAA0B,CAChF,IAAMC,CAAAA,CAAQC,mBAAAA,CAAWH,CAAK,CAAA,CACxBI,CAAAA,CAAKF,CAAAA,CAAM,WAAA,CAAY,IAAID,CAAAA,CAAK,EAAE,CAAA,EAAK,EAAC,CACxCI,CAAAA,CAAMJ,CAAAA,CAAK,WAAA,CACXK,EAAQC,mBAAAA,CAAYL,CAAAA,CAAOD,CAAAA,CAAK,EAAA,CAAIG,CAAE,CAAA,CACtCI,CAAAA,CAAKF,CAAAA,GAAU,QAAaF,CAAAA,CAAG,MAAA,GAAWC,CAAAA,CAAI,MAAA,CAASA,CAAAA,CAAMA,CAAAA,CAAI,KAAA,CAAMA,CAAAA,CAAI,OAASC,CAAK,CAAA,CACzFG,CAAAA,CAAM,IAAI,GAAA,CAChB,IAAA,IAAWC,CAAAA,IAAKF,C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,CACrC,OAAII,CAAAA,GAAS,QAAA,CAAiB,CAAE,MAAO,EAAC,CAAG,IAAA,CAAMJ,CAAAA,CAAO,CAAC,CAAA,CAAI,CAACA,CAAAA,CAAO,CAAC,CAAA,CAAE,EAAE,CAAA,CAAI,EAAG,CAAA,CAC7EI,CAAAA,GAAS,OAAA,CAAgB,CAAE,KAAA,CAAO,EAAC,CAAG,IAAA,CAAM,CAAC,SAAS,CAAE,CAAA,CACxDA,IAAS,iBAAA,CAA0B,CAAE,KAAA,CAAO,CAAC,UAAU,CAAA,CAAG,IAAA,CAAM,EAAG,CAAA,CAChE,CAAE,KAAA,CAAO,EAAC,CAAG,IAAA,CAAM,EAAG,CAC/B,CASO,SAASN,EAAAA,CACdlC,CAAAA,CACmB,CACnB,GAAM,CAAE,YAAA,CAAAyC,EAAc,YAAA,CAAAC,CAAa,CAAA,CAAI1C,CAAAA,CACvC,OAAO,CACL,GAAGA,CAAAA,CACH,aAAavG,CAAAA,CAAOC,CAAAA,CAAMiJ,CAAAA,CAAQ,CAChC,OAAOA,CAAAA,CAAO,EAAA,GAAOrB,CAAAA,CACjBT,GAA0BpH,CAAAA,CAAOC,CAAI,CAAA,CACrC+I,CAAAA,EAAc,IAAA,CAAKzC,CAAAA,CAAavG,CAAAA,CAAOC,CAAAA,CAAMiJ,CAAM,CACzD,CAAA,CACA,YAAA,CAAalJ,CAAAA,CAAOC,CAAAA,CAAM,CACxB,OAAOwF,CAAAA,CAAUzF,EAAOC,CAAI,CAAA,EAAKgJ,CAAAA,EAAc,IAAA,CAAK1C,CAAAA,CAAavG,CAAAA,CAAOC,CAAI,CAC9E,CACF,CACF","file":"chunk-66BO7JFR.cjs","sourcesContent":["// Who worked on an item (design spec section 27, F1 G1-1): the independence checks of the\n// risk-adaptive gate and the context-grounded policy compare an assessor or a snapshot's recorder\n// against every one of them, not only the last author.\nimport { authorOf } from \"../core/authors.ts\";\nimport type { WorkItem, WorkflowState } from \"../core/types.ts\";\nimport { eventIndex, sinceRework } from \"../core/event-index.ts\";\n\n/**\n * The roles that worked on `item`: the `by` of each dispatch (a transition into `in_progress`)\n * since the item's last `item.rework` event (or since creation), in order, then its assigned\n * `role` and its author by the 1.3 rule (`authorOf`), each once. The rework boundary is found by\n * matching `item.transitions` to the events that appended them (`item.transition`, and the\n * `blocker.*` events that carry a `transition`) from the end; when those events are not exactly as\n * many as the transitions, every transition counts (fail closed: more workers, never fewer).\n */\nexport function workersOf(state: WorkflowState<string>, item: WorkItem): string[] {\n const index = eventIndex(state);\n const at = index.transitions.get(item.id) ?? [];\n const all = item.transitions;\n const after = sinceRework(index, item.id, at);\n const ts = after === undefined || at.length !== all.length ? all : all.slice(all.length - after);\n const out = new Set<string>();\n for (const t of ts) if (t.to.status === \"in_progress\") out.add(t.by);\n for (const w of [item.role, authorOf(state, item)]) if (w !== undefined) out.add(w);\n return [...out];\n}\n","// Validation of the risk-adaptive gate options (design spec section 27, #35; F1 G1-4, G1-6): one\n// validator for `withRiskGate` (once, at wrap time) and `riskEscalation` (per call, unless given the\n// frozen options the validator itself returned), so both refuse the same input with invalid-input.\nimport { assertId, fail } from \"../../core/errors.ts\";\nimport type { GateRequirement } from \"../../core/types.ts\";\nimport { deepFreeze } from \"../deep-freeze.ts\";\nimport type { RiskGateOptions, RiskLevel, RiskTable } from \"./escalation.ts\";\n\n/** The levels, least strict first. */\nexport const RISK_LEVELS: readonly RiskLevel[] = /* @__PURE__ */ deepFreeze([\n \"low\",\n \"medium\",\n \"high\",\n \"critical\",\n]);\n\nconst isObj = (x: unknown): x is Record<string, unknown> =>\n typeof x === \"object\" && x !== null && !Array.isArray(x);\n/** `o[k]` only when `o` has it as an own property (G5-5, as `compareRuns` reads its input). */\nconst own = (o: Record<string, unknown>, k: string): unknown =>\n Object.hasOwn(o, k) ? o[k] : undefined;\nconst validated = new WeakSet<object>();\n\n/**\n * `options` validated and copied (deeply frozen), so later changes by the caller do not leak in.\n * Refuses `invalid-input`, prefixed with `who`, for: a non-object or an unknown key; `gates` not an\n * array of valid ids; a `table` that is not an object keyed by exactly the four levels, a row with\n * an unknown key, a requirement that is neither `\"human\"` nor `{ capability: <non-empty string> }`,\n * an evidence kind that is not a non-empty string; and a row that does not include every\n * requirement and evidence kind of the level below it (a stricter level only adds, G1-4).\n * Every key is read as an own property: an inherited one counts as absent (G5-5).\n */\nexport function riskOptions(options: unknown, who: string): Required<RiskGateOptions> {\n if (typeof options === \"object\" && options !== null && validated.has(options))\n return options as Required<RiskGateOptions>;\n const bad = (what: string, fix: string): never =>\n fail(\"invalid-input\", `${who} options: ${what}`, fix);\n const closed = (o: Record<string, unknown>, keys: readonly string[], at: string): void => {\n for (const k of Object.keys(o))\n if (!keys.includes(k)) bad(`unknown key \"${k}\" in ${at}`, `use only: ${keys.join(\", \")}`);\n };\n const requirement = (q: unknown, at: string): GateRequirement => {\n if (q === \"human\") return q;\n const c = isObj(q) ? own(q, \"capability\") : undefined;\n if (typeof c !== \"string\" || c.trim() === \"\" || Object.keys(q as object).length !== 1)\n bad(\n `${at} must be \"human\" or { capability: <name> }`,\n 'e.g. [\"human\"] or [{ \"capability\": \"review\" }]',\n );\n return { capability: c as string };\n };\n if (!isObj(options)) bad(\"must be an object\", 'pass { \"gates\": [\"code-review\"] }');\n const o = options as Record<string, unknown>;\n closed(o, [\"gates\", \"table\"], \"options\");\n const gs = own(o, \"gates\");\n if (!Array.isArray(gs))\n bad(\"gates must be an array of gate ids\", 'e.g. \"gates\": [\"code-review\"]');\n const gates = (gs as unknown[]).map((g) => {\n assertId(g, \"risk gate id\");\n return g as string;\n });\n const raw = own(o, \"table\");\n let table: RiskTable | undefined;\n if (raw !== undefined) {\n if (!isObj(raw))\n bad(\"table must be an object keyed by risk level\", `levels: ${RISK_LEVELS.join(\", \")}`);\n const t = raw as Record<string, unknown>;\n closed(t, RISK_LEVELS, \"table\");\n table = {} as RiskTable;\n let below: string[] = [];\n for (const level of RISK_LEVELS) {\n const row = own(t, level);\n if (!isObj(row))\n bad(\n `table is missing level \"${level}\"`,\n `give every level a row, e.g. \"${level}\": { \"requires\": [] }`,\n );\n const rw = row as Record<string, unknown>;\n closed(rw, [\"requires\", \"evidence\"], `table.${level}`);\n const rq = own(rw, \"requires\");\n if (!Array.isArray(rq))\n bad(`table.${level}.requires must be an array`, 'e.g. \"requires\": [\"human\"]');\n const ev = own(rw, \"evidence\");\n if (\n ev !== undefined &&\n (!Array.isArray(ev) || !ev.every((k) => typeof k === \"string\" && k.trim() !== \"\"))\n )\n bad(\n `table.${level}.evidence must be an array of evidence kinds`,\n 'e.g. \"evidence\": [\"sbom\"]',\n );\n const requires = (rq as unknown[]).map((q, i) =>\n requirement(q, `table.${level}.requires[${i}]`),\n );\n const evidence = ev === undefined ? undefined : [...(ev as string[])];\n // each level includes everything the level below it adds; requirements and evidence kinds\n // are separate sets (G5-4: evidence \"human\" is not the requirement \"human\")\n const here = [\n ...requires.map((x) => JSON.stringify(x)),\n ...(evidence ?? []).map((k) => `evidence ${JSON.stringify(k)}`),\n ];\n const missing = below.filter((x) => !here.includes(x));\n if (missing.length)\n bad(\n `table.${level} must include everything the level below it adds (missing ${missing.join(\", \")})`,\n \"a stricter level only adds: copy the lower level's requires and evidence into it\",\n );\n below = here;\n table[level] = { requires, ...(evidence === undefined ? {} : { evidence }) };\n }\n }\n const out = deepFreeze(table ? { gates, table } : ({ gates } as Required<RiskGateOptions>));\n validated.add(out);\n return out;\n}\n","// Risk-adaptive gate (design spec section 27, #35): the level of the strictest fresh, valid and\n// independent `risk-assessment` evidence picks a row of a table of what the gate additionally needs.\nimport { canDo } from \"../../core/roles/guards.ts\";\nimport { freshEvidence } from \"../../core/items/evidence.ts\";\nimport type {\n Evidence,\n Gate,\n GateEscalation,\n GateRequirement,\n WorkItem,\n WorkflowState,\n} from \"../../core/types.ts\";\nimport { deepFreeze } from \"../deep-freeze.ts\";\nimport { independenceConflicts } from \"../independence.ts\";\nimport { workersOf } from \"../workers.ts\";\nimport { RISK_LEVELS, riskOptions } from \"./options.ts\";\n\nexport type RiskLevel = \"low\" | \"medium\" | \"high\" | \"critical\";\n/** `data` of a `risk-assessment` evidence entry. */\nexport interface RiskAssessmentData {\n level: RiskLevel;\n /** Free strings naming what drives the risk, e.g. `ci-cd`, `prod-infra`, `secrets`, `blast-radius`, `irreversible`. */\n factors: string[];\n /** The item SHA or ref that was assessed. */\n subject?: string;\n}\n/** What each level ADDS to the static gate. */\nexport type RiskTable = Record<RiskLevel, { requires: GateRequirement[]; evidence?: string[] }>;\nexport interface RiskGateOptions {\n /** Ids of the gates the policy applies to; every other gate stays static. */\n gates: string[];\n /** Default `DEFAULT_RISK_TABLE`. */\n table?: RiskTable;\n}\n\nexport { RISK_LEVELS };\n\n/** `low` and `medium` add nothing; `high` and `critical` add a human approval. Deeply frozen. */\nexport const DEFAULT_RISK_TABLE: RiskTable = /* @__PURE__ */ deepFreeze({\n low: { requires: [] },\n medium: { requires: [] },\n high: { requires: [\"human\"] },\n critical: { requires: [\"human\"] },\n});\n\nconst isObj = (x: unknown): x is Record<string, unknown> =>\n typeof x === \"object\" && x !== null && !Array.isArray(x);\n\n/** True when `data` is a well-formed `RiskAssessmentData`. */\nexport function isRiskData(data: unknown): data is RiskAssessmentData {\n return (\n isObj(data) &&\n RISK_LEVELS.includes(data[\"level\"] as RiskLevel) &&\n Array.isArray(data[\"factors\"]) &&\n data[\"factors\"].every((f) => typeof f === \"string\") &&\n (data[\"subject\"] === undefined || typeof data[\"subject\"] === \"string\")\n );\n}\n\n/**\n * Why `by` may not assess `item`: `invalid` when it is neither `human` nor a role with capability\n * `verify`, `not-independent` when it worked on the item (`workersOf`: every role that dispatched\n * it since its last rework, its assigned role, its author); `undefined` when it may. `workers`\n * defaults to `workersOf(state, item)`; pass it to check several assessors against one state.\n */\nexport function assessorIssue(\n state: WorkflowState<string>,\n item: WorkItem,\n by: string,\n workers: readonly string[] = workersOf(state, item),\n): \"invalid\" | \"not-independent\" | undefined {\n if (!canDo(state, by, \"verify\")) return \"invalid\";\n return independenceConflicts(by, workers).length ? \"not-independent\" : undefined;\n}\n\n/**\n * The escalation of `gate` for `item` under `options` (the `escalateGate` hook `withRiskGate`\n * installs): `undefined` for a gate not in `options.gates`, else the table row of the resolved\n * level. The resolved level is the strictest fresh (post-rework) valid assessment, so a later,\n * lower assessment never relaxes an earlier one; with none it is `critical`, and `reason.why` says\n * whether assessments were `missing`, `invalid` or `not-independent` (the latest rejected one).\n * Invalid options fail `invalid-input` as in `withRiskGate`, never a `TypeError`. Pure: no clock,\n * no randomness; the same state gives the same answer.\n */\nexport function riskEscalation(\n state: WorkflowState<string>,\n item: WorkItem,\n gate: Gate,\n options: RiskGateOptions,\n): GateEscalation | undefined {\n // validated here unless these are the frozen options withRiskGate validated (G1-6)\n const opts = riskOptions(options, \"riskEscalation\");\n if (!opts.gates.includes(gate.id)) return undefined;\n let level: RiskLevel | undefined;\n let why = \"missing\";\n let pick: Evidence | undefined;\n let workers: string[] | undefined;\n for (const e of freshEvidence(state, item)) {\n if (e.kind !== \"risk-assessment\") continue;\n const issue = isRiskData(e.data)\n ? assessorIssue(state, item, e.by, (workers ??= workersOf(state, item)))\n : \"invalid\";\n if (issue) {\n if (!level) {\n why = issue;\n pick = e;\n }\n continue;\n }\n const l = (e.data as unknown as RiskAssessmentData).level;\n if (!level || RISK_LEVELS.indexOf(l) >= RISK_LEVELS.indexOf(level)) {\n level = l;\n why = \"assessed\";\n pick = e;\n }\n }\n const resolved = level ?? \"critical\";\n const row = (opts.table ?? DEFAULT_RISK_TABLE)[resolved];\n return {\n requires: row.requires.map((q) => (q === \"human\" ? q : { capability: q.capability })),\n evidence: [...(row.evidence ?? [])],\n reason: { level: resolved, why, assessment: pick?.ref ?? null, by: pick?.by ?? null },\n };\n}\n","// Context snapshots (design spec section 27, #36): what a scout verified about the repository\n// before an item is worked, as evidence `context-snapshot`, and whether a later `repo.changed`\n// event made it stale. Event order decides, never timestamps (principle 5); no file is read.\nimport { fail } from \"../../core/errors.ts\";\nimport { addEvidence } from \"../../core/items/evidence.ts\";\nimport { getItem } from \"../../core/items/record.ts\";\nimport { applyAction } from \"../../core/methodology.ts\";\nimport type {\n ApplyResult,\n BriefContext,\n ContextAssumption,\n ContextSnapshotData,\n Methodology,\n WorkItem,\n WorkflowState,\n} from \"../../core/types.ts\";\nimport { eventIndex, firstAfter, sinceRework } from \"../../core/event-index.ts\";\nimport { workersOf } from \"../workers.ts\";\n\nexport interface ContextSnapshotInput {\n item: string;\n /** The repository revision the snapshot was taken at. */\n revision: string;\n assumptions: ContextAssumption[];\n /** The host's snapshot artifact. */\n ref: string;\n /** Who recorded it: `human` or a registered role that did not work on the item. */\n by: string;\n now?: string;\n}\n\nconst isObj = (x: unknown): x is Record<string, unknown> =>\n typeof x === \"object\" && x !== null && !Array.isArray(x);\nconst nonEmpty = (x: unknown): x is string => typeof x === \"string\" && x.trim() !== \"\";\nconst extra = (o: Record<string, unknown>, keys: string[]) =>\n Object.keys(o).find((k) => !keys.includes(k));\n\n/** True for a C0 or C1 control character or a bidirectional formatting character. */\nfunction hidden(c: number): boolean {\n return (\n c < 0x20 ||\n (c >= 0x7f && c <= 0x9f) ||\n c === 0x61c ||\n c === 0x200e ||\n c === 0x200f ||\n (c >= 0x202a && c <= 0x202e) ||\n (c >= 0x2066 && c <= 0x2069)\n );\n}\n\n/**\n * Why `path` is not a repository-relative POSIX path as Git lists it, or `undefined` when it is:\n * no leading `/`, `./` or drive letter, `/` separators only, no empty, `.` or `..` segment, at most\n * 4096 characters, Unicode NFC, no control or bidirectional formatting character and no leading or\n * trailing whitespace (F1 G2-8, G4-4). Paths are compared exactly (case included), so the recorders\n * accept one spelling per file.\n */\nexport function repoPathIssue(path: unknown): string | undefined {\n const why =\n typeof path !== \"string\"\n ? \"not a string\"\n : path.length > 4096\n ? \"longer than 4096 characters\"\n : [...path].some((ch) => hidden(ch.codePointAt(0)!))\n ? \"has a control or bidirectional formatting character\"\n : path !== path.trim()\n ? \"has leading or trailing whitespace\"\n : path !== path.normalize(\"NFC\")\n ? \"is not Unicode NFC\"\n : path.includes(\"\\\\\") ||\n /^[A-Za-z]:/.test(path) ||\n !path.split(\"/\").every((seg) => seg !== \"\" && seg !== \".\" && seg !== \"..\")\n ? \"is not relative with / separators and no empty, . or .. segment\"\n : undefined;\n if (!why) return undefined;\n const shown = JSON.stringify(\n typeof path === \"string\" && path.length > 80 ? `${path.slice(0, 80)}…` : path,\n );\n return `${shown} is not a repository-relative POSIX path (${why})`;\n}\n\n/** Why `data` is not a well-formed `ContextSnapshotData` (closed objects), or `undefined`. */\nfunction snapshotIssue(data: unknown): string | undefined {\n if (!isObj(data)) return \"data must be an object\";\n const k = extra(data, [\"revision\", \"assumptions\"]);\n if (k) return `unknown key \"${k}\"`;\n if (!nonEmpty(data[\"revision\"])) return \"revision must be a non-empty string\";\n const list = data[\"assumptions\"];\n if (!Array.isArray(list)) return \"assumptions must be an array\";\n for (const [i, a] of list.entries()) {\n const at = `assumptions[${i}]`;\n if (!isObj(a)) return `${at} must be an object`;\n const ka = extra(a, [\"claim\", \"required\", \"source\"]);\n if (ka) return `unknown key \"${ka}\" in ${at}`;\n if (!nonEmpty(a[\"claim\"])) return `${at}.claim must be a non-empty string`;\n if (a[\"required\"] !== undefined && typeof a[\"required\"] !== \"boolean\")\n return `${at}.required must be a boolean`;\n const src = a[\"source\"];\n if (src === undefined) continue;\n if (!isObj(src)) return `${at}.source must be an object`;\n const ks = extra(src, [\"path\", \"lines\", \"hash\"]);\n if (ks) return `unknown key \"${ks}\" in ${at}.source`;\n const pathIssue = repoPathIssue(src[\"path\"]);\n if (pathIssue) return `${at}.source.path ${pathIssue}`;\n if (!nonEmpty(src[\"hash\"])) return `${at}.source.hash must be a non-empty string`;\n const l = src[\"lines\"];\n if (\n l !== undefined &&\n !(\n Array.isArray(l) &&\n l.length === 2 &&\n Number.isInteger(l[0]) &&\n Number.isInteger(l[1]) &&\n 1 <= l[0] &&\n l[0] <= l[1]\n )\n )\n return `${at}.source.lines must be two integers [from, to] with 1 <= from <= to`;\n }\n return undefined;\n}\n\n/**\n * Why `by` may not ground an item whose workers are `workers` (design spec section 27, F1 G1-2,\n * G2-2): it is neither `human` nor a registered role, or it worked on the item; else `undefined`.\n */\nfunction recorderIssue(\n state: WorkflowState<string>,\n by: unknown,\n workers: readonly string[],\n): string | undefined {\n if (typeof by !== \"string\" || (by !== \"human\" && !Object.hasOwn(state.roles, by)))\n return `${JSON.stringify(by)} is neither human nor a registered role`;\n return workers.includes(by) ? `\"${by}\" worked on the item` : undefined;\n}\nconst sourced = (d: ContextSnapshotData): boolean => d.assumptions.some((a) => a.source);\n/** A copy of a validated assumption (closed object: claim, required, source { path, lines, hash }). */\nconst copyOf = ({ source, ...rest }: ContextAssumption): ContextAssumption =>\n source\n ? {\n ...rest,\n source: {\n ...source,\n ...(source.lines ? { lines: [...source.lines] as [number, number] } : {}),\n },\n }\n : rest;\n\n/**\n * The item's current context (design spec section 27, #36): its latest fresh (post-rework)\n * qualifying `context-snapshot` evidence (valid data with at least one sourced assumption,\n * recorded by `human` or a registered role that did not work on the item, `workersOf`), with\n * `stale` the cited source paths a later `repo.changed` event listed (exact match, in event order)\n * and `unverified` the claims with no source; `undefined` when there is none. The `required`\n * claims of every other valid fresh snapshot (earlier or later, whoever recorded it) carry (spec 28, #49): reported\n * `required: true` when the latest has the claim, appended as `{ claim, required: true }` (no\n * source, so unverified) when it lacks it; claims compare by exact text. The answer is a\n * copy. Each evidence entry is located at its own `item.evidence` event, matched from the end as\n * `freshEvidence` does; an entry with no event counts as older than every event.\n */\nexport function contextOf(state: WorkflowState<string>, item: WorkItem): BriefContext | undefined {\n // one indexed pass over the log per state, not per item (F1 G3-2, G3-3, G3-4)\n const index = eventIndex(state);\n const at = index.evidence.get(item.id) ?? [];\n const all = item.evidence;\n const after = sinceRework(index, item.id, at);\n const fresh = after === undefined ? all.length : Math.min(after, all.length);\n let workers: string[] | undefined;\n // the data of entry k when it is a qualifying snapshot; one that does not qualify is ignored, so\n // it cannot supersede one that does (G2-1)\n const qualifying = (k: number): ContextSnapshotData | undefined => {\n const e = all[k]!;\n if (e.kind !== \"context-snapshot\" || snapshotIssue(e.data) !== undefined) return undefined;\n const data = e.data as unknown as ContextSnapshotData;\n return !sourced(data) || recorderIssue(state, e.by, (workers ??= workersOf(state, item)))\n ? undefined\n : data;\n };\n for (let k = all.length - 1; k >= all.length - fresh; k--) {\n const e = all[k]!;\n const data = qualifying(k);\n if (!data) continue;\n // the required claims of every other valid fresh snapshot (earlier or later) carry, whoever recorded\n // it: independence decides who may verify a claim, not which claims are required (spec 28,\n // #49, gate G1-3)\n const carried = new Set<string>();\n for (let j = all.length - 1; j >= all.length - fresh; j--) {\n const d = all[j]!;\n if (j === k) continue;\n if (d.kind === \"context-snapshot\" && snapshotIssue(d.data) === undefined)\n for (const a of (d.data as unknown as ContextSnapshotData).assumptions)\n if (a.required) carried.add(a.claim);\n }\n const assumptions = data.assumptions.map((a) =>\n carried.has(a.claim) ? { ...copyOf(a), required: true } : copyOf(a),\n );\n for (const claim of carried)\n if (!data.assumptions.some((a) => a.claim === claim))\n assumptions.push({ claim, required: true });\n // each cited path's first repo.changed after the snapshot's own event, in event order\n const pos = at[k + at.length - all.length] ?? -1;\n const hits: [number, number, string][] = [];\n for (const path of new Set(data.assumptions.map((a) => a.source?.path))) {\n const list = path === undefined ? undefined : index.changed.get(path);\n const f = list ? firstAfter(list, pos, (x) => x[0]) : 0;\n if (list && f < list.length) hits.push([list[f]![0], list[f]![1], path!]);\n }\n // oxlint-disable-next-line unicorn/no-array-sort -- a fresh local array; toSorted needs Node 20\n hits.sort((a, b) => a[0] - b[0] || a[1] - b[1]);\n return {\n revision: data.revision,\n // copies: a caller (a brief, a host) changing the answer must not change the state (G2-9)\n assumptions,\n snapshot: e.ref,\n by: e.by,\n stale: hits.map((h) => h[2]),\n unverified: assumptions.filter((a) => !a.source).map((a) => a.claim),\n };\n }\n return undefined;\n}\n\nconst KEYS = [\"item\", \"revision\", \"assumptions\", \"ref\", \"by\", \"now\"];\nconst bad = (what: string, fix: string): never =>\n fail(\"invalid-input\", `context snapshot: ${what}`, fix);\n\n/**\n * Records a context snapshot of an item as evidence `context-snapshot` with `data: { revision,\n * assumptions }` (design spec section 27, #36), through `applyAction` (action `context.snapshot`)\n * so the methodology's rules see it. Refuses `invalid-input` for an unknown key, an empty revision,\n * claim or ref, a source with a path that is not repository-relative POSIX or an empty hash,\n * `lines` that are not two integers `1 <= from <= to`, no assumption with a source, and a `by`\n * that is neither `human` nor a registered role or that worked on the item. The input is copied.\n */\nexport function recordContextSnapshot<N extends string>(\n state: WorkflowState<N>,\n methodology: Methodology<unknown, N>,\n input: ContextSnapshotInput,\n): ApplyResult<N> {\n if (!isObj(input)) bad(\"input must be an object\", `pass { ${KEYS.join(\", \")} }`);\n const k = extra(input as unknown as Record<string, unknown>, KEYS);\n if (k) bad(`unknown key \"${k}\"`, `use only: ${KEYS.join(\", \")}`);\n const { item: id, revision, assumptions, ref, by, now } = input;\n if (typeof id !== \"string\") bad(\"item must be an item id\", 'e.g. \"item\": \"CART-12\"');\n const item = getItem(state, id);\n const data = { revision, assumptions } as unknown as Record<string, unknown>;\n const issue = snapshotIssue(data);\n if (issue)\n bad(\n issue,\n 'e.g. { \"revision\": \"4f2c1e0\", \"assumptions\": [{ \"claim\": \"totals are cents\", \"source\": { \"path\": \"src/cart.ts\", \"hash\": \"…\" } }] }',\n );\n if (!nonEmpty(ref))\n bad(\"ref must be a non-empty string\", 'name the snapshot artifact, e.g. \"ctx/CART-12.json\"');\n if (!nonEmpty(by)) bad(\"by must name who recorded it\", 'e.g. \"by\": \"scout\"');\n const who = recorderIssue(state, by, workersOf(state, item));\n if (who)\n bad(\n `${who} and may not record its context`,\n \"record as human or a registered role that did not work on the item\",\n );\n if (!sourced(data as unknown as ContextSnapshotData))\n bad(\n \"a snapshot needs at least one assumption with a source (nothing was verified)\",\n 'cite what was checked, e.g. \"source\": { \"path\": \"src/cart.ts\", \"hash\": \"…\" }',\n );\n if (now !== undefined && typeof now !== \"string\")\n bad(\"now must be an ISO timestamp string\", \"omit now to use the clock\");\n // validated plain data, copied so no reference to the caller's arrays is kept\n const copy = JSON.parse(JSON.stringify(data)) as Record<string, unknown>;\n return applyAction(\n state,\n methodology,\n { type: \"context.snapshot\", by, payload: { item: id, ref, ...copy } },\n (s) => addEvidence(s, id, { kind: \"context-snapshot\", ref, by, data: copy }, now),\n );\n}\n","// The context-grounded entry policy (design spec section 27, #36): an item may enter a stage only\n// with a fresh, verified context snapshot that a human or a registered role other than its workers\n// recorded (contextOf counts only such a snapshot).\nimport type { Violation, WorkItem, WorkflowState } from \"../../core/types.ts\";\nimport { contextOf } from \"./snapshot.ts\";\n\nconst RULE = \"policy:custom:context-grounded\";\nconst RECORD = \"record a fresh one with recordContextSnapshot\";\n\n/**\n * Violations of the custom policy `context-grounded` for `item` (rule\n * `policy:custom:context-grounded`, the 1.2 rule id of a custom policy): no qualifying fresh\n * context snapshot (`contextOf`: valid, at least one sourced assumption, recorded by `human` or a\n * registered role that did not work on the item); a stale one (names the changed paths); a\n * `required` assumption without a source (names the claims). Empty when the item is grounded.\n * Pure: the same state gives the same answer.\n */\nexport function contextGroundedViolations(\n state: WorkflowState<string>,\n item: WorkItem,\n): Violation[] {\n const out: Violation[] = [];\n const v = (message: string, fix: string) =>\n out.push({ rule: RULE, severity: \"error\", item: item.id, message, fix });\n const ctx = contextOf(state, item);\n if (!ctx) {\n v(\n `item \"${item.id}\" has no qualifying context snapshot (none since its last rework is valid, cites a source and was recorded by human or a registered role that did not work on it)`,\n `have an independent role or a human verify the context and ${RECORD}`,\n );\n return out;\n }\n const of = `context snapshot \"${ctx.snapshot}\" of \"${item.id}\"`;\n if (ctx.stale.length)\n v(\n `${of} is stale: ${ctx.stale.join(\", \")} changed since`,\n `re-verify the claims and ${RECORD}`,\n );\n const required = ctx.assumptions.filter((a) => a.required);\n const unverified = required.filter((a) => !a.source).map((a) => a.claim);\n if (unverified.length)\n v(\n `${of} has unverified required assumption(s): ${unverified.join(\" | \")}`,\n `cite a source { path, hash } for each and ${RECORD}`,\n );\n return out;\n}\n","// Wrappers that turn any methodology into one carrying a policy (design spec section 27). The\n// wrapped methodology keeps every other member, its name included, so registerMethodology accepts it.\nimport { assertId, fail } from \"../core/errors.ts\";\nimport type { Methodology, Policy } from \"../core/types.ts\";\nimport { contextGroundedViolations } from \"../common/context/policy.ts\";\nimport { contextOf } from \"../common/context/snapshot.ts\";\nimport { riskEscalation, type RiskGateOptions } from \"../common/risk/escalation.ts\";\nimport { riskOptions } from \"../common/risk/options.ts\";\n\nconst isObj = (x: unknown): x is Record<string, unknown> =>\n typeof x === \"object\" && x !== null && !Array.isArray(x);\n\n/**\n * `methodology` with the risk-adaptive gate policy (design spec section 27, #35): for each gate in\n * `options.gates`, `complete()` adds the requirements of the row of `options.table` (default\n * `DEFAULT_RISK_TABLE`) that the item's strictest fresh, valid, independent risk assessment picks,\n * `critical` when there is none. An `escalateGate` the methodology already has is kept: both widen\n * the gate. Invalid options fail `invalid-input` here, once.\n */\nexport function withRiskGate<C, N extends string>(\n methodology: Methodology<C, N>,\n options: RiskGateOptions,\n): Methodology<C, N> {\n const opts = riskOptions(options, \"withRiskGate\");\n const inner = methodology.escalateGate;\n return {\n ...methodology,\n escalateGate(state, item, gate) {\n const own = riskEscalation(state, item, gate, opts);\n const prior = inner?.call(methodology, state, item, gate);\n if (!prior || !own) return prior ?? own;\n return {\n requires: [...prior.requires, ...own.requires],\n evidence: [...prior.evidence, ...own.evidence],\n reason: { ...prior.reason, ...own.reason },\n };\n },\n };\n}\n\nexport interface ContextGroundingOptions {\n /** Stage ids whose entry policies gain the custom policy `context-grounded`. */\n entry: string[];\n /** Stage ids whose exit policies gain it. */\n exit?: string[];\n}\n\nconst GROUNDED = \"context-grounded\";\nconst groundedPolicy: Policy = {\n kind: \"custom\",\n id: GROUNDED,\n description: \"grounded in a fresh, verified context snapshot\",\n};\nconst badGrounding = (what: string, fix: string): never =>\n fail(\"invalid-input\", `withContextGrounding options: ${what}`, fix);\n\nfunction stageIds(o: Record<string, unknown>, key: \"entry\" | \"exit\"): string[] {\n const ids = o[key];\n if (ids === undefined && key === \"exit\") return [];\n if (!Array.isArray(ids))\n badGrounding(`${key} must be an array of stage ids`, `e.g. \"${key}\": [\"dev\"]`);\n return (ids as unknown[]).map((id) => {\n assertId(id, `context-grounded ${key} stage id`);\n return id as string;\n });\n}\n\n/**\n * `methodology` with the context-grounded policy (design spec section 27, #36): `defaultStages`\n * adds the custom policy `context-grounded` to the entry policies of the `entry` stages and the\n * exit policies of the `exit` stages (an unknown stage id fails `invalid-input` there), and\n * `plan()`/`complete()` answer it with `contextGroundedViolations`; `synthesizeBrief` carries\n * `contextOf` as `Brief.context`. Hooks the methodology already has answer every other policy id\n * and a brief with no snapshot. Invalid options fail `invalid-input` here, once.\n */\nexport function withContextGrounding<C, N extends string>(\n methodology: Methodology<C, N>,\n options: ContextGroundingOptions,\n): Methodology<C, N> {\n if (!isObj(options)) badGrounding(\"must be an object\", 'pass { \"entry\": [\"dev\"] }');\n const o = options as unknown as Record<string, unknown>;\n for (const k of Object.keys(o))\n if (k !== \"entry\" && k !== \"exit\") badGrounding(`unknown key \"${k}\"`, \"use only: entry, exit\");\n const entry = stageIds(o, \"entry\");\n const exit = stageIds(o, \"exit\");\n const add = (list: Policy[], on: boolean): Policy[] =>\n on && !list.some((p) => p.kind === \"custom\" && p.id === GROUNDED)\n ? [...list, groundedPolicy]\n : list;\n return {\n ...withGroundingHooks(methodology),\n defaultStages(config) {\n const stages = methodology.defaultStages(config);\n for (const id of [...entry, ...exit])\n if (!stages.some((st) => st.id === id))\n fail(\n \"invalid-input\",\n `withContextGrounding: unknown stage \"${id}\"`,\n `stages: ${stages.map((st) => st.id).join(\", \")}`,\n );\n // a built-in ceremony checks these policies without the hook, so the policy could never pass\n // there (spec 28, G2 finding 2): refuse them here, once\n const checked = ceremonyChecked(methodology.name, stages);\n for (const [key, ids] of [\n [\"entry\", entry],\n [\"exit\", exit],\n ] as const)\n for (const id of ids)\n if (checked[key].includes(id))\n fail(\n \"invalid-input\",\n `withContextGrounding: the ${methodology.name} ceremony that moves items ${key === \"entry\" ? \"into\" : \"out of\"} \"${id}\" checks its ${key} policies without the grounding hook`,\n `ground a later stage instead, e.g. ${key} [\"${stages.find((st) => !checked.entry.includes(st.id) && !checked.exit.includes(st.id) && st.id !== stages[0]!.id)?.id ?? \"dev\"}\"]`,\n );\n return stages.map((st) => ({\n ...st,\n entryPolicy: add(st.entryPolicy, entry.includes(st.id)),\n exitPolicy: add(st.exitPolicy, exit.includes(st.id)),\n }));\n },\n };\n}\n\n/** Stage policies a built-in methodology's ceremonies check with `assertPolicies` (spec 28). */\nfunction ceremonyChecked(\n name: string,\n stages: readonly { id: string }[],\n): { entry: string[]; exit: string[] } {\n if (name === \"kanban\") return { entry: [], exit: stages[0] ? [stages[0].id] : [] };\n if (name === \"scrum\") return { entry: [], exit: [\"backlog\"] };\n if (name === \"experimentation\") return { entry: [\"building\"], exit: [] };\n return { entry: [], exit: [] };\n}\n\n/**\n * `methodology` with the hooks that answer the custom policy `context-grounded` (spec 28, #47):\n * `customPolicy` with `contextGroundedViolations`, `briefContext` with `contextOf`; hooks the\n * methodology already has answer every other policy id and a brief with no snapshot. Stages are\n * untouched. `withContextGrounding` builds on it, and the CLI wraps every methodology with it so a\n * state the SDK grounded is judged by its snapshots there too. Not exported from an entry point.\n */\nexport function withGroundingHooks<C, N extends string>(\n methodology: Methodology<C, N>,\n): Methodology<C, N> {\n const { customPolicy, briefContext } = methodology;\n return {\n ...methodology,\n customPolicy(state, item, policy) {\n return policy.id === GROUNDED\n ? contextGroundedViolations(state, item)\n : customPolicy?.call(methodology, state, item, policy);\n },\n briefContext(state, item) {\n return contextOf(state, item) ?? briefContext?.call(methodology, state, item);\n },\n };\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunkKLOSFZFK_cjs=require('./chunk-KLOSFZFK.cjs'),chunk6PFJYRM7_cjs=require('./chunk-6PFJYRM7.cjs'),chunkBBI7AKJK_cjs=require('./chunk-BBI7AKJK.cjs'),chunkMU26QW32_cjs=require('./chunk-MU26QW32.cjs'),chunkOSHBJIYD_cjs=require('./chunk-OSHBJIYD.cjs');var m=e=>chunkBBI7AKJK_cjs.a(e,"investigation"),_=(e,i)=>chunkBBI7AKJK_cjs.b(e,"investigation",i);function v(e,i){return [...new Set([...e.events.filter(d=>d.type==="item.completed"&&d.payload.id===i).map(d=>d.by),...(e.items[i]?.transitions??[]).filter(d=>d.to.status==="in_progress").map(d=>d.by)])]}function N(e,i){let d;for(let p=e.events.length-1;p>=0;p--){let s=e.events[p];if(s.type==="item.completed"&&s.payload.id===i){d=s.payload;break}}return d&&["done","needs-review"].includes(d.verdict)?d.produced.filter(p=>p.kind==="experiment-output").map(p=>p.ref):[]}function I(e){return chunkOSHBJIYD_cjs.b("invalid-input",`the investigation state is inconsistent: ${e}`,"restore .workflow/state.json from git, or start a new investigation")}function O(e){return e.rounds.at(-1)??I(`phase ${e.phase} has no round`)}function S(e){return e.iterations.find(i=>i.id==="investigation")??I('there is no "investigation" iteration')}function R(e){let i=e;return (!i||typeof i!="object"||Array.isArray(i)||typeof i.question!="string"||!i.question.trim()||!Number.isSafeInteger(i.maxRounds)||i.maxRounds<1||!i.budget||typeof i.budget!="object"||Array.isArray(i.budget)||!Object.keys(i.budget).length||Object.entries(i.budget).some(([d,p])=>!["tokens","turns","wallclockMs"].includes(d)||typeof p!="number"||!Number.isFinite(p)||p<=0))&&chunkOSHBJIYD_cjs.b("config-invalid","investigation requires question, positive maxRounds and a finite positive budget","provide bounded investigation config"),{question:i.question,maxRounds:i.maxRounds,budget:{...i.budget}}}function H(e,i,d,p){let s=m(e);return chunkOSHBJIYD_cjs.b("invalid-input",`${i} (phase ${s?.phase??"intake"}): ${d}`,p,{items:s?[s.item,...s.rounds.at(-1)?[s.rounds.at(-1).item]:[]]:[]})}var F=(e,i)=>!!e&&!!i&&!chunkKLOSFZFK_cjs.a(e,i,["id","claim","falsifiedBy"]).length,y=e=>typeof e=="string"&&e.trim().length>0,B=e=>Array.isArray(e)&&e.length>0&&e.every(y)&&new Set(e).size===e.length,D=(e,i)=>e&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).find(d=>!i.includes(d)):void 0,E=(e,i)=>Array.isArray(e)?e.map(d=>D(d,i)).find(Boolean):void 0;function Q(e,i,d){chunkMU26QW32_cjs.e(e,i)?.capabilities.includes(d)||chunkOSHBJIYD_cjs.b("missing-capability",`${i} needs ${d}`,"use a registered role with the required capability");}function b(e,i,d,p){return chunkMU26QW32_cjs.c(_(e,i),`investigation.${p}`,d.by,{...i},chunkMU26QW32_cjs.a(d.now))}function C(e,i,d,p,s){let n=chunkMU26QW32_cjs.a(d.now),t=b(e,{...i,phase:"closed",outcome:p,...s?{stopReason:s}:{}},d,p);t={...t,iterations:t.iterations.map(a=>a.id==="investigation"?{...a,endedAt:n,outcome:p==="stopped"?"cancelled":"completed"}:a)};for(let a of Object.values(t.items).filter(r=>r.id===i.item||i.rounds.some(u=>u.item===r.id)))a.status!=="done"&&a.status!=="dropped"&&(t=chunkMU26QW32_cjs.u(t,a.id,{status:p==="resolved"&&a.id===i.item?"done":"dropped"},d.by,n));return t}function U(e){let i,d=()=>i??=e(),p=(s,n,t,a)=>(r,u)=>{Q(r,u.by,n);let o=m(r);return (!o||o.phase==="closed")&&H(r,s,"no active investigation","start a new investigation with intake {item}"),t&&o.phase!==t&&!(s==="hypotheses"&&o.phase==="preregister")&&H(r,s,`expected ${t}, got ${o.phase}`,`finish phase ${o.phase} before calling ${s}; ${s} requires phase ${t}`),chunkMU26QW32_cjs.W(r,d(),{type:`ceremony.${s}`,by:u.by,payload:u},()=>a(r,o,u,(l,g)=>H(r,s,l,g)))};return {intake(s,n){Q(s,n.by,"facilitate");let t=(r,u)=>H(s,"intake",r,u);s.methodology!=="investigation"&&t(`workflow methodology is ${s.methodology}, not investigation`,"init a workflow with the investigation methodology before intake"),m(s)&&t("investigation already started","use the existing investigation or initialize a new workflow"),y(n.item)||t("item is required","set intake.item to a unique investigation item ID");let a=R(s.config);return chunkMU26QW32_cjs.W(s,d(),{type:"ceremony.intake",by:n.by,payload:n},()=>{let r=chunkMU26QW32_cjs.s(s,{id:n.item,title:a.question,acceptance:["Independent evidence-based conclusion"],stage:"intake"},n.by,n.now);return r={...r,iterations:[...r.iterations,{id:"investigation",goal:a.question,budget:{...a.budget},spent:{tokens:0,turns:0,wallclockMs:0},startedAt:chunkMU26QW32_cjs.a(n.now),committed:[],carryover:[]}]},b(r,{item:n.item,phase:"hypotheses",hypotheses:[],rounds:[],contributors:[n.by]},n,"intake")})},hypotheses:p("hypotheses","define-acceptance","hypotheses",(s,n,t,a)=>{let r=t.hypotheses,u=E(r,["id","claim","falsifiedBy"]);return u&&a(`unknown key "${u}" in a hypotheses entry`,"use only id, claim and falsifiedBy in each hypotheses entry"),(!Array.isArray(r)||!r.length||r.some(o=>!o||!y(o.id)||!y(o.claim)||!y(o.falsifiedBy))||new Set(r.map(o=>o.id)).size!==r.length||r.length<2&&!y(t.singleHypothesisRationale))&&a("provide competing falsifiable hypotheses or single-testable rationale","set hypotheses to unique {id, claim, falsifiedBy} entries; supply singleHypothesisRationale when there is only one"),b(s,{...n,hypotheses:r.map(o=>({id:o.id,claim:o.claim,falsifiedBy:o.falsifiedBy})),...y(t.singleHypothesisRationale)?{singleHypothesisRationale:t.singleHypothesisRationale}:{},contributors:[...new Set([...n.contributors,t.by])],phase:"preregister"},t,"hypotheses")}),preregister:p("preregister","define-acceptance","preregister",(s,n,t,a)=>{let r=R(s.config),u=s.iterations.find(c=>c.id==="investigation");(n.rounds.length>=r.maxRounds||!u||chunkMU26QW32_cjs.N(r.budget,u.spent))&&a(`round limit or budget exhausted (${n.rounds.length} of ${r.maxRounds} rounds used)`,"call stop {reason} to close this investigation, or start a new one with a larger maxRounds or budget");let o=t.experiment,l=D(o,["id","procedureRef","predictions","replayOf"])??E(o?.predictions,["hypothesis","prediction"]);if(l&&a(`unknown key "${l}" in experiment`,"use only id, procedureRef, predictions [{hypothesis, prediction}] and replayOf in experiment"),(!o||!y(o.id)||!y(o.procedureRef)||n.rounds.some(c=>c.experiment.id===o.id)||!Array.isArray(o.predictions)||o.predictions.length!==n.hypotheses.length||n.hypotheses.some(c=>o.predictions.filter(f=>f?.hypothesis===c.id&&y(f.prediction)).length!==1)||new Set(o.predictions.map(c=>c.prediction)).size!==o.predictions.length)&&a("preregister unique experiment with differing predictions for every hypothesis","set experiment.id to a new ID, experiment.procedureRef, and one distinct experiment.predictions entry per hypothesis"),o.replayOf){let c=n.rounds.find(f=>f.experiment.id===o.replayOf&&f.result?.valid);(!c||chunkKLOSFZFK_cjs.a(c.experiment,o,["procedureRef"]).length||c.hypotheses.length!==n.hypotheses.length||n.hypotheses.some(f=>!F(f,c.hypotheses.find(q=>q.id===f.id)))||o.predictions.some(f=>!c.experiment.predictions.some(q=>!chunkKLOSFZFK_cjs.a(q,f,["hypothesis","prediction"]).length)))&&a("replay must repeat the procedure, predictions and hypotheses of a prior valid experiment","set experiment.replayOf to a valid prior experiment with identical procedureRef, predictions and hypothesis definitions");}let g=`${n.item}-run-${n.rounds.length+1}`,w=chunkMU26QW32_cjs.s(s,{id:g,title:`Experiment ${o.id}`,stage:"execute",acceptance:[o.procedureRef],iteration:"investigation"},t.by,t.now);return w={...w,iterations:w.iterations.map(c=>c.id==="investigation"?{...c,committed:[...c.committed,g]}:c)},b(w,{...n,phase:"observe",rounds:[...n.rounds,{experiment:{id:o.id,procedureRef:o.procedureRef,predictions:o.predictions.map(c=>({hypothesis:c.hypothesis,prediction:c.prediction})),...o.replayOf?{replayOf:o.replayOf}:{}},hypotheses:n.hypotheses.map(c=>({...c})),item:g,by:t.by}],contributors:[...new Set([...n.contributors,t.by])]},t,"preregister")}),observe:p("observe","verify","observe",(s,n,t,a)=>{let r=O(n),u=t.result,o=D(u,["id","valid","summary","provenanceRefs"]);return o&&a(`unknown key "${o}" in result`,"use only id, valid, summary and provenanceRefs in result"),(t.experiment!==r.experiment.id||!u||!y(u.id)||typeof u.valid!="boolean"||!y(u.summary)||!B(u.provenanceRefs)||n.rounds.some(l=>l.result?.id===u.id))&&a("observation needs current experiment, unique result and provenance","set experiment to the active experiment ID and result to {id, valid, summary, provenanceRefs} with a new result.id"),s.items[r.item]?.status!=="done"&&a("complete experiment execution before recording observations","dispatch and complete the active experiment item before calling observe"),N(s,r.item).some(l=>u.provenanceRefs.includes(l))||a("observation must link fresh experiment-output evidence from the latest completion",`include an experiment-output ref produced by the latest successful completion of item "${r.item}" in result.provenanceRefs`),b(s,{...n,phase:"update-belief",rounds:n.rounds.map(l=>l===r?{...l,result:{id:u.id,valid:u.valid,summary:u.summary,provenanceRefs:[...u.provenanceRefs]}}:l),contributors:[...new Set([...n.contributors,t.by,...v(s,r.item)])]},t,"observe")}),"update-belief":p("update-belief","define-acceptance","update-belief",(s,n,t,a)=>{let r=O(n),u=t.assessments,o=E(u,["hypothesis","assessment","reason"]);o&&a(`unknown key "${o}" in an assessments entry`,"use only hypothesis, assessment and reason in each assessments entry"),(t.result!==r.result?.id||!Array.isArray(u)||u.length!==n.hypotheses.length||n.hypotheses.some(c=>u.filter(f=>f?.hypothesis===c.id&&["supported","refuted","uncertain"].includes(f.assessment)&&y(f.reason)).length!==1)||!["round","conclusion"].includes(t.next))&&a("belief update must assess every hypothesis against current result","set result to the latest result ID, assessments to one {hypothesis, assessment, reason} per hypothesis, and next to round or conclusion"),!(r.result??I(`round ${r.experiment.id} has no result`)).valid&&u.some(c=>c.assessment!=="uncertain")&&a("invalid experiments cannot support beliefs","set every assessment to uncertain for an invalid experiment result");let g=b(s,{...n,phase:t.next==="round"?"preregister":"conclusion",rounds:n.rounds.map(c=>c===r?{...c,update:{result:t.result,assessments:u.map(f=>({hypothesis:f.hypothesis,assessment:f.assessment,reason:f.reason}))}}:c),contributors:[...new Set([...n.contributors,t.by])]},t,"belief-updated"),w=S(g);return t.next==="round"&&(n.rounds.length>=R(s.config).maxRounds||chunkMU26QW32_cjs.N(w.budget,w.spent))&&(g=C(g,m(g),t,"stopped","budget or round limit exhausted")),g}),conclude:p("conclude","define-acceptance","conclusion",(s,n,t,a)=>{let r=t;return (!["resolved","inconclusive"].includes(r.outcome)||!y(r.summary)||!B(r.evidenceRefs)||r.evidenceRefs.some(u=>!n.rounds.some(o=>o.result?.provenanceRefs.includes(u))))&&a("conclusion needs observed evidence references","set outcome, summary and evidenceRefs to references preserved in recorded observations"),r.outcome==="resolved"&&(!y(r.supportedHypothesis)||!n.rounds.slice(-1).some(u=>u.result?.valid&&u.update?.assessments.some(o=>o.hypothesis===r.supportedHypothesis&&o.assessment==="supported")))&&a("resolved conclusion needs a supported hypothesis","set supportedHypothesis to a hypothesis supported by the latest valid round, or choose outcome inconclusive"),b(s,{...n,phase:"review",conclusion:{outcome:r.outcome,summary:r.summary,evidenceRefs:[...r.evidenceRefs],...r.supportedHypothesis?{supportedHypothesis:r.supportedHypothesis}:{},by:t.by},contributors:[...new Set([...n.contributors,t.by])]},t,"conclusion")}),"review-conclusion":p("review-conclusion","review","review",(s,n,t,a)=>{let r=n.conclusion??I("phase review has no conclusion");if(chunk6PFJYRM7_cjs.a(t.by,n.contributors).length&&a("conclusion reviewer must be independent of investigation contributors","use a review-capable role that did not contribute to or execute this investigation"),(typeof t.approve!="boolean"||!y(t.reason))&&a("review needs approval and reason","set approve to a boolean and reason to a nonempty review explanation"),!t.approve){let o=t.next??"conclusion";o!=="round"&&o!=="conclusion"&&a("review rejection next must be round or conclusion","set next to round for more evidence or conclusion for a revised conclusion");let l=b(s,{...n,phase:o==="round"?"preregister":"conclusion",reviewHistory:[...n.reviewHistory??[],{by:t.by,reason:t.reason,approve:false,next:o,replayRefs:[]}]},t,"review-rejected"),g=S(s);return o==="round"&&(n.rounds.length>=R(s.config).maxRounds||chunkMU26QW32_cjs.N(g.budget,g.spent))?C(l,m(l),t,"stopped","budget or round limit exhausted after review requested another round"):l}let u=Array.isArray(t.replayRefs)?t.replayRefs:[];return r.outcome==="resolved"&&(!B(u)||!n.rounds.some(o=>o.experiment.replayOf&&!chunk6PFJYRM7_cjs.a(v(s,o.item),v(s,(n.rounds.find(l=>l.experiment.id===o.experiment.replayOf)??I(`round ${o.experiment.id} replays the unknown experiment ${o.experiment.replayOf}`)).item)).length&&F(o.hypotheses.find(l=>l.id===r.supportedHypothesis),O(n).hypotheses.find(l=>l.id===r.supportedHypothesis))&&o.result?.valid&&u.includes(o.result.id)&&o.update?.assessments.some(l=>l.hypothesis===r.supportedHypothesis&&l.assessment==="supported")))&&a("resolved conclusion requires valid replay result and supporting belief update","set replayRefs to a valid independent replay result supporting the latest supported hypothesis definition, or reject with next round"),C(s,{...n,review:{by:t.by,reason:t.reason,replayRefs:u},reviewHistory:[...n.reviewHistory??[],{by:t.by,reason:t.reason,approve:true,replayRefs:u}]},t,r.outcome)}),stop:p("stop","facilitate",void 0,(s,n,t,a)=>(y(t.reason)||a("stop needs reason","set reason to a nonempty explanation for stopping this investigation"),C(s,n,t,"stopped",t.reason)))}}function V(){return [{id:"independent-replay",severity:"error",check(e,i){if(i.type!=="item.complete")return [];let d=m(e)?.rounds.find(s=>s.item===i.payload?.item),p=m(e)?.rounds.find(s=>s.experiment.id===d?.experiment.replayOf);return p&&chunk6PFJYRM7_cjs.a(i.by,v(e,p.item)).length?[{rule:"independent-replay",item:d.item,severity:"error",message:"Replay executor also executed the original experiment",fix:"assign a different deliver-capable role"}]:[]}},{id:"investigation-execution-only",severity:"error",check(e,i){if(i.type!=="item.complete")return [];let d=i.payload,p=m(e);return p?.phase==="observe"&&p.rounds.at(-1)?.item===d.item?[]:[{rule:"investigation-execution-only",item:d.item,severity:"error",message:"Only the active preregistered experiment can complete",fix:`complete only the active experiment item in phase observe; current phase is ${p?.phase??"intake"}`}]}}]}function G(){return [{id:"replay-worker",name:"Independent replay worker",modelTier:"small",capabilities:["deliver","verify"],canApprove:[],inputs:["preregistered-experiment"],outputs:["experiment-output"],do_not:["Do not change the replay procedure"]},{id:"investigator",name:"Investigator",modelTier:"large",capabilities:["facilitate","define-acceptance","deliver","verify"],canApprove:[],inputs:["question","prior-results"],outputs:["hypotheses","preregistered-experiment","belief-update"],do_not:["Do not revise predictions after execution","Do not approve your own conclusions"]},{id:"conclusion-reviewer",name:"Independent conclusion reviewer",modelTier:"large",capabilities:["review"],canApprove:["investigation-conclusion"],inputs:["evidence","replay","conclusion"],outputs:["conclusion-review"],do_not:["Do not approve unsupported conclusions"]}]}function J(){return [{id:"intake",name:"Intake",entryPolicy:[],exitPolicy:[{kind:"acceptance-written"}]},{id:"execute",name:"Execute preregistered experiment",entryPolicy:[{kind:"acceptance-written"},{kind:"no-open-blockers"}],exitPolicy:[{kind:"evidence",evidenceKind:"experiment-output"}]},{id:"observed",name:"Execution recorded",entryPolicy:[],exitPolicy:[]}]}function L(){return {name:"investigation",validateConfig:R,lockedConfigKeys:["question","maxRounds","budget"],vocabulary:{backlog:"Questions",item:"Investigation artifact",stage:"Investigation phase",iteration:"Investigation budget",increment:"Conclusion",ceremony:"Investigation ceremony",gate:"Independent conclusion review"},defaultStages:J,defaultRoles:G,requiredCapabilities:["facilitate","define-acceptance","deliver","verify","review"],exclusiveCapabilities:[],humanDefaults:{gates:"none"},ceremonies:U(L),plannerOptions:e=>({schedulerMode:"level",concurrencyCap:1,roleFor:i=>{let d=m(e)?.rounds.find(a=>a.item===i.id),p=m(e)?.rounds.find(a=>a.experiment.id===d?.experiment.replayOf),s=p?v(e,p.item):[],n=Object.values(e.roles),t=(p?void 0:n.find(a=>a.capabilities.includes("deliver")&&a.capabilities.includes("define-acceptance")))??n.find(a=>a.capabilities.includes("deliver")&&!chunk6PFJYRM7_cjs.a(a.id,s).length);return t||chunkOSHBJIYD_cjs.b("missing-capability",`No eligible executor for experiment item "${i.id}"`,p?`register an independent deliver-capable role that did not execute "${p.item}"`:"register a role with deliver capability",{items:[i.id]}),t.id},estimateMode:"per-call",fallbackTokensPerWeight:1}),candidates:e=>{let i=m(e),d=i?.rounds.at(-1)?.item;return i?.phase==="observe"&&!chunkMU26QW32_cjs.N(e.config.budget,S(e).spent)?Object.values(e.items).filter(p=>p.id===d&&p.stage==="execute"&&p.status==="todo"):[]},afterComplete:(e,i,d)=>{let p=m(e),s=e.iterations.find(n=>n.id==="investigation");return p?.phase!=="observe"||p.rounds.at(-1)?.item!==i||e.items[i]?.status==="done"||!s||!chunkMU26QW32_cjs.N(s.budget,s.spent)?e:C(e,p,{by:"investigation",now:d},"stopped",`budget exhausted before experiment item "${i}" completed; start a new investigation with sufficient budget`)},invariants:e=>[`Question: ${e.config.question}`,"Execute only the preregistered procedure; retain raw observation provenance; report invalid runs."],rules:V(),metrics:e=>({rounds:m(e)?.rounds.length??0,validRuns:m(e)?.rounds.filter(i=>i.result?.valid).length??0,invalidRuns:m(e)?.rounds.filter(i=>i.result&&!i.result.valid).length??0}),report:e=>({phase:m(e)?.phase??"intake",outcome:m(e)?.outcome??null,rounds:m(e)?.rounds.length??0,conclusion:m(e)?.conclusion??null,stopReason:m(e)?.stopReason??null})}}exports.a=R;exports.b=L;//# sourceMappingURL=chunk-UMG3WOD7.cjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
'use strict';var chunkKLOSFZFK_cjs=require('./chunk-KLOSFZFK.cjs'),chunk6PFJYRM7_cjs=require('./chunk-6PFJYRM7.cjs'),chunkBBI7AKJK_cjs=require('./chunk-BBI7AKJK.cjs'),chunkTBLIZIWH_cjs=require('./chunk-TBLIZIWH.cjs'),chunkOSHBJIYD_cjs=require('./chunk-OSHBJIYD.cjs');var m=e=>chunkBBI7AKJK_cjs.a(e,"investigation"),_=(e,i)=>chunkBBI7AKJK_cjs.b(e,"investigation",i);function v(e,i){return [...new Set([...e.events.filter(d=>d.type==="item.completed"&&d.payload.id===i).map(d=>d.by),...(e.items[i]?.transitions??[]).filter(d=>d.to.status==="in_progress").map(d=>d.by)])]}function N(e,i){let d;for(let p=e.events.length-1;p>=0;p--){let s=e.events[p];if(s.type==="item.completed"&&s.payload.id===i){d=s.payload;break}}return d&&["done","needs-review"].includes(d.verdict)?d.produced.filter(p=>p.kind==="experiment-output").map(p=>p.ref):[]}function I(e){return chunkOSHBJIYD_cjs.b("invalid-input",`the investigation state is inconsistent: ${e}`,"restore .workflow/state.json from git, or start a new investigation")}function O(e){return e.rounds.at(-1)??I(`phase ${e.phase} has no round`)}function S(e){return e.iterations.find(i=>i.id==="investigation")??I('there is no "investigation" iteration')}function R(e){let i=e;return (!i||typeof i!="object"||Array.isArray(i)||typeof i.question!="string"||!i.question.trim()||!Number.isSafeInteger(i.maxRounds)||i.maxRounds<1||!i.budget||typeof i.budget!="object"||Array.isArray(i.budget)||!Object.keys(i.budget).length||Object.entries(i.budget).some(([d,p])=>!["tokens","turns","wallclockMs"].includes(d)||typeof p!="number"||!Number.isFinite(p)||p<=0))&&chunkOSHBJIYD_cjs.b("config-invalid","investigation requires question, positive maxRounds and a finite positive budget","provide bounded investigation config"),{question:i.question,maxRounds:i.maxRounds,budget:{...i.budget}}}function H(e,i,d,p){let s=m(e);return chunkOSHBJIYD_cjs.b("invalid-input",`${i} (phase ${s?.phase??"intake"}): ${d}`,p,{items:s?[s.item,...s.rounds.at(-1)?[s.rounds.at(-1).item]:[]]:[]})}var F=(e,i)=>!!e&&!!i&&!chunkKLOSFZFK_cjs.a(e,i,["id","claim","falsifiedBy"]).length,y=e=>typeof e=="string"&&e.trim().length>0,B=e=>Array.isArray(e)&&e.length>0&&e.every(y)&&new Set(e).size===e.length,D=(e,i)=>e&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).find(d=>!i.includes(d)):void 0,E=(e,i)=>Array.isArray(e)?e.map(d=>D(d,i)).find(Boolean):void 0;function Q(e,i,d){chunkTBLIZIWH_cjs.e(e,i)?.capabilities.includes(d)||chunkOSHBJIYD_cjs.b("missing-capability",`${i} needs ${d}`,"use a registered role with the required capability");}function b(e,i,d,p){return chunkTBLIZIWH_cjs.c(_(e,i),`investigation.${p}`,d.by,{...i},chunkTBLIZIWH_cjs.a(d.now))}function C(e,i,d,p,s){let n=chunkTBLIZIWH_cjs.a(d.now),t=b(e,{...i,phase:"closed",outcome:p,...s?{stopReason:s}:{}},d,p);t={...t,iterations:t.iterations.map(a=>a.id==="investigation"?{...a,endedAt:n,outcome:p==="stopped"?"cancelled":"completed"}:a)};for(let a of Object.values(t.items).filter(r=>r.id===i.item||i.rounds.some(u=>u.item===r.id)))a.status!=="done"&&a.status!=="dropped"&&(t=chunkTBLIZIWH_cjs.v(t,a.id,{status:p==="resolved"&&a.id===i.item?"done":"dropped"},d.by,n));return t}function U(e){let i,d=()=>i??=e(),p=(s,n,t,a)=>(r,u)=>{Q(r,u.by,n);let o=m(r);return (!o||o.phase==="closed")&&H(r,s,"no active investigation","start a new investigation with intake {item}"),t&&o.phase!==t&&!(s==="hypotheses"&&o.phase==="preregister")&&H(r,s,`expected ${t}, got ${o.phase}`,`finish phase ${o.phase} before calling ${s}; ${s} requires phase ${t}`),chunkTBLIZIWH_cjs.V(r,d(),{type:`ceremony.${s}`,by:u.by,payload:u},()=>a(r,o,u,(l,g)=>H(r,s,l,g)))};return {intake(s,n){Q(s,n.by,"facilitate");let t=(r,u)=>H(s,"intake",r,u);s.methodology!=="investigation"&&t(`workflow methodology is ${s.methodology}, not investigation`,"init a workflow with the investigation methodology before intake"),m(s)&&t("investigation already started","use the existing investigation or initialize a new workflow"),y(n.item)||t("item is required","set intake.item to a unique investigation item ID");let a=R(s.config);return chunkTBLIZIWH_cjs.V(s,d(),{type:"ceremony.intake",by:n.by,payload:n},()=>{let r=chunkTBLIZIWH_cjs.t(s,{id:n.item,title:a.question,acceptance:["Independent evidence-based conclusion"],stage:"intake"},n.by,n.now);return r={...r,iterations:[...r.iterations,{id:"investigation",goal:a.question,budget:{...a.budget},spent:{tokens:0,turns:0,wallclockMs:0},startedAt:chunkTBLIZIWH_cjs.a(n.now),committed:[],carryover:[]}]},b(r,{item:n.item,phase:"hypotheses",hypotheses:[],rounds:[],contributors:[n.by]},n,"intake")})},hypotheses:p("hypotheses","define-acceptance","hypotheses",(s,n,t,a)=>{let r=t.hypotheses,u=E(r,["id","claim","falsifiedBy"]);return u&&a(`unknown key "${u}" in a hypotheses entry`,"use only id, claim and falsifiedBy in each hypotheses entry"),(!Array.isArray(r)||!r.length||r.some(o=>!o||!y(o.id)||!y(o.claim)||!y(o.falsifiedBy))||new Set(r.map(o=>o.id)).size!==r.length||r.length<2&&!y(t.singleHypothesisRationale))&&a("provide competing falsifiable hypotheses or single-testable rationale","set hypotheses to unique {id, claim, falsifiedBy} entries; supply singleHypothesisRationale when there is only one"),b(s,{...n,hypotheses:r.map(o=>({id:o.id,claim:o.claim,falsifiedBy:o.falsifiedBy})),...y(t.singleHypothesisRationale)?{singleHypothesisRationale:t.singleHypothesisRationale}:{},contributors:[...new Set([...n.contributors,t.by])],phase:"preregister"},t,"hypotheses")}),preregister:p("preregister","define-acceptance","preregister",(s,n,t,a)=>{let r=R(s.config),u=s.iterations.find(c=>c.id==="investigation");(n.rounds.length>=r.maxRounds||!u||chunkTBLIZIWH_cjs.M(r.budget,u.spent))&&a(`round limit or budget exhausted (${n.rounds.length} of ${r.maxRounds} rounds used)`,"call stop {reason} to close this investigation, or start a new one with a larger maxRounds or budget");let o=t.experiment,l=D(o,["id","procedureRef","predictions","replayOf"])??E(o?.predictions,["hypothesis","prediction"]);if(l&&a(`unknown key "${l}" in experiment`,"use only id, procedureRef, predictions [{hypothesis, prediction}] and replayOf in experiment"),(!o||!y(o.id)||!y(o.procedureRef)||n.rounds.some(c=>c.experiment.id===o.id)||!Array.isArray(o.predictions)||o.predictions.length!==n.hypotheses.length||n.hypotheses.some(c=>o.predictions.filter(f=>f?.hypothesis===c.id&&y(f.prediction)).length!==1)||new Set(o.predictions.map(c=>c.prediction)).size!==o.predictions.length)&&a("preregister unique experiment with differing predictions for every hypothesis","set experiment.id to a new ID, experiment.procedureRef, and one distinct experiment.predictions entry per hypothesis"),o.replayOf){let c=n.rounds.find(f=>f.experiment.id===o.replayOf&&f.result?.valid);(!c||chunkKLOSFZFK_cjs.a(c.experiment,o,["procedureRef"]).length||c.hypotheses.length!==n.hypotheses.length||n.hypotheses.some(f=>!F(f,c.hypotheses.find(q=>q.id===f.id)))||o.predictions.some(f=>!c.experiment.predictions.some(q=>!chunkKLOSFZFK_cjs.a(q,f,["hypothesis","prediction"]).length)))&&a("replay must repeat the procedure, predictions and hypotheses of a prior valid experiment","set experiment.replayOf to a valid prior experiment with identical procedureRef, predictions and hypothesis definitions");}let g=`${n.item}-run-${n.rounds.length+1}`,w=chunkTBLIZIWH_cjs.t(s,{id:g,title:`Experiment ${o.id}`,stage:"execute",acceptance:[o.procedureRef],iteration:"investigation"},t.by,t.now);return w={...w,iterations:w.iterations.map(c=>c.id==="investigation"?{...c,committed:[...c.committed,g]}:c)},b(w,{...n,phase:"observe",rounds:[...n.rounds,{experiment:{id:o.id,procedureRef:o.procedureRef,predictions:o.predictions.map(c=>({hypothesis:c.hypothesis,prediction:c.prediction})),...o.replayOf?{replayOf:o.replayOf}:{}},hypotheses:n.hypotheses.map(c=>({...c})),item:g,by:t.by}],contributors:[...new Set([...n.contributors,t.by])]},t,"preregister")}),observe:p("observe","verify","observe",(s,n,t,a)=>{let r=O(n),u=t.result,o=D(u,["id","valid","summary","provenanceRefs"]);return o&&a(`unknown key "${o}" in result`,"use only id, valid, summary and provenanceRefs in result"),(t.experiment!==r.experiment.id||!u||!y(u.id)||typeof u.valid!="boolean"||!y(u.summary)||!B(u.provenanceRefs)||n.rounds.some(l=>l.result?.id===u.id))&&a("observation needs current experiment, unique result and provenance","set experiment to the active experiment ID and result to {id, valid, summary, provenanceRefs} with a new result.id"),s.items[r.item]?.status!=="done"&&a("complete experiment execution before recording observations","dispatch and complete the active experiment item before calling observe"),N(s,r.item).some(l=>u.provenanceRefs.includes(l))||a("observation must link fresh experiment-output evidence from the latest completion",`include an experiment-output ref produced by the latest successful completion of item "${r.item}" in result.provenanceRefs`),b(s,{...n,phase:"update-belief",rounds:n.rounds.map(l=>l===r?{...l,result:{id:u.id,valid:u.valid,summary:u.summary,provenanceRefs:[...u.provenanceRefs]}}:l),contributors:[...new Set([...n.contributors,t.by,...v(s,r.item)])]},t,"observe")}),"update-belief":p("update-belief","define-acceptance","update-belief",(s,n,t,a)=>{let r=O(n),u=t.assessments,o=E(u,["hypothesis","assessment","reason"]);o&&a(`unknown key "${o}" in an assessments entry`,"use only hypothesis, assessment and reason in each assessments entry"),(t.result!==r.result?.id||!Array.isArray(u)||u.length!==n.hypotheses.length||n.hypotheses.some(c=>u.filter(f=>f?.hypothesis===c.id&&["supported","refuted","uncertain"].includes(f.assessment)&&y(f.reason)).length!==1)||!["round","conclusion"].includes(t.next))&&a("belief update must assess every hypothesis against current result","set result to the latest result ID, assessments to one {hypothesis, assessment, reason} per hypothesis, and next to round or conclusion"),!(r.result??I(`round ${r.experiment.id} has no result`)).valid&&u.some(c=>c.assessment!=="uncertain")&&a("invalid experiments cannot support beliefs","set every assessment to uncertain for an invalid experiment result");let g=b(s,{...n,phase:t.next==="round"?"preregister":"conclusion",rounds:n.rounds.map(c=>c===r?{...c,update:{result:t.result,assessments:u.map(f=>({hypothesis:f.hypothesis,assessment:f.assessment,reason:f.reason}))}}:c),contributors:[...new Set([...n.contributors,t.by])]},t,"belief-updated"),w=S(g);return t.next==="round"&&(n.rounds.length>=R(s.config).maxRounds||chunkTBLIZIWH_cjs.M(w.budget,w.spent))&&(g=C(g,m(g),t,"stopped","budget or round limit exhausted")),g}),conclude:p("conclude","define-acceptance","conclusion",(s,n,t,a)=>{let r=t;return (!["resolved","inconclusive"].includes(r.outcome)||!y(r.summary)||!B(r.evidenceRefs)||r.evidenceRefs.some(u=>!n.rounds.some(o=>o.result?.provenanceRefs.includes(u))))&&a("conclusion needs observed evidence references","set outcome, summary and evidenceRefs to references preserved in recorded observations"),r.outcome==="resolved"&&(!y(r.supportedHypothesis)||!n.rounds.slice(-1).some(u=>u.result?.valid&&u.update?.assessments.some(o=>o.hypothesis===r.supportedHypothesis&&o.assessment==="supported")))&&a("resolved conclusion needs a supported hypothesis","set supportedHypothesis to a hypothesis supported by the latest valid round, or choose outcome inconclusive"),b(s,{...n,phase:"review",conclusion:{outcome:r.outcome,summary:r.summary,evidenceRefs:[...r.evidenceRefs],...r.supportedHypothesis?{supportedHypothesis:r.supportedHypothesis}:{},by:t.by},contributors:[...new Set([...n.contributors,t.by])]},t,"conclusion")}),"review-conclusion":p("review-conclusion","review","review",(s,n,t,a)=>{let r=n.conclusion??I("phase review has no conclusion");if(chunk6PFJYRM7_cjs.a(t.by,n.contributors).length&&a("conclusion reviewer must be independent of investigation contributors","use a review-capable role that did not contribute to or execute this investigation"),(typeof t.approve!="boolean"||!y(t.reason))&&a("review needs approval and reason","set approve to a boolean and reason to a nonempty review explanation"),!t.approve){let o=t.next??"conclusion";o!=="round"&&o!=="conclusion"&&a("review rejection next must be round or conclusion","set next to round for more evidence or conclusion for a revised conclusion");let l=b(s,{...n,phase:o==="round"?"preregister":"conclusion",reviewHistory:[...n.reviewHistory??[],{by:t.by,reason:t.reason,approve:false,next:o,replayRefs:[]}]},t,"review-rejected"),g=S(s);return o==="round"&&(n.rounds.length>=R(s.config).maxRounds||chunkTBLIZIWH_cjs.M(g.budget,g.spent))?C(l,m(l),t,"stopped","budget or round limit exhausted after review requested another round"):l}let u=Array.isArray(t.replayRefs)?t.replayRefs:[];return r.outcome==="resolved"&&(!B(u)||!n.rounds.some(o=>o.experiment.replayOf&&!chunk6PFJYRM7_cjs.a(v(s,o.item),v(s,(n.rounds.find(l=>l.experiment.id===o.experiment.replayOf)??I(`round ${o.experiment.id} replays the unknown experiment ${o.experiment.replayOf}`)).item)).length&&F(o.hypotheses.find(l=>l.id===r.supportedHypothesis),O(n).hypotheses.find(l=>l.id===r.supportedHypothesis))&&o.result?.valid&&u.includes(o.result.id)&&o.update?.assessments.some(l=>l.hypothesis===r.supportedHypothesis&&l.assessment==="supported")))&&a("resolved conclusion requires valid replay result and supporting belief update","set replayRefs to a valid independent replay result supporting the latest supported hypothesis definition, or reject with next round"),C(s,{...n,review:{by:t.by,reason:t.reason,replayRefs:u},reviewHistory:[...n.reviewHistory??[],{by:t.by,reason:t.reason,approve:true,replayRefs:u}]},t,r.outcome)}),stop:p("stop","facilitate",void 0,(s,n,t,a)=>(y(t.reason)||a("stop needs reason","set reason to a nonempty explanation for stopping this investigation"),C(s,n,t,"stopped",t.reason)))}}function V(){return [{id:"independent-replay",severity:"error",check(e,i){if(i.type!=="item.complete")return [];let d=m(e)?.rounds.find(s=>s.item===i.payload?.item),p=m(e)?.rounds.find(s=>s.experiment.id===d?.experiment.replayOf);return p&&chunk6PFJYRM7_cjs.a(i.by,v(e,p.item)).length?[{rule:"independent-replay",item:d.item,severity:"error",message:"Replay executor also executed the original experiment",fix:"assign a different deliver-capable role"}]:[]}},{id:"investigation-execution-only",severity:"error",check(e,i){if(i.type!=="item.complete")return [];let d=i.payload,p=m(e);return p?.phase==="observe"&&p.rounds.at(-1)?.item===d.item?[]:[{rule:"investigation-execution-only",item:d.item,severity:"error",message:"Only the active preregistered experiment can complete",fix:`complete only the active experiment item in phase observe; current phase is ${p?.phase??"intake"}`}]}}]}function G(){return [{id:"replay-worker",name:"Independent replay worker",modelTier:"small",capabilities:["deliver","verify"],canApprove:[],inputs:["preregistered-experiment"],outputs:["experiment-output"],do_not:["Do not change the replay procedure"]},{id:"investigator",name:"Investigator",modelTier:"large",capabilities:["facilitate","define-acceptance","deliver","verify"],canApprove:[],inputs:["question","prior-results"],outputs:["hypotheses","preregistered-experiment","belief-update"],do_not:["Do not revise predictions after execution","Do not approve your own conclusions"]},{id:"conclusion-reviewer",name:"Independent conclusion reviewer",modelTier:"large",capabilities:["review"],canApprove:["investigation-conclusion"],inputs:["evidence","replay","conclusion"],outputs:["conclusion-review"],do_not:["Do not approve unsupported conclusions"]}]}function J(){return [{id:"intake",name:"Intake",entryPolicy:[],exitPolicy:[{kind:"acceptance-written"}]},{id:"execute",name:"Execute preregistered experiment",entryPolicy:[{kind:"acceptance-written"},{kind:"no-open-blockers"}],exitPolicy:[{kind:"evidence",evidenceKind:"experiment-output"}]},{id:"observed",name:"Execution recorded",entryPolicy:[],exitPolicy:[]}]}function L(){return {name:"investigation",validateConfig:R,lockedConfigKeys:["question","maxRounds","budget"],vocabulary:{backlog:"Questions",item:"Investigation artifact",stage:"Investigation phase",iteration:"Investigation budget",increment:"Conclusion",ceremony:"Investigation ceremony",gate:"Independent conclusion review"},defaultStages:J,defaultRoles:G,requiredCapabilities:["facilitate","define-acceptance","deliver","verify","review"],exclusiveCapabilities:[],humanDefaults:{gates:"none"},ceremonies:U(L),plannerOptions:e=>({schedulerMode:"level",concurrencyCap:1,roleFor:i=>{let d=m(e)?.rounds.find(a=>a.item===i.id),p=m(e)?.rounds.find(a=>a.experiment.id===d?.experiment.replayOf),s=p?v(e,p.item):[],n=Object.values(e.roles),t=(p?void 0:n.find(a=>a.capabilities.includes("deliver")&&a.capabilities.includes("define-acceptance")))??n.find(a=>a.capabilities.includes("deliver")&&!chunk6PFJYRM7_cjs.a(a.id,s).length);return t||chunkOSHBJIYD_cjs.b("missing-capability",`No eligible executor for experiment item "${i.id}"`,p?`register an independent deliver-capable role that did not execute "${p.item}"`:"register a role with deliver capability",{items:[i.id]}),t.id},estimateMode:"per-call",fallbackTokensPerWeight:1}),candidates:e=>{let i=m(e),d=i?.rounds.at(-1)?.item;return i?.phase==="observe"&&!chunkTBLIZIWH_cjs.M(e.config.budget,S(e).spent)?Object.values(e.items).filter(p=>p.id===d&&p.stage==="execute"&&p.status==="todo"):[]},afterComplete:(e,i,d)=>{let p=m(e),s=e.iterations.find(n=>n.id==="investigation");return p?.phase!=="observe"||p.rounds.at(-1)?.item!==i||e.items[i]?.status==="done"||!s||!chunkTBLIZIWH_cjs.M(s.budget,s.spent)?e:C(e,p,{by:"investigation",now:d},"stopped",`budget exhausted before experiment item "${i}" completed; start a new investigation with sufficient budget`)},invariants:e=>[`Question: ${e.config.question}`,"Execute only the preregistered procedure; retain raw observation provenance; report invalid runs."],rules:V(),metrics:e=>({rounds:m(e)?.rounds.length??0,validRuns:m(e)?.rounds.filter(i=>i.result?.valid).length??0,invalidRuns:m(e)?.rounds.filter(i=>i.result&&!i.result.valid).length??0}),report:e=>({phase:m(e)?.phase??"intake",outcome:m(e)?.outcome??null,rounds:m(e)?.rounds.length??0,conclusion:m(e)?.conclusion??null,stopReason:m(e)?.stopReason??null})}}exports.a=R;exports.b=L;//# sourceMappingURL=chunk-76ITDJDM.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-76ITDJDM.cjs.map
|